mirror of
https://github.com/darksaid98/nightcore-spigot.git
synced 2026-12-01 14:38:47 +00:00
upload
This commit is contained in:
commit
7535bb18e8
180 files changed
+28365
No files matched your search
@@ -0,0 +1,3 @@
|
||||
/.idea/
|
||||
/pom.xml.versionsBackup
|
||||
/target/
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,34 @@
|
||||
<div align="center">
|
||||
<h1>nightcore</h1>
|
||||
<p>
|
||||
✅ Minimal server version: <b>1.18.2</b><br>
|
||||
✅ Supported software: <b>Spigot</b>, <b>Paper</b>, <b>Pufferfish</b>, <b>Purpur</b>.<br>
|
||||
❌ Not available for <b>Aternos</b> and <b>modded</b> servers.<br>
|
||||
<br>
|
||||
When installed, make sure to check out the <code>/nightcore/</code> folder and edit <b>language</b> and <b>config</b> files.
|
||||
</p>
|
||||
<br>
|
||||
</div>
|
||||
|
||||
**nightcore** is updated version of the [NexEngine](https://github.com/nulli0n/NexEngine-spigot) utility plugin. Changes are unnoticeable for regular users. Almost all plugin's data is compatible, except [Text Formations](https://github.com/nulli0n/nightcore-spigot/wiki/Text-Formation).
|
||||
|
||||
**Technical Changes:**
|
||||
- JAR size is increased due to legacy objects, so users can use old styled data for a while.
|
||||
- Reduced RAM usage by various objects.
|
||||
- Optimized and improved code where possible.
|
||||
- Prepare to use Spigot TextComponents where possible with custom text + tags parser.
|
||||
- Getting rid of unnecessary regex usage (Tab Completer, Text Parsing, Language Messages, Command Flags).
|
||||
- Many packages, classes and methods renamed/relocated so they makes more sense.
|
||||
- Removed useless code.
|
||||
|
||||
**Features:**
|
||||
* Internal command & permission registration (without usage of plugin.yml).
|
||||
* Easily create plugin commands with support of sub-commands and custom flags \[-f\].
|
||||
* Easily manage plugin configurations with auto-generated config files, and a single method to read, write and add configuration key-value.
|
||||
* Easily manage plugin language with auto-generated lang files, support for multiple language configs, and great message customization (JSON, action bar, titles, sounds, prefix).
|
||||
* Easily create custom GUIs with auto-generated config files and flexible menu items.
|
||||
* Easily manage SQL data with query and column builders.
|
||||
* Various wrappers for better handling bukkit and java objects.
|
||||
* Utility classes with a wide set of frequently used methods.
|
||||
* Custom text & tag parser. Get rid of those 'magic' colors: `&1&2&3`.
|
||||
* Improved `Random` class with better random generation.
|
||||
+1617
File diff suppressed because it is too large.
Load diff
+1617
File diff suppressed because it is too large.
Load diff
+1617
File diff suppressed because it is too large.
Load diff
+1617
File diff suppressed because it is too large.
Load diff
+1617
File diff suppressed because it is too large.
Load diff
+1617
File diff suppressed because it is too large.
Load diff
+1617
File diff suppressed because it is too large.
Load diff
+1617
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,117 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>su.nightexpress.nightcore</groupId>
|
||||
<artifactId>nightcore</artifactId>
|
||||
<version>2.5.0</version>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spigot-repo</id>
|
||||
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>papermc</id>
|
||||
<url>https://repo.papermc.io/repository/maven-public/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>placeholderapi</id>
|
||||
<url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>opencollab-snapshot</id>
|
||||
<url>https://repo.opencollab.dev/maven-snapshots/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>minecraft-repo</id>
|
||||
<url>https://libraries.minecraft.net/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>jitpack.io</id>
|
||||
<url>https://jitpack.io</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.spigotmc</groupId>
|
||||
<artifactId>spigot-api</artifactId>
|
||||
<version>1.20.4-R0.1-SNAPSHOT</version>
|
||||
</dependency>
|
||||
<!--<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>1.21</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>1.21</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.papermc.paper</groupId>
|
||||
<artifactId>paper-api</artifactId>
|
||||
<version>1.20.2-R0.1-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>-->
|
||||
<dependency>
|
||||
<groupId>com.zaxxer</groupId>
|
||||
<artifactId>HikariCP</artifactId>
|
||||
<version>5.0.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.mojang</groupId>
|
||||
<artifactId>authlib</artifactId>
|
||||
<version>5.0.47</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.xerial</groupId>
|
||||
<artifactId>sqlite-jdbc</artifactId>
|
||||
<version>3.41.2.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>it.unimi.dsi</groupId>
|
||||
<artifactId>fastutil</artifactId>
|
||||
<version>8.5.11</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.MilkBowl</groupId>
|
||||
<artifactId>VaultAPI</artifactId>
|
||||
<version>1.7</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>me.clip</groupId>
|
||||
<artifactId>placeholderapi</artifactId>
|
||||
<version>2.10.10</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.geysermc.floodgate</groupId>
|
||||
<artifactId>api</artifactId>
|
||||
<version>2.2.0-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory> <!-- (your resources folder location) -->
|
||||
<filtering>true</filtering> <!-- this is the important part, it's what replaces, filters, all placeholders in the resources folder (such as ${project.version} in plugin.yml) -->
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
|
||||
package org.jetbrains.annotations;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* An element annotated with NotNull claims {@code null} value is
|
||||
* <em>forbidden</em> to return (for methods), pass to (parameters) and hold
|
||||
* (local variables and fields). Apart from documentation purposes this
|
||||
* annotation is intended to be used by static analysis tools to validate
|
||||
* against probable runtime errors and element contract violations.
|
||||
*
|
||||
* @author max
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.CLASS)
|
||||
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.TYPE_USE})
|
||||
public @interface NotNull {
|
||||
|
||||
/**
|
||||
* @return Custom exception message
|
||||
*/
|
||||
String value() default "";
|
||||
|
||||
/**
|
||||
* @return Custom exception type that should be thrown when not-nullity contract
|
||||
* is violated. The exception class should have a constructor with one
|
||||
* String argument (message).
|
||||
* <p>
|
||||
* By default, {@link IllegalArgumentException} is thrown on null method
|
||||
* arguments and {@link IllegalStateException} — on null return
|
||||
* value.
|
||||
*/
|
||||
Class<? extends Exception> exception() default Exception.class;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* Copyright 2000-2014 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
|
||||
package org.jetbrains.annotations;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* An element annotated with {@link Nullable} claims {@code null} value is
|
||||
* perfectly <em>valid</em> to return (for methods), pass to (parameters) or
|
||||
* hold in (local variables and fields). Apart from documentation purposes this
|
||||
* annotation is intended to be used by static analysis tools to validate
|
||||
* against probable runtime errors or element contract violations. <br>
|
||||
* By convention, this annotation applied only when the value should
|
||||
* <em>always</em> be checked against {@code null} because the developer could
|
||||
* do nothing to prevent null from happening. Otherwise, too eager
|
||||
* {@link Nullable} usage could lead to too many false positives from static
|
||||
* analysis tools. <br>
|
||||
* For example, {@link java.util.Map#get(Object key)} should <em>not</em> be
|
||||
* annotated {@link Nullable} because someone may have put not-null value in the
|
||||
* map by this key and is expecting to find this value there ever since. <br>
|
||||
* On the other hand, the {@link java.lang.ref.Reference#get()} should be
|
||||
* annotated {@link Nullable} because it returns {@code null} if object got
|
||||
* collected which can happen at any time completely unexpectedly.
|
||||
*
|
||||
* @author max
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.CLASS)
|
||||
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.TYPE_USE})
|
||||
public @interface Nullable {
|
||||
|
||||
String value() default "";
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package su.nightexpress.nightcore;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.command.base.ReloadSubCommand;
|
||||
import su.nightexpress.nightcore.config.PluginDetails;
|
||||
import su.nightexpress.nightcore.core.CoreConfig;
|
||||
import su.nightexpress.nightcore.core.CoreLang;
|
||||
import su.nightexpress.nightcore.core.CoreManager;
|
||||
import su.nightexpress.nightcore.core.CorePerms;
|
||||
import su.nightexpress.nightcore.core.command.CheckPermCommand;
|
||||
import su.nightexpress.nightcore.dialog.Dialog;
|
||||
import su.nightexpress.nightcore.integration.VaultHook;
|
||||
import su.nightexpress.nightcore.language.LangAssets;
|
||||
import su.nightexpress.nightcore.menu.impl.EditorMenu;
|
||||
import su.nightexpress.nightcore.util.Plugins;
|
||||
import su.nightexpress.nightcore.util.blocktracker.PlayerBlockTracker;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class NightCore extends NightPlugin {
|
||||
|
||||
private final Set<NightCorePlugin> childrens;
|
||||
private final CoreManager coreManager;
|
||||
|
||||
public NightCore() {
|
||||
this.childrens = new HashSet<>();
|
||||
this.coreManager = new CoreManager(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enable() {
|
||||
LangAssets.load();
|
||||
|
||||
if (Plugins.hasVault()) {
|
||||
VaultHook.setup();
|
||||
this.getBaseCommand().addChildren(new CheckPermCommand(this));
|
||||
}
|
||||
this.getBaseCommand().addChildren(new ReloadSubCommand(this, CorePerms.COMMAND_RELOAD));
|
||||
|
||||
this.coreManager.setup();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disable() {
|
||||
this.coreManager.shutdown();
|
||||
|
||||
Dialog.shutdown();
|
||||
if (Plugins.hasVault()) {
|
||||
VaultHook.shutdown();
|
||||
}
|
||||
PlayerBlockTracker.shutdown();
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
protected PluginDetails getDefaultDetails() {
|
||||
return PluginDetails.create("nightcore", new String[]{"nightcore", "ncore"})
|
||||
.setConfigClass(CoreConfig.class)
|
||||
.setLangClass(CoreLang.class)
|
||||
.setPermissionsClass(CorePerms.class);
|
||||
}
|
||||
|
||||
void addChildren(@NotNull NightCorePlugin child) {
|
||||
this.childrens.add(child);
|
||||
child.info("Powered by " + this.getName());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<NightCorePlugin> getChildrens() {
|
||||
return new HashSet<>(this.childrens);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package su.nightexpress.nightcore;
|
||||
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
import org.bukkit.scheduler.BukkitScheduler;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.command.api.NightPluginCommand;
|
||||
import su.nightexpress.nightcore.config.FileConfig;
|
||||
import su.nightexpress.nightcore.command.CommandManager;
|
||||
import su.nightexpress.nightcore.config.PluginDetails;
|
||||
import su.nightexpress.nightcore.language.LangManager;
|
||||
import su.nightexpress.nightcore.util.wrapper.UniTask;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public interface NightCorePlugin extends Plugin {
|
||||
|
||||
boolean isEngine();
|
||||
|
||||
void enable();
|
||||
|
||||
void disable();
|
||||
|
||||
void reload();
|
||||
|
||||
@NotNull NightPluginCommand getBaseCommand();
|
||||
|
||||
@Override
|
||||
@NotNull FileConfig getConfig();
|
||||
|
||||
@NotNull FileConfig getLang();
|
||||
|
||||
@NotNull PluginDetails getDetails();
|
||||
|
||||
@NotNull
|
||||
default String getNameLocalized() {
|
||||
return this.getDetails().getName();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
default String getPrefix() {
|
||||
return this.getDetails().getPrefix();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
default String[] getCommandAliases() {
|
||||
return this.getDetails().getCommandAliases();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
default String getLanguage() {
|
||||
return this.getDetails().getLanguage();
|
||||
}
|
||||
|
||||
default void info(@NotNull String msg) {
|
||||
this.getLogger().info(msg);
|
||||
}
|
||||
|
||||
default void warn(@NotNull String msg) {
|
||||
this.getLogger().warning(msg);
|
||||
}
|
||||
|
||||
default void error(@NotNull String msg) {
|
||||
this.getLogger().severe(msg);
|
||||
}
|
||||
|
||||
default void debug(@NotNull String msg) {
|
||||
this.info("[DEBUG] " + msg);
|
||||
}
|
||||
|
||||
@NotNull LangManager getLangManager();
|
||||
|
||||
@NotNull CommandManager getCommandManager();
|
||||
|
||||
@NotNull
|
||||
default BukkitScheduler getScheduler() {
|
||||
return this.getServer().getScheduler();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
default PluginManager getPluginManager() {
|
||||
return this.getServer().getPluginManager();
|
||||
}
|
||||
|
||||
default void runTask(@NotNull Consumer<BukkitTask> consumer) {
|
||||
this.getScheduler().runTask(this, consumer);
|
||||
}
|
||||
|
||||
default void runTaskAsync(@NotNull Consumer<BukkitTask> consumer) {
|
||||
this.getScheduler().runTaskAsynchronously(this, consumer);
|
||||
}
|
||||
|
||||
default void runTaskLater(@NotNull Consumer<BukkitTask> consumer, long delay) {
|
||||
this.getScheduler().runTaskLater(this, consumer, delay);
|
||||
}
|
||||
|
||||
default void runTaskLaterAsync(@NotNull Consumer<BukkitTask> consumer, long delay) {
|
||||
this.getScheduler().runTaskLaterAsynchronously(this, consumer, delay);
|
||||
}
|
||||
|
||||
default void runTaskTimer(@NotNull Consumer<BukkitTask> consumer, long delay, long interval) {
|
||||
this.getScheduler().runTaskTimer(this, consumer, delay, interval);
|
||||
}
|
||||
|
||||
default void runTaskTimerAsync(@NotNull Consumer<BukkitTask> consumer, long delay, long interval) {
|
||||
this.getScheduler().runTaskTimerAsynchronously(this, consumer, delay, interval);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
default UniTask createTask(@NotNull Runnable runnable) {
|
||||
return new UniTask(this, runnable);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
default UniTask createAsyncTask(@NotNull Runnable runnable) {
|
||||
return this.createTask(runnable).setAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package su.nightexpress.nightcore;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.AbstractUserDataHandler;
|
||||
import su.nightexpress.nightcore.database.AbstractUserManager;
|
||||
import su.nightexpress.nightcore.database.DataUser;
|
||||
|
||||
public abstract class NightDataPlugin<U extends DataUser> extends NightPlugin /*implements UserDataHolder*/ {
|
||||
|
||||
//protected AbstractUserDataHandler<NexDataPlugin<U>, U> dataHandler;
|
||||
//protected AbstractUserManager<NexDataPlugin<U>, U> userManager;
|
||||
|
||||
@Override
|
||||
protected void loadManagers() {
|
||||
super.loadManagers();
|
||||
this.getUserManager().loadOnlineUsers();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void unloadManagers() {
|
||||
super.unloadManagers();
|
||||
this.getUserManager().shutdown();
|
||||
this.getData().shutdown();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public abstract AbstractUserDataHandler<? extends NightDataPlugin<U>, U> getData();
|
||||
|
||||
@NotNull
|
||||
public abstract AbstractUserManager<? extends NightDataPlugin<U>, U> getUserManager();
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package su.nightexpress.nightcore;
|
||||
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.command.CommandManager;
|
||||
import su.nightexpress.nightcore.command.api.NightPluginCommand;
|
||||
import su.nightexpress.nightcore.config.FileConfig;
|
||||
import su.nightexpress.nightcore.config.PluginDetails;
|
||||
import su.nightexpress.nightcore.language.LangManager;
|
||||
import su.nightexpress.nightcore.menu.api.Menu;
|
||||
import su.nightexpress.nightcore.menu.impl.AbstractMenu;
|
||||
import su.nightexpress.nightcore.util.Lists;
|
||||
import su.nightexpress.nightcore.util.Plugins;
|
||||
import su.nightexpress.nightcore.util.Reflex;
|
||||
import su.nightexpress.nightcore.util.Version;
|
||||
import su.nightexpress.nightcore.util.wrapper.UniPermission;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public abstract class NightPlugin extends JavaPlugin implements NightCorePlugin {
|
||||
|
||||
protected LangManager langManager;
|
||||
protected CommandManager commandManager;
|
||||
|
||||
protected FileConfig config;
|
||||
protected PluginDetails details;
|
||||
private boolean isEngine;
|
||||
|
||||
public final boolean isEngine() {
|
||||
return this.isEngine;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
long loadTook = System.currentTimeMillis();
|
||||
this.isEngine = this instanceof NightCore;
|
||||
|
||||
if (!this.isEngine()) {
|
||||
Plugins.CORE.addChildren(this);
|
||||
}
|
||||
|
||||
Version version = Version.getCurrent();
|
||||
if (version == Version.UNKNOWN) {
|
||||
this.warn("=".repeat(35));
|
||||
this.warn("WARNING: You're running an unsupported server version!");
|
||||
this.warn("Expect bugs and broken features.");
|
||||
this.warn("=".repeat(35));
|
||||
}
|
||||
else if (version.isDeprecated()) {
|
||||
this.warn("=".repeat(35));
|
||||
this.warn("WARNING: You're running an outdated/deprecated server version (" + Version.getCurrent().getLocalized() + ")!");
|
||||
this.warn("Support for this version will be dropped soon.");
|
||||
this.warn("Please, upgrade your server to at least " + Lists.next(Version.getCurrent(), Predicate.not(Version::isDeprecated)).getLocalized() + ".");
|
||||
this.warn("=".repeat(35));
|
||||
}
|
||||
|
||||
this.loadManagers();
|
||||
this.info("Plugin loaded in " + (System.currentTimeMillis() - loadTook) + " ms!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
this.unloadManagers();
|
||||
}
|
||||
|
||||
public final void reload() {
|
||||
if (this.isEngine()) {
|
||||
this.setupConfig();
|
||||
this.setupLanguage();
|
||||
return;
|
||||
}
|
||||
this.unloadManagers();
|
||||
this.loadManagers();
|
||||
}
|
||||
|
||||
/*@Override
|
||||
public final void reloadConfig() {
|
||||
this.getConfig().reload();
|
||||
this.loadConfig();
|
||||
}
|
||||
|
||||
public final void reloadLang() {
|
||||
this.getLang().reload();
|
||||
this.loadLang();
|
||||
}*/
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public final FileConfig getConfig() {
|
||||
return this.config;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public final FileConfig getLang() {
|
||||
return this.getLangManager().getConfig();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public PluginDetails getDetails() {
|
||||
return this.details == null ? this.getDefaultDetails() : this.details;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
protected abstract PluginDetails getDefaultDetails();
|
||||
|
||||
public void registerPermissions(@NotNull Class<?> clazz) {
|
||||
Reflex.getFields(clazz, UniPermission.class).forEach(permission -> {
|
||||
if (this.getPluginManager().getPermission(permission.getName()) == null) {
|
||||
this.getPluginManager().addPermission(permission);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
protected void setupConfig() {
|
||||
this.config = FileConfig.loadOrExtract(this, "config.yml");
|
||||
this.details = PluginDetails.read(this);
|
||||
|
||||
if (this.getDetails().getConfigClass() != null) {
|
||||
this.getConfig().initializeOptions(this.getDetails().getConfigClass());
|
||||
}
|
||||
}
|
||||
|
||||
protected void setupLanguage() {
|
||||
this.langManager = new LangManager(this);
|
||||
this.langManager.setup();
|
||||
|
||||
if (this.getDetails().getLangClass() != null) {
|
||||
this.getLangManager().loadEntries(this.getDetails().getLangClass());
|
||||
}
|
||||
}
|
||||
|
||||
protected void setupPermissions() {
|
||||
Class<?> clazz = this.getDetails().getPermissionsClass();
|
||||
if (clazz == null) return;
|
||||
|
||||
this.registerPermissions(clazz);
|
||||
}
|
||||
|
||||
protected void setupCommands() {
|
||||
this.commandManager = new CommandManager(this);
|
||||
this.commandManager.setup();
|
||||
}
|
||||
|
||||
protected void loadManagers() {
|
||||
this.setupConfig(); // Load configuration.
|
||||
this.setupLanguage(); // Load language.
|
||||
this.setupPermissions(); // Register plugin permissions.
|
||||
this.setupCommands(); // Register plugin commands.
|
||||
|
||||
this.enable(); // Load the plugin.
|
||||
|
||||
this.getConfig().saveChanges();
|
||||
this.getLang().saveChanges();
|
||||
}
|
||||
|
||||
protected void unloadManagers() {
|
||||
this.getScheduler().cancelTasks(this); // Stop all plugin tasks.
|
||||
|
||||
this.disable();
|
||||
|
||||
HandlerList.unregisterAll(this); // Unregister all plugin listeners.
|
||||
AbstractMenu.PLAYER_MENUS.values().forEach(Menu::close); // Close all GUIs.
|
||||
|
||||
this.getCommandManager().shutdown();
|
||||
this.getLangManager().shutdown();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public final NightPluginCommand getBaseCommand() {
|
||||
return this.getCommandManager().getMainCommand();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public final LangManager getLangManager() {
|
||||
return this.langManager;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public final CommandManager getCommandManager() {
|
||||
return this.commandManager;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package su.nightexpress.nightcore.command;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.World;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.util.Colorizer;
|
||||
import su.nightexpress.nightcore.util.NumberUtil;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
public class CommandFlag<T> {
|
||||
|
||||
public static final char PREFIX = '-';
|
||||
|
||||
private final String name;
|
||||
private final Function<String, T> parser;
|
||||
|
||||
public CommandFlag(@NotNull String name, @NotNull Function<String, T> parser) {
|
||||
this.name = name;
|
||||
this.parser = parser;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static CommandFlag<World> worldFlag(@NotNull String name) {
|
||||
return new CommandFlag<>(name, Bukkit::getWorld);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static CommandFlag<String> stringFlag(@NotNull String name) {
|
||||
return new CommandFlag<>(name, Function.identity());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static CommandFlag<String> textFlag(@NotNull String name) {
|
||||
return new CommandFlag<>(name, Colorizer::apply);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static CommandFlag<Integer> intFlag(@NotNull String name) {
|
||||
return new CommandFlag<>(name, str -> NumberUtil.getAnyInteger(str, 0));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static CommandFlag<Double> doubleFlag(@NotNull String name) {
|
||||
return new CommandFlag<>(name, str -> NumberUtil.getAnyDouble(str, 0D));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static CommandFlag<Boolean> booleanFlag(@NotNull String name) {
|
||||
return new CommandFlag<>(name, str -> true);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getNamePrefixed() {
|
||||
return PREFIX + this.getName();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Function<String, T> getParser() {
|
||||
return parser;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CommandFlag{" +
|
||||
"name='" + name + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package su.nightexpress.nightcore.command;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.api.NightPluginCommand;
|
||||
import su.nightexpress.nightcore.manager.SimpleManager;
|
||||
import su.nightexpress.nightcore.command.base.HelpSubCommand;
|
||||
import su.nightexpress.nightcore.command.impl.BaseCommand;
|
||||
import su.nightexpress.nightcore.util.CommandUtil;
|
||||
import su.nightexpress.nightcore.util.Lists;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class CommandManager extends SimpleManager<NightCorePlugin> {
|
||||
|
||||
private final Set<NightPluginCommand> commands;
|
||||
|
||||
private BaseCommand mainCommand;
|
||||
|
||||
public CommandManager(@NotNull NightCorePlugin plugin) {
|
||||
super(plugin);
|
||||
this.commands = new HashSet<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
String[] aliases = this.plugin.getCommandAliases();
|
||||
if (aliases == null || aliases.length == 0) {
|
||||
this.plugin.error("Could not register plugin commands!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Create main plugin command and attach help sub-command as a default executor.
|
||||
this.mainCommand = new BaseCommand(this.plugin);
|
||||
this.mainCommand.addDefaultCommand(new HelpSubCommand(this.plugin));
|
||||
|
||||
// Register main command as a bukkit command.
|
||||
this.registerCommand(this.mainCommand);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onShutdown() {
|
||||
for (NightPluginCommand command : new HashSet<>(this.getCommands())) {
|
||||
this.unregisterCommand(command);
|
||||
command.getChildrens().clear();
|
||||
}
|
||||
this.getCommands().clear();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<NightPluginCommand> getCommands() {
|
||||
return this.commands;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public BaseCommand getMainCommand() {
|
||||
return this.mainCommand;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public NightPluginCommand getCommand(@NotNull String alias) {
|
||||
return this.getCommands().stream()
|
||||
.filter(command -> Lists.contains(command.getAliases(), alias))
|
||||
.findFirst().orElse(null);
|
||||
}
|
||||
|
||||
public void registerCommand(@NotNull NightPluginCommand command) {
|
||||
if (this.commands.add(command)) {
|
||||
CommandUtil.register(this.plugin, command);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean unregisterCommand(@NotNull String alias) {
|
||||
NightPluginCommand command = this.getCommand(alias);
|
||||
if (command != null) {
|
||||
return this.unregisterCommand(command);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean unregisterCommand(@NotNull NightPluginCommand command) {
|
||||
if (this.commands.remove(command)) {
|
||||
return CommandUtil.unregister(command.getAliases()[0]);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package su.nightexpress.nightcore.command;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.util.NumberUtil;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class CommandResult {
|
||||
|
||||
private final String label;
|
||||
private final String[] args;
|
||||
private final Map<CommandFlag<?>, String> flags;
|
||||
|
||||
public CommandResult(@NotNull String label, String[] args, @NotNull Map<CommandFlag<?>, StringBuilder> flags) {
|
||||
this.label = label;
|
||||
this.flags = new HashMap<>();
|
||||
this.args = args;
|
||||
|
||||
flags.forEach((flag, content) -> this.flags.put(flag, content.toString()));
|
||||
}
|
||||
|
||||
public int length() {
|
||||
return this.args.length;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getArg(int index) {
|
||||
return this.getArgs()[index];
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getArg(int index, @NotNull String def) {
|
||||
if (index >= this.length()) return def;
|
||||
|
||||
return this.getArgs()[index];
|
||||
}
|
||||
|
||||
public int getInt(int index, int def) {
|
||||
return NumberUtil.getAnyInteger(this.getArg(index, ""), def);
|
||||
}
|
||||
|
||||
public double getDouble(int index, double def) {
|
||||
return NumberUtil.getAnyDouble(this.getArg(index, ""), def);
|
||||
}
|
||||
|
||||
public boolean hasFlag(@NotNull CommandFlag<?> flag) {
|
||||
return this.getFlags().containsKey(flag);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public <T> T getFlag(@NotNull CommandFlag<T> flag) {
|
||||
String value = this.getFlags().get(flag);
|
||||
if (value == null) return null;
|
||||
|
||||
return flag.getParser().apply(value);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T> T getFlag(@NotNull CommandFlag<T> flag, @NotNull T def) {
|
||||
T value = this.getFlag(flag);
|
||||
return value == null ? def : value;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getLabel() {
|
||||
return label;
|
||||
}
|
||||
|
||||
public String[] getArgs() {
|
||||
return args;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Map<CommandFlag<?>, String> getFlags() {
|
||||
return flags;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package su.nightexpress.nightcore.command.api;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.permissions.Permission;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.command.CommandFlag;
|
||||
import su.nightexpress.nightcore.language.entry.LangString;
|
||||
import su.nightexpress.nightcore.language.legacy.LegacyLangString;
|
||||
import su.nightexpress.nightcore.util.placeholder.Placeholder;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
public interface NightCommand extends Placeholder {
|
||||
|
||||
@NotNull List<String> getTab(@NotNull Player player, int arg, @NotNull String[] args);
|
||||
|
||||
void execute(@NotNull CommandSender sender, @NotNull String label, @NotNull String[] args);
|
||||
|
||||
void addChildren(@NotNull NightCommand children);
|
||||
|
||||
void removeChildren(@NotNull String alias);
|
||||
|
||||
default boolean hasPermission(@NotNull CommandSender sender) {
|
||||
return this.getPermission() == null || sender.hasPermission(this.getPermission());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
default String getLabelWithParents() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
NightCommand parent = this.getParent();
|
||||
while (parent != null) {
|
||||
builder.insert(0, parent.getAliases()[0] + " ");
|
||||
parent = parent.getParent();
|
||||
}
|
||||
builder.append(this.getAliases()[0]);
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
@Nullable NightCommand getParent();
|
||||
|
||||
void setParent(@Nullable NightCommand parent);
|
||||
|
||||
@Nullable NightCommand getChildren(@NotNull String alias);
|
||||
|
||||
@NotNull Collection<NightCommand> getChildrens();
|
||||
|
||||
@NotNull String[] getAliases();
|
||||
|
||||
@Nullable String getPermission();
|
||||
|
||||
default void setPermission(@Nullable Permission permission) {
|
||||
this.setPermission(permission == null ? null : permission.getName());
|
||||
}
|
||||
|
||||
void setPermission(@Nullable String permission);
|
||||
|
||||
@Nullable CommandFlag<?> getFlag(@NotNull String name);
|
||||
|
||||
@NotNull Collection<CommandFlag<?>> getFlags();
|
||||
|
||||
default void addFlag(@NotNull CommandFlag<?>... flags) {
|
||||
for (CommandFlag<?> flag : flags) this.addFlag(flag);
|
||||
}
|
||||
|
||||
void addFlag(@NotNull CommandFlag<?> flag);
|
||||
|
||||
@NotNull String getUsage();
|
||||
|
||||
@Deprecated
|
||||
default void setUsage(@NotNull LegacyLangString string) {
|
||||
this.setUsage(string.getString());
|
||||
}
|
||||
|
||||
default void setUsage(@NotNull LangString string) {
|
||||
this.setUsage(string.getString());
|
||||
}
|
||||
|
||||
void setUsage(@NotNull String usage);
|
||||
|
||||
@NotNull String getDescription();
|
||||
|
||||
@Deprecated
|
||||
default void setDescription(@NotNull LegacyLangString string) {
|
||||
this.setDescription(string.getString());
|
||||
}
|
||||
|
||||
default void setDescription(@NotNull LangString string) {
|
||||
this.setDescription(string.getString());
|
||||
}
|
||||
|
||||
void setDescription(@NotNull String description);
|
||||
|
||||
boolean isPlayerOnly();
|
||||
|
||||
void setPlayerOnly(boolean playerOnly);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package su.nightexpress.nightcore.command.api;
|
||||
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.TabExecutor;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public interface NightPluginCommand extends NightCommand, TabExecutor {
|
||||
|
||||
@Nullable NightCommand getDefaultCommand();
|
||||
|
||||
void addDefaultCommand(@NotNull NightCommand command);
|
||||
|
||||
Command getBackend();
|
||||
|
||||
void setBackend(@NotNull Command backend);
|
||||
|
||||
//@NotNull NightCommand findChildren(@NotNull String[] args);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package su.nightexpress.nightcore.command.base;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.impl.AbstractCommand;
|
||||
import su.nightexpress.nightcore.command.CommandResult;
|
||||
import su.nightexpress.nightcore.command.api.NightCommand;
|
||||
import su.nightexpress.nightcore.core.CoreLang;
|
||||
import su.nightexpress.nightcore.util.Placeholders;
|
||||
|
||||
public class HelpSubCommand extends AbstractCommand<NightCorePlugin> {
|
||||
|
||||
public HelpSubCommand(@NotNull NightCorePlugin plugin) {
|
||||
super(plugin, new String[]{"help"});
|
||||
this.setDescription(CoreLang.COMMAND_HELP_DESC);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onExecute(@NotNull CommandSender sender, @NotNull CommandResult result) {
|
||||
NightCommand parent = this.getParent();
|
||||
if (parent == null) return;
|
||||
|
||||
if (!parent.hasPermission(sender)) {
|
||||
this.errorPermission(sender);
|
||||
return;
|
||||
}
|
||||
|
||||
CoreLang.COMMAND_HELP_LIST.getMessage()
|
||||
.replace(Placeholders.GENERIC_NAME, this.plugin.getNameLocalized())
|
||||
.replace(Placeholders.GENERIC_ENTRY, list -> {
|
||||
parent.getChildrens().forEach(children -> {
|
||||
if (!children.hasPermission(sender)) return;
|
||||
|
||||
list.add(children.replacePlaceholders().apply(CoreLang.COMMAND_HELP_ENTRY.getString()));
|
||||
});
|
||||
}).send(sender);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package su.nightexpress.nightcore.command.base;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.permissions.Permission;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.CommandResult;
|
||||
import su.nightexpress.nightcore.command.impl.AbstractCommand;
|
||||
import su.nightexpress.nightcore.core.CoreLang;
|
||||
|
||||
public class ReloadSubCommand extends AbstractCommand<NightCorePlugin> {
|
||||
|
||||
public ReloadSubCommand(@NotNull NightCorePlugin plugin, @NotNull Permission permission) {
|
||||
this(plugin, permission.getName());
|
||||
}
|
||||
|
||||
public ReloadSubCommand(@NotNull NightCorePlugin plugin, @NotNull String permission) {
|
||||
super(plugin, new String[]{"reload"}, permission);
|
||||
this.setDescription(CoreLang.COMMAND_RELOAD_DESC);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onExecute(@NotNull CommandSender sender, @NotNull CommandResult result) {
|
||||
this.plugin.reload();
|
||||
CoreLang.COMMAND_RELOAD_DONE.getMessage().send(sender);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package su.nightexpress.nightcore.command.impl;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.permissions.Permission;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.CommandFlag;
|
||||
import su.nightexpress.nightcore.command.CommandResult;
|
||||
import su.nightexpress.nightcore.command.api.NightCommand;
|
||||
import su.nightexpress.nightcore.core.CoreLang;
|
||||
import su.nightexpress.nightcore.core.CorePerms;
|
||||
import su.nightexpress.nightcore.util.Placeholders;
|
||||
import su.nightexpress.nightcore.util.placeholder.PlaceholderMap;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public abstract class AbstractCommand<P extends NightCorePlugin> implements NightCommand {
|
||||
|
||||
protected final P plugin;
|
||||
private final String[] aliases;
|
||||
private final Map<String, NightCommand> childrens;
|
||||
private final Map<String, CommandFlag<?>> commandFlags;
|
||||
private final PlaceholderMap placeholderMap;
|
||||
|
||||
private NightCommand parent;
|
||||
private String permission;
|
||||
private String usage;
|
||||
private String description;
|
||||
private boolean playerOnly;
|
||||
|
||||
public AbstractCommand(@NotNull P plugin, @NotNull String[] aliases) {
|
||||
this(plugin, aliases, (String) null);
|
||||
}
|
||||
|
||||
public AbstractCommand(@NotNull P plugin, @NotNull String[] aliases, @Nullable Permission permission) {
|
||||
this(plugin, aliases, permission == null ? null : permission.getName());
|
||||
}
|
||||
|
||||
public AbstractCommand(@NotNull P plugin, @NotNull String[] aliases, @Nullable String permission) {
|
||||
this.plugin = plugin;
|
||||
this.aliases = Stream.of(aliases).map(String::toLowerCase).toArray(String[]::new);
|
||||
this.permission = permission;
|
||||
this.childrens = new TreeMap<>();
|
||||
this.commandFlags = new HashMap<>();
|
||||
this.placeholderMap = new PlaceholderMap()
|
||||
.add(Placeholders.COMMAND_DESCRIPTION, this::getDescription)
|
||||
.add(Placeholders.COMMAND_USAGE, this::getUsage)
|
||||
.add(Placeholders.COMMAND_LABEL, this::getLabelWithParents);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public PlaceholderMap getPlaceholders() {
|
||||
return this.placeholderMap;
|
||||
}
|
||||
|
||||
protected abstract void onExecute(@NotNull CommandSender sender, @NotNull CommandResult result);
|
||||
|
||||
@NotNull
|
||||
public List<String> getTab(@NotNull Player player, int arg, @NotNull String[] args) {
|
||||
if (player.hasPermission(CorePerms.COMMAND_FLAGS)) {
|
||||
return this.getFlags().stream().map(CommandFlag::getNamePrefixed).toList();
|
||||
}
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void execute(@NotNull CommandSender sender, @NotNull String label, @NotNull String[] args) {
|
||||
if (this.isPlayerOnly() && !(sender instanceof Player)) {
|
||||
this.errorSender(sender);
|
||||
return;
|
||||
}
|
||||
if (!this.hasPermission(sender)) {
|
||||
this.errorPermission(sender);
|
||||
return;
|
||||
}
|
||||
|
||||
List<String> cleanArgs = new ArrayList<>();
|
||||
Map<CommandFlag<?>, StringBuilder> flagContent = new HashMap<>();
|
||||
CommandFlag<?> lastFlag = null;
|
||||
|
||||
for (String arg : args) {
|
||||
CommandFlag<?> found = arg.charAt(0) == CommandFlag.PREFIX ? this.getFlag(arg.substring(1)) : null;
|
||||
|
||||
if (found != null) {
|
||||
flagContent.put(found, new StringBuilder());
|
||||
lastFlag = found;
|
||||
}
|
||||
else if (lastFlag != null) {
|
||||
StringBuilder builder = flagContent.get(lastFlag);
|
||||
if (!builder.isEmpty()) builder.append(" ");
|
||||
|
||||
builder.append(arg);
|
||||
}
|
||||
else {
|
||||
cleanArgs.add(arg);
|
||||
}
|
||||
}
|
||||
if (!sender.hasPermission(CorePerms.COMMAND_FLAGS)) {
|
||||
flagContent.clear();
|
||||
}
|
||||
|
||||
CommandResult result = new CommandResult(label, cleanArgs.toArray(new String[0]), flagContent);
|
||||
|
||||
this.onExecute(sender, result);
|
||||
}
|
||||
|
||||
public final void addChildren(@NotNull NightCommand children) {
|
||||
if (children.getParent() != null) return;
|
||||
|
||||
Stream.of(children.getAliases()).forEach(alias -> {
|
||||
this.childrens.put(alias, children);
|
||||
});
|
||||
children.setParent(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void removeChildren(@NotNull String alias) {
|
||||
this.childrens.keySet().removeIf(key -> key.equalsIgnoreCase(alias));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public NightCommand getParent() {
|
||||
return parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setParent(@Nullable NightCommand parent) {
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public final NightCommand getChildren(@NotNull String alias) {
|
||||
return this.childrens.get(alias);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Collection<NightCommand> getChildrens() {
|
||||
return new HashSet<>(this.childrens.values());
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public final String[] getAliases() {
|
||||
return this.aliases;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public final String getPermission() {
|
||||
return this.permission;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPermission(@Nullable String permission) {
|
||||
this.permission = permission;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public CommandFlag<?> getFlag(@NotNull String name) {
|
||||
return this.commandFlags.get(name.toLowerCase());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addFlag(@NotNull CommandFlag<?> flag) {
|
||||
this.commandFlags.put(flag.getName(), flag);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Collection<CommandFlag<?>> getFlags() {
|
||||
return this.commandFlags.values();
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getUsage() {
|
||||
return this.usage == null ? "" : this.usage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setUsage(@NotNull String usage) {
|
||||
this.usage = usage;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getDescription() {
|
||||
return this.description == null ? "" : this.description;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDescription(@NotNull String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPlayerOnly() {
|
||||
return this.playerOnly;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPlayerOnly(boolean playerOnly) {
|
||||
this.playerOnly = playerOnly;
|
||||
}
|
||||
|
||||
protected final void errorUsage(@NotNull CommandSender sender) {
|
||||
CoreLang.ERROR_COMMAND_USAGE.getMessage().replace(this.replacePlaceholders()).send(sender);
|
||||
}
|
||||
|
||||
protected final void errorPermission(@NotNull CommandSender sender) {
|
||||
CoreLang.ERROR_NO_PERMISSION.getMessage().send(sender);
|
||||
}
|
||||
|
||||
protected final void errorPlayer(@NotNull CommandSender sender) {
|
||||
CoreLang.ERROR_INVALID_PLAYER.getMessage().send(sender);
|
||||
}
|
||||
|
||||
protected final void errorSender(@NotNull CommandSender sender) {
|
||||
CoreLang.ERROR_COMMAND_PLAYER_ONLY.getMessage().send(sender);
|
||||
}
|
||||
|
||||
protected final void errorNumber(@NotNull CommandSender sender, @NotNull String from) {
|
||||
CoreLang.ERROR_INVALID_NUMBER.getMessage().replace(Placeholders.GENERIC_VALUE, from).send(sender);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package su.nightexpress.nightcore.command.impl;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.CommandResult;
|
||||
|
||||
public class BaseCommand extends PluginCommand<NightCorePlugin> {
|
||||
|
||||
public BaseCommand(@NotNull NightCorePlugin plugin) {
|
||||
super(plugin, plugin.getCommandAliases());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onExecute(@NotNull CommandSender sender, @NotNull CommandResult result) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package su.nightexpress.nightcore.command.impl;
|
||||
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.permissions.Permission;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.command.api.NightCommand;
|
||||
import su.nightexpress.nightcore.command.api.NightPluginCommand;
|
||||
import su.nightexpress.nightcore.util.Lists;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public abstract class PluginCommand<P extends NightCorePlugin> extends AbstractCommand<P> implements NightPluginCommand {
|
||||
|
||||
private Command backend;
|
||||
private NightCommand defaultCommand;
|
||||
|
||||
public PluginCommand(@NotNull P plugin, @NotNull String[] aliases) {
|
||||
this(plugin, aliases, (String) null);
|
||||
}
|
||||
|
||||
public PluginCommand(@NotNull P plugin, @NotNull String[] aliases, @Nullable Permission permission) {
|
||||
super(plugin, aliases, permission);
|
||||
}
|
||||
|
||||
public PluginCommand(@NotNull P plugin, @NotNull String[] aliases, @Nullable String permission) {
|
||||
super(plugin, aliases, permission);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addDefaultCommand(@NotNull NightCommand command) {
|
||||
this.addChildren(command);
|
||||
this.defaultCommand = command;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public NightCommand getDefaultCommand() {
|
||||
return defaultCommand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Command getBackend() {
|
||||
return backend;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBackend(@NotNull Command backend) {
|
||||
this.backend = backend;
|
||||
}
|
||||
|
||||
//@Override
|
||||
@NotNull
|
||||
private NightCommand findChildren(@NotNull String[] args) {
|
||||
NightCommand command = this;//.defaultCommand;
|
||||
int childCount = 0;
|
||||
while (args.length > childCount) {
|
||||
NightCommand child = command.getChildren(args[childCount++]);
|
||||
if (child == null) break;
|
||||
|
||||
command = child;
|
||||
}
|
||||
return command;
|
||||
}
|
||||
|
||||
/*private int countChildren(@NotNull String[] args) {
|
||||
AbstractCommand<P> command = this;
|
||||
int childCount = 0;
|
||||
while (args.length > childCount) {
|
||||
AbstractCommand<P> child = command.getChildren(args[childCount]);
|
||||
if (child == null) break;
|
||||
|
||||
command = child;
|
||||
childCount++;
|
||||
}
|
||||
return childCount;
|
||||
}*/
|
||||
|
||||
@Override
|
||||
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, String[] args) {
|
||||
NightCommand command = this.findChildren(args);
|
||||
if (command instanceof NightPluginCommand pluginCommand) {
|
||||
if (pluginCommand.getDefaultCommand() != null) {
|
||||
command = pluginCommand.getDefaultCommand();
|
||||
}
|
||||
}
|
||||
command.execute(sender, label, args);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd,
|
||||
@NotNull String label, String[] args) {
|
||||
|
||||
if (!(sender instanceof Player player) || args.length == 0) return Collections.emptyList();
|
||||
|
||||
NightCommand command = this.findChildren(args);
|
||||
if (!command.hasPermission(sender)) return Collections.emptyList();
|
||||
|
||||
List<String> list = new ArrayList<>();
|
||||
if (!command.getChildrens().isEmpty()) {
|
||||
command.getChildrens().stream().filter(child -> child.hasPermission(sender))
|
||||
.forEach(child -> list.addAll(Arrays.asList(child.getAliases())));
|
||||
}
|
||||
else {
|
||||
list.addAll(command.getTab(player, command.equals(this) ? (args.length) : (args.length - 1), args));
|
||||
}
|
||||
return Lists.getSequentialMatches(list, args[args.length - 1]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package su.nightexpress.nightcore.command.impl;
|
||||
|
||||
import org.bukkit.command.*;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.command.api.NightPluginCommand;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class WrappedCommand extends Command implements PluginIdentifiableCommand {
|
||||
|
||||
protected final Plugin plugin;
|
||||
protected final CommandExecutor executor;
|
||||
protected final TabCompleter tabCompleter;
|
||||
|
||||
public WrappedCommand(@NotNull Plugin plugin, @NotNull NightPluginCommand command) {
|
||||
this(plugin, command, command, command.getAliases(), command.getDescription(), command.getUsage());
|
||||
this.setPermission(command.getPermission());
|
||||
}
|
||||
|
||||
public WrappedCommand(@NotNull Plugin plugin,
|
||||
@NotNull CommandExecutor executor,
|
||||
@NotNull TabCompleter tabCompleter,
|
||||
@NotNull String[] aliases,
|
||||
@NotNull String description,
|
||||
@NotNull String usage) {
|
||||
super(aliases[0], description, usage, Arrays.asList(aliases));
|
||||
this.plugin = plugin;
|
||||
this.executor = executor;
|
||||
this.tabCompleter = tabCompleter;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Plugin getPlugin() {
|
||||
return this.plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean execute(@NotNull CommandSender sender, @NotNull String label, @NotNull String[] args) {
|
||||
return this.executor.onCommand(sender, this, label, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) {
|
||||
List<String> list = this.tabCompleter.onTabComplete(sender, this, alias, args);
|
||||
return list == null ? Collections.emptyList() : list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
package su.nightexpress.nightcore.config;
|
||||
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.util.TriFunction;
|
||||
import su.nightexpress.nightcore.util.wrapper.UniParticle;
|
||||
import su.nightexpress.nightcore.util.wrapper.UniSound;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class ConfigValue<T> {
|
||||
|
||||
private final String path;
|
||||
private final T defaultValue;
|
||||
private final String[] description;
|
||||
private final Reader<T> reader;
|
||||
private final Writer<T> writer;
|
||||
|
||||
private T value;
|
||||
|
||||
public ConfigValue(@NotNull String path,
|
||||
@NotNull Reader<T> reader,
|
||||
@NotNull Writer<T> writer,
|
||||
@NotNull T defaultValue,
|
||||
@Nullable String... description) {
|
||||
this.path = path;
|
||||
this.description = description == null ? new String[0] : description;
|
||||
this.reader = reader;
|
||||
this.writer = writer;
|
||||
this.defaultValue = defaultValue;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T> ConfigValue<T> create(@NotNull String path,
|
||||
@NotNull Reader<T> reader,
|
||||
@NotNull Writer<T> writer,
|
||||
@NotNull T defaultValue,
|
||||
@Nullable String... description) {
|
||||
return new ConfigValue<>(path, reader, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T> ConfigValue<T> create(@NotNull String path,
|
||||
@NotNull Reader<T> reader,
|
||||
@NotNull Writer<T> writer,
|
||||
|
||||
@NotNull Supplier<T> defaultValue,
|
||||
@Nullable String... description) {
|
||||
return create(path, reader, writer, defaultValue.get(), description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T> ConfigValue<T> create(@NotNull String path, @NotNull Reader<T> reader, @NotNull T defaultValue, @Nullable String... description) {
|
||||
return create(path, reader, FileConfig::set, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T> ConfigValue<T> create(@NotNull String path, @NotNull Reader<T> reader, @NotNull Supplier<T> defaultValue, @Nullable String... description) {
|
||||
return create(path, reader, FileConfig::set, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<Boolean> create(@NotNull String path, boolean defaultValue, @Nullable String... description) {
|
||||
return create(path, FileConfig::getBoolean, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<Integer> create(@NotNull String path, int defaultValue, @Nullable String... description) {
|
||||
return create(path, FileConfig::getInt, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<int[]> create(@NotNull String path, int[] defaultValue, @Nullable String... description) {
|
||||
return create(path, FileConfig::getIntArray, FileConfig::setIntArray, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<Double> create(@NotNull String path, double defaultValue, @Nullable String... description) {
|
||||
return create(path, FileConfig::getDouble, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<Long> create(@NotNull String path, long defaultValue, @Nullable String... description) {
|
||||
return create(path, FileConfig::getLong, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<String> create(@NotNull String path, @NotNull String defaultValue, @Nullable String... description) {
|
||||
return create(path, FileConfig::getString, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<String[]> create(@NotNull String path, @NotNull String[] defaultValue, @Nullable String... description) {
|
||||
return create(path, FileConfig::getStringArray, FileConfig::setStringArray, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<List<String>> create(@NotNull String path, @NotNull List<String> defaultValue, @Nullable String... description) {
|
||||
return create(path, (cfg, path1, def) -> cfg.getStringList(path1), defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<Set<String>> create(@NotNull String path, @NotNull Set<String> defaultValue, @Nullable String... description) {
|
||||
return create(path, (cfg, path1, def) -> cfg.getStringSet(path1), defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<ItemStack> create(@NotNull String path, @NotNull ItemStack defaultValue, @Nullable String... description) {
|
||||
return create(path, FileConfig::getItem, FileConfig::setItem, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<UniSound> create(@NotNull String path, @NotNull UniSound defaultValue, @Nullable String... description) {
|
||||
Reader<UniSound> reader = (cfg, path1, def) -> UniSound.read(cfg, path1);
|
||||
Writer<UniSound> writer = (cfg, path1, obj) -> obj.write(cfg, path1);
|
||||
|
||||
return create(path, reader, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ConfigValue<UniParticle> create(@NotNull String path, @NotNull UniParticle defaultValue, @Nullable String... description) {
|
||||
Reader<UniParticle> reader = (cfg, path1, def) -> UniParticle.read(cfg, path1);
|
||||
Writer<UniParticle> writer = (cfg, path1, obj) -> obj.write(cfg, path1);
|
||||
|
||||
return create(path, reader, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <E extends Enum<E>> ConfigValue<E> create(@NotNull String path, @NotNull Class<E> clazz, @NotNull E defaultValue, @Nullable String... description) {
|
||||
Reader<E> reader = (cfg, path1, def) -> cfg.getEnum(path1, clazz, def);
|
||||
Writer<E> writer = (cfg, path1, obj) -> cfg.set(path1, obj.name());
|
||||
|
||||
return create(path, reader, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <V> ConfigValue<Set<V>> forSet(@NotNull String path,
|
||||
@NotNull Function<String, V> reader,
|
||||
@NotNull Writer<Set<V>> writer,
|
||||
@NotNull Supplier<Set<V>> defaultValue,
|
||||
@Nullable String... description) {
|
||||
return forSet(path, reader, writer, defaultValue.get(), description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <V> ConfigValue<Set<V>> forSet(@NotNull String path,
|
||||
@NotNull Function<String, V> valFun,
|
||||
@NotNull Writer<Set<V>> writer,
|
||||
@NotNull Set<V> defaultValue,
|
||||
@Nullable String... description) {
|
||||
|
||||
Reader<Set<V>> reader = (cfg, path1, def) -> cfg.getStringSet(path1).stream().map(valFun).filter(Objects::nonNull).collect(Collectors.toCollection(HashSet::new));
|
||||
|
||||
return create(path, reader, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <K, V> ConfigValue<Map<K, V>> forMap(@NotNull String path,
|
||||
@NotNull Function<String, K> keyFun,
|
||||
@NotNull TriFunction<FileConfig, String, String, V> valFun,
|
||||
@NotNull Writer<Map<K, V>> writer,
|
||||
@NotNull Supplier<Map<K, V>> defaultValue,
|
||||
@Nullable String... description) {
|
||||
return forMap(path, keyFun, valFun, writer, defaultValue.get(), description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <K, V> ConfigValue<Map<K, V>> forMap(@NotNull String path,
|
||||
@NotNull Function<String, K> keyFun,
|
||||
@NotNull TriFunction<FileConfig, String, String, V> valFun,
|
||||
@NotNull Writer<Map<K, V>> writer,
|
||||
@NotNull Map<K, V> defaultValue,
|
||||
@Nullable String... description) {
|
||||
return forMap(path, keyFun, valFun, HashMap::new, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <K, V> ConfigValue<TreeMap<K, V>> forTreeMap(@NotNull String path,
|
||||
@NotNull Function<String, K> keyFun,
|
||||
@NotNull TriFunction<FileConfig, String, String, V> valFun,
|
||||
@NotNull Writer<TreeMap<K, V>> writer,
|
||||
@NotNull Supplier<TreeMap<K, V>> defaultValue, @Nullable String... description) {
|
||||
return forTreeMap(path, keyFun, valFun, writer, defaultValue.get(), description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <K, V> ConfigValue<TreeMap<K, V>> forTreeMap(@NotNull String path,
|
||||
@NotNull Function<String, K> keyFun,
|
||||
@NotNull TriFunction<FileConfig, String, String, V> valFun,
|
||||
@NotNull Writer<TreeMap<K, V>> writer,
|
||||
@NotNull TreeMap<K, V> defaultValue, @Nullable String... description) {
|
||||
return forMap(path, keyFun, valFun, TreeMap::new, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <K, V, M extends Map<K, V>> ConfigValue<M> forMap(@NotNull String path,
|
||||
@NotNull Function<String, K> keyFun,
|
||||
@NotNull TriFunction<FileConfig, String, String, V> valFun,
|
||||
@NotNull Supplier<M> mapSupplier,
|
||||
@NotNull Writer<M> writer,
|
||||
@NotNull M defaultValue, @Nullable String... description) {
|
||||
Reader<M> reader = (cfg, path1, def) -> {
|
||||
M map = mapSupplier.get();
|
||||
for (String id : cfg.getSection(path1)) {
|
||||
K key = keyFun.apply(id);
|
||||
V val = valFun.apply(cfg, path1, id);
|
||||
if (key == null || val == null) continue;
|
||||
|
||||
map.put(key, val);
|
||||
}
|
||||
return map;
|
||||
};
|
||||
|
||||
return create(path, reader, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <V> ConfigValue<Map<String, V>> forMap(@NotNull String path,
|
||||
@NotNull TriFunction<FileConfig, String, String, V> function,
|
||||
@NotNull Writer<Map<String, V>> writer,
|
||||
@NotNull Supplier<Map<String, V>> defaultValue,
|
||||
@Nullable String... description) {
|
||||
return forMap(path, String::toLowerCase, function, writer, defaultValue.get(), description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <V> ConfigValue<Map<String, V>> forMap(@NotNull String path,
|
||||
@NotNull TriFunction<FileConfig, String, String, V> function,
|
||||
@NotNull Writer<Map<String, V>> writer,
|
||||
@NotNull Map<String, V> defaultValue,
|
||||
@Nullable String... description) {
|
||||
return forMap(path, String::toLowerCase, function, writer, defaultValue, description);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public T read(@NotNull FileConfig cfg) {
|
||||
if (!cfg.contains(this.getPath())) {
|
||||
this.write(cfg);
|
||||
}
|
||||
if (this.getDescription().length > 0 && !this.getDescription()[0].isEmpty()) {
|
||||
cfg.setComments(this.getPath(), this.getDescription());
|
||||
}
|
||||
return (this.value = this.reader.read(cfg, this.getPath(), this.getDefaultValue()));
|
||||
}
|
||||
|
||||
public void write(@NotNull FileConfig cfg) {
|
||||
this.getWriter().write(cfg, this.getPath(), this.get());
|
||||
}
|
||||
|
||||
public boolean remove(@NotNull FileConfig cfg) {
|
||||
return cfg.remove(this.getPath());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public T get() {
|
||||
return this.value == null ? this.getDefaultValue() : this.value;
|
||||
}
|
||||
|
||||
public void set(@NotNull T value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getPath() {
|
||||
return path;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String[] getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public T getDefaultValue() {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Reader<T> getReader() {
|
||||
return reader;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Writer<T> getWriter() {
|
||||
return writer;
|
||||
}
|
||||
|
||||
public interface Reader<T> {
|
||||
|
||||
@NotNull T read(@NotNull FileConfig cfg, @NotNull String path, @NotNull T def);
|
||||
}
|
||||
|
||||
public interface Writer<T> {
|
||||
|
||||
void write(@NotNull FileConfig cfg, @NotNull String path, @NotNull T obj);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
package su.nightexpress.nightcore.config;
|
||||
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.InvalidConfigurationException;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.inventory.ItemFlag;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.Damageable;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.inventory.meta.LeatherArmorMeta;
|
||||
import org.bukkit.inventory.meta.PotionMeta;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.util.Version;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.util.*;
|
||||
import su.nightexpress.nightcore.util.text.NightMessage;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.*;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class FileConfig extends YamlConfiguration {
|
||||
|
||||
private final File file;
|
||||
private boolean isChanged = false;
|
||||
|
||||
public FileConfig(@NotNull String path, @NotNull String file) {
|
||||
this(new File(path, file));
|
||||
}
|
||||
|
||||
public FileConfig(@NotNull File file) {
|
||||
this.options().width(512);
|
||||
|
||||
FileUtil.create(file);
|
||||
this.file = file;
|
||||
this.reload();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static FileConfig loadOrExtract(@NotNull NightCorePlugin plugin, @NotNull String path, @NotNull String file) {
|
||||
if (!path.endsWith("/")) {
|
||||
path += "/";
|
||||
}
|
||||
return loadOrExtract(plugin, path + file);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static FileConfig loadOrExtract(@NotNull NightCorePlugin plugin, @NotNull String filePath) {
|
||||
if (!filePath.startsWith("/")) {
|
||||
filePath = "/" + filePath;
|
||||
}
|
||||
|
||||
File file = new File(plugin.getDataFolder() + filePath);
|
||||
if (FileUtil.create(file)) {
|
||||
try {
|
||||
InputStream input = plugin.getClass().getResourceAsStream(filePath);
|
||||
if (input != null) FileUtil.copy(input, file);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
return new FileConfig(file);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static List<FileConfig> loadAll(@NotNull String path) {
|
||||
return loadAll(path, false);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static List<FileConfig> loadAll(@NotNull String path, boolean deep) {
|
||||
return FileUtil.getFiles(path, deep).stream().filter(file -> file.getName().endsWith(".yml")).map(FileConfig::new).toList();
|
||||
}
|
||||
|
||||
public void initializeOptions(@NotNull Class<?> clazz) {
|
||||
initializeOptions(clazz, this);
|
||||
}
|
||||
|
||||
public static void initializeOptions(@NotNull Class<?> clazz, @NotNull FileConfig cfg) {
|
||||
for (ConfigValue<?> value : Reflex.getFields(clazz, ConfigValue.class)) {
|
||||
value.read(cfg);
|
||||
}
|
||||
cfg.saveChanges();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public File getFile() {
|
||||
return this.file;
|
||||
}
|
||||
|
||||
public void save() {
|
||||
try {
|
||||
this.save(this.file);
|
||||
}
|
||||
catch (IOException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean saveChanges() {
|
||||
if (!this.isChanged) return false;
|
||||
|
||||
this.save();
|
||||
this.isChanged = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean reload() {
|
||||
try {
|
||||
this.load(this.file);
|
||||
this.isChanged = false;
|
||||
return true;
|
||||
}
|
||||
catch (IOException | InvalidConfigurationException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean addMissing(@NotNull String path, @Nullable Object val) {
|
||||
if (this.contains(path)) return false;
|
||||
this.set(path, val);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(@NotNull String path, @Nullable Object value) {
|
||||
if (value instanceof String str) {
|
||||
value = Colorizer.plain(str);
|
||||
}
|
||||
else if (value instanceof Collection<?> collection) {
|
||||
List<Object> list = new ArrayList<>(collection);
|
||||
list.replaceAll(obj -> obj instanceof String str ? Colorizer.plain(str) : obj);
|
||||
value = list;
|
||||
}
|
||||
else if (value instanceof Location location) {
|
||||
value = LocationUtil.serialize(location);
|
||||
}
|
||||
else if (value instanceof Enum<?> en) {
|
||||
value = en.name();
|
||||
}
|
||||
super.set(path, value);
|
||||
this.isChanged = true;
|
||||
}
|
||||
|
||||
public void setComments(@NotNull String path, @Nullable String... comments) {
|
||||
this.setComments(path, Arrays.asList(comments));
|
||||
}
|
||||
|
||||
public void setInlineComments(@NotNull String path, @Nullable String... comments) {
|
||||
this.setInlineComments(path, Arrays.asList(comments));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setComments(@NotNull String path, @Nullable List<String> comments) {
|
||||
if (this.getComments(path).equals(comments)) return;
|
||||
|
||||
super.setComments(path, comments);
|
||||
this.isChanged = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setInlineComments(@NotNull String path, @Nullable List<String> comments) {
|
||||
super.setInlineComments(path, comments);
|
||||
}
|
||||
|
||||
public boolean remove(@NotNull String path) {
|
||||
if (!this.contains(path)) return false;
|
||||
this.set(path, null);
|
||||
return true;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<String> getSection(@NotNull String path) {
|
||||
ConfigurationSection section = this.getConfigurationSection(path);
|
||||
return section == null ? Collections.emptySet() : section.getKeys(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public String getString(@NotNull String path) {
|
||||
String str = super.getString(path);
|
||||
return str == null || str.isEmpty() ? null : str;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getString(@NotNull String path, @Nullable String def) {
|
||||
String str = super.getString(path, def);
|
||||
return str == null ? "" : str;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<String> getStringSet(@NotNull String path) {
|
||||
return new HashSet<>(this.getStringList(path));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public Location getLocation(@NotNull String path) {
|
||||
String raw = this.getString(path);
|
||||
return raw == null ? null : LocationUtil.deserialize(raw);
|
||||
}
|
||||
|
||||
public int[] getIntArray(@NotNull String path) {
|
||||
return getIntArray(path, new int[0]);
|
||||
}
|
||||
|
||||
public int[] getIntArray(@NotNull String path, int[] def) {
|
||||
String str = this.getString(path);
|
||||
return str == null ? def : NumberUtil.getIntArray(str);
|
||||
}
|
||||
|
||||
public void setIntArray(@NotNull String path, int[] arr) {
|
||||
if (arr == null) {
|
||||
this.set(path, null);
|
||||
return;
|
||||
}
|
||||
this.set(path, String.join(",", IntStream.of(arr).boxed().map(String::valueOf).toList()));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String @NotNull [] getStringArray(@NotNull String path, @NotNull String[] def) {
|
||||
String str = this.getString(path);
|
||||
return str == null ? def : str.split(",");
|
||||
}
|
||||
|
||||
public void setStringArray(@NotNull String path, String[] arr) {
|
||||
if (arr == null) {
|
||||
this.set(path, null);
|
||||
return;
|
||||
}
|
||||
this.set(path, String.join(",", arr));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public <T extends Enum<T>> T getEnum(@NotNull String path, @NotNull Class<T> clazz) {
|
||||
return StringUtil.getEnum(this.getString(path), clazz).orElse(null);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T extends Enum<T>> T getEnum(@NotNull String path, @NotNull Class<T> clazz, @NotNull T def) {
|
||||
return StringUtil.getEnum(this.getString(path), clazz).orElse(def);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T extends Enum<T>> List<T> getEnumList(@NotNull String path, @NotNull Class<T> clazz) {
|
||||
return this.getStringSet(path).stream().map(str -> StringUtil.getEnum(str, clazz).orElse(null))
|
||||
.filter(Objects::nonNull).toList();
|
||||
}
|
||||
|
||||
/*@NotNull
|
||||
public Set<FireworkEffect> getFireworkEffects(@NotNull String path) {
|
||||
Set<FireworkEffect> effects = new HashSet<>();
|
||||
for (String sId : this.getSection(path)) {
|
||||
String path2 = path + "." + sId + ".";
|
||||
FireworkEffect.Type type = this.getEnum(path2 + "Type", FireworkEffect.Type.class);
|
||||
if (type == null) continue;
|
||||
|
||||
boolean flicker = this.getBoolean(path2 + "Flicker");
|
||||
boolean trail = this.getBoolean(path2 + "Trail");
|
||||
|
||||
Set<Color> colors = new HashSet<>();
|
||||
for (String colorRaw : this.getStringList(path2 + "Colors")) {
|
||||
colors.add(StringUtil.parseColor(colorRaw));
|
||||
}
|
||||
|
||||
Set<Color> fadeColors = new HashSet<>();
|
||||
for (String colorRaw : this.getStringList(path2 + "Fade_Colors")) {
|
||||
fadeColors.add(StringUtil.parseColor(colorRaw));
|
||||
}
|
||||
|
||||
FireworkEffect.Builder builder = FireworkEffect.builder()
|
||||
.with(type).flicker(flicker).trail(trail).withColor(colors).withFade(fadeColors);
|
||||
effects.add(builder.build());
|
||||
}
|
||||
|
||||
return effects;
|
||||
}*/
|
||||
|
||||
@NotNull
|
||||
public ItemStack getItem(@NotNull String path, @Nullable ItemStack def) {
|
||||
ItemStack item = this.getItem(path);
|
||||
return item.getType().isAir() && def != null ? def : item;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ItemStack getItem(@NotNull String path) {
|
||||
if (!path.isEmpty() && !path.endsWith(".")) path = path + ".";
|
||||
|
||||
Material material = Material.getMaterial(this.getString(path + "Material", "").toUpperCase());
|
||||
if (material == null || material == Material.AIR) return new ItemStack(Material.AIR);
|
||||
|
||||
ItemStack item = new ItemStack(material);
|
||||
item.setAmount(this.getInt(path + "Amount", 1));
|
||||
|
||||
String headSkin = this.getString(path + "SkinURL", "");
|
||||
if (!headSkin.isEmpty()) {
|
||||
ItemUtil.setHeadSkin(item, headSkin);
|
||||
}
|
||||
else {
|
||||
String headTexture = this.getString(path + "Head_Texture", "");
|
||||
if (!headTexture.isEmpty()) {
|
||||
ItemUtil.setSkullTexture(item, headTexture);
|
||||
}
|
||||
}
|
||||
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
if (meta == null) return item;
|
||||
|
||||
int durability = this.getInt(path + "Durability");
|
||||
if (durability > 0 && meta instanceof Damageable damageable) {
|
||||
damageable.setDamage(durability);
|
||||
}
|
||||
|
||||
String name = this.getString(path + "Name");
|
||||
meta.setDisplayName(name != null ? NightMessage.asLegacy(Colorizer.apply(name)) : null);
|
||||
meta.setLore(NightMessage.asLegacy(Colorizer.apply(this.getStringList(path + "Lore"))));
|
||||
|
||||
for (String sKey : this.getSection(path + "Enchants")) {
|
||||
Enchantment enchantment;
|
||||
NamespacedKey key = NamespacedKey.minecraft(sKey.toLowerCase());
|
||||
|
||||
if (Version.isAtLeast(Version.V1_19_R3)) {
|
||||
enchantment = Registry.ENCHANTMENT.get(key);
|
||||
}
|
||||
else {
|
||||
enchantment = Enchantment.getByKey(key);
|
||||
}
|
||||
if (enchantment == null) continue;
|
||||
|
||||
int eLvl = this.getInt(path + "Enchants." + sKey);
|
||||
if (eLvl <= 0) continue;
|
||||
|
||||
meta.addEnchant(enchantment, eLvl, true);
|
||||
}
|
||||
|
||||
int model = this.getInt(path + "Custom_Model_Data");
|
||||
meta.setCustomModelData(model != 0 ? model : null);
|
||||
|
||||
List<String> flags = this.getStringList(path + "Item_Flags");
|
||||
if (flags.contains(Placeholders.WILDCARD)) {
|
||||
meta.addItemFlags(ItemFlag.values());
|
||||
}
|
||||
else {
|
||||
flags.stream().map(str -> StringUtil.getEnum(str, ItemFlag.class).orElse(null)).filter(Objects::nonNull).forEach(meta::addItemFlags);
|
||||
}
|
||||
|
||||
String colorRaw = this.getString(path + "Color");
|
||||
if (colorRaw != null && !colorRaw.isEmpty()) {
|
||||
Color color = StringUtil.getColor(colorRaw);
|
||||
if (meta instanceof LeatherArmorMeta armorMeta) {
|
||||
armorMeta.setColor(color);
|
||||
}
|
||||
else if (meta instanceof PotionMeta potionMeta) {
|
||||
potionMeta.setColor(color);
|
||||
}
|
||||
}
|
||||
|
||||
meta.setUnbreakable(this.getBoolean(path + "Unbreakable"));
|
||||
item.setItemMeta(meta);
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
public void setItem(@NotNull String path, @Nullable ItemStack item) {
|
||||
if (item == null) {
|
||||
this.set(path, null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!path.endsWith(".")) path = path + ".";
|
||||
this.set(path.substring(0, path.length() - 1), null);
|
||||
|
||||
Material material = item.getType();
|
||||
this.set(path + "Material", material.name());
|
||||
this.set(path + "Amount", item.getAmount() <= 1 ? null : item.getAmount());
|
||||
this.set(path + "SkinURL", ItemUtil.getHeadSkin(item));
|
||||
if (!this.contains(path + "SkinURL")) {
|
||||
this.set(path + "Head_Texture", ItemUtil.getSkullTexture(item));
|
||||
}
|
||||
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
if (meta == null) return;
|
||||
|
||||
if (meta instanceof Damageable damageable) {
|
||||
this.set(path + "Durability", damageable.getDamage() <= 0 ? null : damageable.getDamage());
|
||||
}
|
||||
|
||||
this.set(path + "Name", meta.getDisplayName().isEmpty() ? null : meta.getDisplayName());
|
||||
this.set(path + "Lore", meta.getLore());
|
||||
|
||||
for (Map.Entry<Enchantment, Integer> entry : meta.getEnchants().entrySet()) {
|
||||
this.set(path + "Enchants." + entry.getKey().getKey().getKey(), entry.getValue());
|
||||
}
|
||||
this.set(path + "Custom_Model_Data", meta.hasCustomModelData() ? meta.getCustomModelData() : null);
|
||||
|
||||
Color color = null;
|
||||
String colorRaw = null;
|
||||
if (meta instanceof PotionMeta potionMeta) {
|
||||
color = potionMeta.getColor();
|
||||
}
|
||||
else if (meta instanceof LeatherArmorMeta armorMeta) {
|
||||
color = armorMeta.getColor();
|
||||
}
|
||||
if (color != null) {
|
||||
colorRaw = color.getRed() + "," + color.getGreen() + "," + color.getBlue();
|
||||
}
|
||||
this.set(path + "Color", colorRaw);
|
||||
|
||||
List<String> itemFlags = new ArrayList<>(meta.getItemFlags().stream().map(ItemFlag::name).toList());
|
||||
this.set(path + "Item_Flags", itemFlags.isEmpty() ? null : itemFlags);
|
||||
this.set(path + "Unbreakable", meta.isUnbreakable() ? true : null);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public ItemStack getItemEncoded(@NotNull String path) {
|
||||
String compressed = this.getString(path);
|
||||
if (compressed == null) return null;
|
||||
|
||||
return ItemUtil.decompress(compressed);
|
||||
}
|
||||
|
||||
public void setItemEncoded(@NotNull String path, @Nullable ItemStack item) {
|
||||
this.set(path, item == null ? null : ItemUtil.compress(item));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ItemStack[] getItemsEncoded(@NotNull String path) {
|
||||
return ItemUtil.decompress(this.getStringList(path));
|
||||
}
|
||||
|
||||
public void setItemsEncoded(@NotNull String path, @NotNull List<ItemStack> item) {
|
||||
this.set(path, ItemUtil.compress(item));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package su.nightexpress.nightcore.config;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.language.LangManager;
|
||||
import su.nightexpress.nightcore.util.text.tag.Tags;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public class PluginDetails {
|
||||
|
||||
private final String name;
|
||||
private final String prefix;
|
||||
private final String[] commandAliases;
|
||||
private final String language;
|
||||
|
||||
private Class<?> configClass;
|
||||
private Class<?> langClass;
|
||||
private Class<?> permissionsClass;
|
||||
|
||||
public PluginDetails(
|
||||
@NotNull String name,
|
||||
@NotNull String prefix,
|
||||
@NotNull String[] commandAliases,
|
||||
@NotNull String language
|
||||
) {
|
||||
this.name = name;
|
||||
this.prefix = prefix;
|
||||
this.commandAliases = commandAliases;
|
||||
this.language = language.toLowerCase();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static PluginDetails create(@NotNull String name, @NotNull String[] commandAliases) {
|
||||
String prefix = Tags.YELLOW.enclose(name) + Tags.DARK_GRAY.enclose(" » ") + Tags.GRAY.getFullName();
|
||||
String language = Locale.getDefault().getLanguage();
|
||||
|
||||
return new PluginDetails(name, prefix, commandAliases, language);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static PluginDetails read(@NotNull NightCorePlugin plugin) {
|
||||
FileConfig config = plugin.getConfig();
|
||||
PluginDetails defaults = plugin.getDetails();
|
||||
|
||||
String pluginName = ConfigValue.create("Plugin.Name", defaults.getName(),
|
||||
"Localized plugin name. It's used in messages and with internal placeholders.")
|
||||
.read(config);
|
||||
|
||||
String pluginPrefix = ConfigValue.create("Plugin.Prefix", defaults.getPrefix(),
|
||||
"Plugin prefix. Used in messages."
|
||||
).read(config);
|
||||
|
||||
String[] commandAliases = ConfigValue.create("Plugin.Command_Aliases", defaults.getCommandAliases(),
|
||||
"Command names that will be registered as main plugin commands.",
|
||||
"Do not leave this empty. Split multiple names with a comma.")
|
||||
.read(config);
|
||||
|
||||
String languageCode = ConfigValue.create("Plugin.Language", defaults.getLanguage(),
|
||||
"Sets the plugin language.",
|
||||
"Basically it tells the plugin to use certain messages config from the '" + LangManager.DIR_LANG + "' sub-folder.",
|
||||
"If specified language is not available, default one (English) will be used instead.",
|
||||
"[Default is System Locale]")
|
||||
.read(config);
|
||||
|
||||
return new PluginDetails(pluginName, pluginPrefix, commandAliases, languageCode)
|
||||
.setConfigClass(defaults.getConfigClass())
|
||||
.setLangClass(defaults.getLangClass())
|
||||
.setPermissionsClass(defaults.getPermissionsClass());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getPrefix() {
|
||||
return prefix;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String[] getCommandAliases() {
|
||||
return commandAliases;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getLanguage() {
|
||||
return language;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Class<?> getConfigClass() {
|
||||
return configClass;
|
||||
}
|
||||
|
||||
public PluginDetails setConfigClass(@Nullable Class<?> configClass) {
|
||||
this.configClass = configClass;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Class<?> getLangClass() {
|
||||
return langClass;
|
||||
}
|
||||
|
||||
public PluginDetails setLangClass(@Nullable Class<?> langClass) {
|
||||
this.langClass = langClass;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Class<?> getPermissionsClass() {
|
||||
return permissionsClass;
|
||||
}
|
||||
|
||||
public PluginDetails setPermissionsClass(@Nullable Class<?> permissionsClass) {
|
||||
this.permissionsClass = permissionsClass;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package su.nightexpress.nightcore.core;
|
||||
|
||||
import su.nightexpress.nightcore.config.ConfigValue;
|
||||
import su.nightexpress.nightcore.util.text.NightMessage;
|
||||
import su.nightexpress.nightcore.util.text.tag.impl.ColorTag;
|
||||
|
||||
import java.awt.*;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class CoreConfig {
|
||||
|
||||
public static final ConfigValue<Boolean> MODERN_TEXT_PRECOMPILE_LANG = ConfigValue.create("ModernTextFormation.Precompile_Language",
|
||||
true,
|
||||
"When enabled, parses (deserializes) language messages to Spigot TextComponent(s) on plugin load.",
|
||||
"When disabled, parses (deserializes) language texts to Spigot TextComponent(s) in runtime when sending it to player.",
|
||||
"Enabling this setting is good for performance, however messages with placeholders will be recompiled in runtime anyway.",
|
||||
"(Side Note) Unlike NexEngine, it does not uses regex anymore, which makes deserialization significantly faster and accurate.",
|
||||
"[Default is true]");
|
||||
|
||||
public static final ConfigValue<Map<String, Color>> MODERN_TEXT_DEFAULT_COLORS = ConfigValue.forMap("ModernTextFormation.Default_Colors",
|
||||
(cfg, path, id) -> {
|
||||
try {
|
||||
Color color = Color.decode(cfg.getString(path + "." + id, "#ffffff"));
|
||||
NightMessage.registerTag(new ColorTag(id, color));
|
||||
return color;
|
||||
}
|
||||
catch (Exception exception) {
|
||||
exception.printStackTrace();
|
||||
return Color.WHITE;
|
||||
}
|
||||
},
|
||||
(cfg, path, map) -> map.forEach((id, value) -> cfg.set(path + "." + id, "#" + Integer.toHexString(value.getRGB()).substring(2))),
|
||||
() -> {
|
||||
Map<String, Color> map = new HashMap<>();
|
||||
map.put("aqua", Color.CYAN);
|
||||
return map;
|
||||
},
|
||||
"Here you can define custom colors to use it in all nightcore plugins like <aqua>Text</aqua>.",
|
||||
"You can also override default ones."
|
||||
);
|
||||
|
||||
public static final ConfigValue<Long> MENU_CLICK_COOLDOWN = ConfigValue.create("Menu.Click_Cooldown",
|
||||
150L,
|
||||
"Sets cooldown (in milliseconds) for player clicks in GUIs.",
|
||||
"[Default is 150ms]");
|
||||
|
||||
public static final ConfigValue<Boolean> USER_DEBUG_ENABLED = ConfigValue.create("UserData.Debug",
|
||||
false,
|
||||
"Enables debug messages for user data management.",
|
||||
"[Default is false]");
|
||||
|
||||
public static final ConfigValue<Integer> USER_CACHE_LIFETIME = ConfigValue.create("UserData.Cache.LifeTime",
|
||||
300,
|
||||
"Sets how long (in seconds) user data will be cached for offline users",
|
||||
"until removed and needs to be loaded from the database again.",
|
||||
"[Default is 300 (5 minutes)]");
|
||||
|
||||
public static final ConfigValue<Boolean> USER_CACHE_NAME_AND_UUID = ConfigValue.create("UserData.Cache.Names_And_UUIDs",
|
||||
true,
|
||||
"Sets whether or not plugin will cache player names and UUIDs.",
|
||||
"This will improve database performance when checking if user exists, but will increase memory usage.",
|
||||
"[Default is true]");
|
||||
|
||||
public static final ConfigValue<Boolean> RESPECT_PLAYER_DISPLAYNAME = ConfigValue.create("Engine.Respect_Player_DisplayName",
|
||||
false,
|
||||
"Sets whether or not 'Player#getDisplayName' can be used to find & get players in addition to regular 'Player#getName'.",
|
||||
"This is useful if you want to use custom player nicknames in commands.",
|
||||
"(Works only for nightcore based plugins.)",
|
||||
"[Default is false]");
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package su.nightexpress.nightcore.core;
|
||||
|
||||
import net.md_5.bungee.api.chat.ClickEvent;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.dialog.Dialog;
|
||||
import su.nightexpress.nightcore.language.entry.LangItem;
|
||||
import su.nightexpress.nightcore.language.entry.LangString;
|
||||
import su.nightexpress.nightcore.language.entry.LangText;
|
||||
import su.nightexpress.nightcore.util.Placeholders;
|
||||
|
||||
import static su.nightexpress.nightcore.util.Placeholders.*;
|
||||
import static su.nightexpress.nightcore.language.tag.MessageTags.*;
|
||||
import static su.nightexpress.nightcore.util.text.tag.Tags.*;
|
||||
|
||||
public class CoreLang {
|
||||
|
||||
public static final LangText COMMAND_HELP_LIST = LangText.of("Command.Help.List",
|
||||
TAG_NO_PREFIX,
|
||||
" " + YELLOW.enclose(BOLD.enclose(GENERIC_NAME)) + GRAY.enclose(" - ") + YELLOW.enclose(BOLD.enclose("Commands:")),
|
||||
"",
|
||||
GRAY.enclose(" " + RED.enclose(BOLD.enclose("<>")) + " - Required, " + GREEN.enclose(BOLD.enclose("[]")) + " - Optional."),
|
||||
"",
|
||||
GENERIC_ENTRY,
|
||||
" "
|
||||
);
|
||||
|
||||
public static final LangString COMMAND_HELP_ENTRY = LangString.of("Command.Help.Entry",
|
||||
" " + YELLOW.enclose( "/" + COMMAND_LABEL) + " " + ORANGE.enclose(Placeholders.COMMAND_USAGE) + GRAY.enclose(" - " + COMMAND_DESCRIPTION)
|
||||
);
|
||||
|
||||
public static final LangString COMMAND_HELP_DESC = LangString.of("Command.Help.Desc", "Show help page.");
|
||||
|
||||
public static final LangString COMMAND_CHECKPERM_DESC = LangString.of("Command.CheckPerm.Desc", "Print player permission info.");
|
||||
public static final LangString COMMAND_CHECKPERM_USAGE = LangString.of("Command.CheckPerm.Usage", "<player>");
|
||||
|
||||
public static final LangString COMMAND_RELOAD_DESC = LangString.of("Command.Reload.Desc", "Reload the plugin.");
|
||||
public static final LangText COMMAND_RELOAD_DONE = LangText.of("Command.Reload.Done", "Plugin " + GREEN.enclose("reloaded") + "!");
|
||||
|
||||
public static final LangString TIME_DAY = LangString.of("Time.Day", GENERIC_AMOUNT + "d.");
|
||||
public static final LangString TIME_HOUR = LangString.of("Time.Hour", GENERIC_AMOUNT + "h.");
|
||||
public static final LangString TIME_MINUTE = LangString.of("Time.Min", GENERIC_AMOUNT + "min.");
|
||||
public static final LangString TIME_SECOND = LangString.of("Time.Sec", GENERIC_AMOUNT + "sec.");
|
||||
public static final LangString TIME_DELIMITER = LangString.of("Time.Delimiter", " ");
|
||||
|
||||
public static final LangString OTHER_YES = LangString.of("Other.Yes", GREEN.enclose("Yes"));
|
||||
public static final LangString OTHER_NO = LangString.of("Other.No", RED.enclose("No"));
|
||||
public static final LangString OTHER_ENABLED = LangString.of("Other.Enabled", GREEN.enclose("Enabled"));
|
||||
public static final LangString OTHER_DISABLED = LangString.of("Other.Disabled", RED.enclose("Disabled"));
|
||||
public static final LangString OTHER_ANY = LangString.of("Other.Any", "Any");
|
||||
public static final LangString OTHER_NONE = LangString.of("Other.None", "None");
|
||||
public static final LangString OTHER_NEVER = LangString.of("Other.Never", "Never");
|
||||
public static final LangString OTHER_ONE_TIMED = LangString.of("Other.OneTimed", "One-Timed");
|
||||
public static final LangString OTHER_UNLIMITED = LangString.of("Other.Unlimited", "Unlimited");
|
||||
public static final LangString OTHER_INFINITY = LangString.of("Other.Infinity", "∞");
|
||||
|
||||
public static final LangText ERROR_INVALID_PLAYER = LangText.of("Error.Invalid_Player", RED.enclose("Player not found."));
|
||||
public static final LangText ERROR_INVALID_WORLD = LangText.of("Error.Invalid_World", RED.enclose("Invalid world."));
|
||||
public static final LangText ERROR_INVALID_NUMBER = LangText.of("Error.Invalid_Number", RED.enclose(GENERIC_VALUE + " is not a valid number."));
|
||||
public static final LangText ERROR_NO_PERMISSION = LangText.of("Error.NoPermission", RED.enclose("You don't have permissions to do that!"));
|
||||
public static final LangText ERROR_COMMAND_NOT_YOURSELF = LangText.of("Error.Command.NotYourself", RED.enclose("This command can not be used on yourself."));
|
||||
public static final LangText ERROR_COMMAND_PLAYER_ONLY = LangText.of("Error.Command.PlayerOnly", RED.enclose("This command is for players only."));
|
||||
public static final LangText ERROR_COMMAND_USAGE = LangText.of("Error.Command.Usage",
|
||||
TAG_NO_PREFIX,
|
||||
RED.enclose("Error: ") + GRAY.enclose("Wrong arguments!"),
|
||||
RED.enclose("Usage: ") + YELLOW.enclose("/" + Placeholders.COMMAND_LABEL) + " " + ORANGE.enclose(Placeholders.COMMAND_USAGE),
|
||||
" "
|
||||
);
|
||||
|
||||
public static final LangText EDITOR_ACTION_EXIT = LangText.of("Editor.Action.Exit",
|
||||
TAG_NO_PREFIX,
|
||||
GRAY.enclose("Click " +
|
||||
CLICK.enclose(
|
||||
ClickEvent.Action.RUN_COMMAND,
|
||||
HOVER.enclose(GREEN.enclose("[Here]"), GRAY.enclose("Click to cancel")),
|
||||
"/" + Dialog.EXIT
|
||||
)
|
||||
+ " to leave input mode."),
|
||||
" ");
|
||||
|
||||
public static final LangString EDITOR_INPUT_HEADER_MAIN = LangString.of("Editor.Input.Header.Main", GREEN.enclose(BOLD.enclose("Input Mode")));
|
||||
public static final LangString EDITOR_INPUT_HEADER_ERROR = LangString.of("Editor.Input.Header.Error", RED.enclose(BOLD.enclose("ERROR")));
|
||||
public static final LangString EDITOR_INPUT_ERROR_NOT_INTEGER = LangString.of("Editor.Input.Error.NotInteger", GRAY.enclose("Expecting " + RED.enclose("whole") + " number!"));
|
||||
public static final LangString EDITOR_INPUT_ERROR_GENERIC = LangString.of("Editor.Input.Error.Generic", GRAY.enclose("Invalid value!"));
|
||||
|
||||
public static final LangItem EDITOR_ITEM_CLOSE = LangItem.of("Editor.Generic.Close", RED.enclose("(✕) Exit"));
|
||||
public static final LangItem EDITOR_ITEM_RETURN = LangItem.of("Editor.Generic.Return", GRAY.enclose("(↓) ") + WHITE.enclose("Return"));
|
||||
public static final LangItem EDITOR_ITEM_NEXT_PAGE = LangItem.of("Editor.Generic.NextPage", WHITE.enclose("Next Page") + GRAY.enclose(" (→)"));
|
||||
public static final LangItem EDITOR_ITEM_PREVIOUS_PAGE = LangItem.of("Editor.Generic.PreviousPage", GRAY.enclose("(←) ") + WHITE.enclose("Previous Page"));
|
||||
|
||||
@NotNull
|
||||
public static String getYesOrNo(boolean value) {
|
||||
return (value ? OTHER_YES : OTHER_NO).getString();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String getEnabledOrDisabled(boolean value) {
|
||||
return (value ? OTHER_ENABLED : OTHER_DISABLED).getString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package su.nightexpress.nightcore.core;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCore;
|
||||
import su.nightexpress.nightcore.core.listener.CoreListener;
|
||||
import su.nightexpress.nightcore.dialog.DialogListener;
|
||||
import su.nightexpress.nightcore.manager.AbstractManager;
|
||||
import su.nightexpress.nightcore.menu.MenuListener;
|
||||
import su.nightexpress.nightcore.menu.impl.AbstractMenu;
|
||||
|
||||
public class CoreManager extends AbstractManager<NightCore> {
|
||||
|
||||
public CoreManager(@NotNull NightCore plugin) {
|
||||
super(plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onLoad() {
|
||||
this.addListener(new CoreListener(this.plugin));
|
||||
this.addListener(new DialogListener(this.plugin));
|
||||
this.addListener(new MenuListener(this.plugin));
|
||||
|
||||
this.addTask(this.plugin.createTask(() -> {
|
||||
AbstractMenu.PLAYER_MENUS.values().forEach(menu -> {
|
||||
if (menu.getOptions().isReadyToRefresh()) {
|
||||
menu.flush();
|
||||
menu.getOptions().setLastAutoRefresh(System.currentTimeMillis());
|
||||
}
|
||||
});
|
||||
}).setSecondsInterval(1));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onShutdown() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package su.nightexpress.nightcore.core;
|
||||
|
||||
import su.nightexpress.nightcore.util.wrapper.UniPermission;
|
||||
|
||||
public class CorePerms {
|
||||
|
||||
public static final UniPermission COMMAND_RELOAD = new UniPermission("nightcore.command.reload");
|
||||
public static final UniPermission COMMAND_CHECK_PERM = new UniPermission("nightcore.command.checkperm");
|
||||
public static final UniPermission COMMAND_FLAGS = new UniPermission("nightcore.command.flags");
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package su.nightexpress.nightcore.core.command;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCore;
|
||||
import su.nightexpress.nightcore.command.CommandResult;
|
||||
import su.nightexpress.nightcore.command.impl.AbstractCommand;
|
||||
import su.nightexpress.nightcore.core.CoreLang;
|
||||
import su.nightexpress.nightcore.core.CorePerms;
|
||||
import su.nightexpress.nightcore.integration.VaultHook;
|
||||
import su.nightexpress.nightcore.util.Colorizer;
|
||||
import su.nightexpress.nightcore.util.Players;
|
||||
import su.nightexpress.nightcore.util.text.NightMessage;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static su.nightexpress.nightcore.util.text.tag.Tags.*;
|
||||
|
||||
public class CheckPermCommand extends AbstractCommand<NightCore> {
|
||||
|
||||
public CheckPermCommand(@NotNull NightCore plugin) {
|
||||
super(plugin, new String[]{"checkperm"}, CorePerms.COMMAND_CHECK_PERM);
|
||||
this.setDescription(CoreLang.COMMAND_CHECKPERM_DESC);
|
||||
this.setUsage(CoreLang.COMMAND_CHECKPERM_USAGE);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public List<String> getTab(@NotNull Player player, int arg, @NotNull String[] args) {
|
||||
if (arg == 1) {
|
||||
return Players.playerNames(player);
|
||||
}
|
||||
return super.getTab(player, arg, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onExecute(@NotNull CommandSender sender, @NotNull CommandResult result) {
|
||||
if (result.length() < 2) {
|
||||
this.errorUsage(sender);
|
||||
return;
|
||||
}
|
||||
|
||||
Player player = Players.getPlayer(result.getArg(1));
|
||||
if (player == null) {
|
||||
this.errorPlayer(sender);
|
||||
return;
|
||||
}
|
||||
|
||||
String builder =
|
||||
BOLD.enclose(LIGHT_YELLOW.enclose("Permissions report for ") + LIGHT_ORANGE.enclose(player.getName() + ":")) +
|
||||
LIGHT_ORANGE.enclose("▪ " + LIGHT_YELLOW.enclose("Primary Group: ") + Colorizer.plain(VaultHook.getPermissionGroup(player))) +
|
||||
LIGHT_ORANGE.enclose("▪ " + LIGHT_YELLOW.enclose("All Groups: ") + Colorizer.plain(String.join(", ", VaultHook.getPermissionGroups(player)))) +
|
||||
LIGHT_ORANGE.enclose("▪ " + LIGHT_YELLOW.enclose("Prefix: ") + VaultHook.getPrefix(player)) +
|
||||
LIGHT_ORANGE.enclose("▪ " + LIGHT_YELLOW.enclose("Suffix: ") + VaultHook.getSuffix(player));
|
||||
NightMessage.create(builder).send(sender);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package su.nightexpress.nightcore.core.listener;
|
||||
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.server.ServiceRegisterEvent;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCore;
|
||||
import su.nightexpress.nightcore.integration.VaultHook;
|
||||
import su.nightexpress.nightcore.manager.AbstractListener;
|
||||
import su.nightexpress.nightcore.util.Plugins;
|
||||
|
||||
public class CoreListener extends AbstractListener<NightCore> {
|
||||
|
||||
public CoreListener(@NotNull NightCore plugin) {
|
||||
super(plugin);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void onServiceRegisterEvent(ServiceRegisterEvent event) {
|
||||
if (!Plugins.hasVault()) return;
|
||||
|
||||
VaultHook.onServiceRegisterEvent(event);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package su.nightexpress.nightcore.database;
|
||||
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public abstract class AbstractConnector {
|
||||
|
||||
protected final NightCorePlugin plugin;
|
||||
//protected final String url;
|
||||
protected final HikariConfig config;
|
||||
protected final HikariDataSource dataSource;
|
||||
|
||||
public AbstractConnector(@NotNull NightCorePlugin plugin, @NotNull DatabaseConfig config) {
|
||||
this.plugin = plugin;
|
||||
//this.url = getURL(config);
|
||||
|
||||
this.config = new HikariConfig();
|
||||
this.config.setJdbcUrl(this.getURL(config));
|
||||
this.setupConfig(config);
|
||||
this.config.addDataSourceProperty("cachePrepStmts", "true");
|
||||
this.config.addDataSourceProperty("prepStmtCacheSize", "250");
|
||||
this.config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
|
||||
this.dataSource = new HikariDataSource(this.config);
|
||||
}
|
||||
|
||||
protected abstract String getURL(@NotNull DatabaseConfig config);
|
||||
|
||||
protected abstract void setupConfig(@NotNull DatabaseConfig config);
|
||||
|
||||
public void close() {
|
||||
this.dataSource.close();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public final Connection getConnection() throws SQLException {
|
||||
return this.dataSource.getConnection();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package su.nightexpress.nightcore.database;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.database.connection.MySQLConnector;
|
||||
import su.nightexpress.nightcore.database.connection.SQLiteConnector;
|
||||
import su.nightexpress.nightcore.database.serialize.ItemStackSerializer;
|
||||
import su.nightexpress.nightcore.database.sql.SQLColumn;
|
||||
import su.nightexpress.nightcore.database.sql.SQLCondition;
|
||||
import su.nightexpress.nightcore.database.sql.SQLQueries;
|
||||
import su.nightexpress.nightcore.database.sql.SQLValue;
|
||||
import su.nightexpress.nightcore.database.sql.executor.*;
|
||||
import su.nightexpress.nightcore.manager.SimpleManager;
|
||||
import su.nightexpress.nightcore.util.wrapper.UniTask;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
public abstract class AbstractDataHandler<P extends NightCorePlugin> extends SimpleManager<P> {
|
||||
|
||||
protected final DatabaseConfig config;
|
||||
protected final AbstractConnector connector;
|
||||
protected final Gson gson;
|
||||
|
||||
private UniTask syncTask;
|
||||
private UniTask saveTask;
|
||||
|
||||
public AbstractDataHandler(@NotNull P plugin) {
|
||||
this(plugin, DatabaseConfig.read(plugin));
|
||||
}
|
||||
|
||||
public AbstractDataHandler(@NotNull P plugin, @NotNull DatabaseConfig config) {
|
||||
super(plugin);
|
||||
|
||||
this.config = config;
|
||||
if (this.getDatabaseType() == DatabaseType.MYSQL) {
|
||||
this.connector = new MySQLConnector(plugin, config);
|
||||
}
|
||||
else {
|
||||
this.connector = new SQLiteConnector(plugin, config);
|
||||
}
|
||||
this.gson = this.registerAdapters(new GsonBuilder().setPrettyPrinting()).create();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onLoad() {
|
||||
if (this.getConfig().getSaveInterval() > 0) {
|
||||
this.saveTask = this.plugin.createAsyncTask(this::onSave)
|
||||
.setSecondsInterval(this.getConfig().getSaveInterval() * 60)
|
||||
.start();
|
||||
}
|
||||
|
||||
if (this.getConfig().getSyncInterval() > 0 && this.getDatabaseType() != DatabaseType.SQLITE) {
|
||||
this.syncTask = this.plugin.createAsyncTask(this::onSynchronize)
|
||||
.setSecondsInterval(this.getConfig().getSyncInterval())
|
||||
.start();
|
||||
this.plugin.info("Enabled data synchronization with " + config.getSyncInterval() + " seconds interval.");
|
||||
}
|
||||
|
||||
if (this.getConfig().isPurgeEnabled() && this.getConfig().getPurgePeriod() > 0) {
|
||||
this.onPurge();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onShutdown() {
|
||||
if (this.syncTask != null) this.syncTask.stop();
|
||||
if (this.saveTask != null) this.saveTask.stop();
|
||||
//this.onSynchronize();
|
||||
this.onSave();
|
||||
this.getConnector().close();
|
||||
}
|
||||
|
||||
public abstract void onSynchronize();
|
||||
|
||||
public abstract void onSave();
|
||||
|
||||
public abstract void onPurge();
|
||||
|
||||
@NotNull
|
||||
public DatabaseConfig getConfig() {
|
||||
return this.config;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public DatabaseType getDatabaseType() {
|
||||
return this.getConfig().getStorageType();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getTablePrefix() {
|
||||
return this.getConfig().getTablePrefix();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public AbstractConnector getConnector() {
|
||||
return this.connector;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
protected GsonBuilder registerAdapters(@NotNull GsonBuilder builder) {
|
||||
return builder.registerTypeAdapter(ItemStack.class, new ItemStackSerializer());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
protected final Connection getConnection() throws SQLException {
|
||||
return this.getConnector().getConnection();
|
||||
}
|
||||
|
||||
public void createTable(@NotNull String table, @NotNull List<SQLColumn> columns) {
|
||||
CreateTableExecutor.builder(table, this.getDatabaseType()).columns(columns).execute(this.getConnector());
|
||||
}
|
||||
|
||||
public void renameTable(@NotNull String from, @NotNull String to) {
|
||||
RenameTableExecutor.builder(from, this.getDatabaseType()).renameTo(to).execute(this.getConnector());
|
||||
}
|
||||
|
||||
public void addColumn(@NotNull String table, @NotNull SQLValue... columns) {
|
||||
AlterTableExecutor.builder(table, this.getDatabaseType()).addColumn(columns).execute(this.getConnector());
|
||||
}
|
||||
|
||||
public void renameColumn(@NotNull String table, @NotNull SQLValue... columns) {
|
||||
AlterTableExecutor.builder(table, this.getDatabaseType()).renameColumn(columns).execute(this.getConnector());
|
||||
}
|
||||
|
||||
public void dropColumn(@NotNull String table, @NotNull SQLColumn... columns) {
|
||||
AlterTableExecutor.builder(table, this.getDatabaseType()).dropColumn(columns).execute(this.getConnector());
|
||||
}
|
||||
|
||||
public boolean hasColumn(@NotNull String table, @NotNull SQLColumn column) {
|
||||
return SQLQueries.hasColumn(this.getConnector(), table, column);
|
||||
}
|
||||
|
||||
public void insert(@NotNull String table, @NotNull List<SQLValue> values) {
|
||||
InsertQueryExecutor.builder(table).values(values).execute(this.getConnector());
|
||||
}
|
||||
|
||||
public void update(@NotNull String table, @NotNull List<SQLValue> values, @NotNull SQLCondition... conditions) {
|
||||
UpdateQueryExecutor.builder(table).values(values).where(conditions).execute(this.getConnector());
|
||||
}
|
||||
|
||||
public void delete(@NotNull String table, @NotNull SQLCondition... conditions) {
|
||||
DeleteQueryExecutor.builder(table).where(conditions).execute(this.getConnector());
|
||||
}
|
||||
|
||||
public boolean contains(@NotNull String table, @NotNull SQLCondition... conditions) {
|
||||
return this.load(table, (resultSet -> true), Collections.emptyList(), Arrays.asList(conditions)).isPresent();
|
||||
}
|
||||
|
||||
public boolean contains(@NotNull String table, @NotNull List<SQLColumn> columns, @NotNull SQLCondition... conditions) {
|
||||
return this.load(table, (resultSet -> true), columns, Arrays.asList(conditions)).isPresent();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T> Optional<T> load(@NotNull String table, @NotNull Function<ResultSet, T> function,
|
||||
@NotNull List<SQLColumn> columns,
|
||||
@NotNull List<SQLCondition> conditions) {
|
||||
List<T> list = this.load(table, function, columns, conditions, 1);
|
||||
return list.isEmpty() ? Optional.empty() : Optional.of(list.get(0));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T> List<T> load(@NotNull String table, @NotNull Function<ResultSet, T> dataFunction) {
|
||||
return this.load(table, dataFunction, -1);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T> List<T> load(@NotNull String table, @NotNull Function<ResultSet, T> dataFunction, int amount) {
|
||||
return this.load(table, dataFunction, Collections.emptyList(), amount);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T> List<T> load(@NotNull String table,
|
||||
@NotNull Function<ResultSet, T> dataFunction,
|
||||
@NotNull List<SQLColumn> columns,
|
||||
int amount) {
|
||||
return this.load(table, dataFunction, columns, Collections.emptyList(), amount);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <T> List<T> load(@NotNull String table,
|
||||
@NotNull Function<ResultSet, T> dataFunction,
|
||||
@NotNull List<SQLColumn> columns,
|
||||
@NotNull List<SQLCondition> conditions,
|
||||
int amount) {
|
||||
return SelectQueryExecutor.builder(table, dataFunction).columns(columns).where(conditions).execute(this.getConnector());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package su.nightexpress.nightcore.database;
|
||||
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class AbstractUser<P extends NightCorePlugin> implements DataUser {
|
||||
|
||||
protected final P plugin;
|
||||
protected final UUID uuid;
|
||||
|
||||
protected String name;
|
||||
protected long dateCreated;
|
||||
protected long lastOnline;
|
||||
protected long cachedUntil;
|
||||
|
||||
public AbstractUser(@NotNull P plugin, @NotNull UUID uuid, @NotNull String name, long dateCreated, long lastOnline) {
|
||||
this.plugin = plugin;
|
||||
this.uuid = uuid;
|
||||
this.name = name;
|
||||
this.setDateCreated(dateCreated);
|
||||
this.setLastOnline(lastOnline);
|
||||
this.setCachedUntil(-1);
|
||||
}
|
||||
|
||||
public void onLoad() {
|
||||
|
||||
}
|
||||
|
||||
public void onUnload() {
|
||||
|
||||
}
|
||||
|
||||
public boolean isCacheExpired() {
|
||||
return this.getCachedUntil() > 0 && System.currentTimeMillis() > this.getCachedUntil();
|
||||
}
|
||||
|
||||
public long getCachedUntil() {
|
||||
return cachedUntil;
|
||||
}
|
||||
|
||||
public void setCachedUntil(long cachedUntil) {
|
||||
this.cachedUntil = cachedUntil;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public final UUID getId() {
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public final String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public final long getDateCreated() {
|
||||
return dateCreated;
|
||||
}
|
||||
|
||||
public final void setDateCreated(long dateCreated) {
|
||||
this.dateCreated = dateCreated;
|
||||
}
|
||||
|
||||
public final long getLastOnline() {
|
||||
return this.lastOnline;
|
||||
}
|
||||
|
||||
public final void setLastOnline(long lastOnline) {
|
||||
this.lastOnline = lastOnline;
|
||||
}
|
||||
|
||||
public final boolean isOnline() {
|
||||
return this.getPlayer() != null;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public final OfflinePlayer getOfflinePlayer() {
|
||||
return this.plugin.getServer().getOfflinePlayer(this.getId());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public final Player getPlayer() {
|
||||
return this.plugin.getServer().getPlayer(this.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "AbstractUser [uuid=" + this.uuid + ", name=" + this.name + ", lastOnline=" + this.lastOnline + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package su.nightexpress.nightcore.database;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightDataPlugin;
|
||||
import su.nightexpress.nightcore.database.sql.SQLColumn;
|
||||
import su.nightexpress.nightcore.database.sql.SQLCondition;
|
||||
import su.nightexpress.nightcore.database.sql.SQLQueries;
|
||||
import su.nightexpress.nightcore.database.sql.SQLValue;
|
||||
import su.nightexpress.nightcore.database.sql.column.ColumnType;
|
||||
import su.nightexpress.nightcore.core.CoreConfig;
|
||||
import su.nightexpress.nightcore.util.TimeUtil;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
|
||||
public abstract class AbstractUserDataHandler<P extends NightDataPlugin<U>, U extends DataUser> extends AbstractDataHandler<P> {
|
||||
|
||||
protected static final SQLColumn COLUMN_USER_ID = SQLColumn.of("uuid", ColumnType.STRING);
|
||||
protected static final SQLColumn COLUMN_USER_NAME = SQLColumn.of("name", ColumnType.STRING);
|
||||
protected static final SQLColumn COLUMN_USER_DATE_CREATED = SQLColumn.of("dateCreated", ColumnType.LONG);
|
||||
protected static final SQLColumn COLUMN_USER_LAST_ONLINE = SQLColumn.of("last_online", ColumnType.LONG);
|
||||
|
||||
protected final String tableUsers;
|
||||
|
||||
protected final Set<UUID> existIDs;
|
||||
protected final Set<String> existNames;
|
||||
|
||||
protected AbstractUserDataHandler(@NotNull P plugin) {
|
||||
this(plugin, DatabaseConfig.read(plugin));
|
||||
}
|
||||
|
||||
protected AbstractUserDataHandler(@NotNull P plugin, @NotNull DatabaseConfig config) {
|
||||
super(plugin, config);
|
||||
this.tableUsers = this.getTablePrefix() + "_users";
|
||||
this.existIDs = new HashSet<>();
|
||||
this.existNames = new HashSet<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onLoad() {
|
||||
super.onLoad();
|
||||
this.createUserTable();
|
||||
this.cacheNamesAndIds();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onShutdown() {
|
||||
super.onShutdown();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSave() {
|
||||
for (U user : this.plugin.getUserManager().getLoaded()) {
|
||||
this.saveUser(user);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPurge() {
|
||||
if (!SQLQueries.hasTable(this.getConnector(), this.tableUsers)) return;
|
||||
|
||||
LocalDateTime deadline = LocalDateTime.now().minusDays(this.getConfig().getPurgePeriod());
|
||||
long deadlineMs = TimeUtil.toEpochMillis(deadline);
|
||||
|
||||
this.delete(this.tableUsers, SQLCondition.smaller(COLUMN_USER_LAST_ONLINE.toValue(deadlineMs)));
|
||||
}
|
||||
|
||||
protected void createUserTable() {
|
||||
List<SQLColumn> columns = new ArrayList<>();
|
||||
columns.add(COLUMN_USER_ID);
|
||||
columns.add(COLUMN_USER_NAME);
|
||||
columns.add(COLUMN_USER_DATE_CREATED);
|
||||
columns.add(COLUMN_USER_LAST_ONLINE);
|
||||
columns.addAll(this.getExtraColumns());
|
||||
|
||||
this.createTable(this.tableUsers, columns);
|
||||
}
|
||||
|
||||
public void cacheNamesAndIds() {
|
||||
if (!CoreConfig.USER_CACHE_NAME_AND_UUID.get()) return;
|
||||
|
||||
Function<ResultSet, Void> function = resultSet -> {
|
||||
try {
|
||||
this.existIDs.add(UUID.fromString(resultSet.getString(COLUMN_USER_ID.getName())));
|
||||
this.existNames.add(resultSet.getString(COLUMN_USER_NAME.getName()).toLowerCase());
|
||||
}
|
||||
catch (SQLException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
this.load(this.tableUsers, function, Arrays.asList(COLUMN_USER_ID, COLUMN_USER_NAME), Collections.emptyList(), -1);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
protected abstract List<SQLColumn> getExtraColumns();
|
||||
|
||||
@NotNull
|
||||
protected List<SQLColumn> getReadColumns() {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
protected abstract List<SQLValue> getSaveColumns(@NotNull U user);
|
||||
|
||||
@NotNull
|
||||
protected abstract Function<ResultSet, U> getUserFunction();
|
||||
|
||||
@NotNull
|
||||
public List<U> getUsers() {
|
||||
return this.load(this.tableUsers, this.getUserFunction(), Collections.emptyList(), Collections.emptyList(), -1);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public U getUser(@NotNull Player player) {
|
||||
return this.getUser(player.getUniqueId());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public final U getUser(@NotNull String name) {
|
||||
return this.load(this.tableUsers, this.getUserFunction(), this.getReadColumns(),
|
||||
Collections.singletonList(SQLCondition.equal(COLUMN_USER_NAME.asLowerCase().toValue(name.toLowerCase())))
|
||||
).orElse(null);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public final U getUser(@NotNull UUID uuid) {
|
||||
return this.load(this.tableUsers, this.getUserFunction(), this.getReadColumns(),
|
||||
Collections.singletonList(SQLCondition.equal(COLUMN_USER_ID.toValue(uuid)))
|
||||
).orElse(null);
|
||||
}
|
||||
|
||||
public boolean isUserExists(@NotNull String name) {
|
||||
if (CoreConfig.USER_CACHE_NAME_AND_UUID.get()) {
|
||||
return this.existNames.contains(name.toLowerCase());
|
||||
}
|
||||
return this.contains(this.tableUsers, Collections.singletonList(COLUMN_USER_NAME), SQLCondition.equal(COLUMN_USER_NAME.asLowerCase().toValue(name.toLowerCase())));
|
||||
}
|
||||
|
||||
public boolean isUserExists(@NotNull UUID uuid) {
|
||||
if (CoreConfig.USER_CACHE_NAME_AND_UUID.get()) {
|
||||
return this.existIDs.contains(uuid);
|
||||
}
|
||||
return this.contains(this.tableUsers, Collections.singletonList(COLUMN_USER_ID), SQLCondition.equal(COLUMN_USER_ID.toValue(uuid)));
|
||||
}
|
||||
|
||||
public void saveUser(@NotNull U user) {
|
||||
List<SQLValue> values = new ArrayList<>();
|
||||
values.add(COLUMN_USER_NAME.toValue(user.getName()));
|
||||
values.add(COLUMN_USER_DATE_CREATED.toValue(user.getDateCreated()));
|
||||
values.add(COLUMN_USER_LAST_ONLINE.toValue(user.getLastOnline()));
|
||||
values.addAll(this.getSaveColumns(user));
|
||||
|
||||
this.update(this.tableUsers, values, SQLCondition.equal(COLUMN_USER_ID.toValue(user.getId())));
|
||||
}
|
||||
|
||||
public void addUser(@NotNull U user) {
|
||||
List<SQLValue> values = new ArrayList<>();
|
||||
values.add(COLUMN_USER_ID.toValue(user.getId()));
|
||||
values.add(COLUMN_USER_NAME.toValue(user.getName()));
|
||||
values.add(COLUMN_USER_DATE_CREATED.toValue(user.getDateCreated()));
|
||||
values.add(COLUMN_USER_LAST_ONLINE.toValue(user.getLastOnline()));
|
||||
values.addAll(this.getSaveColumns(user));
|
||||
|
||||
this.insert(this.tableUsers, values);
|
||||
|
||||
this.existIDs.add(user.getId());
|
||||
this.existNames.add(user.getName());
|
||||
}
|
||||
|
||||
public void deleteUser(@NotNull UUID uuid) {
|
||||
this.delete(this.tableUsers, SQLCondition.equal(COLUMN_USER_ID.toValue(uuid)));
|
||||
|
||||
this.existIDs.clear();
|
||||
this.existNames.clear();
|
||||
this.cacheNamesAndIds();
|
||||
}
|
||||
|
||||
public void deleteUser(@NotNull DataUser user) {
|
||||
this.delete(this.tableUsers, SQLCondition.equal(COLUMN_USER_ID.toValue(user.getId())));
|
||||
|
||||
this.existIDs.remove(user.getId());
|
||||
this.existNames.remove(user.getName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
package su.nightexpress.nightcore.database;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.NightDataPlugin;
|
||||
import su.nightexpress.nightcore.manager.AbstractManager;
|
||||
import su.nightexpress.nightcore.core.CoreConfig;
|
||||
import su.nightexpress.nightcore.database.listener.UserListener;
|
||||
import su.nightexpress.nightcore.util.Players;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public abstract class AbstractUserManager<P extends NightDataPlugin<U>, U extends DataUser> extends AbstractManager<P> {
|
||||
|
||||
private final Map<UUID, U> loadedById;
|
||||
private final Map<String, U> loadedByName;
|
||||
|
||||
public AbstractUserManager(@NotNull P plugin) {
|
||||
super(plugin);
|
||||
this.loadedById = new ConcurrentHashMap<>();
|
||||
this.loadedByName = new ConcurrentHashMap<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onLoad() {
|
||||
this.addListener(new UserListener<>(this.plugin));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onShutdown() {
|
||||
this.getLoaded().forEach(this::save);
|
||||
this.getLoadedByIdMap().clear();
|
||||
this.getLoadedByNameMap().clear();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public abstract U createUserData(@NotNull UUID uuid, @NotNull String name);
|
||||
|
||||
public void loadOnlineUsers() {
|
||||
this.plugin.getServer().getOnlinePlayers().stream().map(Player::getUniqueId).forEach(id -> {
|
||||
U user = this.getUserData(id);
|
||||
if (user != null) this.cachePermanent(user);
|
||||
});
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public final U getUserData(@NotNull Player player) {
|
||||
UUID uuid = player.getUniqueId();
|
||||
|
||||
U user = this.getLoaded(uuid);
|
||||
if (user != null) return user;
|
||||
|
||||
if (Players.isReal(player)) {
|
||||
user = this.getUserData(uuid);
|
||||
if (user != null) {
|
||||
if (CoreConfig.USER_DEBUG_ENABLED.get()) {
|
||||
new Throwable().printStackTrace();
|
||||
this.plugin.warn("Main thread user data load for '" + uuid + "' aka '" + player.getName() + "'.");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
||||
return this.createUserData(uuid, player.getName());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public final U getUserData(@NotNull String name) {
|
||||
Player player = Players.getPlayer(name);
|
||||
if (player != null) return this.getUserData(player);
|
||||
|
||||
U user = this.getLoaded(name);
|
||||
if (user != null) return user;
|
||||
|
||||
user = this.plugin.getData().getUser(name);
|
||||
if (user != null) {
|
||||
user.onLoad();
|
||||
//this.plugin.debug("Loaded by name from DB: " + user.getName());
|
||||
this.cacheTemporary(user);
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public final U getUserData(@NotNull UUID uuid) {
|
||||
U user = this.getLoaded(uuid);
|
||||
if (user != null) return user;
|
||||
|
||||
user = this.plugin.getData().getUser(uuid);
|
||||
if (user != null) {
|
||||
user.onLoad();
|
||||
//this.plugin.debug("Loaded by UUID from DB: " + user.getName());
|
||||
this.cacheTemporary(user);
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
public final CompletableFuture<U> getUserDataAsync(@NotNull String name) {
|
||||
return CompletableFuture.supplyAsync(() -> this.getUserData(name));
|
||||
}
|
||||
|
||||
public final CompletableFuture<U> getUserDataAsync(@NotNull UUID uuid) {
|
||||
return CompletableFuture.supplyAsync(() -> this.getUserData(uuid));
|
||||
}
|
||||
|
||||
public void getUserDataAndPerform(@NotNull String name, Consumer<U> consumer) {
|
||||
U user = this.getLoaded(name);
|
||||
if (user != null) {
|
||||
consumer.accept(user);
|
||||
}
|
||||
else this.getUserDataAsync(name).thenAccept(user2 -> this.plugin.runTask(task -> consumer.accept(user2)));
|
||||
}
|
||||
|
||||
public void getUserDataAndPerform(@NotNull UUID uuid, Consumer<U> consumer) {
|
||||
U user = this.getLoaded(uuid);
|
||||
if (user != null) {
|
||||
consumer.accept(user);
|
||||
}
|
||||
else this.getUserDataAsync(uuid).thenAccept(user2 -> this.plugin.runTask(task -> consumer.accept(user2)));
|
||||
}
|
||||
|
||||
public void getUserDataAndPerformAsync(@NotNull String name, Consumer<U> consumer) {
|
||||
U user = this.getLoaded(name);
|
||||
if (user != null) {
|
||||
consumer.accept(user);
|
||||
}
|
||||
else this.getUserDataAsync(name).thenAccept(consumer);
|
||||
}
|
||||
|
||||
public void getUserDataAndPerformAsync(@NotNull UUID uuid, Consumer<U> consumer) {
|
||||
U user = this.getLoaded(uuid);
|
||||
if (user != null) {
|
||||
consumer.accept(user);
|
||||
}
|
||||
else this.getUserDataAsync(uuid).thenAccept(consumer);
|
||||
}
|
||||
|
||||
public final void unload(@NotNull Player player) {
|
||||
this.unload(player.getUniqueId());
|
||||
}
|
||||
|
||||
public final void unload(@NotNull UUID uuid) {
|
||||
U user = this.getLoadedByIdMap().get(uuid);
|
||||
if (user == null) return;
|
||||
|
||||
this.unload(user);
|
||||
}
|
||||
|
||||
public void unload(@NotNull U user) {
|
||||
Player player = user.getPlayer();
|
||||
if (player != null) {
|
||||
user.setName(player.getName());
|
||||
user.setLastOnline(System.currentTimeMillis());
|
||||
}
|
||||
this.saveAsync(user);
|
||||
this.cacheTemporary(user);
|
||||
}
|
||||
|
||||
public void save(@NotNull U user) {
|
||||
this.plugin.getData().saveUser(user);
|
||||
}
|
||||
|
||||
public void saveAsync(@NotNull U user) {
|
||||
this.plugin.runTaskAsync(task -> this.save(user));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<U> getAllUsers() {
|
||||
Map<UUID, U> users = new HashMap<>();
|
||||
this.getLoaded().forEach(user -> users.put(user.getId(), user));
|
||||
this.plugin.getData().getUsers().forEach(user -> {
|
||||
users.putIfAbsent(user.getId(), user);
|
||||
});
|
||||
return new HashSet<>(users.values());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Map<UUID, U> getLoadedByIdMap() {
|
||||
this.removeExpired(this.loadedById.values());
|
||||
|
||||
return this.loadedById;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Map<String, U> getLoadedByNameMap() {
|
||||
this.removeExpired(this.loadedByName.values());
|
||||
|
||||
return loadedByName;
|
||||
}
|
||||
|
||||
private void removeExpired(@NotNull Collection<U> collection) {
|
||||
collection.removeIf(user -> {
|
||||
if (user.isCacheExpired()) {
|
||||
user.onUnload();
|
||||
//this.plugin.debug("Cache expired: " + user.getName());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<U> getLoaded() {
|
||||
return new HashSet<>(this.getLoadedByIdMap().values());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public U getLoaded(@NotNull UUID uuid) {
|
||||
return this.getLoadedByIdMap().get(uuid);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public U getLoaded(@NotNull String name) {
|
||||
return this.getLoadedByNameMap().get(name.toLowerCase());
|
||||
}
|
||||
|
||||
public boolean isLoaded(@NotNull Player player) {
|
||||
return this.isLoaded(player.getUniqueId());
|
||||
}
|
||||
|
||||
public boolean isLoaded(@NotNull UUID id) {
|
||||
return this.getLoadedByIdMap().containsKey(id);
|
||||
}
|
||||
|
||||
public boolean isLoaded(@NotNull String name) {
|
||||
return this.getLoadedByNameMap().containsKey(name.toLowerCase());
|
||||
}
|
||||
|
||||
public boolean isCreated(@NotNull String name) {
|
||||
return this.plugin.getData().isUserExists(name);
|
||||
}
|
||||
|
||||
public boolean isCreated(@NotNull UUID uuid) {
|
||||
return this.plugin.getData().isUserExists(uuid);
|
||||
}
|
||||
|
||||
public void cacheTemporary(@NotNull U user) {
|
||||
user.setCachedUntil(System.currentTimeMillis() + CoreConfig.USER_CACHE_LIFETIME.get() * 1000L);
|
||||
this.cache(user);
|
||||
//this.plugin.debug("Temp user cache: " + user.getName());
|
||||
}
|
||||
|
||||
public void cachePermanent(@NotNull U user) {
|
||||
user.setCachedUntil(-1);
|
||||
this.cache(user);
|
||||
//this.plugin.debug("Permanent user cache: " + user.getName());
|
||||
}
|
||||
|
||||
private void cache(@NotNull U user) {
|
||||
this.getLoadedByIdMap().putIfAbsent(user.getId(), user);
|
||||
this.getLoadedByNameMap().putIfAbsent(user.getName().toLowerCase(), user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package su.nightexpress.nightcore.database;
|
||||
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public interface DataUser {
|
||||
|
||||
void onLoad();
|
||||
|
||||
void onUnload();
|
||||
|
||||
boolean isCacheExpired();
|
||||
|
||||
long getCachedUntil();
|
||||
|
||||
void setCachedUntil(long cachedUntil);
|
||||
|
||||
@NotNull UUID getId();
|
||||
|
||||
@NotNull String getName();
|
||||
|
||||
void setName(String name);
|
||||
|
||||
long getDateCreated();
|
||||
|
||||
void setDateCreated(long dateCreated);
|
||||
|
||||
long getLastOnline();
|
||||
|
||||
void setLastOnline(long lastOnline);
|
||||
|
||||
boolean isOnline();
|
||||
|
||||
@NotNull OfflinePlayer getOfflinePlayer();
|
||||
|
||||
@Nullable Player getPlayer();
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package su.nightexpress.nightcore.database;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.config.ConfigValue;
|
||||
import su.nightexpress.nightcore.config.FileConfig;
|
||||
import su.nightexpress.nightcore.util.StringUtil;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class DatabaseConfig {
|
||||
|
||||
private final int saveInterval;
|
||||
private final int syncInterval;
|
||||
private final DatabaseType databaseType;
|
||||
private final String tablePrefix;
|
||||
private final boolean purgeEnabled;
|
||||
private final int purgePeriod;
|
||||
|
||||
private final String username;
|
||||
private final String password;
|
||||
private final String host;
|
||||
private final String database;
|
||||
private final String urlOptions;
|
||||
|
||||
private final String filename;
|
||||
|
||||
public DatabaseConfig(
|
||||
int saveInterval,
|
||||
int syncInterval,
|
||||
@NotNull DatabaseType databaseType,
|
||||
@NotNull String tablePrefix,
|
||||
boolean purgeEnabled,
|
||||
int purgePeriod,
|
||||
|
||||
@NotNull String username,
|
||||
@NotNull String password,
|
||||
@NotNull String host,
|
||||
@NotNull String database,
|
||||
@NotNull String urlOptions,
|
||||
|
||||
@NotNull String filename
|
||||
) {
|
||||
this.saveInterval = saveInterval;
|
||||
this.syncInterval = syncInterval;
|
||||
this.databaseType = databaseType;
|
||||
this.tablePrefix = tablePrefix;
|
||||
this.purgeEnabled = purgeEnabled;
|
||||
this.purgePeriod = purgePeriod;
|
||||
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.host = host;
|
||||
this.database = database;
|
||||
this.urlOptions = urlOptions;
|
||||
|
||||
this.filename = filename;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static DatabaseConfig read(@NotNull NightCorePlugin plugin) {
|
||||
FileConfig cfg = plugin.getConfig();
|
||||
String path = "Database.";
|
||||
|
||||
DatabaseType databaseType = ConfigValue.create(path + "Type", DatabaseType.class, DatabaseType.SQLITE,
|
||||
"Sets database type.",
|
||||
"Available values: " + String.join(",", Stream.of(DatabaseType.values()).map(Enum::name).toList()))
|
||||
.read(cfg);
|
||||
|
||||
int saveInterval = ConfigValue.create(path + "Auto_Save_Interval", 20,
|
||||
"Sets how often (in minutes) plugin data of online players will be saved to the database.",
|
||||
"Set to '-1' to disable.")
|
||||
.read(cfg);
|
||||
|
||||
int syncInterval = ConfigValue.create(path + "Sync_Interval", -1,
|
||||
"Sets how often (in seconds) plugin data will be fetched and loaded from the remote database.",
|
||||
"Useless for " + DatabaseType.SQLITE.name() + ".",
|
||||
"Set to '-1' to disable.")
|
||||
.read(cfg);
|
||||
|
||||
String tablePrefix = ConfigValue.create(path + "Table_Prefix", StringUtil.lowerCaseUnderscore(plugin.getName()),
|
||||
"Custom prefix for plugin tables in database.")
|
||||
.read(cfg);
|
||||
|
||||
String mysqlUser = ConfigValue.create(path + "MySQL.Username", "root",
|
||||
"Database user name.")
|
||||
.read(cfg);
|
||||
|
||||
String mysqlPassword = ConfigValue.create(path + "MySQL.Password", "root",
|
||||
"Database password.")
|
||||
.read(cfg);
|
||||
|
||||
String mysqlHost = ConfigValue.create(path + "MySQL.Host", "localhost:3306",
|
||||
"Database address. Like http://127.0.0.1:3306/")
|
||||
.read(cfg);
|
||||
|
||||
String mysqlBase = ConfigValue.create(path + "MySQL.Database", "minecraft",
|
||||
"Name of the MySQL database where plugin will create tables.")
|
||||
.read(cfg);
|
||||
|
||||
String urlOptions = ConfigValue.create(path + "MySQL.Options",
|
||||
"?allowPublicKeyRetrieval=true&useSSL=false",
|
||||
"Connection options. Do not touch unless you know what you're doing."
|
||||
).read(cfg);
|
||||
|
||||
String sqliteFilename = ConfigValue.create(path + "SQLite.FileName", "data.db",
|
||||
"File name for the SQLite database file.",
|
||||
"Actually it's a path to the file, so you can use directories here.")
|
||||
.read(cfg);
|
||||
|
||||
|
||||
path = "Database.Purge.";
|
||||
boolean purgeEnabled = ConfigValue.create(path + "Enabled", false,
|
||||
"Enables the purge feature.",
|
||||
"Purge will remove all records from the plugin tables that are 'old' enough.")
|
||||
.read(cfg);
|
||||
|
||||
int purgePeriod = ConfigValue.create(path + "For_Period", 60,
|
||||
"Sets maximal 'age' for the database records before they will be purged.",
|
||||
"This option may have different behavior depends on the plugin.",
|
||||
"By default it's days of inactivity for the plugin users.")
|
||||
.read(cfg);
|
||||
|
||||
return new DatabaseConfig(
|
||||
saveInterval, syncInterval,
|
||||
databaseType, tablePrefix,
|
||||
purgeEnabled, purgePeriod,
|
||||
|
||||
mysqlUser, mysqlPassword, mysqlHost, mysqlBase, urlOptions,
|
||||
|
||||
sqliteFilename
|
||||
);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public DatabaseType getStorageType() {
|
||||
return databaseType;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getTablePrefix() {
|
||||
return tablePrefix;
|
||||
}
|
||||
|
||||
public int getSaveInterval() {
|
||||
return saveInterval;
|
||||
}
|
||||
|
||||
public int getSyncInterval() {
|
||||
return syncInterval;
|
||||
}
|
||||
|
||||
public boolean isPurgeEnabled() {
|
||||
return purgeEnabled;
|
||||
}
|
||||
|
||||
public int getPurgePeriod() {
|
||||
return purgePeriod;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getDatabase() {
|
||||
return database;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getUrlOptions() {
|
||||
return urlOptions;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getFilename() {
|
||||
return filename;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package su.nightexpress.nightcore.database;
|
||||
|
||||
public enum DatabaseType {
|
||||
|
||||
MYSQL,
|
||||
SQLITE,
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package su.nightexpress.nightcore.database.connection;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
import su.nightexpress.nightcore.database.DatabaseConfig;
|
||||
|
||||
public class MySQLConnector extends AbstractConnector {
|
||||
|
||||
public MySQLConnector(@NotNull NightCorePlugin plugin, @NotNull DatabaseConfig config) {
|
||||
super(plugin, config);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getURL(@NotNull DatabaseConfig config) {
|
||||
String host = config.getHost();
|
||||
String database = config.getDatabase();
|
||||
String options = config.getUrlOptions();
|
||||
|
||||
return "jdbc:mysql://" + host + "/" + database + options;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setupConfig(@NotNull DatabaseConfig config) {
|
||||
this.config.setUsername(config.getUsername());
|
||||
this.config.setPassword(config.getPassword());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package su.nightexpress.nightcore.database.connection;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
import su.nightexpress.nightcore.database.DatabaseConfig;
|
||||
|
||||
public class SQLiteConnector extends AbstractConnector {
|
||||
|
||||
public SQLiteConnector(@NotNull NightCorePlugin plugin, @NotNull DatabaseConfig config) {
|
||||
super(plugin, config);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getURL(@NotNull DatabaseConfig config) {
|
||||
String filePath = plugin.getDataFolder().getAbsolutePath() + "/" + config.getFilename();
|
||||
return "jdbc:sqlite:" + filePath;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setupConfig(@NotNull DatabaseConfig config) {
|
||||
this.config.setMaximumPoolSize(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package su.nightexpress.nightcore.database.listener;
|
||||
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightDataPlugin;
|
||||
import su.nightexpress.nightcore.core.CoreConfig;
|
||||
import su.nightexpress.nightcore.database.DataUser;
|
||||
import su.nightexpress.nightcore.manager.AbstractListener;
|
||||
import su.nightexpress.nightcore.database.AbstractUserManager;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class UserListener<P extends NightDataPlugin<U>, U extends DataUser> extends AbstractListener<P> {
|
||||
|
||||
private final AbstractUserManager<? extends NightDataPlugin<U>, U> userManager;
|
||||
|
||||
public UserListener(@NotNull P plugin) {
|
||||
super(plugin);
|
||||
this.userManager = plugin.getUserManager();
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onUserLogin(AsyncPlayerPreLoginEvent event) {
|
||||
if (event.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) return;
|
||||
|
||||
UUID uuid = event.getUniqueId();
|
||||
U user;
|
||||
if (!this.userManager.isCreated(uuid)) {
|
||||
user = this.userManager.createUserData(uuid, event.getName());
|
||||
plugin.getData().addUser(user);
|
||||
if (CoreConfig.USER_DEBUG_ENABLED.get()) {
|
||||
plugin.info("Created new data for: '" + uuid + "'");
|
||||
}
|
||||
}
|
||||
else user = this.userManager.getUserData(uuid);
|
||||
|
||||
if (user != null) {
|
||||
this.userManager.cachePermanent(user);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onUserQuit(PlayerQuitEvent event) {
|
||||
this.plugin.getUserManager().unload(event.getPlayer());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package su.nightexpress.nightcore.database.serialize;
|
||||
|
||||
import com.google.gson.*;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import su.nightexpress.nightcore.util.ItemUtil;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
public class ItemStackSerializer implements JsonSerializer<ItemStack>, JsonDeserializer<ItemStack> {
|
||||
|
||||
@Override
|
||||
public JsonElement serialize(ItemStack item, Type type, JsonSerializationContext context) {
|
||||
JsonObject object = new JsonObject();
|
||||
object.addProperty("data64", ItemUtil.compress(item));
|
||||
return object;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
|
||||
JsonObject object = json.getAsJsonObject();
|
||||
return ItemUtil.decompress(object.get("data64").getAsString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package su.nightexpress.nightcore.database.sql;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.DatabaseType;
|
||||
import su.nightexpress.nightcore.database.sql.column.ColumnType;
|
||||
|
||||
public class SQLColumn {
|
||||
|
||||
private final String name;
|
||||
private final String nameEscaped;
|
||||
private final ColumnType type;
|
||||
private final int length;
|
||||
|
||||
public SQLColumn(@NotNull String name, @NotNull ColumnType type, int length) {
|
||||
this(name, "`" + name + "`", type, length);
|
||||
}
|
||||
|
||||
public SQLColumn(@NotNull String name, @NotNull String nameEscaped, @NotNull ColumnType type, int length) {
|
||||
this.name = name;
|
||||
this.nameEscaped = nameEscaped;
|
||||
this.type = type;
|
||||
this.length = length;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static SQLColumn of(@NotNull String name, @NotNull ColumnType type) {
|
||||
return SQLColumn.of(name, type, -1);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static SQLColumn of(@NotNull String name, @NotNull ColumnType type, int length) {
|
||||
return new SQLColumn(name, type, length);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public SQLColumn asLowerCase() {
|
||||
return new SQLColumn("LOWER(" + this.getName() + ")", this.getName(), this.getType(), this.getLength());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getNameEscaped() {
|
||||
return this.nameEscaped;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ColumnType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public int getLength() {
|
||||
return length;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String formatType(@NotNull DatabaseType databaseType) {
|
||||
return this.getType().getFormer().build(databaseType, this.getLength());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public SQLValue toValue(@NotNull Object value) {
|
||||
return SQLValue.of(this, String.valueOf(value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package su.nightexpress.nightcore.database.sql;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class SQLCondition {
|
||||
|
||||
private final SQLValue value;
|
||||
private final Type type;
|
||||
|
||||
public SQLCondition(@NotNull SQLValue value, @NotNull Type type) {
|
||||
this.value = value;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static SQLCondition of(@NotNull SQLValue value, @NotNull Type type) {
|
||||
return new SQLCondition(value, type);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static SQLCondition equal(@NotNull SQLValue value) {
|
||||
return of(value, Type.EQUAL);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static SQLCondition not(@NotNull SQLValue value) {
|
||||
return of(value, Type.NOT_EQUAL);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static SQLCondition smaller(@NotNull SQLValue value) {
|
||||
return of(value, Type.SMALLER);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static SQLCondition greater(@NotNull SQLValue value) {
|
||||
return of(value, Type.GREATER);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Type getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public SQLValue getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public SQLColumn getColumn() {
|
||||
return this.getValue().getColumn();
|
||||
}
|
||||
|
||||
public enum Type {
|
||||
GREATER(">"),
|
||||
SMALLER("<"),
|
||||
EQUAL("="),
|
||||
NOT_EQUAL("!=");
|
||||
|
||||
private final String operator;
|
||||
|
||||
Type(@NotNull String operator) {
|
||||
this.operator = operator;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getOperator() {
|
||||
return operator;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package su.nightexpress.nightcore.database.sql;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
|
||||
public abstract class SQLExecutor<T> {
|
||||
|
||||
protected final String table;
|
||||
|
||||
protected SQLExecutor(@NotNull String table) {
|
||||
this.table = table;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getTable() {
|
||||
return "`" + this.table + "`";
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public abstract T execute(@NotNull AbstractConnector connector);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package su.nightexpress.nightcore.database.sql;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class SQLQueries {
|
||||
|
||||
public static boolean hasTable(@NotNull AbstractConnector connector, @NotNull String table) {
|
||||
try (Connection connection = connector.getConnection()) {
|
||||
|
||||
boolean has;
|
||||
DatabaseMetaData metaData = connection.getMetaData();
|
||||
ResultSet tables = metaData.getTables(null, null, table, null);
|
||||
has = tables.next();
|
||||
tables.close();
|
||||
return has;
|
||||
}
|
||||
catch (SQLException exception) {
|
||||
exception.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean hasColumn(@NotNull AbstractConnector connector,
|
||||
@NotNull String table,
|
||||
@NotNull SQLColumn column) {
|
||||
String sql = "SELECT * FROM " + table;
|
||||
String columnName = column.getName();
|
||||
try (Connection connection = connector.getConnection();
|
||||
Statement statement = connection.createStatement()) {
|
||||
|
||||
ResultSet resultSet = statement.executeQuery(sql);
|
||||
ResultSetMetaData metaData = resultSet.getMetaData();
|
||||
int columns = metaData.getColumnCount();
|
||||
for (int index = 1; index <= columns; index++) {
|
||||
if (columnName.equals(metaData.getColumnName(index))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
catch (SQLException exception) {
|
||||
exception.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void executeStatement(@NotNull AbstractConnector connector,
|
||||
@NotNull String sql) {
|
||||
executeStatement(connector, sql, Collections.emptySet());
|
||||
}
|
||||
|
||||
public static void executeStatement(@NotNull AbstractConnector connector,
|
||||
@NotNull String sql,
|
||||
@NotNull Collection<String> values1) {
|
||||
executeStatement(connector, sql, values1, Collections.emptySet());
|
||||
}
|
||||
|
||||
public static void executeStatement(@NotNull AbstractConnector connector,
|
||||
@NotNull String sql,
|
||||
@NotNull Collection<String> values1,
|
||||
@NotNull Collection<String> values2) {
|
||||
|
||||
try (Connection connection = connector.getConnection();
|
||||
PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
|
||||
int count = 1;
|
||||
for (String columnName : values1) {
|
||||
statement.setString(count++, columnName);
|
||||
}
|
||||
for (String columnValue : values2) {
|
||||
statement.setString(count++, columnValue);
|
||||
}
|
||||
|
||||
statement.executeUpdate();
|
||||
}
|
||||
catch (SQLException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T> List<@NotNull T> executeQuery(@NotNull AbstractConnector connector,
|
||||
@NotNull String sql,
|
||||
@NotNull Collection<String> values,
|
||||
@NotNull Function<ResultSet, T> dataFunction,
|
||||
int amount) {
|
||||
|
||||
List<T> list = new ArrayList<>();
|
||||
try (Connection connection = connector.getConnection();
|
||||
PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
|
||||
int count = 1;
|
||||
for (String wValue : values) {
|
||||
statement.setString(count++, wValue);
|
||||
}
|
||||
|
||||
ResultSet resultSet = statement.executeQuery();
|
||||
while (resultSet.next() && (amount < 0 || list.size() < amount)) {
|
||||
list.add(dataFunction.apply(resultSet));
|
||||
}
|
||||
resultSet.close();
|
||||
}
|
||||
catch (SQLException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
list.removeIf(Objects::isNull);
|
||||
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package su.nightexpress.nightcore.database.sql;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class SQLValue {
|
||||
|
||||
private final SQLColumn column;
|
||||
private final String value;
|
||||
|
||||
public SQLValue(@NotNull SQLColumn column, @NotNull String value) {
|
||||
this.column = column;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static SQLValue of(@NotNull SQLColumn column, @NotNull String value) {
|
||||
return new SQLValue(column, value);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public SQLColumn getColumn() {
|
||||
return column;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package su.nightexpress.nightcore.database.sql.column;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.DatabaseType;
|
||||
|
||||
public interface ColumnFormer {
|
||||
|
||||
ColumnFormer STRING = (storageType, length) -> {
|
||||
if (length < 1 || storageType == DatabaseType.SQLITE) {
|
||||
return storageType == DatabaseType.SQLITE ? "TEXT NOT NULL" : "MEDIUMTEXT NOT NULL";
|
||||
}
|
||||
return "varchar(" + length + ") CHARACTER SET utf8 NOT NULL";
|
||||
};
|
||||
|
||||
ColumnFormer INTEGER = (storageType, length) -> {
|
||||
if (length < 1 || storageType == DatabaseType.SQLITE) {
|
||||
return "INTEGER NOT NULL";
|
||||
}
|
||||
return "int(" + length + ") NOT NULL";
|
||||
};
|
||||
|
||||
ColumnFormer DOUBLE = (storageType, length) -> {
|
||||
return storageType == DatabaseType.SQLITE ? "REAL NOT NULL" : "double NOT NULL";
|
||||
};
|
||||
|
||||
ColumnFormer LONG = (storageType, length) -> {
|
||||
return length < 1 || storageType == DatabaseType.SQLITE ? "BIGINT NOT NULL" : "bigint(" + length + ") NOT NULL";
|
||||
};
|
||||
|
||||
ColumnFormer BOOLEAN = (storageType, length) -> {
|
||||
return storageType == DatabaseType.SQLITE ? "INTEGER NOT NULL" : "tinyint(1) NOT NULL";
|
||||
};
|
||||
|
||||
@NotNull String build(@NotNull DatabaseType databaseType, int length);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package su.nightexpress.nightcore.database.sql.column;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class ColumnType {
|
||||
|
||||
public static final ColumnType INTEGER = new ColumnType(ColumnFormer.INTEGER);
|
||||
public static final ColumnType DOUBLE = new ColumnType(ColumnFormer.DOUBLE);
|
||||
public static final ColumnType LONG = new ColumnType(ColumnFormer.LONG);
|
||||
public static final ColumnType BOOLEAN = new ColumnType(ColumnFormer.BOOLEAN);
|
||||
public static final ColumnType STRING = new ColumnType(ColumnFormer.STRING);
|
||||
|
||||
private final ColumnFormer former;
|
||||
|
||||
public ColumnType(@NotNull ColumnFormer former) {
|
||||
this.former = former;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ColumnFormer getFormer() {
|
||||
return former;
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
package su.nightexpress.nightcore.database.sql.executor;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.DatabaseType;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
import su.nightexpress.nightcore.database.connection.SQLiteConnector;
|
||||
import su.nightexpress.nightcore.database.sql.SQLColumn;
|
||||
import su.nightexpress.nightcore.database.sql.SQLExecutor;
|
||||
import su.nightexpress.nightcore.database.sql.SQLQueries;
|
||||
import su.nightexpress.nightcore.database.sql.SQLValue;
|
||||
import su.nightexpress.nightcore.database.sql.column.ColumnType;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public final class AlterTableExecutor extends SQLExecutor<Void> {
|
||||
|
||||
private final DatabaseType databaseType;
|
||||
private final List<SQLValue> columns;
|
||||
private Type type;
|
||||
|
||||
private AlterTableExecutor(@NotNull String table, @NotNull DatabaseType databaseType) {
|
||||
super(table);
|
||||
this.databaseType = databaseType;
|
||||
this.columns = new ArrayList<>();
|
||||
}
|
||||
|
||||
private enum Type {
|
||||
ADD_COLUMN, RENAME_COLUMN, DROP_COLUMN
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static AlterTableExecutor builder(@NotNull String table, @NotNull DatabaseType databaseType) {
|
||||
return new AlterTableExecutor(table, databaseType);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public AlterTableExecutor addColumn(@NotNull SQLValue... columns) {
|
||||
return this.addColumn(Arrays.asList(columns));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public AlterTableExecutor addColumn(@NotNull List<SQLValue> columns) {
|
||||
return this.columns(columns, Type.ADD_COLUMN);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public AlterTableExecutor renameColumn(@NotNull SQLValue... columns) {
|
||||
return this.addColumn(Arrays.asList(columns));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public AlterTableExecutor renameColumn(@NotNull List<SQLValue> columns) {
|
||||
return this.columns(columns, Type.RENAME_COLUMN);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public AlterTableExecutor dropColumn(@NotNull SQLColumn... columns) {
|
||||
return this.dropColumn(Arrays.asList(columns));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public AlterTableExecutor dropColumn(@NotNull List<SQLColumn> columns) {
|
||||
return this.columns(columns.stream().map(column -> column.toValue("dummy")).toList(), Type.DROP_COLUMN);
|
||||
}
|
||||
|
||||
private AlterTableExecutor columns(@NotNull List<SQLValue> values, @NotNull Type type) {
|
||||
this.columns.clear();
|
||||
this.columns.addAll(values);
|
||||
this.type = type;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Void execute(@NotNull AbstractConnector connector) {
|
||||
if (this.columns.isEmpty()) return null;
|
||||
|
||||
if (this.type == Type.ADD_COLUMN) {
|
||||
this.columns.forEach(value -> {
|
||||
if (SQLQueries.hasColumn(connector, this.getTable(), value.getColumn())) return;
|
||||
|
||||
String sql = "ALTER TABLE " + this.getTable() + " ADD "
|
||||
+ value.getColumn().getName() + " " + value.getColumn().formatType(this.databaseType);
|
||||
|
||||
if (connector instanceof SQLiteConnector || value.getColumn().getType() != ColumnType.STRING) {
|
||||
sql = sql + " DEFAULT '" + value.getValue() + "'";
|
||||
}
|
||||
|
||||
SQLQueries.executeStatement(connector, sql);
|
||||
});
|
||||
}
|
||||
else if (this.type == Type.RENAME_COLUMN) {
|
||||
this.columns.forEach(value -> {
|
||||
if (!SQLQueries.hasColumn(connector, this.getTable(), value.getColumn())) return;
|
||||
|
||||
String sql = "ALTER TABLE " + this.getTable() + " RENAME COLUMN " + value.getColumn().getName() + " TO " + value.getValue();
|
||||
SQLQueries.executeStatement(connector, sql);
|
||||
});
|
||||
}
|
||||
else if (this.type == Type.DROP_COLUMN) {
|
||||
this.columns.forEach(value -> {
|
||||
if (!SQLQueries.hasColumn(connector, this.getTable(), value.getColumn())) return;
|
||||
|
||||
String sql = "ALTER TABLE " + this.getTable() + " DROP COLUMN " + value.getColumn().getName();
|
||||
SQLQueries.executeStatement(connector, sql);
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package su.nightexpress.nightcore.database.sql.executor;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.DatabaseType;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
import su.nightexpress.nightcore.database.sql.SQLColumn;
|
||||
import su.nightexpress.nightcore.database.sql.SQLExecutor;
|
||||
import su.nightexpress.nightcore.database.sql.SQLQueries;
|
||||
import su.nightexpress.nightcore.database.sql.column.ColumnFormer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public final class CreateTableExecutor extends SQLExecutor<Void> {
|
||||
|
||||
private final DatabaseType databaseType;
|
||||
private final List<SQLColumn> columns;
|
||||
|
||||
private CreateTableExecutor(@NotNull String table, @NotNull DatabaseType databaseType) {
|
||||
super(table);
|
||||
this.databaseType = databaseType;
|
||||
this.columns = new ArrayList<>();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static CreateTableExecutor builder(@NotNull String table, @NotNull DatabaseType databaseType) {
|
||||
return new CreateTableExecutor(table, databaseType);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public CreateTableExecutor columns(@NotNull SQLColumn... columns) {
|
||||
return this.columns(Arrays.asList(columns));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public CreateTableExecutor columns(@NotNull List<SQLColumn> columns) {
|
||||
this.columns.clear();
|
||||
this.columns.addAll(columns);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Void execute(@NotNull AbstractConnector connector) {
|
||||
if (this.columns.isEmpty()) return null;
|
||||
|
||||
String id = "`id` " + ColumnFormer.INTEGER.build(this.databaseType, 11);
|
||||
if (this.databaseType == DatabaseType.SQLITE) {
|
||||
id += " PRIMARY KEY AUTOINCREMENT";
|
||||
}
|
||||
else {
|
||||
id += " PRIMARY KEY AUTO_INCREMENT";
|
||||
}
|
||||
|
||||
String columns = id + "," + this.columns.stream()
|
||||
.map(column -> column.getNameEscaped() + " " + column.formatType(this.databaseType))
|
||||
.collect(Collectors.joining(", "));
|
||||
|
||||
String sql = "CREATE TABLE IF NOT EXISTS " + this.getTable() + "(" + columns + ");";
|
||||
|
||||
SQLQueries.executeStatement(connector, sql);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package su.nightexpress.nightcore.database.sql.executor;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
import su.nightexpress.nightcore.database.sql.SQLCondition;
|
||||
import su.nightexpress.nightcore.database.sql.SQLExecutor;
|
||||
import su.nightexpress.nightcore.database.sql.SQLQueries;
|
||||
import su.nightexpress.nightcore.database.sql.SQLValue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public final class DeleteQueryExecutor extends SQLExecutor<Void> {
|
||||
|
||||
private final List<SQLCondition> wheres;
|
||||
|
||||
private DeleteQueryExecutor(@NotNull String table) {
|
||||
super(table);
|
||||
this.wheres = new ArrayList<>();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static DeleteQueryExecutor builder(@NotNull String table) {
|
||||
return new DeleteQueryExecutor(table);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public DeleteQueryExecutor where(@NotNull SQLCondition... wheres) {
|
||||
return this.where(Arrays.asList(wheres));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public DeleteQueryExecutor where(@NotNull List<SQLCondition> wheres) {
|
||||
this.wheres.clear();
|
||||
this.wheres.addAll(wheres);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Void execute(@NotNull AbstractConnector connector) {
|
||||
if (this.wheres.isEmpty()) return null;
|
||||
|
||||
String whereCols = this.wheres.stream()
|
||||
.map(where -> where.getValue().getColumn().getNameEscaped() + " " + where.getType().getOperator() + " ?")
|
||||
.collect(Collectors.joining(" AND "));
|
||||
String sql = "DELETE FROM " + this.getTable() + (whereCols.isEmpty() ? "" : " WHERE " + whereCols);
|
||||
|
||||
List<String> whereVals = this.wheres.stream().map(SQLCondition::getValue).map(SQLValue::getValue).toList();
|
||||
|
||||
SQLQueries.executeStatement(connector, sql, whereVals);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package su.nightexpress.nightcore.database.sql.executor;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
import su.nightexpress.nightcore.database.sql.SQLColumn;
|
||||
import su.nightexpress.nightcore.database.sql.SQLExecutor;
|
||||
import su.nightexpress.nightcore.database.sql.SQLQueries;
|
||||
import su.nightexpress.nightcore.database.sql.SQLValue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public final class InsertQueryExecutor extends SQLExecutor<Void> {
|
||||
|
||||
private final List<SQLValue> values;
|
||||
|
||||
private InsertQueryExecutor(@NotNull String table) {
|
||||
super(table);
|
||||
this.values = new ArrayList<>();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static InsertQueryExecutor builder(@NotNull String table) {
|
||||
return new InsertQueryExecutor(table);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public InsertQueryExecutor values(@NotNull SQLValue... values) {
|
||||
return this.values(Arrays.asList(values));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public InsertQueryExecutor values(@NotNull List<SQLValue> values) {
|
||||
this.values.clear();
|
||||
this.values.addAll(values);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Void execute(@NotNull AbstractConnector connector) {
|
||||
if (this.values.isEmpty()) return null;
|
||||
|
||||
String columns = this.values.stream().map(SQLValue::getColumn).map(SQLColumn::getNameEscaped).collect(Collectors.joining(","));
|
||||
String values = this.values.stream().map(value -> "?").collect(Collectors.joining(","));
|
||||
String sql = "INSERT INTO " + this.getTable() + "(" + columns + ") VALUES(" + values + ")";
|
||||
List<String> values2 = this.values.stream().map(SQLValue::getValue).toList();
|
||||
|
||||
SQLQueries.executeStatement(connector, sql, values2);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package su.nightexpress.nightcore.database.sql.executor;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.DatabaseType;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
import su.nightexpress.nightcore.database.sql.SQLExecutor;
|
||||
import su.nightexpress.nightcore.database.sql.SQLQueries;
|
||||
|
||||
public final class RenameTableExecutor extends SQLExecutor<Void> {
|
||||
|
||||
private final DatabaseType databaseType;
|
||||
private String renameTo;
|
||||
|
||||
private RenameTableExecutor(@NotNull String table, @NotNull DatabaseType databaseType) {
|
||||
super(table);
|
||||
this.databaseType = databaseType;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static RenameTableExecutor builder(@NotNull String table, @NotNull DatabaseType databaseType) {
|
||||
return new RenameTableExecutor(table, databaseType);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public RenameTableExecutor renameTo(@NotNull String renameTo) {
|
||||
this.renameTo = renameTo;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Void execute(@NotNull AbstractConnector connector) {
|
||||
if (this.renameTo == null || this.renameTo.isEmpty()) return null;
|
||||
if (!SQLQueries.hasTable(connector, this.getTable())) return null;
|
||||
|
||||
StringBuilder sql = new StringBuilder();
|
||||
if (this.databaseType == DatabaseType.MYSQL) {
|
||||
sql.append("RENAME TABLE ").append(this.getTable()).append(" TO ").append(this.renameTo).append(";");
|
||||
}
|
||||
else {
|
||||
sql.append("ALTER TABLE ").append(this.getTable()).append(" RENAME TO ").append(this.renameTo);
|
||||
}
|
||||
SQLQueries.executeStatement(connector, sql.toString());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package su.nightexpress.nightcore.database.sql.executor;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
import su.nightexpress.nightcore.database.sql.*;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public final class SelectQueryExecutor<T> extends SQLExecutor<List<T>> {
|
||||
|
||||
private final List<SQLColumn> columns;
|
||||
private final List<SQLCondition> wheres;
|
||||
private final Function<ResultSet, T> dataFunction;
|
||||
private int amount;
|
||||
|
||||
private SelectQueryExecutor(@NotNull String table, @NotNull Function<ResultSet, T> dataFunction) {
|
||||
super(table);
|
||||
this.columns = new ArrayList<>();
|
||||
this.wheres = new ArrayList<>();
|
||||
this.dataFunction = dataFunction;
|
||||
this.amount = -1;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static <T> SelectQueryExecutor<T> builder(@NotNull String table, @NotNull Function<ResultSet, T> dataFunction) {
|
||||
return new SelectQueryExecutor<>(table, dataFunction);
|
||||
}
|
||||
|
||||
/*@NotNull
|
||||
public SelectQueryExecutor<T> all() {
|
||||
return this.columns(new SQLColumn("*", ColumnType.STRING, -1));
|
||||
}*/
|
||||
|
||||
@NotNull
|
||||
public SelectQueryExecutor<T> columns(@NotNull SQLColumn... columns) {
|
||||
return this.columns(Arrays.asList(columns));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public SelectQueryExecutor<T> columns(@NotNull List<SQLColumn> columns) {
|
||||
//if (columns.isEmpty()) return this.all();
|
||||
this.columns.clear();
|
||||
this.columns.addAll(columns);
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public SelectQueryExecutor<T> where(@NotNull SQLCondition... wheres) {
|
||||
return this.where(Arrays.asList(wheres));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public SelectQueryExecutor<T> where(@NotNull List<SQLCondition> wheres) {
|
||||
this.wheres.clear();
|
||||
this.wheres.addAll(wheres);
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public SelectQueryExecutor<T> amount(int amount) {
|
||||
this.amount = amount;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public List<T> execute(@NotNull AbstractConnector connector) {
|
||||
String columns = this.columns.stream().map(SQLColumn::getNameEscaped).collect(Collectors.joining(","));
|
||||
if (columns.isEmpty()) columns = "*";
|
||||
|
||||
String wheres = this.wheres.stream().map(where -> where.getColumn().getNameEscaped() + " " + where.getType().getOperator() + " ?")
|
||||
.collect(Collectors.joining(" AND "));
|
||||
|
||||
String sql = "SELECT " + columns + " FROM " + this.getTable() + (wheres.isEmpty() ? "" : " WHERE " + wheres);
|
||||
|
||||
List<String> values = this.wheres.stream().map(SQLCondition::getValue).map(SQLValue::getValue).toList();
|
||||
|
||||
return SQLQueries.executeQuery(connector, sql, values, this.dataFunction, this.amount);
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package su.nightexpress.nightcore.database.sql.executor;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.database.AbstractConnector;
|
||||
import su.nightexpress.nightcore.database.sql.SQLCondition;
|
||||
import su.nightexpress.nightcore.database.sql.SQLExecutor;
|
||||
import su.nightexpress.nightcore.database.sql.SQLQueries;
|
||||
import su.nightexpress.nightcore.database.sql.SQLValue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public final class UpdateQueryExecutor extends SQLExecutor<Void> {
|
||||
|
||||
private final List<SQLValue> values;
|
||||
private final List<SQLCondition> wheres;
|
||||
|
||||
private UpdateQueryExecutor(@NotNull String table) {
|
||||
super(table);
|
||||
this.values = new ArrayList<>();
|
||||
this.wheres = new ArrayList<>();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static UpdateQueryExecutor builder(@NotNull String table) {
|
||||
return new UpdateQueryExecutor(table);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public UpdateQueryExecutor values(@NotNull SQLValue... values) {
|
||||
return this.values(Arrays.asList(values));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public UpdateQueryExecutor values(@NotNull List<SQLValue> values) {
|
||||
this.values.clear();
|
||||
this.values.addAll(values);
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public UpdateQueryExecutor where(@NotNull SQLCondition... wheres) {
|
||||
return this.where(Arrays.asList(wheres));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public UpdateQueryExecutor where(@NotNull List<SQLCondition> wheres) {
|
||||
this.wheres.clear();
|
||||
this.wheres.addAll(wheres);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Void execute(@NotNull AbstractConnector connector) {
|
||||
if (this.values.isEmpty()) return null;
|
||||
|
||||
String values = this.values.stream().map(value -> value.getColumn().getNameEscaped() + " = ?")
|
||||
.collect(Collectors.joining(","));
|
||||
|
||||
String wheres = this.wheres.stream().map(where -> where.getColumn().getNameEscaped() + " " + where.getType().getOperator() + " ?")
|
||||
.collect(Collectors.joining(" AND "));
|
||||
|
||||
String sql = "UPDATE " + this.getTable() + " SET " + values + (wheres.isEmpty() ? "" : " WHERE " + wheres);
|
||||
|
||||
List<String> values2 = this.values.stream().map(SQLValue::getValue).toList();
|
||||
List<String> whers2 = this.wheres.stream().map(SQLCondition::getValue).map(SQLValue::getValue).toList();
|
||||
|
||||
SQLQueries.executeStatement(connector, sql, values2, whers2);
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package su.nightexpress.nightcore.dialog;
|
||||
|
||||
import net.md_5.bungee.api.chat.ClickEvent;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.core.CoreLang;
|
||||
import su.nightexpress.nightcore.menu.api.Menu;
|
||||
import su.nightexpress.nightcore.menu.impl.AbstractMenu;
|
||||
import su.nightexpress.nightcore.util.Colorizer;
|
||||
import su.nightexpress.nightcore.util.text.NightMessage;
|
||||
import su.nightexpress.nightcore.util.text.WrappedMessage;
|
||||
import su.nightexpress.nightcore.util.text.tag.Tags;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Dialog {
|
||||
|
||||
private static final Map<UUID, Dialog> DIALOG_MAP = new ConcurrentHashMap<>();
|
||||
|
||||
public static final String EXIT = "#exit";
|
||||
public static final String VALUES = "#values";
|
||||
|
||||
private final Player player;
|
||||
private final DialogHandler handler;
|
||||
|
||||
private Menu lastMenu;
|
||||
private List<String> suggestions;
|
||||
|
||||
public Dialog(@NotNull Player player, @NotNull DialogHandler handler) {
|
||||
this.player = player;
|
||||
this.handler = handler;
|
||||
this.suggestions = new ArrayList<>();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Player getPlayer() {
|
||||
return player;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public DialogHandler getHandler() {
|
||||
return handler;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Menu getLastMenu() {
|
||||
return lastMenu;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Dialog setLastMenu(@Nullable Menu lastMenu) {
|
||||
this.lastMenu = lastMenu;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> getSuggestions() {
|
||||
return suggestions;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Dialog setSuggestions(@NotNull Collection<String> suggestions, boolean autoRun) {
|
||||
this.suggestions = suggestions.stream().sorted(String::compareTo).collect(Collectors.toCollection(ArrayList::new));
|
||||
this.displaySuggestions(autoRun, 1);
|
||||
return this;
|
||||
}
|
||||
|
||||
public void displaySuggestions(boolean autoRun, int page) {
|
||||
List<String> values = this.getSuggestions();
|
||||
if (values.isEmpty()) return;
|
||||
|
||||
int perPage = 10;
|
||||
int pages = (int) Math.ceil((double) values.size() / (double) perPage);
|
||||
if (page < 1) page = 1;
|
||||
else if (page > pages) page = pages;
|
||||
int skip = (page - 1) * perPage;
|
||||
|
||||
boolean isLastPage = page == pages;
|
||||
boolean isFirstPage = page == 1;
|
||||
List<String> items = values.stream().skip(skip).limit(perPage).toList();
|
||||
ClickEvent.Action action = autoRun ? ClickEvent.Action.RUN_COMMAND : ClickEvent.Action.SUGGEST_COMMAND;
|
||||
|
||||
NightMessage.Builder builder = NightMessage.builder();
|
||||
builder.append("=".repeat(8) + "[ ", Tags.ORANGE);
|
||||
builder.append("Value Helper", Tags.YELLOW);
|
||||
builder.append("] " + "=".repeat(8), Tags.ORANGE);
|
||||
builder.appendLineBreak();
|
||||
|
||||
items.forEach(element -> {
|
||||
String value = element.charAt(0) == '/' ? element : '/' + element;
|
||||
builder.append("> ", Tags.DARK_GRAY);
|
||||
builder.append(element, Tags.GREEN)
|
||||
.showText(Tags.GRAY.enclose( "Click me to select " + Tags.CYAN.enclose(element) + "."))
|
||||
.clickEvent(action, value);
|
||||
builder.appendLineBreak();
|
||||
});
|
||||
|
||||
builder.append("=".repeat(9) + " ", Tags.ORANGE);
|
||||
|
||||
if (isFirstPage) {
|
||||
builder.append("[<]", Tags.GRAY);
|
||||
}
|
||||
else {
|
||||
builder.append("[<]", Tags.LIGHT_RED)
|
||||
.showText(Tags.GRAY.enclose("Previous Page"))
|
||||
.runCommand("/" + VALUES + " " + (page - 1) + " " + autoRun);
|
||||
}
|
||||
|
||||
builder.append(" " + page, Tags.YELLOW);
|
||||
builder.append("/", Tags.ORANGE);
|
||||
builder.append(pages + " ", Tags.YELLOW);
|
||||
|
||||
if (isLastPage) {
|
||||
builder.append("[>]", Tags.GRAY);
|
||||
}
|
||||
else {
|
||||
builder.append("[>]", Tags.LIGHT_RED)
|
||||
.showText(Tags.GRAY.enclose("Next Page"))
|
||||
.runCommand("/" + VALUES + " " + (page + 1) + " " + autoRun);
|
||||
}
|
||||
|
||||
builder.append(" " + "=".repeat(9), Tags.ORANGE);
|
||||
builder.send(this.getPlayer());
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void prompt(@NotNull String text) {
|
||||
this.sendInfo(CoreLang.EDITOR_INPUT_HEADER_MAIN.getMessage().toLegacy(), Colorizer.apply(text));
|
||||
}
|
||||
|
||||
public void prompt(@NotNull WrappedMessage text) {
|
||||
this.info(CoreLang.EDITOR_INPUT_HEADER_MAIN.getMessage(), text);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void error(@NotNull String text) {
|
||||
this.sendInfo(CoreLang.EDITOR_INPUT_HEADER_ERROR.getMessage().toLegacy(), Colorizer.apply(text));
|
||||
}
|
||||
|
||||
public void error(@NotNull WrappedMessage text) {
|
||||
this.info(CoreLang.EDITOR_INPUT_HEADER_ERROR.getMessage(), text);
|
||||
}
|
||||
|
||||
public void info(@NotNull WrappedMessage title, @NotNull WrappedMessage text) {
|
||||
this.sendInfo(title.toLegacy(), text.toLegacy());
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void info(@NotNull String title, @NotNull String text) {
|
||||
this.sendInfo(Colorizer.apply(title), Colorizer.apply(text));
|
||||
}
|
||||
|
||||
private void sendInfo(@NotNull String title, @NotNull String text) {
|
||||
this.getPlayer().sendTitle(title, text, 20, Short.MAX_VALUE, 20);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static Dialog create(@NotNull Player player, @NotNull DialogHandler handler) {
|
||||
Dialog dialog = new Dialog(player, handler)
|
||||
.setLastMenu(AbstractMenu.getMenu(player));
|
||||
|
||||
DIALOG_MAP.put(player.getUniqueId(), dialog);
|
||||
CoreLang.EDITOR_ACTION_EXIT.getMessage().send(player);
|
||||
return dialog;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static Dialog get(@NotNull Player player) {
|
||||
return DIALOG_MAP.get(player.getUniqueId());
|
||||
}
|
||||
|
||||
public static void stop(@NotNull Player player) {
|
||||
Dialog dialog = DIALOG_MAP.remove(player.getUniqueId());
|
||||
if (dialog == null) return;
|
||||
|
||||
Menu menu = dialog.getLastMenu();
|
||||
if (menu != null) {
|
||||
menu.open(player);
|
||||
}
|
||||
player.sendTitle("", "", 1, 1, 1);
|
||||
}
|
||||
|
||||
public static void shutdown() {
|
||||
DIALOG_MAP.clear();
|
||||
}
|
||||
|
||||
public static boolean contains(@NotNull Player player) {
|
||||
return get(player) != null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package su.nightexpress.nightcore.dialog;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public interface DialogHandler {
|
||||
|
||||
boolean onInput(@NotNull WrappedInput input);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package su.nightexpress.nightcore.dialog;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.player.AsyncPlayerChatEvent;
|
||||
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCore;
|
||||
import su.nightexpress.nightcore.manager.AbstractListener;
|
||||
import su.nightexpress.nightcore.util.Colorizer;
|
||||
import su.nightexpress.nightcore.util.NumberUtil;
|
||||
|
||||
import java.util.HashSet;
|
||||
|
||||
public class DialogListener extends AbstractListener<NightCore> {
|
||||
|
||||
public DialogListener(@NotNull NightCore plugin) {
|
||||
super(plugin);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
Dialog.stop(event.getPlayer());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onChatText(AsyncPlayerChatEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
Dialog dialog = Dialog.get(player);
|
||||
if (dialog == null) return;
|
||||
|
||||
event.getRecipients().clear();
|
||||
event.setCancelled(true);
|
||||
|
||||
WrappedInput input = new WrappedInput(event);
|
||||
|
||||
this.plugin.runTask(task -> {
|
||||
if (input.getTextRaw().equalsIgnoreCase(Dialog.EXIT) || dialog.getHandler().onInput(input)) {
|
||||
Dialog.stop(player);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onChatCommand(PlayerCommandPreprocessEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
Dialog dialog = Dialog.get(player);
|
||||
if (dialog == null) return;
|
||||
|
||||
event.setCancelled(true);
|
||||
|
||||
String raw = event.getMessage();
|
||||
String text = Colorizer.apply(raw.substring(1));
|
||||
if (text.startsWith(Dialog.VALUES)) {
|
||||
String[] split = text.split(" ");
|
||||
int page = split.length >= 2 ? NumberUtil.getInteger(split[1], 0) : 0;
|
||||
boolean auto = split.length >= 3 && Boolean.parseBoolean(split[2]);
|
||||
dialog.displaySuggestions(auto, page);
|
||||
return;
|
||||
}
|
||||
|
||||
AsyncPlayerChatEvent chatEvent = new AsyncPlayerChatEvent(true, player, text, new HashSet<>());
|
||||
WrappedInput input = new WrappedInput(chatEvent);
|
||||
|
||||
this.plugin.runTask(task -> {
|
||||
if (input.getTextRaw().equalsIgnoreCase(Dialog.EXIT) || dialog.getHandler().onInput(input)) {
|
||||
Dialog.stop(player);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package su.nightexpress.nightcore.dialog;
|
||||
|
||||
import org.bukkit.event.player.AsyncPlayerChatEvent;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.util.Colorizer;
|
||||
import su.nightexpress.nightcore.util.NumberUtil;
|
||||
import su.nightexpress.nightcore.util.StringUtil;
|
||||
import su.nightexpress.nightcore.util.wrapper.UniDouble;
|
||||
import su.nightexpress.nightcore.util.wrapper.UniInt;
|
||||
|
||||
public class WrappedInput {
|
||||
|
||||
private final String text;
|
||||
private final String textRaw;
|
||||
private final String textColored;
|
||||
|
||||
public WrappedInput(@NotNull AsyncPlayerChatEvent event) {
|
||||
this(event.getMessage());
|
||||
}
|
||||
|
||||
public WrappedInput(@NotNull String text) {
|
||||
this.text = text;
|
||||
this.textRaw = Colorizer.restrip(text); // TODO Modern formation, but keep colorizer to support legacy codes for other chat format plugins
|
||||
this.textColored = Colorizer.apply(text);
|
||||
}
|
||||
|
||||
public int asInt() {
|
||||
return this.asInt(0);
|
||||
}
|
||||
|
||||
public int asInt(int def) {
|
||||
return NumberUtil.getInteger(this.getTextRaw(), def);
|
||||
}
|
||||
|
||||
public int asAnyInt(int def) {
|
||||
return NumberUtil.getAnyInteger(this.getTextRaw(), def);
|
||||
}
|
||||
|
||||
public double asDouble() {
|
||||
return this.asDouble(0D);
|
||||
}
|
||||
|
||||
public double asDouble(double def) {
|
||||
return NumberUtil.getDouble(this.getTextRaw(), def);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public UniDouble asUniDouble() {
|
||||
return this.asUniDouble(0, 0);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public UniDouble asUniDouble(double min, double max) {
|
||||
String[] split = this.getTextRaw().split(" ");
|
||||
return UniDouble.of(NumberUtil.getDouble(split[0], min), NumberUtil.getDouble(split.length >= 2 ? split[1] : split[0], max));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public UniInt asUniInt() {
|
||||
return this.asUniDouble().asInt();
|
||||
}
|
||||
|
||||
public double asAnyDouble(double def) {
|
||||
return NumberUtil.getAnyDouble(this.getTextRaw(), def);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public <E extends Enum<E>> E asEnum(@NotNull Class<E> clazz) {
|
||||
return StringUtil.getEnum(this.getTextRaw(), clazz).orElse(null);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public <E extends Enum<E>> E asEnum(@NotNull Class<E> clazz, @NotNull E def) {
|
||||
return StringUtil.getEnum(this.getTextRaw(), clazz).orElse(def);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getTextRaw() {
|
||||
return textRaw;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getTextColored() {
|
||||
return textColored;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package su.nightexpress.nightcore.integration;
|
||||
|
||||
import net.milkbowl.vault.chat.Chat;
|
||||
import net.milkbowl.vault.economy.Economy;
|
||||
import net.milkbowl.vault.permission.Permission;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.server.ServiceRegisterEvent;
|
||||
import org.bukkit.plugin.RegisteredServiceProvider;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.util.Plugins;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class VaultHook {
|
||||
|
||||
private static Economy economy;
|
||||
private static Permission permission;
|
||||
private static Chat chat;
|
||||
|
||||
public static void setup() {
|
||||
setPermission();
|
||||
setEconomy();
|
||||
setChat();
|
||||
}
|
||||
|
||||
public static void shutdown() {
|
||||
economy = null;
|
||||
permission = null;
|
||||
chat = null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static <T> T getProvider(@NotNull Class<T> clazz) {
|
||||
RegisteredServiceProvider<T> rsp = Bukkit.getServer().getServicesManager().getRegistration(clazz);
|
||||
return rsp == null ? null : rsp.getProvider();
|
||||
}
|
||||
|
||||
private static void setPermission() {
|
||||
permission = getProvider(Permission.class);
|
||||
if (permission != null) {
|
||||
Plugins.CORE.info("Found permissions provider: " + permission.getName());
|
||||
}
|
||||
}
|
||||
|
||||
private static void setEconomy() {
|
||||
economy = getProvider(Economy.class);
|
||||
if (economy != null) {
|
||||
Plugins.CORE.info("Found economy provider: " + economy.getName());
|
||||
}
|
||||
}
|
||||
|
||||
private static void setChat() {
|
||||
chat = getProvider(Chat.class);
|
||||
if (chat != null) {
|
||||
Plugins.CORE.info("Found chat provider: " + chat.getName());
|
||||
}
|
||||
}
|
||||
|
||||
public static void onServiceRegisterEvent(@NotNull ServiceRegisterEvent event) {
|
||||
Object provider = event.getProvider().getProvider();
|
||||
|
||||
if (economy == null && provider instanceof Economy) {
|
||||
setEconomy();
|
||||
}
|
||||
else if (permission == null && provider instanceof Permission) {
|
||||
setPermission();
|
||||
}
|
||||
else if (chat == null && provider instanceof Chat) {
|
||||
setChat();
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean hasPermissions() {
|
||||
return getPermissions() != null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static Permission getPermissions() {
|
||||
return permission;
|
||||
}
|
||||
|
||||
public static boolean hasChat() {
|
||||
return getChat() != null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static Chat getChat() {
|
||||
return chat;
|
||||
}
|
||||
|
||||
public static boolean hasEconomy() {
|
||||
return getEconomy() != null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static Economy getEconomy() {
|
||||
return economy;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String getEconomyName() {
|
||||
return hasEconomy() ? economy.getName() : "null";
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String getPermissionGroup(@NotNull Player player) {
|
||||
if (!hasPermissions() || !permission.hasGroupSupport()) return "";
|
||||
|
||||
String group = permission.getPrimaryGroup(player);
|
||||
return group == null ? "" : group.toLowerCase();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static Set<String> getPermissionGroups(@NotNull Player player) {
|
||||
if (!hasPermissions() || !permission.hasGroupSupport()) return Collections.emptySet();
|
||||
|
||||
String[] groups = permission.getPlayerGroups(player);
|
||||
if (groups == null) groups = new String[] {getPermissionGroup(player)};
|
||||
|
||||
return Stream.of(groups).map(String::toLowerCase).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String getPrefix(@NotNull Player player) {
|
||||
return hasChat() ? chat.getPlayerPrefix(player) : "";
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String getSuffix(@NotNull Player player) {
|
||||
return hasChat() ? chat.getPlayerSuffix(player) : "";
|
||||
}
|
||||
|
||||
public static double getBalance(@NotNull Player player) {
|
||||
return economy.getBalance(player);
|
||||
}
|
||||
|
||||
public static double getBalance(@NotNull OfflinePlayer player) {
|
||||
return economy.getBalance(player);
|
||||
}
|
||||
|
||||
public static boolean addMoney(@NotNull Player player, double amount) {
|
||||
return addMoney((OfflinePlayer) player, amount);
|
||||
}
|
||||
|
||||
public static boolean addMoney(@NotNull OfflinePlayer player, double amount) {
|
||||
return economy.depositPlayer(player, amount).transactionSuccess();
|
||||
}
|
||||
|
||||
public static boolean takeMoney(@NotNull Player player, double amount) {
|
||||
return takeMoney((OfflinePlayer) player, amount);
|
||||
}
|
||||
|
||||
public static boolean takeMoney(@NotNull OfflinePlayer player, double amount) {
|
||||
return economy.withdrawPlayer(player, Math.abs(amount)).transactionSuccess();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package su.nightexpress.nightcore.language;
|
||||
|
||||
import org.bukkit.Keyed;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.entity.EntityType;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCore;
|
||||
import su.nightexpress.nightcore.config.FileConfig;
|
||||
import su.nightexpress.nightcore.util.*;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Optional;
|
||||
|
||||
public class LangAssets {
|
||||
|
||||
private static FileConfig config;
|
||||
|
||||
public static void load() {
|
||||
NightCore core = Plugins.CORE;
|
||||
String langCode = core.getLanguage();
|
||||
|
||||
String assetsCode = downloadAssets(core, langCode);
|
||||
config = FileConfig.loadOrExtract(core, LangManager.DIR_LANG, getFileName(assetsCode));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private static String downloadAssets(@NotNull NightCore plugin, @NotNull String langCode) {
|
||||
File file = new File(plugin.getDataFolder().getAbsolutePath() + LangManager.DIR_LANG, getFileName(langCode));
|
||||
if (file.exists()) return langCode;
|
||||
|
||||
FileUtil.create(file);
|
||||
|
||||
String url = Placeholders.GITHUB_URL + "/raw/master/assets/" + langCode + ".yml";
|
||||
try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream());
|
||||
FileOutputStream fileOutputStream = new FileOutputStream(file)) {
|
||||
plugin.info("Downloading '" + langCode + "' assets from github...");
|
||||
byte[] dataBuffer = new byte[1024];
|
||||
int bytesRead;
|
||||
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
|
||||
fileOutputStream.write(dataBuffer, 0, bytesRead);
|
||||
}
|
||||
return langCode;
|
||||
}
|
||||
catch (IOException exception) {
|
||||
//exception.printStackTrace();
|
||||
plugin.error("Could not download language assets for '" + langCode + "' (no such assets?).");
|
||||
return LangManager.isDefault(langCode) ? langCode : downloadAssets(plugin, LangManager.DEFAULT_LANGUAGE);
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private static String getFileName(@NotNull String langCode) {
|
||||
return "assets_" + langCode + ".yml";
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static FileConfig getConfig() {
|
||||
return config;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String get(@NotNull PotionEffectType type) {
|
||||
return getAsset("PotionEffectType", type);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String get(@NotNull EntityType type) {
|
||||
return getAsset("EntityType", type);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String get(@NotNull Material type) {
|
||||
return getAsset("Material", type);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String get(@NotNull World world) {
|
||||
return getOrCreate("World", world);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String get(@NotNull Enchantment enchantment) {
|
||||
return getOrCreate("Enchantment", enchantment);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String getAsset(@NotNull String path, @NotNull Keyed keyed) {
|
||||
return getAsset(path, keyed.getKey().getKey());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String getAsset(@NotNull String path, @NotNull String nameRaw) {
|
||||
return getAsset(path + "." + nameRaw).orElse(nameRaw);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static Optional<String> getAsset(@NotNull String path) {
|
||||
return Optional.ofNullable(config.getString(path)).map(Colorizer::apply);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String getOrCreate(@NotNull String path, @NotNull Keyed keyed) {
|
||||
return getOrCreate(path, keyed.getKey().getKey());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static String getOrCreate(@NotNull String path, @NotNull String nameRaw) {
|
||||
config.addMissing(path + "." + nameRaw, StringUtil.capitalizeUnderscored(nameRaw));
|
||||
config.saveChanges();
|
||||
|
||||
return getAsset(path, nameRaw);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package su.nightexpress.nightcore.language;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.config.FileConfig;
|
||||
import su.nightexpress.nightcore.manager.SimpleManager;
|
||||
import su.nightexpress.nightcore.language.entry.LangEntry;
|
||||
import su.nightexpress.nightcore.util.FileUtil;
|
||||
import su.nightexpress.nightcore.util.Plugins;
|
||||
import su.nightexpress.nightcore.util.Reflex;
|
||||
import su.nightexpress.nightcore.util.StringUtil;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
|
||||
public class LangManager extends SimpleManager<NightCorePlugin> {
|
||||
|
||||
public static final String DEFAULT_LANGUAGE = "en";
|
||||
public static final String DIR_LANG = "/lang/";
|
||||
|
||||
private FileConfig config;
|
||||
|
||||
public LangManager(@NotNull NightCorePlugin plugin) {
|
||||
super(plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onLoad() {
|
||||
String langCode = this.plugin.getLanguage();
|
||||
String realCode = this.extractConfig(langCode);
|
||||
this.config = new FileConfig(this.plugin.getDataFolder() + DIR_LANG, this.getFileName(realCode));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onShutdown() {
|
||||
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private String extractConfig(@NotNull String langCode) {
|
||||
String fileName = this.getFileName(langCode);
|
||||
|
||||
File file = new File(plugin.getDataFolder() + DIR_LANG, fileName);
|
||||
if (file.exists()) return langCode;
|
||||
|
||||
try {
|
||||
InputStream input = plugin.getClass().getResourceAsStream(DIR_LANG + fileName);
|
||||
if (input != null) {
|
||||
FileUtil.create(file);
|
||||
FileUtil.copy(input, file);
|
||||
return langCode;
|
||||
}
|
||||
return isDefault(langCode) ? langCode : this.extractConfig(DEFAULT_LANGUAGE);
|
||||
}
|
||||
catch (Exception exception) {
|
||||
exception.printStackTrace();
|
||||
return isDefault(langCode) ? langCode : this.extractConfig(DEFAULT_LANGUAGE);
|
||||
}
|
||||
}
|
||||
|
||||
public void loadEntries(@NotNull Class<?> clazz) {
|
||||
Reflex.getFields(clazz, LangEntry.class).forEach(entry -> {
|
||||
entry.load(this.plugin);
|
||||
});
|
||||
}
|
||||
|
||||
/*public void loadEditor(@NotNull Class<?> clazz) {
|
||||
Reflex.getFields(clazz, LangItem.class).forEach(entry -> {
|
||||
entry.load(this.plugin);
|
||||
});
|
||||
}*/
|
||||
|
||||
public void loadEnum(@NotNull Class<? extends Enum<?>> clazz) {
|
||||
for (Object eName : clazz.getEnumConstants()) {
|
||||
String name = eName.toString();
|
||||
String path = clazz.getSimpleName() + "." + name;
|
||||
String val = StringUtil.capitalizeUnderscored(name);
|
||||
this.getConfig().addMissing(path, val);
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getEnum(@NotNull Enum<?> entry) {
|
||||
String path = entry.getDeclaringClass().getSimpleName() + "." + entry.name();
|
||||
String locEnum = this.config.getString(path);
|
||||
if (locEnum == null && !this.plugin.isEngine()) {
|
||||
return Plugins.CORE.getLangManager().getEnum(entry);
|
||||
}
|
||||
return locEnum == null ? StringUtil.capitalizeFully(entry.name()) : locEnum;
|
||||
}
|
||||
|
||||
public static boolean isDefault(@NotNull String langCode) {
|
||||
return langCode.equalsIgnoreCase(DEFAULT_LANGUAGE);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getFileName(@NotNull String langCode) {
|
||||
return "messages_" + langCode + ".yml";
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public FileConfig getConfig() {
|
||||
return config;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package su.nightexpress.nightcore.language.entry;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.config.FileConfig;
|
||||
|
||||
public abstract class LangEntry<T> {
|
||||
|
||||
protected final String path;
|
||||
protected final String defaultText;
|
||||
|
||||
public LangEntry(@NotNull String path, @NotNull String defaultText) {
|
||||
this.path = path;
|
||||
this.defaultText = defaultText;
|
||||
}
|
||||
|
||||
public abstract boolean write(@NotNull FileConfig config);
|
||||
|
||||
@NotNull
|
||||
public abstract T load(@NotNull NightCorePlugin plugin);
|
||||
|
||||
@NotNull
|
||||
public String getPath() {
|
||||
return path;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getDefaultText() {
|
||||
return defaultText;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package su.nightexpress.nightcore.language.entry;
|
||||
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.config.FileConfig;
|
||||
import su.nightexpress.nightcore.util.ItemUtil;
|
||||
import su.nightexpress.nightcore.util.Pair;
|
||||
import su.nightexpress.nightcore.util.text.NightMessage;
|
||||
import su.nightexpress.nightcore.util.text.WrappedMessage;
|
||||
import su.nightexpress.nightcore.util.text.tag.Tags;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class LangItem extends LangEntry<Pair<String, List<String>>> {
|
||||
|
||||
private final List<String> defaultLore;
|
||||
|
||||
private String localizedName;
|
||||
private List<String> localizedLore;
|
||||
|
||||
private WrappedMessage wrappedName;
|
||||
private List<WrappedMessage> wrappedLore;
|
||||
|
||||
public LangItem(@NotNull String key, @NotNull String defaultName, @NotNull List<String> defaultLore) {
|
||||
super(key, defaultName);
|
||||
this.defaultLore = defaultLore;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static LangItem of(@NotNull String key, @NotNull String name, @NotNull String... lore) {
|
||||
return new LangItem(key, name, Arrays.asList(lore));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean write(@NotNull FileConfig config) {
|
||||
if (!config.contains(this.getPath())) {
|
||||
config.set(this.getPath() + ".Name", this.getDefaultName());
|
||||
config.set(this.getPath() + ".Lore", this.getDefaultLore());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Pair<String, List<String>> load(@NotNull NightCorePlugin plugin) {
|
||||
FileConfig config = plugin.getLang();
|
||||
|
||||
this.write(config);
|
||||
|
||||
this.setLocalizedName(config.getString(this.getPath() + ".Name", this.getDefaultName()));
|
||||
this.setLocalizedLore(config.getStringList(this.getPath() + ".Lore"));
|
||||
|
||||
return Pair.of(this.getLocalizedName(), this.getLocalizedLore());
|
||||
}
|
||||
|
||||
public void apply(@NotNull ItemStack item) {
|
||||
ItemUtil.editMeta(item, meta -> {
|
||||
meta.setDisplayName(this.getWrappedName().toLegacy());
|
||||
meta.setLore(this.getWrappedLore().stream().map(WrappedMessage::toLegacy).toList());
|
||||
});
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getDefaultName() {
|
||||
return this.getDefaultText();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> getDefaultLore() {
|
||||
return defaultLore;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getLocalizedName() {
|
||||
return localizedName;
|
||||
}
|
||||
|
||||
public void setLocalizedName(@NotNull String localizedName) {
|
||||
this.localizedName = localizedName;
|
||||
this.wrappedName = NightMessage.create(localizedName);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> getLocalizedLore() {
|
||||
return localizedLore;
|
||||
}
|
||||
|
||||
public void setLocalizedLore(@NotNull List<String> localizedLore) {
|
||||
this.localizedLore = localizedLore;
|
||||
this.wrappedLore = new ArrayList<>();
|
||||
localizedLore.forEach(line -> wrappedLore.add(NightMessage.create(line)));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public WrappedMessage getWrappedName() {
|
||||
return wrappedName;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<WrappedMessage> getWrappedLore() {
|
||||
return wrappedLore;
|
||||
}
|
||||
|
||||
protected static final String LMB = "Left-Click";
|
||||
protected static final String RMB = "Right-Click";
|
||||
protected static final String DROP_KEY = "[Q] Drop Key";
|
||||
protected static final String SWAP_KEY = "[F] Swap Key";
|
||||
protected static final String SHIFT_LMB = "Shift-Left";
|
||||
protected static final String SHIFT_RMB = "Shift-Right";
|
||||
protected static final String DRAG_DROP = "Drag & Drop";
|
||||
|
||||
@NotNull
|
||||
public static Builder builder(@NotNull String key) {
|
||||
return new Builder(key);
|
||||
}
|
||||
|
||||
public static final class Builder {
|
||||
|
||||
private final String key;
|
||||
private String name;
|
||||
private final List<String> lore;
|
||||
|
||||
public Builder(@NotNull String key) {
|
||||
this.key = key;
|
||||
this.name = "";
|
||||
this.lore = new ArrayList<>();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public LangItem build() {
|
||||
return new LangItem(this.key, this.name, this.lore);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Builder name(@NotNull String name) {
|
||||
this.name = Tags.YELLOW.enclose(Tags.BOLD.enclose(name));
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Builder text(@NotNull String... text) {
|
||||
for (String str : text) {
|
||||
this.addLore(Tags.GRAY.enclose(str));
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Builder textRaw(@NotNull String... text) {
|
||||
return this.addLore(text);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Builder currentHeader() {
|
||||
return this.addLore(Tags.YELLOW.enclose(Tags.BOLD.enclose("Current:")));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Builder current(@NotNull String type, @NotNull String value) {
|
||||
return this.addLore(Tags.YELLOW.enclose("▪ " + Tags.GRAY.enclose(type) + ": " + value));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Builder leftClick(@NotNull String action) {
|
||||
return this.click(LMB, action);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Builder rightClick(@NotNull String action) {
|
||||
return this.click(RMB, action);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Builder shiftLeft(@NotNull String action) {
|
||||
return this.click(SHIFT_LMB, action);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Builder shiftRight(@NotNull String action) {
|
||||
return this.click(SHIFT_RMB, action);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Builder dropKey(@NotNull String action) {
|
||||
return this.click(DROP_KEY, action);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Builder swapKey(@NotNull String action) {
|
||||
return this.click(SWAP_KEY, action);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Builder dragAndDrop(@NotNull String action) {
|
||||
return this.click(DRAG_DROP, action);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Builder click(@NotNull String click, @NotNull String action) {
|
||||
return this.addLore(Tags.GRAY.enclose("(" + Tags.WHITE.enclose(click) + " to " + action + ")"));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Builder emptyLine() {
|
||||
return this.addLore("");
|
||||
}
|
||||
|
||||
/*@NotNull
|
||||
private Builder addLore(@NotNull String prefix, @NotNull String... text) {
|
||||
for (String str : text) {
|
||||
this.lore.add(prefix + str);
|
||||
}
|
||||
return this;
|
||||
}*/
|
||||
|
||||
@NotNull
|
||||
private Builder addLore(@NotNull String... text) {
|
||||
Collections.addAll(this.lore, text);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package su.nightexpress.nightcore.language.entry;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.config.FileConfig;
|
||||
import su.nightexpress.nightcore.util.text.NightMessage;
|
||||
import su.nightexpress.nightcore.util.text.WrappedMessage;
|
||||
|
||||
public class LangString extends LangEntry<String> {
|
||||
|
||||
private String string;
|
||||
private WrappedMessage message;
|
||||
|
||||
public LangString(@NotNull String path, @NotNull String defaultText) {
|
||||
super(path, defaultText);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static LangString of(@NotNull String path, @NotNull String defaultText) {
|
||||
return new LangString(path, defaultText);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean write(@NotNull FileConfig config) {
|
||||
if (!config.contains(this.getPath())) {
|
||||
String textDefault = this.getDefaultText();
|
||||
config.set(this.getPath(), textDefault);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String load(@NotNull NightCorePlugin plugin) {
|
||||
FileConfig config = plugin.getLang();
|
||||
|
||||
this.write(config);
|
||||
String text = config.getString(this.getPath(), this.getPath());
|
||||
this.setString(text);
|
||||
|
||||
return this.getString();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getString() {
|
||||
return string;
|
||||
}
|
||||
|
||||
public void setString(@NotNull String string) {
|
||||
this.string = string;
|
||||
this.message = NightMessage.from(string);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public WrappedMessage getMessage() {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getLegacy() {
|
||||
return this.getMessage().toLegacy();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package su.nightexpress.nightcore.language.entry;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.config.FileConfig;
|
||||
import su.nightexpress.nightcore.language.message.LangMessage;
|
||||
import su.nightexpress.nightcore.util.Placeholders;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class LangText extends LangEntry<LangMessage> {
|
||||
|
||||
private LangMessage message;
|
||||
|
||||
public LangText(@NotNull String path, @NotNull String... defaultText) {
|
||||
super(path, String.join("\n", defaultText));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static LangText of(@NotNull String path, @NotNull String defaultText) {
|
||||
return new LangText(path, defaultText);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static LangText of(@NotNull String path, @NotNull String... defaultText) {
|
||||
return new LangText(path, defaultText);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean write(@NotNull FileConfig config) {
|
||||
if (!config.contains(this.getPath())) {
|
||||
String textDefault = this.getDefaultText();
|
||||
String[] textSplit = textDefault.split("\n");
|
||||
config.set(this.getPath(), textSplit.length > 1 ? Arrays.asList(textSplit) : textDefault);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public LangMessage load(@NotNull NightCorePlugin plugin) {
|
||||
FileConfig config = plugin.getLang();
|
||||
|
||||
this.write(config);
|
||||
|
||||
List<String> text = new ArrayList<>(config.getStringList(this.getPath()));
|
||||
if (text.isEmpty()) {
|
||||
text.add(config.getString(this.getPath(), this.getPath()));
|
||||
}
|
||||
|
||||
this.setMessage(LangMessage.parse(plugin, String.join(Placeholders.TAG_LINE_BREAK, text)));
|
||||
|
||||
return this.getMessage();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public LangMessage getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(@NotNull LangMessage message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package su.nightexpress.nightcore.language.legacy;
|
||||
|
||||
import me.clip.placeholderapi.PlaceholderAPI;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.language.message.OutputType;
|
||||
import su.nightexpress.nightcore.util.Colorizer;
|
||||
import su.nightexpress.nightcore.util.Players;
|
||||
import su.nightexpress.nightcore.util.message.NexParser;
|
||||
import su.nightexpress.nightcore.util.regex.TimedMatcher;
|
||||
import su.nightexpress.nightcore.util.wrapper.UniSound;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.UnaryOperator;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Deprecated
|
||||
public class LegacyLangMessage {
|
||||
|
||||
private static final Pattern OPTIONS_PATTERN = Pattern.compile("<\\!(.*?)\\!>");
|
||||
|
||||
private final NightCorePlugin plugin;
|
||||
private final LegacyMessageOptions options;
|
||||
private final List<String> defaultText;
|
||||
|
||||
private List<String> text;
|
||||
|
||||
public LegacyLangMessage(@NotNull NightCorePlugin plugin, @NotNull List<String> defaultText) {
|
||||
this.plugin = plugin;
|
||||
this.options = new LegacyMessageOptions();
|
||||
this.defaultText = defaultText;
|
||||
this.setText(defaultText);
|
||||
this.setOptions();
|
||||
}
|
||||
|
||||
private LegacyLangMessage(@NotNull LegacyLangMessage from) {
|
||||
this.plugin = from.plugin;
|
||||
this.options = from.options.copy();
|
||||
this.defaultText = new ArrayList<>(from.defaultText);
|
||||
this.text = new ArrayList<>(from.text);
|
||||
}
|
||||
|
||||
private void setOptions() {
|
||||
List<String> text = this.getText();
|
||||
if (text.isEmpty()) return;
|
||||
|
||||
String msg = text.get(0);
|
||||
TimedMatcher matcher = TimedMatcher.create(OPTIONS_PATTERN, msg);
|
||||
if (!matcher.find()) return;
|
||||
|
||||
String optionTag = matcher.getMatcher().group(0);
|
||||
String optionArgs = matcher.getMatcher().group(1).trim();
|
||||
this.text.set(0, msg.replace(optionTag, ""));
|
||||
this.text.removeIf(String::isEmpty);
|
||||
this.options.read(optionArgs);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> getDefaultText() {
|
||||
return this.defaultText;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> getText() {
|
||||
return this.text;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> getText(@NotNull CommandSender sender) {
|
||||
if (!this.options.hasPlaceholderAPI() || !(sender instanceof Player player)) return this.getText();
|
||||
|
||||
List<String> text = new ArrayList<>(this.getText());
|
||||
text.replaceAll(line -> PlaceholderAPI.setPlaceholders(player, line));
|
||||
return text;
|
||||
}
|
||||
|
||||
private void setText(@NotNull List<String> text) {
|
||||
this.text = Colorizer.apply(text);
|
||||
this.text.removeIf(String::isEmpty);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public LegacyLangMessage replace(@NotNull String var, @NotNull Object replacer) {
|
||||
return this.replace(str -> str.replace(var, String.valueOf(replacer)));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public LegacyLangMessage replace(@NotNull UnaryOperator<String> replacer) {
|
||||
if (this.isEmpty()) return this;
|
||||
|
||||
LegacyLangMessage msgCopy = new LegacyLangMessage(this);
|
||||
msgCopy.getText().replaceAll(replacer);
|
||||
return msgCopy;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public LegacyLangMessage replace(@NotNull Predicate<String> predicate, @NotNull BiConsumer<String, List<String>> replacer) {
|
||||
if (this.isEmpty()) return this;
|
||||
|
||||
LegacyLangMessage msgCopy = new LegacyLangMessage(this);
|
||||
List<String> replaced = new ArrayList<>();
|
||||
msgCopy.getText().forEach(line -> {
|
||||
if (predicate.test(line)) {
|
||||
replacer.accept(line, replaced);
|
||||
return;
|
||||
}
|
||||
replaced.add(line);
|
||||
});
|
||||
msgCopy.setText(replaced);
|
||||
return msgCopy;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return (this.options.getType() == OutputType.NONE || this.getText().isEmpty());
|
||||
}
|
||||
|
||||
public void broadcast() {
|
||||
if (this.isEmpty()) return;
|
||||
|
||||
Bukkit.getServer().getOnlinePlayers().forEach(this::send);
|
||||
this.send(Bukkit.getServer().getConsoleSender());
|
||||
}
|
||||
|
||||
public void send(@NotNull CommandSender sender) {
|
||||
if (this.isEmpty()) return;
|
||||
|
||||
if (this.options.getSound() != null && sender instanceof Player player) {
|
||||
UniSound.of(this.options.getSound()).play(player);
|
||||
}
|
||||
|
||||
if (this.options.getType() == OutputType.CHAT) {
|
||||
String prefix = this.options.hasPrefix() ? plugin.getPrefix() : "";
|
||||
this.getText(sender).forEach(line -> {
|
||||
Players.sendRichMessage(sender, prefix + line);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (sender instanceof Player player) {
|
||||
if (this.options.getType() == OutputType.ACTION_BAR) {
|
||||
Players.sendActionBar(player, String.join(" ", this.getText(player)));
|
||||
}
|
||||
else if (this.options.getType() == OutputType.TITLES) {
|
||||
List<String> list = this.getText(player);
|
||||
String title = list.size() > 0 ? NexParser.toPlainText(list.get(0)) : "";
|
||||
String subtitle = list.size() > 1 ? NexParser.toPlainText(list.get(1)) : "";
|
||||
player.sendTitle(title, subtitle, this.options.getTitleTimes()[0], this.options.getTitleTimes()[1], this.options.getTitleTimes()[2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*@NotNull
|
||||
public List<String> asList() {
|
||||
return this.asList(this.getText());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> asList(@NotNull CommandSender sender) {
|
||||
return this.asList(this.getText(sender));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private List<String> asList(@NotNull String localized) {
|
||||
return this.isEmpty() ? Collections.emptyList() : Stream.of(localized.split("\\\\n"))
|
||||
.filter(Predicate.not(String::isEmpty)).toList();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Deprecated
|
||||
public String normalizeLines() {
|
||||
return String.join("\n", this.asList());
|
||||
}*/
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package su.nightexpress.nightcore.language.legacy;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.config.FileConfig;
|
||||
import su.nightexpress.nightcore.language.entry.LangEntry;
|
||||
import su.nightexpress.nightcore.util.Colorizer;
|
||||
|
||||
@Deprecated
|
||||
public class LegacyLangString extends LangEntry<String> {
|
||||
|
||||
private String string;
|
||||
|
||||
public LegacyLangString(@NotNull String path, @NotNull String defaultText) {
|
||||
super(path, defaultText);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static LegacyLangString of(@NotNull String path, @NotNull String defaultText) {
|
||||
return new LegacyLangString(path, defaultText);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean write(@NotNull FileConfig config) {
|
||||
if (!config.contains(this.getPath())) {
|
||||
String textDefault = this.getDefaultText();
|
||||
config.set(this.getPath(), textDefault);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String load(@NotNull NightCorePlugin plugin) {
|
||||
FileConfig config = plugin.getLang();
|
||||
|
||||
this.write(config);
|
||||
String text = config.getString(this.getPath(), "<" + this.getPath() + ">");
|
||||
this.setString(text);
|
||||
|
||||
return this.getString();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getString() {
|
||||
return string;
|
||||
}
|
||||
|
||||
public void setString(@NotNull String string) {
|
||||
this.string = Colorizer.apply(string);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package su.nightexpress.nightcore.language.legacy;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.config.FileConfig;
|
||||
import su.nightexpress.nightcore.language.entry.LangEntry;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@Deprecated
|
||||
public class LegacyLangText extends LangEntry<LegacyLangMessage> {
|
||||
|
||||
private LegacyLangMessage message;
|
||||
|
||||
public LegacyLangText(@NotNull String path, @NotNull String... defaultText) {
|
||||
super(path, String.join("\n", defaultText));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static LegacyLangText of(@NotNull String path, @NotNull String defaultText) {
|
||||
return new LegacyLangText(path, defaultText);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static LegacyLangText of(@NotNull String path, @NotNull String... defaultText) {
|
||||
return new LegacyLangText(path, defaultText);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean write(@NotNull FileConfig config) {
|
||||
if (!config.contains(this.getPath())) {
|
||||
String textDefault = this.getDefaultText();
|
||||
String[] textSplit = textDefault.split("\n");
|
||||
config.set(this.getPath(), textSplit.length > 1 ? Arrays.asList(textSplit) : textDefault);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public LegacyLangMessage load(@NotNull NightCorePlugin plugin) {
|
||||
FileConfig config = plugin.getLang();
|
||||
|
||||
this.write(config);
|
||||
|
||||
List<String> text = new ArrayList<>(config.getStringList(this.getPath()));
|
||||
if (text.isEmpty()) {
|
||||
text.add(config.getString(this.getPath(), "<" + this.getPath() + ">"));
|
||||
}
|
||||
|
||||
//String text = !list.isEmpty() ? String.join("\\n", list) : config.getString(this.getPath(), "<" + this.getPath() + ">");
|
||||
this.setMessage(new LegacyLangMessage(plugin, text));
|
||||
|
||||
return this.getMessage();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public LegacyLangMessage getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(@NotNull LegacyLangMessage message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package su.nightexpress.nightcore.language.legacy;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Deprecated
|
||||
public enum LegacyMessageOption {
|
||||
|
||||
PREFIX("prefix"),
|
||||
SOUND("sound"),
|
||||
TYPE("type"),
|
||||
PAPI("papi"),
|
||||
;
|
||||
|
||||
private final Pattern pattern;
|
||||
|
||||
LegacyMessageOption(@NotNull String name) {
|
||||
this.pattern = Pattern.compile(name + ":(?:'|\")(.*?)(?:'|\")(?=>|\\s|$)");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Pattern getPattern() {
|
||||
return pattern;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package su.nightexpress.nightcore.language.legacy;
|
||||
|
||||
import org.bukkit.Sound;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.language.message.OutputType;
|
||||
import su.nightexpress.nightcore.util.NumberUtil;
|
||||
import su.nightexpress.nightcore.util.Plugins;
|
||||
import su.nightexpress.nightcore.util.StringUtil;
|
||||
import su.nightexpress.nightcore.util.regex.TimedMatcher;
|
||||
|
||||
@Deprecated
|
||||
public class LegacyMessageOptions {
|
||||
|
||||
private OutputType type;
|
||||
private boolean hasPrefix;
|
||||
private boolean papi;
|
||||
private Sound sound;
|
||||
private int[] titleTimes;
|
||||
|
||||
public LegacyMessageOptions() {
|
||||
this.type = OutputType.CHAT;
|
||||
this.hasPrefix = true;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public LegacyMessageOptions copy() {
|
||||
LegacyMessageOptions copy = new LegacyMessageOptions();
|
||||
copy.type = this.type;
|
||||
copy.hasPrefix = this.hasPrefix;
|
||||
copy.papi = this.papi;
|
||||
copy.sound = this.sound;
|
||||
copy.titleTimes = this.titleTimes;
|
||||
return copy;
|
||||
}
|
||||
|
||||
public void read(@NotNull String matchOptions) {
|
||||
for (LegacyMessageOption option : LegacyMessageOption.values()) {
|
||||
TimedMatcher matcherParam = TimedMatcher.create(option.getPattern(), matchOptions);
|
||||
if (!matcherParam.find()) continue;
|
||||
|
||||
String optionValue = matcherParam.getMatcher().group(1).stripLeading();
|
||||
switch (option) {
|
||||
case TYPE -> {
|
||||
String[] split = optionValue.split(":");
|
||||
this.type = StringUtil.getEnum(split[0], OutputType.class).orElse(OutputType.CHAT);
|
||||
if (this.type == OutputType.TITLES) {
|
||||
this.titleTimes = new int[3];
|
||||
if (split.length >= 4) {
|
||||
this.titleTimes[0] = NumberUtil.getInteger(split[1]);
|
||||
this.titleTimes[1] = NumberUtil.getAnyInteger(split[2], -1);
|
||||
this.titleTimes[2] = NumberUtil.getInteger(split[3]);
|
||||
}
|
||||
|
||||
if (this.titleTimes[1] < 0) this.titleTimes[1] = Short.MAX_VALUE;
|
||||
}
|
||||
}
|
||||
case PREFIX -> this.hasPrefix = Boolean.parseBoolean(optionValue);
|
||||
case PAPI -> this.papi = Boolean.parseBoolean(optionValue) && Plugins.hasPlaceholderAPI();
|
||||
case SOUND -> this.sound = StringUtil.getEnum(optionValue, Sound.class).orElse(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public OutputType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public boolean hasPrefix() {
|
||||
return this.hasPrefix;
|
||||
}
|
||||
|
||||
public boolean hasPlaceholderAPI() {
|
||||
return this.papi;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Sound getSound() {
|
||||
return sound;
|
||||
}
|
||||
|
||||
public int[] getTitleTimes() {
|
||||
return titleTimes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package su.nightexpress.nightcore.language.message;
|
||||
|
||||
import me.clip.placeholderapi.PlaceholderAPI;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
import net.md_5.bungee.api.chat.ComponentBuilder;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.core.CoreConfig;
|
||||
import su.nightexpress.nightcore.language.tag.MessageDecorator;
|
||||
import su.nightexpress.nightcore.language.tag.MessageTags;
|
||||
import su.nightexpress.nightcore.util.Placeholders;
|
||||
import su.nightexpress.nightcore.util.Players;
|
||||
import su.nightexpress.nightcore.util.text.NightMessage;
|
||||
import su.nightexpress.nightcore.util.text.WrappedMessage;
|
||||
import su.nightexpress.nightcore.util.text.tag.api.DynamicTag;
|
||||
import su.nightexpress.nightcore.util.text.tag.api.Tag;
|
||||
import su.nightexpress.nightcore.util.wrapper.UniSound;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
public class LangMessage {
|
||||
|
||||
private final NightCorePlugin plugin;
|
||||
private final String defaultText;
|
||||
private final MessageOptions options;
|
||||
private final WrappedMessage message;
|
||||
|
||||
public LangMessage(@NotNull NightCorePlugin plugin, @NotNull String defaultText, @NotNull MessageOptions options) {
|
||||
this.plugin = plugin;
|
||||
this.defaultText = defaultText;
|
||||
this.options = options;
|
||||
this.message = NightMessage.from(defaultText);
|
||||
if (CoreConfig.MODERN_TEXT_PRECOMPILE_LANG.get()) {
|
||||
this.message.compile();
|
||||
}
|
||||
}
|
||||
|
||||
private LangMessage(@NotNull LangMessage from) {
|
||||
this.plugin = from.plugin;
|
||||
this.defaultText = from.defaultText;
|
||||
this.options = from.options.copy();
|
||||
this.message = from.message.copy();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static LangMessage parse(@NotNull NightCorePlugin plugin, @NotNull String string) {
|
||||
MessageOptions options = new MessageOptions();
|
||||
StringBuilder builder = new StringBuilder();
|
||||
|
||||
int length = string.length();
|
||||
for (int index = 0; index < length; index++) {
|
||||
char letter = string.charAt(index);
|
||||
|
||||
Tag:
|
||||
if (letter == Tag.OPEN_BRACKET && index != (length - 1)) {
|
||||
int indexEnd = string.indexOf(Tag.CLOSE_BRACKET, index);
|
||||
if (indexEnd == -1) break Tag;
|
||||
|
||||
char next = string.charAt(index + 1);
|
||||
if (next == Tag.CLOSE_BRACKET) break Tag;
|
||||
|
||||
String leading = string.substring(index + 1);
|
||||
String brackets = string.substring(index + 1, indexEnd);
|
||||
|
||||
Tag tag = MessageTags.getTag(brackets);
|
||||
|
||||
if (tag == null) {
|
||||
for (Tag registered : MessageTags.getTags()) {
|
||||
String tagName = registered.getName();
|
||||
if (leading.startsWith(tagName)) {
|
||||
char latest = leading.charAt(tagName.length());
|
||||
|
||||
if (latest == Tag.CLOSE_BRACKET || registered instanceof DynamicTag) {
|
||||
tag = registered;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!(tag instanceof MessageDecorator decorator)) break Tag;
|
||||
|
||||
if (tag instanceof DynamicTag) {
|
||||
int prefixSize = tag.getName().length() + 1; // 1 for semicolon
|
||||
|
||||
String content = DynamicTag.parseQuotedContent(leading.substring(prefixSize));
|
||||
if (content == null) break Tag;
|
||||
|
||||
decorator.apply(options, content);
|
||||
|
||||
indexEnd = index + prefixSize + content.length() + 3; // 1 for close bracket, 2 for quotes
|
||||
}
|
||||
else {
|
||||
decorator.apply(options, leading);
|
||||
}
|
||||
|
||||
index = indexEnd;
|
||||
continue;
|
||||
}
|
||||
builder.append(letter);
|
||||
}
|
||||
|
||||
if (options.getOutputType() == OutputType.CHAT && options.hasPrefix()) {
|
||||
builder.insert(0, plugin.getPrefix());
|
||||
}
|
||||
|
||||
String text = builder.toString();
|
||||
|
||||
return new LangMessage(plugin, text, options);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getDefaultText() {
|
||||
return this.defaultText;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public WrappedMessage getMessage() {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public WrappedMessage getMessage(@NotNull CommandSender sender) {
|
||||
if (!this.options.usePlaceholderAPI() || !(sender instanceof Player player)) return this.getMessage();
|
||||
|
||||
return this.message.copy().replace(line -> PlaceholderAPI.setPlaceholders(player, line));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public LangMessage replace(@NotNull String var, @NotNull Object replacer) {
|
||||
return this.replace(str -> str.replace(var, String.valueOf(replacer)));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public LangMessage replace(@NotNull String var, @NotNull Consumer<List<String>> replacer) {
|
||||
List<String> list = new ArrayList<>();
|
||||
replacer.accept(list);
|
||||
|
||||
return this.replace(var, list);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public LangMessage replace(@NotNull String var, @NotNull List<String> replacer) {
|
||||
//String delimiter = CoreConfig.MODERN_TEXT_PRECOMPILE_LANG.get() ? "\n" : StandardTags.LINE_BREAK;
|
||||
|
||||
return this.replace(str -> str.replace(var, String.join(Placeholders.TAG_LINE_BREAK, replacer)));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public LangMessage replace(@NotNull UnaryOperator<String> replacer) {
|
||||
if (this.isDisabled()) return this;
|
||||
|
||||
LangMessage copy = new LangMessage(this);
|
||||
copy.getMessage().replace(replacer);
|
||||
|
||||
return copy;
|
||||
}
|
||||
|
||||
/*@NotNull
|
||||
public LangMessage replace(@NotNull Predicate<String> predicate, @NotNull BiConsumer<String, List<String>> replacer) {
|
||||
if (this.isEmpty()) return this;
|
||||
|
||||
LangMessage msgCopy = new LangMessage(this);
|
||||
List<String> replaced = new ArrayList<>();
|
||||
List<String> text
|
||||
|
||||
msgCopy.getText().forEach(line -> {
|
||||
if (predicate.test(line)) {
|
||||
replacer.accept(line, replaced);
|
||||
return;
|
||||
}
|
||||
replaced.add(line);
|
||||
});
|
||||
msgCopy.setText(replaced);
|
||||
|
||||
return msgCopy;
|
||||
}*/
|
||||
|
||||
public boolean isDisabled() {
|
||||
return this.options.getOutputType() == OutputType.NONE;
|
||||
}
|
||||
|
||||
public void broadcast() {
|
||||
if (this.isDisabled()) return;
|
||||
|
||||
this.plugin.getServer().getOnlinePlayers().forEach(this::send);
|
||||
this.send(this.plugin.getServer().getConsoleSender());
|
||||
}
|
||||
|
||||
public void send(@NotNull CommandSender sender) {
|
||||
if (this.isDisabled()) return;
|
||||
|
||||
if (this.options.getSound() != null && sender instanceof Player player) {
|
||||
UniSound.of(this.options.getSound()).play(player);
|
||||
}
|
||||
|
||||
if (this.options.getOutputType() == OutputType.CHAT) {
|
||||
this.getMessage(sender).send(sender);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sender instanceof Player player) {
|
||||
if (this.options.getOutputType() == OutputType.ACTION_BAR) {
|
||||
Players.sendActionBar(player, this.getMessage(player));
|
||||
//player.spigot().sendMessage(ChatMessageType.ACTION_BAR, this.getMessage(player).parseIfAbsent());
|
||||
}
|
||||
else if (this.options.getOutputType() == OutputType.TITLES) {
|
||||
ComponentBuilder titleBuilder = new ComponentBuilder();
|
||||
ComponentBuilder subBuilder = new ComponentBuilder();
|
||||
ComponentBuilder current = titleBuilder;
|
||||
|
||||
for (BaseComponent component : this.getMessage(player).parseIfAbsent()) {
|
||||
if (component instanceof TextComponent textComponent && textComponent.getText().equals("\n")) {
|
||||
current = subBuilder;
|
||||
continue;
|
||||
}
|
||||
current.append(component);
|
||||
}
|
||||
|
||||
String title = TextComponent.toLegacyText(titleBuilder.create());
|
||||
String subtitle = TextComponent.toLegacyText(subBuilder.create());
|
||||
player.sendTitle(title, subtitle, this.options.getTitleTimes()[0], this.options.getTitleTimes()[1], this.options.getTitleTimes()[2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package su.nightexpress.nightcore.language.message;
|
||||
|
||||
import org.bukkit.Sound;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class MessageOptions {
|
||||
|
||||
private OutputType outputType;
|
||||
private boolean hasPrefix;
|
||||
private boolean usePlaceholderAPI;
|
||||
private Sound sound;
|
||||
private int[] titleTimes;
|
||||
|
||||
public MessageOptions() {
|
||||
this.setOutputType(OutputType.CHAT);
|
||||
this.setHasPrefix(true);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public MessageOptions copy() {
|
||||
MessageOptions copy = new MessageOptions();
|
||||
copy.outputType = this.outputType;
|
||||
copy.hasPrefix = this.hasPrefix;
|
||||
copy.usePlaceholderAPI = this.usePlaceholderAPI;
|
||||
copy.sound = this.sound;
|
||||
copy.titleTimes = this.titleTimes;
|
||||
return copy;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public OutputType getOutputType() {
|
||||
return outputType;
|
||||
}
|
||||
|
||||
public void setOutputType(OutputType outputType) {
|
||||
this.outputType = outputType;
|
||||
}
|
||||
|
||||
public boolean hasPrefix() {
|
||||
return hasPrefix;
|
||||
}
|
||||
|
||||
public void setHasPrefix(boolean hasPrefix) {
|
||||
this.hasPrefix = hasPrefix;
|
||||
}
|
||||
|
||||
public boolean usePlaceholderAPI() {
|
||||
return this.usePlaceholderAPI;
|
||||
}
|
||||
|
||||
public void setUsePlaceholderAPI(boolean usePlaceholderAPI) {
|
||||
this.usePlaceholderAPI = usePlaceholderAPI;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Sound getSound() {
|
||||
return sound;
|
||||
}
|
||||
|
||||
public void setSound(Sound sound) {
|
||||
this.sound = sound;
|
||||
}
|
||||
|
||||
public int[] getTitleTimes() {
|
||||
return titleTimes;
|
||||
}
|
||||
|
||||
public void setTitleTimes(int[] titleTimes) {
|
||||
this.titleTimes = titleTimes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package su.nightexpress.nightcore.language.message;
|
||||
|
||||
public enum OutputType {
|
||||
CHAT, ACTION_BAR, TITLES, NONE,
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package su.nightexpress.nightcore.language.tag;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.language.message.MessageOptions;
|
||||
|
||||
public interface MessageDecorator {
|
||||
|
||||
void apply(@NotNull MessageOptions options, @NotNull String value);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package su.nightexpress.nightcore.language.tag;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.language.tag.impl.NoPrefixTag;
|
||||
import su.nightexpress.nightcore.language.tag.impl.PlaceholderTag;
|
||||
import su.nightexpress.nightcore.language.tag.impl.SoundTag;
|
||||
import su.nightexpress.nightcore.language.tag.impl.OutputTag;
|
||||
import su.nightexpress.nightcore.util.text.tag.api.Tag;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class MessageTags {
|
||||
|
||||
private static final Map<String, Tag> TAG_MAP = new HashMap<>();
|
||||
|
||||
public static final NoPrefixTag NO_PREFIX = new NoPrefixTag();
|
||||
public static final OutputTag OUTPUT = new OutputTag();
|
||||
public static final SoundTag SOUND = new SoundTag();
|
||||
public static final PlaceholderTag PLACEHOLDER = new PlaceholderTag();
|
||||
|
||||
static {
|
||||
registerTags(NO_PREFIX, OUTPUT, SOUND, PLACEHOLDER);
|
||||
}
|
||||
|
||||
public static void registerTags(@NotNull Tag... tags) {
|
||||
for (Tag tag : tags) {
|
||||
registerTag(tag);
|
||||
}
|
||||
}
|
||||
|
||||
public static void registerTag(@NotNull Tag tag, @NotNull String... aliases) {
|
||||
TAG_MAP.put(tag.getName(), tag);
|
||||
for (String alias : aliases) {
|
||||
TAG_MAP.put(alias, tag);
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static Collection<Tag> getTags() {
|
||||
return TAG_MAP.values();
|
||||
}
|
||||
|
||||
public static Tag getTag(@NotNull String name) {
|
||||
return TAG_MAP.get(name.toLowerCase());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package su.nightexpress.nightcore.language.tag.impl;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.language.message.MessageOptions;
|
||||
import su.nightexpress.nightcore.language.tag.MessageDecorator;
|
||||
import su.nightexpress.nightcore.util.text.tag.api.Tag;
|
||||
|
||||
public class NoPrefixTag extends Tag implements MessageDecorator {
|
||||
|
||||
public NoPrefixTag() {
|
||||
super("noprefix");
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getWeight() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void apply(@NotNull MessageOptions options, @NotNull String value) {
|
||||
options.setHasPrefix(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package su.nightexpress.nightcore.language.tag.impl;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.language.message.MessageOptions;
|
||||
import su.nightexpress.nightcore.language.message.OutputType;
|
||||
import su.nightexpress.nightcore.language.tag.MessageDecorator;
|
||||
import su.nightexpress.nightcore.util.NumberUtil;
|
||||
import su.nightexpress.nightcore.util.StringUtil;
|
||||
import su.nightexpress.nightcore.util.text.tag.api.DynamicTag;
|
||||
|
||||
public class OutputTag extends DynamicTag implements MessageDecorator {
|
||||
|
||||
public OutputTag() {
|
||||
super("output");
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getWeight() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String enclose(@NotNull OutputType type) {
|
||||
String prefix = type.name().toLowerCase();
|
||||
return this.leading(null, prefix);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String enclose(int fade, int stay) {
|
||||
String prefix = OutputType.TITLES.name().toLowerCase();
|
||||
return this.leading(null, prefix + ":" + fade + ":" + stay + ":" + fade);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void apply(@NotNull MessageOptions options, @NotNull String content) {
|
||||
String[] split = content.split(":");
|
||||
OutputType outputType = StringUtil.getEnum(split[0], OutputType.class).orElse(OutputType.CHAT);
|
||||
|
||||
options.setOutputType(outputType);
|
||||
if (outputType == OutputType.TITLES) {
|
||||
int[] titleTimes = new int[3];
|
||||
if (split.length >= 4) {
|
||||
titleTimes[0] = NumberUtil.getInteger(split[1]);
|
||||
titleTimes[1] = NumberUtil.getAnyInteger(split[2], -1);
|
||||
titleTimes[2] = NumberUtil.getInteger(split[3]);
|
||||
}
|
||||
|
||||
if (titleTimes[1] < 0) titleTimes[1] = Short.MAX_VALUE;
|
||||
|
||||
options.setTitleTimes(titleTimes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package su.nightexpress.nightcore.language.tag.impl;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.language.message.MessageOptions;
|
||||
import su.nightexpress.nightcore.language.tag.MessageDecorator;
|
||||
import su.nightexpress.nightcore.util.text.tag.api.Tag;
|
||||
|
||||
public class PlaceholderTag extends Tag implements MessageDecorator {
|
||||
|
||||
public PlaceholderTag() {
|
||||
super("papi");
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getWeight() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void apply(@NotNull MessageOptions options, @NotNull String value) {
|
||||
options.setUsePlaceholderAPI(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package su.nightexpress.nightcore.language.tag.impl;
|
||||
|
||||
import org.bukkit.Sound;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.language.message.MessageOptions;
|
||||
import su.nightexpress.nightcore.language.tag.MessageDecorator;
|
||||
import su.nightexpress.nightcore.util.StringUtil;
|
||||
import su.nightexpress.nightcore.util.text.tag.api.DynamicTag;
|
||||
|
||||
public class SoundTag extends DynamicTag implements MessageDecorator {
|
||||
|
||||
public SoundTag() {
|
||||
super("sound");
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getWeight() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String enclose(@NotNull Sound sound) {
|
||||
return this.leading(null, sound.name().toLowerCase());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void apply(@NotNull MessageOptions options, @NotNull String value) {
|
||||
Sound sound = StringUtil.getEnum(value, Sound.class).orElse(null);
|
||||
options.setSound(sound);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package su.nightexpress.nightcore.manager;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.config.FileConfig;
|
||||
import su.nightexpress.nightcore.util.StringUtil;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public abstract class AbstractFileData<P extends NightCorePlugin> {
|
||||
|
||||
protected final P plugin;
|
||||
protected final File file;
|
||||
private final String id;
|
||||
|
||||
public AbstractFileData(@NotNull P plugin, @NotNull String filePath) {
|
||||
this(plugin, new File(filePath));
|
||||
}
|
||||
|
||||
public AbstractFileData(@NotNull P plugin, @NotNull File file) {
|
||||
this(plugin, file, file.getName().replace(".yml", ""));
|
||||
}
|
||||
|
||||
public AbstractFileData(@NotNull P plugin, @NotNull String filePath, @NotNull String id) {
|
||||
this(plugin, new File(filePath), id);
|
||||
}
|
||||
|
||||
public AbstractFileData(@NotNull P plugin, @NotNull File file, @NotNull String id) {
|
||||
this.plugin = plugin;
|
||||
this.file = file;
|
||||
this.id = StringUtil.lowerCaseUnderscore(id);
|
||||
}
|
||||
|
||||
public final boolean load() {
|
||||
FileConfig config = this.getConfig();
|
||||
if (!this.onLoad(config)) return false;
|
||||
|
||||
config.saveChanges();
|
||||
return true;
|
||||
}
|
||||
|
||||
public final void save() {
|
||||
FileConfig config = this.getConfig();
|
||||
this.onSave(config);
|
||||
config.saveChanges();
|
||||
}
|
||||
|
||||
protected abstract boolean onLoad(@NotNull FileConfig cfg);
|
||||
|
||||
protected abstract void onSave(@NotNull FileConfig cfg);
|
||||
|
||||
@NotNull
|
||||
public final File getFile() {
|
||||
return this.file;
|
||||
}
|
||||
|
||||
/*@NotNull
|
||||
public P plugin() {
|
||||
return this.plugin;
|
||||
}*/
|
||||
|
||||
@NotNull
|
||||
public final String getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public final FileConfig getConfig() {
|
||||
return new FileConfig(this.getFile());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package su.nightexpress.nightcore.manager;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
|
||||
public abstract class AbstractListener<P extends NightCorePlugin> implements SimpeListener {
|
||||
|
||||
@NotNull
|
||||
public final P plugin;
|
||||
|
||||
public AbstractListener(@NotNull P plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerListeners() {
|
||||
this.plugin.getPluginManager().registerEvents(this, this.plugin);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package su.nightexpress.nightcore.manager;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
import su.nightexpress.nightcore.util.wrapper.UniTask;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public abstract class AbstractManager<P extends NightCorePlugin> extends SimpleManager<P> {
|
||||
|
||||
protected final Set<SimpeListener> listeners;
|
||||
protected final List<UniTask> tasks;
|
||||
|
||||
public AbstractManager(@NotNull P plugin) {
|
||||
super(plugin);
|
||||
this.listeners = new HashSet<>();
|
||||
this.tasks = new ArrayList<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
this.tasks.forEach(UniTask::stop);
|
||||
this.tasks.clear();
|
||||
this.listeners.forEach(SimpeListener::unregisterListeners);
|
||||
this.listeners.clear();
|
||||
super.shutdown();
|
||||
}
|
||||
|
||||
protected void addListener(@NotNull SimpeListener listener) {
|
||||
if (this.listeners.add(listener)) {
|
||||
listener.registerListeners();
|
||||
}
|
||||
}
|
||||
|
||||
protected void addTask(@NotNull UniTask task) {
|
||||
this.tasks.add(task);
|
||||
task.start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package su.nightexpress.nightcore.manager;
|
||||
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
public interface SimpeListener extends Listener {
|
||||
|
||||
void registerListeners();
|
||||
|
||||
default void unregisterListeners() {
|
||||
HandlerList.unregisterAll(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package su.nightexpress.nightcore.manager;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCorePlugin;
|
||||
|
||||
public abstract class SimpleManager<P extends NightCorePlugin> {
|
||||
|
||||
protected final P plugin;
|
||||
|
||||
public SimpleManager(@NotNull P plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public P plugin() {
|
||||
return this.plugin;
|
||||
}
|
||||
|
||||
public void setup() {
|
||||
this.onLoad();
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
this.onShutdown();
|
||||
}
|
||||
|
||||
public void reload() {
|
||||
this.shutdown();
|
||||
this.setup();
|
||||
}
|
||||
|
||||
protected abstract void onLoad();
|
||||
|
||||
protected abstract void onShutdown();
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package su.nightexpress.nightcore.menu;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.event.inventory.InventoryCloseEvent;
|
||||
import org.bukkit.event.inventory.InventoryDragEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.NightCore;
|
||||
import su.nightexpress.nightcore.core.CoreConfig;
|
||||
import su.nightexpress.nightcore.menu.api.Menu;
|
||||
import su.nightexpress.nightcore.manager.AbstractListener;
|
||||
import su.nightexpress.nightcore.menu.click.ClickResult;
|
||||
import su.nightexpress.nightcore.menu.impl.AbstractMenu;
|
||||
|
||||
public class MenuListener extends AbstractListener<NightCore> {
|
||||
|
||||
public MenuListener(@NotNull NightCore core) {
|
||||
super(core);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
AbstractMenu.PLAYER_MENUS.remove(event.getPlayer().getUniqueId());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
|
||||
public void onMenuItemClick(InventoryClickEvent event) {
|
||||
Player player = (Player) event.getWhoClicked();
|
||||
|
||||
Menu menu = AbstractMenu.getMenu(player);
|
||||
if (menu == null) return;
|
||||
|
||||
MenuViewer viewer = menu.getViewer(player);
|
||||
if (viewer == null) return;
|
||||
|
||||
if (!viewer.canClickAgain(CoreConfig.MENU_CLICK_COOLDOWN.get())) {
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
Inventory inventory = event.getInventory();
|
||||
ItemStack item = event.getCurrentItem();
|
||||
|
||||
int slot = event.getRawSlot();
|
||||
boolean isMenu = slot < inventory.getSize();
|
||||
boolean isEmptyItem = item == null || item.getType().isAir();
|
||||
ClickResult result = new ClickResult(slot, item, isMenu);
|
||||
|
||||
menu.onClick(viewer, result, event);
|
||||
viewer.setLastClickTime(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
|
||||
public void onMenuItemDrag(InventoryDragEvent event) {
|
||||
Player player = (Player) event.getWhoClicked();
|
||||
|
||||
Menu menu = AbstractMenu.getMenu(player);
|
||||
if (menu == null) return;
|
||||
|
||||
MenuViewer viewer = menu.getViewer(player);
|
||||
if (viewer == null) return;
|
||||
|
||||
menu.onDrag(viewer, event);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void onMenuClose(InventoryCloseEvent event) {
|
||||
Player player = (Player) event.getPlayer();
|
||||
|
||||
Menu menu = AbstractMenu.getMenu(player);
|
||||
if (menu == null) return;
|
||||
|
||||
MenuViewer viewer = menu.getViewer(player);
|
||||
if (viewer == null) return;
|
||||
|
||||
menu.onClose(viewer, event);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package su.nightexpress.nightcore.menu;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.event.inventory.InventoryType;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.util.Colorizer;
|
||||
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
public class MenuOptions {
|
||||
|
||||
private String title;
|
||||
private int size;
|
||||
private InventoryType type;
|
||||
private int autoRefresh;
|
||||
|
||||
private long lastAutoRefresh;
|
||||
|
||||
public MenuOptions(@NotNull String title, int size, @NotNull InventoryType type) {
|
||||
this(title, size, type, 0);
|
||||
}
|
||||
|
||||
public MenuOptions(@NotNull String title, int size, @NotNull InventoryType type, int autoRefresh) {
|
||||
this.setTitle(title);
|
||||
this.setSize(size);
|
||||
this.setType(type);
|
||||
this.setAutoRefresh(autoRefresh);
|
||||
}
|
||||
|
||||
public MenuOptions(@NotNull MenuOptions options) {
|
||||
this(options.getTitle(), options.getSize(), options.getType(), options.getAutoRefresh());
|
||||
this.lastAutoRefresh = 0L;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Inventory createInventory() {
|
||||
String title = this.getTitle();
|
||||
if (this.getType() == InventoryType.CHEST) {
|
||||
return Bukkit.getServer().createInventory(null, this.getSize(), title);
|
||||
}
|
||||
else {
|
||||
return Bukkit.getServer().createInventory(null, this.getType(), title);
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(@NotNull String title) {
|
||||
this.title = Colorizer.apply(title);
|
||||
}
|
||||
|
||||
public void editTitle(@NotNull UnaryOperator<String> function) {
|
||||
this.setTitle(function.apply(this.getTitle()));
|
||||
}
|
||||
|
||||
public int getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
public void setSize(int size) {
|
||||
if (size <= 0 || size % 9 != 0 || size > 54) size = 27;
|
||||
this.size = size;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public InventoryType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(@NotNull InventoryType type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public int getAutoRefresh() {
|
||||
return autoRefresh;
|
||||
}
|
||||
|
||||
public void setAutoRefresh(int autoRefresh) {
|
||||
this.autoRefresh = Math.max(0, autoRefresh);
|
||||
}
|
||||
|
||||
public long getLastAutoRefresh() {
|
||||
return lastAutoRefresh;
|
||||
}
|
||||
|
||||
public void setLastAutoRefresh(long lastAutoRefresh) {
|
||||
this.lastAutoRefresh = lastAutoRefresh;
|
||||
}
|
||||
|
||||
public boolean isReadyToRefresh() {
|
||||
return this.getAutoRefresh() > 0 && System.currentTimeMillis() - this.getLastAutoRefresh() >= this.getAutoRefresh();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package su.nightexpress.nightcore.menu;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryView;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.util.Version;
|
||||
|
||||
public class MenuViewer {
|
||||
|
||||
private final Player player;
|
||||
|
||||
private Inventory inventory;
|
||||
private InventoryView view;
|
||||
private int page;
|
||||
private int pages;
|
||||
private long lastClickTime;
|
||||
|
||||
public MenuViewer(@NotNull Player player) {
|
||||
this.player = player;
|
||||
this.setPage(1);
|
||||
this.setPages(1);
|
||||
}
|
||||
|
||||
public void openInventory(@NotNull Inventory inventory) {
|
||||
this.inventory = inventory;
|
||||
this.view = this.getPlayer().openInventory(inventory);
|
||||
}
|
||||
|
||||
public void flushInventory(@NotNull MenuOptions options) {
|
||||
this.inventory.clear();
|
||||
|
||||
if (Version.isAtLeast(Version.V1_19_R3)) {
|
||||
this.view.setTitle(options.getTitle());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasInventory() {
|
||||
return this.getInventory() != null && this.getView() != null;
|
||||
}
|
||||
|
||||
public boolean canClickAgain(long cooldown) {
|
||||
return this.getLastClickTime() == 0 || (System.currentTimeMillis() - this.getLastClickTime()) > cooldown;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Player getPlayer() {
|
||||
return player;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Inventory getInventory() {
|
||||
return inventory;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public InventoryView getView() {
|
||||
return view;
|
||||
}
|
||||
|
||||
public int getPage() {
|
||||
return page;
|
||||
}
|
||||
|
||||
public void setPage(int page) {
|
||||
this.page = Math.max(1, page);
|
||||
}
|
||||
|
||||
public int getPages() {
|
||||
return pages;
|
||||
}
|
||||
|
||||
public void setPages(int pages) {
|
||||
this.pages = Math.max(1, pages);
|
||||
}
|
||||
|
||||
public long getLastClickTime() {
|
||||
return lastClickTime;
|
||||
}
|
||||
|
||||
public void setLastClickTime(long lastClickTime) {
|
||||
this.lastClickTime = lastClickTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package su.nightexpress.nightcore.menu.api;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.menu.MenuViewer;
|
||||
import su.nightexpress.nightcore.menu.click.ClickAction;
|
||||
import su.nightexpress.nightcore.menu.item.ItemOptions;
|
||||
import su.nightexpress.nightcore.menu.item.MenuItem;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public interface AutoFilled<I> extends Menu {
|
||||
|
||||
int[] getAutoFillSlots();
|
||||
|
||||
@NotNull List<I> getAutoFills(@NotNull Player player);
|
||||
|
||||
@NotNull ItemStack getAutoFillStack(@NotNull Player player, @NotNull I object);
|
||||
|
||||
@NotNull ClickAction getAutoFillClick(@NotNull I object);
|
||||
|
||||
default void autoFill(@NotNull MenuViewer viewer) {
|
||||
this.getAutoFillItems(viewer).forEach(this::addItem);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
default List<MenuItem> getAutoFillItems(@NotNull MenuViewer viewer) {
|
||||
Player player = viewer.getPlayer();
|
||||
List<MenuItem> items = new ArrayList<>();
|
||||
List<I> origin = this.getAutoFills(player);
|
||||
|
||||
int[] slots = this.getAutoFillSlots();
|
||||
int limit = slots.length;
|
||||
int pages = (int) Math.ceil((double) origin.size() / (double) limit);
|
||||
viewer.setPages(pages);
|
||||
viewer.setPage(Math.min(viewer.getPage(), viewer.getPages()));
|
||||
|
||||
int skip = (viewer.getPage() - 1) * limit;
|
||||
|
||||
List<I> list = origin.stream().skip(skip).limit(limit).toList();
|
||||
|
||||
int count = 0;
|
||||
for (I object : list) {
|
||||
ItemStack item = this.getAutoFillStack(player, object);
|
||||
ItemOptions options = ItemOptions.personalWeak(player);
|
||||
MenuItem menuItem = new MenuItem(item).setPriority(100).setOptions(options).setSlots(slots[count++])
|
||||
.addClick(this.getAutoFillClick(object));
|
||||
//MenuItem menuItem = new MenuItem(item, 100, options, slots[count++]);
|
||||
//menuItem.addClick(this.getAutoFillClick(object));
|
||||
items.add(menuItem);
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package su.nightexpress.nightcore.menu.api;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.event.inventory.InventoryCloseEvent;
|
||||
import org.bukkit.event.inventory.InventoryDragEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import su.nightexpress.nightcore.menu.MenuOptions;
|
||||
import su.nightexpress.nightcore.menu.MenuViewer;
|
||||
import su.nightexpress.nightcore.menu.click.ClickResult;
|
||||
import su.nightexpress.nightcore.menu.item.MenuItem;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public interface Menu {
|
||||
|
||||
void clear();
|
||||
|
||||
void flush();
|
||||
|
||||
void close();
|
||||
|
||||
void runNextTick(@NotNull Runnable runnable);
|
||||
|
||||
void onClick(@NotNull MenuViewer viewer, @NotNull ClickResult result, @NotNull InventoryClickEvent event);
|
||||
|
||||
void onDrag(@NotNull MenuViewer viewer, @NotNull InventoryDragEvent event);
|
||||
|
||||
void onClose(@NotNull MenuViewer viewer, @NotNull InventoryCloseEvent event);
|
||||
|
||||
boolean open(@NotNull MenuViewer viewer);
|
||||
|
||||
boolean open(@NotNull Player player);
|
||||
|
||||
boolean canOpen(@NotNull Player player);
|
||||
|
||||
boolean isPersistent();
|
||||
|
||||
@NotNull Collection<MenuViewer> getViewers();
|
||||
|
||||
@Nullable MenuViewer getViewer(@NotNull Player player);
|
||||
|
||||
|
||||
|
||||
@NotNull List<MenuItem> getItems(@NotNull MenuViewer viewer);
|
||||
|
||||
@Nullable MenuItem getItem(int slot);
|
||||
|
||||
@Nullable MenuItem getItem(@NotNull MenuViewer viewer, int slot);
|
||||
|
||||
@NotNull MenuItem addItem(@NotNull ItemStack item, int... slots);
|
||||
|
||||
@NotNull MenuItem addWeakItem(@NotNull Player player, @NotNull ItemStack item, int... slots);
|
||||
|
||||
@NotNull MenuItem addItem(@NotNull MenuItem menuItem);
|
||||
|
||||
@NotNull UUID getId();
|
||||
|
||||
//@NotNull Map<UUID, MenuViewer> getViewersMap();
|
||||
|
||||
@NotNull Set<MenuItem> getItems();
|
||||
|
||||
@NotNull MenuOptions getOptions();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package su.nightexpress.nightcore.menu.click;
|
||||
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import su.nightexpress.nightcore.menu.MenuViewer;
|
||||
|
||||
public interface ClickAction {
|
||||
|
||||
void onClick(@NotNull MenuViewer viewer, @NotNull InventoryClickEvent event);
|
||||
}
|
||||
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user