commit 2f03847ec2d6b314809d4c0ed2f815dde890972f Author: BuildTools Date: Mon Jan 1 02:24:43 2024 +0500 release diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..76d5773 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/.idea/ +/pom.xml.versionsBackup +/assets/ +/target/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 +. + + 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 +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..aae848e --- /dev/null +++ b/README.md @@ -0,0 +1,31 @@ +Utility Spigot plugin that provides the most common & useful features for plugin development to reduce duplicated code. + +# About +The main purpose of **NexEngine** is to provide abilities for more easier plugin creation and better maintaining. And most importantly, to stay lightweight and well performed. + +**List of Features:** +* Internal command & permission registration (without using plugin.yml). +* **Command API** to create commands with multiple levels of sub-commands and custom flags \[-f\]. +* **Config API** with auto-generated fields and options & custom **FileConfiguration** class with some useful methods. +* **Database API** to store plugin & user data with **SQLite** and **MySQL** support. Including utility classes for building SQL queries, columns and tables. +* **Editor API** to handle player's chat / command input when prompted (used in GUI Editors mostly). +* **Language API** to handle multiple language configs and great message customization (JSON, action bar, titles, sounds, prefix). +* **Manager API** to create "manager" classes and event listeners. +* **Menu API** to create customizable flexible GUIs programatically or from config files. +* **Placeholder API** to create and handle internal placeholders and replace them in plugin texts/messages very fast instead of regular Java `.replace`. +* **Vault Integration** to obtain server's economy & permissions datas. +* **JSON Parser** custom utility to create & parse messages with multiple JSON components, such as: Hover, Run Command, Show Item, etc. +* **Wrappers** a few wrapper classes over Spigot ones for easier creation and usage. +* **Utilities** a lot of classes with different utilities, such as Location, Item, String, File, Number, Player, Time, Array and others. +* **Regex API** custom `CharSequence` implementation to prevent plugin / server stutter of unoptimized regex expressions after specified timeout. +* **Random API** custom random algorhythm with useful methods to roll chances, weights, or just numbers. +* **TriFunction** function class. + +# Performance +**NexEngine**, itself, uses almost no server resources, because there is no events, tasks, GUIs, commands, etc. If you see it in your spark timings near the top, then some plugin that utilizes NexEngine is either bad designed or misuses the API. + +# Paper Version + +Akiranya fork, that allows to use all Paper's features. + +https://github.com/Akiranya/NexEngine-paper diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..d10d7d0 --- /dev/null +++ b/pom.xml @@ -0,0 +1,117 @@ + + + 4.0.0 + + su.nightexpress.nightcore + nightcore + 2.5.0 + + + 17 + 17 + + + + + spigot-repo + https://hub.spigotmc.org/nexus/content/repositories/snapshots/ + + + papermc + https://repo.papermc.io/repository/maven-public/ + + + placeholderapi + https://repo.extendedclip.com/content/repositories/placeholderapi/ + + false + + + + opencollab-snapshot + https://repo.opencollab.dev/maven-snapshots/ + + + minecraft-repo + https://libraries.minecraft.net/ + + + jitpack.io + https://jitpack.io + + + + + + org.spigotmc + spigot-api + 1.20.4-R0.1-SNAPSHOT + + + + com.zaxxer + HikariCP + 5.0.1 + + + com.mojang + authlib + 5.0.47 + + + org.xerial + sqlite-jdbc + 3.41.2.2 + + + it.unimi.dsi + fastutil + 8.5.11 + + + com.github.MilkBowl + VaultAPI + 1.7 + provided + + + me.clip + placeholderapi + 2.10.10 + provided + + + org.geysermc.floodgate + api + 2.2.0-SNAPSHOT + provided + + + + + + + src/main/resources + true + + + + + \ No newline at end of file diff --git a/src/main/java/org/jetbrains/annotations/NotNull.java b/src/main/java/org/jetbrains/annotations/NotNull.java new file mode 100644 index 0000000..6e980e2 --- /dev/null +++ b/src/main/java/org/jetbrains/annotations/NotNull.java @@ -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 + * forbidden 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). + *

+ * By default, {@link IllegalArgumentException} is thrown on null method + * arguments and {@link IllegalStateException} — on null return + * value. + */ + Class exception() default Exception.class; +} diff --git a/src/main/java/org/jetbrains/annotations/Nullable.java b/src/main/java/org/jetbrains/annotations/Nullable.java new file mode 100644 index 0000000..a275e33 --- /dev/null +++ b/src/main/java/org/jetbrains/annotations/Nullable.java @@ -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 valid 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.
+ * By convention, this annotation applied only when the value should + * always 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.
+ * For example, {@link java.util.Map#get(Object key)} should not 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.
+ * 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 ""; +} diff --git a/src/main/java/su/nightexpress/nightcore/NightCore.java b/src/main/java/su/nightexpress/nightcore/NightCore.java new file mode 100644 index 0000000..5d4c0a0 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/NightCore.java @@ -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 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 getChildrens() { + return new HashSet<>(this.childrens); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/NightCorePlugin.java b/src/main/java/su/nightexpress/nightcore/NightCorePlugin.java new file mode 100644 index 0000000..f1fefd3 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/NightCorePlugin.java @@ -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 consumer) { + this.getScheduler().runTask(this, consumer); + } + + default void runTaskAsync(@NotNull Consumer consumer) { + this.getScheduler().runTaskAsynchronously(this, consumer); + } + + default void runTaskLater(@NotNull Consumer consumer, long delay) { + this.getScheduler().runTaskLater(this, consumer, delay); + } + + default void runTaskLaterAsync(@NotNull Consumer consumer, long delay) { + this.getScheduler().runTaskLaterAsynchronously(this, consumer, delay); + } + + default void runTaskTimer(@NotNull Consumer consumer, long delay, long interval) { + this.getScheduler().runTaskTimer(this, consumer, delay, interval); + } + + default void runTaskTimerAsync(@NotNull Consumer 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(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/NightDataPlugin.java b/src/main/java/su/nightexpress/nightcore/NightDataPlugin.java new file mode 100644 index 0000000..442ff27 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/NightDataPlugin.java @@ -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 extends NightPlugin /*implements UserDataHolder*/ { + + //protected AbstractUserDataHandler, U> dataHandler; + //protected AbstractUserManager, 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, U> getData(); + + @NotNull + public abstract AbstractUserManager, U> getUserManager(); +} diff --git a/src/main/java/su/nightexpress/nightcore/NightPlugin.java b/src/main/java/su/nightexpress/nightcore/NightPlugin.java new file mode 100644 index 0000000..024f66c --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/NightPlugin.java @@ -0,0 +1,180 @@ +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(); + + 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; + + Reflex.getFields(clazz, UniPermission.class).forEach(permission -> { + if (this.getPluginManager().getPermission(permission.getName()) == null) { + this.getPluginManager().addPermission(permission); + } + }); + } + + 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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/command/CommandFlag.java b/src/main/java/su/nightexpress/nightcore/command/CommandFlag.java new file mode 100644 index 0000000..438c696 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/command/CommandFlag.java @@ -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 { + + public static final char PREFIX = '-'; + + private final String name; + private final Function parser; + + public CommandFlag(@NotNull String name, @NotNull Function parser) { + this.name = name; + this.parser = parser; + } + + @NotNull + public static CommandFlag worldFlag(@NotNull String name) { + return new CommandFlag<>(name, Bukkit::getWorld); + } + + @NotNull + public static CommandFlag stringFlag(@NotNull String name) { + return new CommandFlag<>(name, Function.identity()); + } + + @NotNull + public static CommandFlag textFlag(@NotNull String name) { + return new CommandFlag<>(name, Colorizer::apply); + } + + @NotNull + public static CommandFlag intFlag(@NotNull String name) { + return new CommandFlag<>(name, str -> NumberUtil.getAnyInteger(str, 0)); + } + + @NotNull + public static CommandFlag doubleFlag(@NotNull String name) { + return new CommandFlag<>(name, str -> NumberUtil.getAnyDouble(str, 0D)); + } + + @NotNull + public static CommandFlag 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 getParser() { + return parser; + } + + @Override + public String toString() { + return "CommandFlag{" + + "name='" + name + '\'' + + '}'; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/command/CommandManager.java b/src/main/java/su/nightexpress/nightcore/command/CommandManager.java new file mode 100644 index 0000000..981c81f --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/command/CommandManager.java @@ -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 { + + private final Set 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 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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/command/CommandResult.java b/src/main/java/su/nightexpress/nightcore/command/CommandResult.java new file mode 100644 index 0000000..1ca9a29 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/command/CommandResult.java @@ -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, String> flags; + + public CommandResult(@NotNull String label, String[] args, @NotNull Map, 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 getFlag(@NotNull CommandFlag flag) { + String value = this.getFlags().get(flag); + if (value == null) return null; + + return flag.getParser().apply(value); + } + + @NotNull + public T getFlag(@NotNull CommandFlag 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, String> getFlags() { + return flags; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/command/api/NightCommand.java b/src/main/java/su/nightexpress/nightcore/command/api/NightCommand.java new file mode 100644 index 0000000..0fd567d --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/command/api/NightCommand.java @@ -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 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 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> 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); +} diff --git a/src/main/java/su/nightexpress/nightcore/command/api/NightPluginCommand.java b/src/main/java/su/nightexpress/nightcore/command/api/NightPluginCommand.java new file mode 100644 index 0000000..5be56f6 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/command/api/NightPluginCommand.java @@ -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); +} diff --git a/src/main/java/su/nightexpress/nightcore/command/base/HelpSubCommand.java b/src/main/java/su/nightexpress/nightcore/command/base/HelpSubCommand.java new file mode 100644 index 0000000..3295394 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/command/base/HelpSubCommand.java @@ -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 { + + 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); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/command/base/ReloadSubCommand.java b/src/main/java/su/nightexpress/nightcore/command/base/ReloadSubCommand.java new file mode 100644 index 0000000..28efb97 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/command/base/ReloadSubCommand.java @@ -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 { + + 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); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/command/impl/AbstractCommand.java b/src/main/java/su/nightexpress/nightcore/command/impl/AbstractCommand.java new file mode 100644 index 0000000..76e54b0 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/command/impl/AbstractCommand.java @@ -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

implements NightCommand { + + protected final P plugin; + private final String[] aliases; + private final Map childrens; + private final Map> 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 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 cleanArgs = new ArrayList<>(); + Map, 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 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> 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); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/command/impl/BaseCommand.java b/src/main/java/su/nightexpress/nightcore/command/impl/BaseCommand.java new file mode 100644 index 0000000..131ecb7 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/command/impl/BaseCommand.java @@ -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 { + + public BaseCommand(@NotNull NightCorePlugin plugin) { + super(plugin, plugin.getCommandAliases()); + } + + @Override + protected void onExecute(@NotNull CommandSender sender, @NotNull CommandResult result) { + + } +} diff --git a/src/main/java/su/nightexpress/nightcore/command/impl/PluginCommand.java b/src/main/java/su/nightexpress/nightcore/command/impl/PluginCommand.java new file mode 100644 index 0000000..f398403 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/command/impl/PluginCommand.java @@ -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

extends AbstractCommand

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

command = this; + int childCount = 0; + while (args.length > childCount) { + AbstractCommand

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 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 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]); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/command/impl/WrappedCommand.java b/src/main/java/su/nightexpress/nightcore/command/impl/WrappedCommand.java new file mode 100644 index 0000000..fdebde0 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/command/impl/WrappedCommand.java @@ -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 tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) { + List list = this.tabCompleter.onTabComplete(sender, this, alias, args); + return list == null ? Collections.emptyList() : list; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/config/ConfigValue.java b/src/main/java/su/nightexpress/nightcore/config/ConfigValue.java new file mode 100644 index 0000000..7b509bd --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/config/ConfigValue.java @@ -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 { + + private final String path; + private final T defaultValue; + private final String[] description; + private final Reader reader; + private final Writer writer; + + private T value; + + public ConfigValue(@NotNull String path, + @NotNull Reader reader, + @NotNull Writer 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 ConfigValue create(@NotNull String path, + @NotNull Reader reader, + @NotNull Writer writer, + @NotNull T defaultValue, + @Nullable String... description) { + return new ConfigValue<>(path, reader, writer, defaultValue, description); + } + + @NotNull + public static ConfigValue create(@NotNull String path, + @NotNull Reader reader, + @NotNull Writer writer, + + @NotNull Supplier defaultValue, + @Nullable String... description) { + return create(path, reader, writer, defaultValue.get(), description); + } + + @NotNull + public static ConfigValue create(@NotNull String path, @NotNull Reader reader, @NotNull T defaultValue, @Nullable String... description) { + return create(path, reader, FileConfig::set, defaultValue, description); + } + + @NotNull + public static ConfigValue create(@NotNull String path, @NotNull Reader reader, @NotNull Supplier defaultValue, @Nullable String... description) { + return create(path, reader, FileConfig::set, defaultValue, description); + } + + @NotNull + public static ConfigValue create(@NotNull String path, boolean defaultValue, @Nullable String... description) { + return create(path, FileConfig::getBoolean, defaultValue, description); + } + + @NotNull + public static ConfigValue create(@NotNull String path, int defaultValue, @Nullable String... description) { + return create(path, FileConfig::getInt, defaultValue, description); + } + + @NotNull + public static ConfigValue create(@NotNull String path, int[] defaultValue, @Nullable String... description) { + return create(path, FileConfig::getIntArray, FileConfig::setIntArray, defaultValue, description); + } + + @NotNull + public static ConfigValue create(@NotNull String path, double defaultValue, @Nullable String... description) { + return create(path, FileConfig::getDouble, defaultValue, description); + } + + @NotNull + public static ConfigValue create(@NotNull String path, long defaultValue, @Nullable String... description) { + return create(path, FileConfig::getLong, defaultValue, description); + } + + @NotNull + public static ConfigValue create(@NotNull String path, @NotNull String defaultValue, @Nullable String... description) { + return create(path, FileConfig::getString, defaultValue, description); + } + + @NotNull + public static ConfigValue create(@NotNull String path, @NotNull String[] defaultValue, @Nullable String... description) { + return create(path, FileConfig::getStringArray, FileConfig::setStringArray, defaultValue, description); + } + + @NotNull + public static ConfigValue> create(@NotNull String path, @NotNull List defaultValue, @Nullable String... description) { + return create(path, (cfg, path1, def) -> cfg.getStringList(path1), defaultValue, description); + } + + @NotNull + public static ConfigValue> create(@NotNull String path, @NotNull Set defaultValue, @Nullable String... description) { + return create(path, (cfg, path1, def) -> cfg.getStringSet(path1), defaultValue, description); + } + + @NotNull + public static ConfigValue create(@NotNull String path, @NotNull ItemStack defaultValue, @Nullable String... description) { + return create(path, FileConfig::getItem, FileConfig::setItem, defaultValue, description); + } + + @NotNull + public static ConfigValue create(@NotNull String path, @NotNull UniSound defaultValue, @Nullable String... description) { + Reader reader = (cfg, path1, def) -> UniSound.read(cfg, path1); + Writer writer = (cfg, path1, obj) -> obj.write(cfg, path1); + + return create(path, reader, writer, defaultValue, description); + } + + @NotNull + public static ConfigValue create(@NotNull String path, @NotNull UniParticle defaultValue, @Nullable String... description) { + Reader reader = (cfg, path1, def) -> UniParticle.read(cfg, path1); + Writer writer = (cfg, path1, obj) -> obj.write(cfg, path1); + + return create(path, reader, writer, defaultValue, description); + } + + @NotNull + public static > ConfigValue create(@NotNull String path, @NotNull Class clazz, @NotNull E defaultValue, @Nullable String... description) { + Reader reader = (cfg, path1, def) -> cfg.getEnum(path1, clazz, def); + Writer writer = (cfg, path1, obj) -> cfg.set(path1, obj.name()); + + return create(path, reader, writer, defaultValue, description); + } + + @NotNull + public static ConfigValue> forSet(@NotNull String path, + @NotNull Function reader, + @NotNull Writer> writer, + @NotNull Supplier> defaultValue, + @Nullable String... description) { + return forSet(path, reader, writer, defaultValue.get(), description); + } + + @NotNull + public static ConfigValue> forSet(@NotNull String path, + @NotNull Function valFun, + @NotNull Writer> writer, + @NotNull Set defaultValue, + @Nullable String... description) { + + Reader> 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 ConfigValue> forMap(@NotNull String path, + @NotNull Function keyFun, + @NotNull TriFunction valFun, + @NotNull Writer> writer, + @NotNull Supplier> defaultValue, + @Nullable String... description) { + return forMap(path, keyFun, valFun, writer, defaultValue.get(), description); + } + + @NotNull + public static ConfigValue> forMap(@NotNull String path, + @NotNull Function keyFun, + @NotNull TriFunction valFun, + @NotNull Writer> writer, + @NotNull Map defaultValue, + @Nullable String... description) { + return forMap(path, keyFun, valFun, HashMap::new, writer, defaultValue, description); + } + + @NotNull + public static ConfigValue> forTreeMap(@NotNull String path, + @NotNull Function keyFun, + @NotNull TriFunction valFun, + @NotNull Writer> writer, + @NotNull Supplier> defaultValue, @Nullable String... description) { + return forTreeMap(path, keyFun, valFun, writer, defaultValue.get(), description); + } + + @NotNull + public static ConfigValue> forTreeMap(@NotNull String path, + @NotNull Function keyFun, + @NotNull TriFunction valFun, + @NotNull Writer> writer, + @NotNull TreeMap defaultValue, @Nullable String... description) { + return forMap(path, keyFun, valFun, TreeMap::new, writer, defaultValue, description); + } + + @NotNull + public static > ConfigValue forMap(@NotNull String path, + @NotNull Function keyFun, + @NotNull TriFunction valFun, + @NotNull Supplier mapSupplier, + @NotNull Writer writer, + @NotNull M defaultValue, @Nullable String... description) { + Reader 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 ConfigValue> forMap(@NotNull String path, + @NotNull TriFunction function, + @NotNull Writer> writer, + @NotNull Supplier> defaultValue, + @Nullable String... description) { + return forMap(path, String::toLowerCase, function, writer, defaultValue.get(), description); + } + + @NotNull + public static ConfigValue> forMap(@NotNull String path, + @NotNull TriFunction function, + @NotNull Writer> writer, + @NotNull Map 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 getReader() { + return reader; + } + + @NotNull + public Writer getWriter() { + return writer; + } + + public interface Reader { + + @NotNull T read(@NotNull FileConfig cfg, @NotNull String path, @NotNull T def); + } + + public interface Writer { + + void write(@NotNull FileConfig cfg, @NotNull String path, @NotNull T obj); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/config/FileConfig.java b/src/main/java/su/nightexpress/nightcore/config/FileConfig.java new file mode 100644 index 0000000..a026eaa --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/config/FileConfig.java @@ -0,0 +1,441 @@ +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 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 loadAll(@NotNull String path) { + return loadAll(path, false); + } + + @NotNull + public static List 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 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 comments) { + if (this.getComments(path).equals(comments)) return; + + super.setComments(path, comments); + this.isChanged = true; + } + + @Override + public void setInlineComments(@NotNull String path, @Nullable List 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 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 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 getEnum(@NotNull String path, @NotNull Class clazz) { + return StringUtil.getEnum(this.getString(path), clazz).orElse(null); + } + + @NotNull + public > T getEnum(@NotNull String path, @NotNull Class clazz, @NotNull T def) { + return StringUtil.getEnum(this.getString(path), clazz).orElse(def); + } + + @NotNull + public > List getEnumList(@NotNull String path, @NotNull Class clazz) { + return this.getStringSet(path).stream().map(str -> StringUtil.getEnum(str, clazz).orElse(null)) + .filter(Objects::nonNull).toList(); + } + + /*@NotNull + public Set getFireworkEffects(@NotNull String path) { + Set 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 colors = new HashSet<>(); + for (String colorRaw : this.getStringList(path2 + "Colors")) { + colors.add(StringUtil.parseColor(colorRaw)); + } + + Set 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 ? Colorizer.apply(name) : null); + meta.setLore(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 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 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 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 item) { + this.set(path, ItemUtil.compress(item)); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/config/PluginDetails.java b/src/main/java/su/nightexpress/nightcore/config/PluginDetails.java new file mode 100644 index 0000000..2a429a0 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/config/PluginDetails.java @@ -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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/core/CoreConfig.java b/src/main/java/su/nightexpress/nightcore/core/CoreConfig.java new file mode 100644 index 0000000..aee3b8a --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/core/CoreConfig.java @@ -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 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> 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 map = new HashMap<>(); + map.put("aqua", Color.CYAN); + return map; + }, + "Here you can define custom colors to use it in all nightcore plugins like Text.", + "You can also override default ones." + ); + + public static final ConfigValue 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 USER_DEBUG_ENABLED = ConfigValue.create("UserData.Debug", + false, + "Enables debug messages for user data management.", + "[Default is false]"); + + public static final ConfigValue 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 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 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]"); +} diff --git a/src/main/java/su/nightexpress/nightcore/core/CoreLang.java b/src/main/java/su/nightexpress/nightcore/core/CoreLang.java new file mode 100644 index 0000000..0326581 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/core/CoreLang.java @@ -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", ""); + + 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(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/core/CoreManager.java b/src/main/java/su/nightexpress/nightcore/core/CoreManager.java new file mode 100644 index 0000000..fd770d7 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/core/CoreManager.java @@ -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 { + + 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() { + + } +} diff --git a/src/main/java/su/nightexpress/nightcore/core/CorePerms.java b/src/main/java/su/nightexpress/nightcore/core/CorePerms.java new file mode 100644 index 0000000..52770f0 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/core/CorePerms.java @@ -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"); + +} diff --git a/src/main/java/su/nightexpress/nightcore/core/command/CheckPermCommand.java b/src/main/java/su/nightexpress/nightcore/core/command/CheckPermCommand.java new file mode 100644 index 0000000..c8f7700 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/core/command/CheckPermCommand.java @@ -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 { + + 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 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); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/core/listener/CoreListener.java b/src/main/java/su/nightexpress/nightcore/core/listener/CoreListener.java new file mode 100644 index 0000000..f2eed84 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/core/listener/CoreListener.java @@ -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 { + + public CoreListener(@NotNull NightCore plugin) { + super(plugin); + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onServiceRegisterEvent(ServiceRegisterEvent event) { + if (!Plugins.hasVault()) return; + + VaultHook.onServiceRegisterEvent(event); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractConnector.java b/src/main/java/su/nightexpress/nightcore/database/AbstractConnector.java new file mode 100644 index 0000000..bcefc2e --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/AbstractConnector.java @@ -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(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractDataHandler.java b/src/main/java/su/nightexpress/nightcore/database/AbstractDataHandler.java new file mode 100644 index 0000000..7ae2f4a --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/AbstractDataHandler.java @@ -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

extends SimpleManager

{ + + 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 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 values) { + InsertQueryExecutor.builder(table).values(values).execute(this.getConnector()); + } + + public void update(@NotNull String table, @NotNull List 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 columns, @NotNull SQLCondition... conditions) { + return this.load(table, (resultSet -> true), columns, Arrays.asList(conditions)).isPresent(); + } + + @NotNull + public Optional load(@NotNull String table, @NotNull Function function, + @NotNull List columns, + @NotNull List conditions) { + List list = this.load(table, function, columns, conditions, 1); + return list.isEmpty() ? Optional.empty() : Optional.of(list.get(0)); + } + + @NotNull + public List load(@NotNull String table, @NotNull Function dataFunction) { + return this.load(table, dataFunction, -1); + } + + @NotNull + public List load(@NotNull String table, @NotNull Function dataFunction, int amount) { + return this.load(table, dataFunction, Collections.emptyList(), amount); + } + + @NotNull + public List load(@NotNull String table, + @NotNull Function dataFunction, + @NotNull List columns, + int amount) { + return this.load(table, dataFunction, columns, Collections.emptyList(), amount); + } + + @NotNull + public List load(@NotNull String table, + @NotNull Function dataFunction, + @NotNull List columns, + @NotNull List conditions, + int amount) { + return SelectQueryExecutor.builder(table, dataFunction).columns(columns).where(conditions).execute(this.getConnector()); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractUser.java b/src/main/java/su/nightexpress/nightcore/database/AbstractUser.java new file mode 100644 index 0000000..e4566c2 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/AbstractUser.java @@ -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

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 + "]"; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java b/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java new file mode 100644 index 0000000..e6549b4 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java @@ -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

, U extends DataUser> extends AbstractDataHandler

{ + + 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 existIDs; + protected final Set 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 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 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 getExtraColumns(); + + @NotNull + protected List getReadColumns() { + return Collections.emptyList(); + } + + @NotNull + protected abstract List getSaveColumns(@NotNull U user); + + @NotNull + protected abstract Function getUserFunction(); + + @NotNull + public List 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 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 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()); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java b/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java new file mode 100644 index 0000000..a3992d4 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java @@ -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

, U extends DataUser> extends AbstractManager

{ + + private final Map loadedById; + private final Map 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 getUserDataAsync(@NotNull String name) { + return CompletableFuture.supplyAsync(() -> this.getUserData(name)); + } + + public final CompletableFuture getUserDataAsync(@NotNull UUID uuid) { + return CompletableFuture.supplyAsync(() -> this.getUserData(uuid)); + } + + public void getUserDataAndPerform(@NotNull String name, Consumer 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 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 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 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 getAllUsers() { + Map 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 getLoadedByIdMap() { + this.removeExpired(this.loadedById.values()); + + return this.loadedById; + } + + @NotNull + public Map getLoadedByNameMap() { + this.removeExpired(this.loadedByName.values()); + + return loadedByName; + } + + private void removeExpired(@NotNull Collection collection) { + collection.removeIf(user -> { + if (user.isCacheExpired()) { + user.onUnload(); + //this.plugin.debug("Cache expired: " + user.getName()); + return true; + } + return false; + }); + } + + @NotNull + public Set 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); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/DataUser.java b/src/main/java/su/nightexpress/nightcore/database/DataUser.java new file mode 100644 index 0000000..69c7933 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/DataUser.java @@ -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(); +} diff --git a/src/main/java/su/nightexpress/nightcore/database/DatabaseConfig.java b/src/main/java/su/nightexpress/nightcore/database/DatabaseConfig.java new file mode 100644 index 0000000..f513781 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/DatabaseConfig.java @@ -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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/DatabaseType.java b/src/main/java/su/nightexpress/nightcore/database/DatabaseType.java new file mode 100644 index 0000000..c850fcd --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/DatabaseType.java @@ -0,0 +1,7 @@ +package su.nightexpress.nightcore.database; + +public enum DatabaseType { + + MYSQL, + SQLITE, +} diff --git a/src/main/java/su/nightexpress/nightcore/database/connection/MySQLConnector.java b/src/main/java/su/nightexpress/nightcore/database/connection/MySQLConnector.java new file mode 100644 index 0000000..59782c1 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/connection/MySQLConnector.java @@ -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()); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/connection/SQLiteConnector.java b/src/main/java/su/nightexpress/nightcore/database/connection/SQLiteConnector.java new file mode 100644 index 0000000..6749698 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/connection/SQLiteConnector.java @@ -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); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/listener/UserListener.java b/src/main/java/su/nightexpress/nightcore/database/listener/UserListener.java new file mode 100644 index 0000000..505d855 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/listener/UserListener.java @@ -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

, U extends DataUser> extends AbstractListener

{ + + private final AbstractUserManager, 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()); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/serialize/ItemStackSerializer.java b/src/main/java/su/nightexpress/nightcore/database/serialize/ItemStackSerializer.java new file mode 100644 index 0000000..8d91f9a --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/serialize/ItemStackSerializer.java @@ -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, JsonDeserializer { + + @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()); + } + +} diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLColumn.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLColumn.java new file mode 100644 index 0000000..8e955c2 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLColumn.java @@ -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)); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLCondition.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLCondition.java new file mode 100644 index 0000000..af832ad --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLCondition.java @@ -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; + } + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLExecutor.java new file mode 100644 index 0000000..586b25f --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLExecutor.java @@ -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 { + + 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); +} diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLQueries.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLQueries.java new file mode 100644 index 0000000..81dad55 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLQueries.java @@ -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 values1) { + executeStatement(connector, sql, values1, Collections.emptySet()); + } + + public static void executeStatement(@NotNull AbstractConnector connector, + @NotNull String sql, + @NotNull Collection values1, + @NotNull Collection 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 List<@NotNull T> executeQuery(@NotNull AbstractConnector connector, + @NotNull String sql, + @NotNull Collection values, + @NotNull Function dataFunction, + int amount) { + + List 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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLValue.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLValue.java new file mode 100644 index 0000000..3b8c9e5 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLValue.java @@ -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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnFormer.java b/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnFormer.java new file mode 100644 index 0000000..976d99f --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnFormer.java @@ -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); +} diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnType.java b/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnType.java new file mode 100644 index 0000000..0b8c0b7 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnType.java @@ -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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/AlterTableExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/AlterTableExecutor.java new file mode 100644 index 0000000..9348ccc --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/AlterTableExecutor.java @@ -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 { + + private final DatabaseType databaseType; + private final List 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 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 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 columns) { + return this.columns(columns.stream().map(column -> column.toValue("dummy")).toList(), Type.DROP_COLUMN); + } + + private AlterTableExecutor columns(@NotNull List 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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/CreateTableExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/CreateTableExecutor.java new file mode 100644 index 0000000..34066ec --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/CreateTableExecutor.java @@ -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 { + + private final DatabaseType databaseType; + private final List 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 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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/DeleteQueryExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/DeleteQueryExecutor.java new file mode 100644 index 0000000..6d30178 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/DeleteQueryExecutor.java @@ -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 { + + private final List 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 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 whereVals = this.wheres.stream().map(SQLCondition::getValue).map(SQLValue::getValue).toList(); + + SQLQueries.executeStatement(connector, sql, whereVals); + return null; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/InsertQueryExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/InsertQueryExecutor.java new file mode 100644 index 0000000..8b47b7d --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/InsertQueryExecutor.java @@ -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 { + + private final List 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 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 values2 = this.values.stream().map(SQLValue::getValue).toList(); + + SQLQueries.executeStatement(connector, sql, values2); + return null; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/RenameTableExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/RenameTableExecutor.java new file mode 100644 index 0000000..6c4eb8e --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/RenameTableExecutor.java @@ -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 { + + 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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/SelectQueryExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/SelectQueryExecutor.java new file mode 100644 index 0000000..a0cf8ad --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/SelectQueryExecutor.java @@ -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 extends SQLExecutor> { + + private final List columns; + private final List wheres; + private final Function dataFunction; + private int amount; + + private SelectQueryExecutor(@NotNull String table, @NotNull Function dataFunction) { + super(table); + this.columns = new ArrayList<>(); + this.wheres = new ArrayList<>(); + this.dataFunction = dataFunction; + this.amount = -1; + } + + @NotNull + public static SelectQueryExecutor builder(@NotNull String table, @NotNull Function dataFunction) { + return new SelectQueryExecutor<>(table, dataFunction); + } + + /*@NotNull + public SelectQueryExecutor all() { + return this.columns(new SQLColumn("*", ColumnType.STRING, -1)); + }*/ + + @NotNull + public SelectQueryExecutor columns(@NotNull SQLColumn... columns) { + return this.columns(Arrays.asList(columns)); + } + + @NotNull + public SelectQueryExecutor columns(@NotNull List columns) { + //if (columns.isEmpty()) return this.all(); + this.columns.clear(); + this.columns.addAll(columns); + return this; + } + + @NotNull + public SelectQueryExecutor where(@NotNull SQLCondition... wheres) { + return this.where(Arrays.asList(wheres)); + } + + @NotNull + public SelectQueryExecutor where(@NotNull List wheres) { + this.wheres.clear(); + this.wheres.addAll(wheres); + return this; + } + + @NotNull + public SelectQueryExecutor amount(int amount) { + this.amount = amount; + return this; + } + + @Override + @NotNull + public List 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 values = this.wheres.stream().map(SQLCondition::getValue).map(SQLValue::getValue).toList(); + + return SQLQueries.executeQuery(connector, sql, values, this.dataFunction, this.amount); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/UpdateQueryExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/UpdateQueryExecutor.java new file mode 100644 index 0000000..0984a4e --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/UpdateQueryExecutor.java @@ -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 { + + private final List values; + private final List 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 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 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 values2 = this.values.stream().map(SQLValue::getValue).toList(); + List whers2 = this.wheres.stream().map(SQLCondition::getValue).map(SQLValue::getValue).toList(); + + SQLQueries.executeStatement(connector, sql, values2, whers2); + return null; + } + +} diff --git a/src/main/java/su/nightexpress/nightcore/dialog/Dialog.java b/src/main/java/su/nightexpress/nightcore/dialog/Dialog.java new file mode 100644 index 0000000..9c50df7 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/dialog/Dialog.java @@ -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 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 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 getSuggestions() { + return suggestions; + } + + @NotNull + public Dialog setSuggestions(@NotNull Collection 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 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 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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/dialog/DialogHandler.java b/src/main/java/su/nightexpress/nightcore/dialog/DialogHandler.java new file mode 100644 index 0000000..dba117c --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/dialog/DialogHandler.java @@ -0,0 +1,8 @@ +package su.nightexpress.nightcore.dialog; + +import org.jetbrains.annotations.NotNull; + +public interface DialogHandler { + + boolean onInput(@NotNull WrappedInput input); +} diff --git a/src/main/java/su/nightexpress/nightcore/dialog/DialogListener.java b/src/main/java/su/nightexpress/nightcore/dialog/DialogListener.java new file mode 100644 index 0000000..20e9193 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/dialog/DialogListener.java @@ -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 { + + 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); + } + }); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/dialog/WrappedInput.java b/src/main/java/su/nightexpress/nightcore/dialog/WrappedInput.java new file mode 100644 index 0000000..23acd6c --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/dialog/WrappedInput.java @@ -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 asEnum(@NotNull Class clazz) { + return StringUtil.getEnum(this.getTextRaw(), clazz).orElse(null); + } + + @NotNull + public > E asEnum(@NotNull Class 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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/integration/VaultHook.java b/src/main/java/su/nightexpress/nightcore/integration/VaultHook.java new file mode 100644 index 0000000..bf3fb7c --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/integration/VaultHook.java @@ -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 getProvider(@NotNull Class clazz) { + RegisteredServiceProvider 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 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(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/language/LangAssets.java b/src/main/java/su/nightexpress/nightcore/language/LangAssets.java new file mode 100644 index 0000000..f9ba9ce --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/LangAssets.java @@ -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 = "https://github.com/nulli0n/NexEngine-spigot/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 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); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/language/LangManager.java b/src/main/java/su/nightexpress/nightcore/language/LangManager.java new file mode 100644 index 0000000..c94bf2f --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/LangManager.java @@ -0,0 +1,94 @@ +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.Reflex; +import su.nightexpress.nightcore.util.StringUtil; + +import java.io.File; +import java.io.InputStream; + +public class LangManager extends SimpleManager { + + 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> 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); + } + } + + 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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/language/entry/LangEntry.java b/src/main/java/su/nightexpress/nightcore/language/entry/LangEntry.java new file mode 100644 index 0000000..fba687c --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/entry/LangEntry.java @@ -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 { + + 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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/language/entry/LangItem.java b/src/main/java/su/nightexpress/nightcore/language/entry/LangItem.java new file mode 100644 index 0000000..a881c85 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/entry/LangItem.java @@ -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>> { + + private final List defaultLore; + + private String localizedName; + private List localizedLore; + + private WrappedMessage wrappedName; + private List wrappedLore; + + public LangItem(@NotNull String key, @NotNull String defaultName, @NotNull List 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> 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 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 getLocalizedLore() { + return localizedLore; + } + + public void setLocalizedLore(@NotNull List 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 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 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; + } + } +} diff --git a/src/main/java/su/nightexpress/nightcore/language/entry/LangString.java b/src/main/java/su/nightexpress/nightcore/language/entry/LangString.java new file mode 100644 index 0000000..16adc86 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/entry/LangString.java @@ -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 { + + 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(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/language/entry/LangText.java b/src/main/java/su/nightexpress/nightcore/language/entry/LangText.java new file mode 100644 index 0000000..879321e --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/entry/LangText.java @@ -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 { + + 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 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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/language/legacy/LegacyLangMessage.java b/src/main/java/su/nightexpress/nightcore/language/legacy/LegacyLangMessage.java new file mode 100644 index 0000000..db59b50 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/legacy/LegacyLangMessage.java @@ -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 defaultText; + + private List text; + + public LegacyLangMessage(@NotNull NightCorePlugin plugin, @NotNull List 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 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 getDefaultText() { + return this.defaultText; + } + + @NotNull + public List getText() { + return this.text; + } + + @NotNull + public List getText(@NotNull CommandSender sender) { + if (!this.options.hasPlaceholderAPI() || !(sender instanceof Player player)) return this.getText(); + + List text = new ArrayList<>(this.getText()); + text.replaceAll(line -> PlaceholderAPI.setPlaceholders(player, line)); + return text; + } + + private void setText(@NotNull List 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 replacer) { + if (this.isEmpty()) return this; + + LegacyLangMessage msgCopy = new LegacyLangMessage(this); + msgCopy.getText().replaceAll(replacer); + return msgCopy; + } + + @NotNull + public LegacyLangMessage replace(@NotNull Predicate predicate, @NotNull BiConsumer> replacer) { + if (this.isEmpty()) return this; + + LegacyLangMessage msgCopy = new LegacyLangMessage(this); + List 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 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 asList() { + return this.asList(this.getText()); + } + + @NotNull + public List asList(@NotNull CommandSender sender) { + return this.asList(this.getText(sender)); + } + + @NotNull + private List 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()); + }*/ +} diff --git a/src/main/java/su/nightexpress/nightcore/language/legacy/LegacyLangString.java b/src/main/java/su/nightexpress/nightcore/language/legacy/LegacyLangString.java new file mode 100644 index 0000000..e70294c --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/legacy/LegacyLangString.java @@ -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 { + + 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); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/language/legacy/LegacyLangText.java b/src/main/java/su/nightexpress/nightcore/language/legacy/LegacyLangText.java new file mode 100644 index 0000000..3e4d6f3 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/legacy/LegacyLangText.java @@ -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 { + + 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 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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/language/legacy/LegacyMessageOption.java b/src/main/java/su/nightexpress/nightcore/language/legacy/LegacyMessageOption.java new file mode 100644 index 0000000..6a7617c --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/legacy/LegacyMessageOption.java @@ -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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/language/legacy/LegacyMessageOptions.java b/src/main/java/su/nightexpress/nightcore/language/legacy/LegacyMessageOptions.java new file mode 100644 index 0000000..f62a985 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/legacy/LegacyMessageOptions.java @@ -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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java b/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java new file mode 100644 index 0000000..0c2d2c0 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/message/LangMessage.java @@ -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> replacer) { + List list = new ArrayList<>(); + replacer.accept(list); + + return this.replace(var, list); + } + + @NotNull + public LangMessage replace(@NotNull String var, @NotNull List 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 replacer) { + if (this.isDisabled()) return this; + + LangMessage copy = new LangMessage(this); + copy.getMessage().replace(replacer); + + return copy; + } + + /*@NotNull + public LangMessage replace(@NotNull Predicate predicate, @NotNull BiConsumer> replacer) { + if (this.isEmpty()) return this; + + LangMessage msgCopy = new LangMessage(this); + List replaced = new ArrayList<>(); + List 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]); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/su/nightexpress/nightcore/language/message/MessageOptions.java b/src/main/java/su/nightexpress/nightcore/language/message/MessageOptions.java new file mode 100644 index 0000000..2f7b109 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/message/MessageOptions.java @@ -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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/language/message/OutputType.java b/src/main/java/su/nightexpress/nightcore/language/message/OutputType.java new file mode 100644 index 0000000..59a1a44 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/message/OutputType.java @@ -0,0 +1,5 @@ +package su.nightexpress.nightcore.language.message; + +public enum OutputType { + CHAT, ACTION_BAR, TITLES, NONE, +} diff --git a/src/main/java/su/nightexpress/nightcore/language/tag/MessageDecorator.java b/src/main/java/su/nightexpress/nightcore/language/tag/MessageDecorator.java new file mode 100644 index 0000000..edc6627 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/tag/MessageDecorator.java @@ -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); +} diff --git a/src/main/java/su/nightexpress/nightcore/language/tag/MessageTags.java b/src/main/java/su/nightexpress/nightcore/language/tag/MessageTags.java new file mode 100644 index 0000000..e558142 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/tag/MessageTags.java @@ -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 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 getTags() { + return TAG_MAP.values(); + } + + public static Tag getTag(@NotNull String name) { + return TAG_MAP.get(name.toLowerCase()); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/language/tag/impl/NoPrefixTag.java b/src/main/java/su/nightexpress/nightcore/language/tag/impl/NoPrefixTag.java new file mode 100644 index 0000000..594b1ee --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/tag/impl/NoPrefixTag.java @@ -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); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/language/tag/impl/OutputTag.java b/src/main/java/su/nightexpress/nightcore/language/tag/impl/OutputTag.java new file mode 100644 index 0000000..44ebb8e --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/tag/impl/OutputTag.java @@ -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); + } + } +} diff --git a/src/main/java/su/nightexpress/nightcore/language/tag/impl/PlaceholderTag.java b/src/main/java/su/nightexpress/nightcore/language/tag/impl/PlaceholderTag.java new file mode 100644 index 0000000..4894652 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/tag/impl/PlaceholderTag.java @@ -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); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/language/tag/impl/SoundTag.java b/src/main/java/su/nightexpress/nightcore/language/tag/impl/SoundTag.java new file mode 100644 index 0000000..3f62b37 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/language/tag/impl/SoundTag.java @@ -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); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/manager/AbstractFileData.java b/src/main/java/su/nightexpress/nightcore/manager/AbstractFileData.java new file mode 100644 index 0000000..397aef8 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/manager/AbstractFileData.java @@ -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

{ + + 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()); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/manager/AbstractListener.java b/src/main/java/su/nightexpress/nightcore/manager/AbstractListener.java new file mode 100644 index 0000000..a27a292 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/manager/AbstractListener.java @@ -0,0 +1,19 @@ +package su.nightexpress.nightcore.manager; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.NightCorePlugin; + +public abstract class AbstractListener

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); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/manager/AbstractManager.java b/src/main/java/su/nightexpress/nightcore/manager/AbstractManager.java new file mode 100644 index 0000000..2c086ee --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/manager/AbstractManager.java @@ -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

extends SimpleManager

{ + + protected final Set listeners; + protected final List 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(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/manager/SimpeListener.java b/src/main/java/su/nightexpress/nightcore/manager/SimpeListener.java new file mode 100644 index 0000000..2ea13c4 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/manager/SimpeListener.java @@ -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); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/manager/SimpleManager.java b/src/main/java/su/nightexpress/nightcore/manager/SimpleManager.java new file mode 100644 index 0000000..2a4f484 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/manager/SimpleManager.java @@ -0,0 +1,35 @@ +package su.nightexpress.nightcore.manager; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.NightCorePlugin; + +public abstract class SimpleManager

{ + + 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(); +} diff --git a/src/main/java/su/nightexpress/nightcore/menu/MenuListener.java b/src/main/java/su/nightexpress/nightcore/menu/MenuListener.java new file mode 100644 index 0000000..e918e68 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/menu/MenuListener.java @@ -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 { + + 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); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/menu/MenuOptions.java b/src/main/java/su/nightexpress/nightcore/menu/MenuOptions.java new file mode 100644 index 0000000..1d5363c --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/menu/MenuOptions.java @@ -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 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(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/menu/MenuViewer.java b/src/main/java/su/nightexpress/nightcore/menu/MenuViewer.java new file mode 100644 index 0000000..33ee568 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/menu/MenuViewer.java @@ -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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/menu/api/AutoFilled.java b/src/main/java/su/nightexpress/nightcore/menu/api/AutoFilled.java new file mode 100644 index 0000000..709aaf2 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/menu/api/AutoFilled.java @@ -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 extends Menu { + + int[] getAutoFillSlots(); + + @NotNull List 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 getAutoFillItems(@NotNull MenuViewer viewer) { + Player player = viewer.getPlayer(); + List items = new ArrayList<>(); + List 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 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; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/menu/api/Menu.java b/src/main/java/su/nightexpress/nightcore/menu/api/Menu.java new file mode 100644 index 0000000..d912f10 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/menu/api/Menu.java @@ -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 getViewers(); + + @Nullable MenuViewer getViewer(@NotNull Player player); + + + + @NotNull List 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 getViewersMap(); + + @NotNull Set getItems(); + + @NotNull MenuOptions getOptions(); +} diff --git a/src/main/java/su/nightexpress/nightcore/menu/click/ClickAction.java b/src/main/java/su/nightexpress/nightcore/menu/click/ClickAction.java new file mode 100644 index 0000000..e826ff7 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/menu/click/ClickAction.java @@ -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); +} diff --git a/src/main/java/su/nightexpress/nightcore/menu/click/ClickResult.java b/src/main/java/su/nightexpress/nightcore/menu/click/ClickResult.java new file mode 100644 index 0000000..fa4741f --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/menu/click/ClickResult.java @@ -0,0 +1,38 @@ +package su.nightexpress.nightcore.menu.click; + +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; + +public class ClickResult { + + private final int slot; + private final ItemStack itemStack; + private final boolean isMenu; + + public ClickResult(int slot, @Nullable ItemStack itemStack, boolean isMenu) { + this.slot = slot; + this.itemStack = itemStack; + this.isMenu = isMenu; + } + + public int getSlot() { + return slot; + } + + @Nullable + public ItemStack getItemStack() { + return itemStack; + } + + public boolean isEmptySlot() { + return this.itemStack == null || this.itemStack.getType().isAir(); + } + + public boolean isMenu() { + return isMenu; + } + + public boolean isInventory() { + return !this.isMenu(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/menu/click/ClickType.java b/src/main/java/su/nightexpress/nightcore/menu/click/ClickType.java new file mode 100644 index 0000000..11d2e0c --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/menu/click/ClickType.java @@ -0,0 +1,45 @@ +package su.nightexpress.nightcore.menu.click; + +import org.bukkit.event.inventory.InventoryClickEvent; +import org.jetbrains.annotations.NotNull; + +public enum ClickType { + + LEFT, RIGHT, SHIFT_LEFT, SHIFT_RIGHT, + DROP_KEY, SWAP_KEY, + NUMBER_1, + NUMBER_2, + NUMBER_3, + NUMBER_4, + NUMBER_5, + NUMBER_6, + NUMBER_7, + NUMBER_8, + NUMBER_9, + ; + + @NotNull + public static ClickType from(@NotNull InventoryClickEvent event) { + if (event.getClick() == org.bukkit.event.inventory.ClickType.DROP) return DROP_KEY; + if (event.getClick() == org.bukkit.event.inventory.ClickType.SWAP_OFFHAND) return SWAP_KEY; + if (event.getHotbarButton() >= 0) { + return switch (event.getHotbarButton()) { + case 0 -> NUMBER_1; + case 1 -> NUMBER_2; + case 2 -> NUMBER_3; + case 3 -> NUMBER_4; + case 4 -> NUMBER_5; + case 5 -> NUMBER_6; + case 6 -> NUMBER_7; + case 7 -> NUMBER_8; + case 8 -> NUMBER_9; + default -> throw new IllegalStateException("Unexpected value: " + event.getHotbarButton()); + }; + } + + if (event.isShiftClick()) { + return event.isLeftClick() ? SHIFT_LEFT : SHIFT_RIGHT; + } + return event.isLeftClick() ? LEFT : RIGHT; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/menu/impl/AbstractMenu.java b/src/main/java/su/nightexpress/nightcore/menu/impl/AbstractMenu.java new file mode 100644 index 0000000..49cf89d --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/menu/impl/AbstractMenu.java @@ -0,0 +1,266 @@ +package su.nightexpress.nightcore.menu.impl; + +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.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.NightCorePlugin; +import su.nightexpress.nightcore.dialog.Dialog; +import su.nightexpress.nightcore.menu.api.Menu; +import su.nightexpress.nightcore.menu.link.Linked; +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.ItemOptions; +import su.nightexpress.nightcore.menu.item.MenuItem; +import su.nightexpress.nightcore.util.Lists; + +import java.util.*; + +public abstract class AbstractMenu

implements Menu { + + public static final Map PLAYER_MENUS = new HashMap<>(); + + protected final P plugin; + protected final UUID id; + protected final MenuOptions options; + protected final Map viewers; + protected final Set items; + + public AbstractMenu(@NotNull P plugin) { + this(plugin, "NC Inventory", InventoryType.CHEST); + } + + public AbstractMenu(@NotNull P plugin, @NotNull String title, @NotNull InventoryType type) { + this(plugin, new MenuOptions(title, 27, type)); + } + + public AbstractMenu(@NotNull P plugin, @NotNull String title, int size) { + this(plugin, new MenuOptions(title, size, InventoryType.CHEST)); + } + + public AbstractMenu(@NotNull P plugin, @NotNull MenuOptions options) { + this.plugin = plugin; + this.id = UUID.randomUUID(); + this.options = new MenuOptions(options); + this.viewers = new HashMap<>(); + this.items = new HashSet<>(); + } + + @Nullable + public static Menu getMenu(@NotNull Player player) { + return PLAYER_MENUS.get(player.getUniqueId()); + } + + @Override + public void clear() { + this.close(); + this.getItems().clear(); + this.getViewers().clear(); + } + + @Override + public void close() { + new HashSet<>(this.getViewers()).forEach(viewer -> viewer.getPlayer().closeInventory()); + } + + /*@NotNull + public P plugin() { + return this.plugin; + }*/ + + @Override + public void runNextTick(@NotNull Runnable runnable) { + this.plugin.runTask(task -> runnable.run()); + } + + @Override + public void flush() { + this.getViewers().forEach(viewer -> this.open(viewer.getPlayer())); + } + + @Override + public boolean canOpen(@NotNull Player player) { + return !player.isSleeping(); + } + + @Override + public boolean open(@NotNull MenuViewer viewer) { + return this.open(viewer.getPlayer()); + } + + @Override + public boolean open(@NotNull Player player) { + if (!this.canOpen(player)) return false; + + MenuOptions options = new MenuOptions(this.getOptions()); + MenuViewer viewer = this.getViewerOrCreate(player); + + this.getItems().removeIf(menuItem -> menuItem.getOptions().canBeDestroyed(viewer)); + this.onPrepare(viewer, options); + + if (!viewer.hasInventory()) { + viewer.openInventory(options.createInventory()); + } + else { + viewer.flushInventory(options); + } + + Inventory inventory = viewer.getInventory(); + if (inventory == null) { + this.plugin.debug("Could not create " + this.getClass().getSimpleName() + " inventory for '" + player.getName() + "'."); + return false; + } + + this.getItems(viewer).forEach(menuItem -> { + ItemStack item = menuItem.getItemStack(); + menuItem.getOptions().modifyDisplay(viewer, item); + + for (int slot : menuItem.getSlots()) { + if (slot < 0 || slot >= inventory.getSize()) continue; + inventory.setItem(slot, item); + } + }); + + this.onReady(viewer, inventory); + + PLAYER_MENUS.put(player.getUniqueId(), this); + return true; + } + + protected abstract void onPrepare(@NotNull MenuViewer viewer, @NotNull MenuOptions options); + + protected abstract void onReady(@NotNull MenuViewer viewer, @NotNull Inventory inventory); + + @Override + public void onClick(@NotNull MenuViewer viewer, @NotNull ClickResult result, @NotNull InventoryClickEvent event) { + event.setCancelled(true); + + if (result.isInventory()) return; + + MenuItem menuItem = this.getItem(viewer, result.getSlot()); + if (menuItem == null) return; + + menuItem.getHandler().getClickActions().forEach(action -> action.onClick(viewer, event)); + } + + @Override + public void onDrag(@NotNull MenuViewer viewer, @NotNull InventoryDragEvent event) { + event.setCancelled(true); + } + + @Override + public void onClose(@NotNull MenuViewer viewer, @NotNull InventoryCloseEvent event) { + Player player = viewer.getPlayer(); + + this.getViewersMap().remove(player.getUniqueId()); + this.getItems().removeIf(menuItem -> menuItem.getOptions().canBeDestroyed(viewer)); + PLAYER_MENUS.remove(player.getUniqueId()); + + // Do not clear link if entered Editor, so it can reopen menu without data loss when done. + if (this instanceof Linked linked && !Dialog.contains(player)) { + linked.getLink().clear(viewer); + } + + if (this.getViewers().isEmpty() && !this.isPersistent()) { + this.clear(); + } + } + + @Override + public boolean isPersistent() { + return true; + } + + @Override + @NotNull + public Collection getViewers() { + return this.getViewersMap().values(); + } + + @Override + @Nullable + public MenuViewer getViewer(@NotNull Player player) { + return this.getViewersMap().get(player.getUniqueId()); + } + + @NotNull + private MenuViewer getViewerOrCreate(@NotNull Player player) { + return this.getViewersMap().computeIfAbsent(player.getUniqueId(), k -> new MenuViewer(player)); + } + + + + @Override + @NotNull + public List getItems(@NotNull MenuViewer viewer) { + return this.getItems().stream() + .filter(menuItem -> menuItem.canSee(viewer)) + .sorted(Comparator.comparingInt(MenuItem::getPriority)).toList(); + } + + @Override + @Nullable + public MenuItem getItem(int slot) { + return this.getItems().stream() + .filter(item -> Lists.contains(item.getSlots(), slot)) + .max(Comparator.comparingInt(MenuItem::getPriority)).orElse(null); + } + + @Override + @Nullable + public MenuItem getItem(@NotNull MenuViewer viewer, int slot) { + return this.getItems(viewer).stream() + .filter(menuItem -> Lists.contains(menuItem.getSlots(), slot)) + .max(Comparator.comparingInt(MenuItem::getPriority)).orElse(null); + } + + @Override + @NotNull + public MenuItem addItem(@NotNull ItemStack item, int... slots) { + return this.addItem(new MenuItem(item, slots)); + } + + @Override + @NotNull + public MenuItem addWeakItem(@NotNull Player player, @NotNull ItemStack item, int... slots) { + MenuItem menuItem = new MenuItem(item, slots); + menuItem.setOptions(ItemOptions.personalWeak(player)); + return this.addItem(menuItem); + } + + @Override + @NotNull + public MenuItem addItem(@NotNull MenuItem menuItem) { + this.getItems().add(menuItem); + return menuItem; + } + + @Override + @NotNull + public UUID getId() { + return id; + } + + @NotNull + private Map getViewersMap() { + return viewers; + } + + @Override + @NotNull + public Set getItems() { + return items; + } + + @Override + @NotNull + public MenuOptions getOptions() { + return options; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/menu/impl/ConfigMenu.java b/src/main/java/su/nightexpress/nightcore/menu/impl/ConfigMenu.java new file mode 100644 index 0000000..f711913 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/menu/impl/ConfigMenu.java @@ -0,0 +1,178 @@ +package su.nightexpress.nightcore.menu.impl; + +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.NightCorePlugin; +import su.nightexpress.nightcore.config.ConfigValue; +import su.nightexpress.nightcore.config.FileConfig; +import su.nightexpress.nightcore.menu.api.AutoFilled; +import su.nightexpress.nightcore.menu.MenuOptions; +import su.nightexpress.nightcore.menu.click.ClickAction; +import su.nightexpress.nightcore.menu.click.ClickType; +import su.nightexpress.nightcore.menu.item.ItemHandler; +import su.nightexpress.nightcore.menu.item.MenuItem; +import su.nightexpress.nightcore.util.*; + +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; + +public abstract class ConfigMenu

extends AbstractMenu

{ + + protected final FileConfig cfg; + protected final Map handlerMap; + protected String itemSection = "Content"; + + public ConfigMenu(@NotNull P plugin, @NotNull FileConfig cfg) { + super(plugin); + this.cfg = cfg; + this.handlerMap = new HashMap<>(); + + this.addHandler(ItemHandler.forClose(this)); + if (this instanceof AutoFilled) { + this.addHandler(ItemHandler.forNextPage(this)); + this.addHandler(ItemHandler.forPreviousPage(this)); + } + } + + @NotNull + protected abstract MenuOptions createDefaultOptions(); + + @NotNull + protected abstract List createDefaultItems(); + + public void load() { + this.loadConfig(); + } + + protected abstract void loadAdditional(); + + public void loadConfig() { + MenuOptions defaultOptions = this.createDefaultOptions(); + + String title = ConfigValue.create("Settings.Title", defaultOptions.getTitle(), + "Sets GUI title." + ).read(cfg); + + int size = ConfigValue.create("Settings.Size", defaultOptions.getSize(), + "Sets GUI size. Must be multiply of 9.", + "Useful for '" + InventoryType.CHEST.name() + "' Inventory Type only." + ).read(cfg); + + InventoryType type = ConfigValue.create("Settings.Inventory_Type", InventoryType.class, defaultOptions.getType(), + "Sets GUI type.", + "https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/event/inventory/InventoryType.html" + ).read(cfg); + + int autoRefresh = ConfigValue.create("Settings.Auto_Refresh", defaultOptions.getAutoRefresh(), + "Sets GUI auto-refresh interval (in seconds). Set this to 0 to disable." + ).read(cfg); + + this.getOptions().setTitle(title); + this.getOptions().setSize(size); + this.getOptions().setType(type); + this.getOptions().setAutoRefresh(autoRefresh); + + this.loadAdditional(); + + if (!this.cfg.contains(this.itemSection)) { + AtomicInteger count = new AtomicInteger(); + this.createDefaultItems().forEach(menuItem -> { + String name = StringUtil.lowerCaseUnderscore(ItemUtil.getItemName(menuItem.getItemStack())); + + this.writeItem(menuItem, this.itemSection + "." + name + "_" + count.incrementAndGet()); + }); + } + + this.cfg.getSection(this.itemSection).forEach(sId -> { + MenuItem menuItem = this.readItem(this.itemSection + "." + sId); + this.addItem(menuItem); + }); + + List comments = new ArrayList<>(); + comments.add("=".repeat(20) + " GUI CONTENT " + "=".repeat(20)); + comments.add("You can freely edit items in this section as you wish (add, remove, modify items)."); + comments.add("The following values are available as button Types:"); + comments.addAll(handlerMap.keySet().stream().map(String::toUpperCase).sorted(String::compareTo).toList()); + comments.add("=".repeat(20) + " ITEM OPTIONS " + "=".repeat(20)); + comments.add("> Item: Item to display. Please check: " + Placeholders.WIKI_ITEMS_URL); + comments.add("> Priority: Button priority. Better values will override other item(s) in the same slot(s)."); + comments.add("> Slots: Button slots. From [0] to [Size - 1]. Split them with a comma."); + comments.add("> Click_Commands: Execute custom commands on click. " + Plugins.PLACEHOLDER_API + " available here."); + comments.add(" Available click types: " + String.join(", ", Lists.getEnums(ClickType.class))); + comments.add(" Click_Commands:"); + comments.add(" LEFT:"); + comments.add(" - say Hello"); + comments.add(" - give " + Placeholders.PLAYER_NAME + " diamond 1"); + comments.add("=".repeat(50)); + this.cfg.setComments(this.itemSection, comments); + this.cfg.saveChanges(); + } + + @Override + public void clear() { + super.clear(); + this.handlerMap.clear(); + } + + public void addHandler(@NotNull ItemHandler handler) { + this.handlerMap.put(handler.getName(), handler); + } + + public void addHandler(@NotNull String name, @NotNull ClickAction action) { + this.addHandler(new ItemHandler(name, action)); + } + + @Nullable + public ItemHandler getHandler(@NotNull String name) { + return this.handlerMap.get(name.toLowerCase()); + } + + public boolean removeHandler(@NotNull String name) { + return this.handlerMap.remove(name.toLowerCase()) != null; + } + + @NotNull + protected MenuItem readItem(@NotNull String path) { + String handlerName = cfg.getString(path + ".Type", Placeholders.DEFAULT); + ItemStack item = cfg.getItem(path + ".Item"); + int[] slots = cfg.getIntArray(path + ".Slots"); + int priority = cfg.getInt(path + ".Priority"); + + MenuItem menuItem = new MenuItem(item).setPriority(priority).setSlots(slots); + + ItemHandler handler = this.getHandler(handlerName); + if (handler != null) { + menuItem.setHandler(handler); + } + + if (cfg.contains(path + ".Click_Actions")) { + Map> commandMap = new HashMap<>(); + for (String sType : cfg.getSection(path + ".Click_Actions")) { + ClickType clickType = StringUtil.getEnum(sType, ClickType.class).orElse(null); + if (clickType == null) continue; + + List commands = cfg.getStringList(path + ".Click_Actions." + sType); + commandMap.put(clickType, commands); + } + commandMap.values().removeIf(List::isEmpty); + + ClickAction clickCommands = (viewer, event) -> { + List commands = commandMap.getOrDefault(ClickType.from(event), Collections.emptyList()); + commands.forEach(command -> Players.dispatchCommand(viewer.getPlayer(), command)); + }; + + menuItem.addClick(clickCommands); + } + + return menuItem; + } + + protected void writeItem(@NotNull MenuItem menuItem, @NotNull String path) { + this.cfg.set(path + ".Priority", menuItem.getPriority()); + this.cfg.setItem(path + ".Item", menuItem.getItemStack()); + this.cfg.setIntArray(path + ".Slots", menuItem.getSlots()); + this.cfg.set(path + ".Type", menuItem.getHandler().getName()); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/menu/impl/EditorMenu.java b/src/main/java/su/nightexpress/nightcore/menu/impl/EditorMenu.java new file mode 100644 index 0000000..3c38159 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/menu/impl/EditorMenu.java @@ -0,0 +1,131 @@ +package su.nightexpress.nightcore.menu.impl; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.NightCorePlugin; +import su.nightexpress.nightcore.core.CoreLang; +import su.nightexpress.nightcore.dialog.Dialog; +import su.nightexpress.nightcore.dialog.DialogHandler; +import su.nightexpress.nightcore.language.entry.LangItem; +import su.nightexpress.nightcore.language.entry.LangString; +import su.nightexpress.nightcore.language.legacy.LegacyLangString; +import su.nightexpress.nightcore.menu.MenuViewer; +import su.nightexpress.nightcore.menu.item.ItemHandler; +import su.nightexpress.nightcore.menu.item.MenuItem; +import su.nightexpress.nightcore.menu.link.Linked; +import su.nightexpress.nightcore.menu.link.ViewLink; +import su.nightexpress.nightcore.util.ItemUtil; +import su.nightexpress.nightcore.util.text.WrappedMessage; + +public abstract class EditorMenu

extends AbstractMenu

implements Linked { + + protected final ViewLink link; + + public EditorMenu(@NotNull P plugin, @NotNull String title, int size) { + super(plugin, title, size); + this.link = new ViewLink<>(); + } + + @NotNull + @Override + public ViewLink getLink() { + return link; + } + + @NotNull + protected MenuItem addNextPage(int... slots) { + ItemStack item = new ItemStack(Material.PLAYER_HEAD); + ItemUtil.setSkullTexture(item, "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNjgyYWQxYjljYjRkZDIxMjU5YzBkNzVhYTMxNWZmMzg5YzNjZWY3NTJiZTM5NDkzMzgxNjRiYWM4NGE5NmUifX19"); + return this.addItem(item, CoreLang.EDITOR_ITEM_NEXT_PAGE, slots).setHandler(ItemHandler.forNextPage(this)); + } + + @NotNull + protected MenuItem addPreviousPage(int... slots) { + ItemStack item = new ItemStack(Material.PLAYER_HEAD); + ItemUtil.setSkullTexture(item, "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMzdhZWU5YTc1YmYwZGY3ODk3MTgzMDE1Y2NhMGIyYTdkNzU1YzYzMzg4ZmYwMTc1MmQ1ZjQ0MTlmYzY0NSJ9fX0="); + return this.addItem(item, CoreLang.EDITOR_ITEM_PREVIOUS_PAGE, slots).setHandler(ItemHandler.forPreviousPage(this)); + } + + @NotNull + protected MenuItem addReturn(int... slots) { + ItemStack item = new ItemStack(Material.PLAYER_HEAD); + ItemUtil.setSkullTexture(item, "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYTM4NTJiZjYxNmYzMWVkNjdjMzdkZTRiMGJhYTJjNWY4ZDhmY2E4MmU3MmRiY2FmY2JhNjY5NTZhODFjNCJ9fX0="); + return this.addItem(item, CoreLang.EDITOR_ITEM_RETURN, slots); + } + + @NotNull + protected MenuItem addCreation(@NotNull LangItem locale, int... slots) { + ItemStack item = new ItemStack(Material.PLAYER_HEAD); + ItemUtil.setSkullTexture(item, "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNWZmMzE0MzFkNjQ1ODdmZjZlZjk4YzA2NzU4MTA2ODFmOGMxM2JmOTZmNTFkOWNiMDdlZDc4NTJiMmZmZDEifX19"); + return this.addItem(item, locale, slots); + } + + @NotNull + protected MenuItem addExit(int... slots) { + ItemStack item = new ItemStack(Material.PLAYER_HEAD); + ItemUtil.setSkullTexture(item, "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYmViNTg4YjIxYTZmOThhZDFmZjRlMDg1YzU1MmRjYjA1MGVmYzljYWI0MjdmNDYwNDhmMThmYzgwMzQ3NWY3In19fQ=="); + return this.addItem(item, CoreLang.EDITOR_ITEM_CLOSE, slots).setHandler(ItemHandler.forClose(this)); + } + + @NotNull + public MenuItem addItem(@NotNull Material material, @NotNull LangItem locale, int... slots) { + return this.addItem(new ItemStack(material), locale, slots); + } + + @NotNull + public MenuItem addItem(@NotNull ItemStack item, @NotNull LangItem locale, int... slots) { + ItemUtil.editMeta(item, meta -> { + meta.setDisplayName(locale.getLocalizedName()); + meta.setLore(locale.getLocalizedLore()); + meta.addItemFlags(ItemFlag.values()); + }); + + MenuItem menuItem = new MenuItem(item).setPriority(100).setSlots(slots); + this.addItem(menuItem); + return menuItem; + } + + @Deprecated + public void handleInput(@NotNull MenuViewer viewer, @NotNull LegacyLangString prompt, @NotNull DialogHandler handler) { + this.handleInput(viewer.getPlayer(), prompt, handler); + } + + @Deprecated + public void handleInput(@NotNull Player player, @NotNull LegacyLangString prompt, @NotNull DialogHandler handler) { + this.handleInput(player, prompt.getString(), handler); + } + + public void handleInput(@NotNull MenuViewer viewer, @NotNull LangString prompt, @NotNull DialogHandler handler) { + this.handleInput(viewer.getPlayer(), prompt, handler); + } + + public void handleInput(@NotNull Player player, @NotNull LangString prompt, @NotNull DialogHandler handler) { + this.handleInput(player, prompt.getString(), handler); + } + + @NotNull + public Dialog handleInput(@NotNull Player player, @NotNull WrappedMessage prompt, @NotNull DialogHandler handler) { + this.runNextTick(player::closeInventory); + + Dialog dialog = Dialog.create(player, handler); + dialog.prompt(prompt); + return dialog; + } + + @NotNull + public Dialog handleInput(@NotNull Player player, @NotNull String prompt, @NotNull DialogHandler handler) { + this.runNextTick(player::closeInventory); + + Dialog dialog = Dialog.create(player, handler); + dialog.prompt(prompt); + return dialog; + } + + @NotNull + public T getObject(@NotNull MenuViewer viewer) { + return this.getLink().get(viewer); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/menu/item/ItemHandler.java b/src/main/java/su/nightexpress/nightcore/menu/item/ItemHandler.java new file mode 100644 index 0000000..44c17a7 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/menu/item/ItemHandler.java @@ -0,0 +1,95 @@ +package su.nightexpress.nightcore.menu.item; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.menu.api.Menu; +import su.nightexpress.nightcore.menu.MenuViewer; +import su.nightexpress.nightcore.menu.click.ClickAction; +import su.nightexpress.nightcore.util.Placeholders; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; + +public class ItemHandler { + + public static final String RETURN = "return"; + public static final String CLOSE = "close"; + public static final String NEXT_PAGE = "page_next"; + public static final String PREVIOUS_PAGE = "page_previous"; + + private final String name; + private final List clickActions; + private final Predicate visibilityPolicy; + + public ItemHandler() { + this(Placeholders.DEFAULT, null, null); + } + + public ItemHandler(@NotNull String name) { + this(name, null, null); + } + + public ItemHandler(@NotNull String name, @Nullable ClickAction clickAction) { + this(name, clickAction, null); + } + + public ItemHandler(@NotNull String name, @Nullable ClickAction clickAction, @Nullable Predicate visibilityPolicy) { + this.name = name.toLowerCase(); + this.clickActions = new ArrayList<>(); + this.visibilityPolicy = visibilityPolicy; + + if (clickAction != null) { + this.getClickActions().add(clickAction); + } + } + + @NotNull + public static ItemHandler forNextPage(@NotNull Menu menu) { + return new ItemHandler(NEXT_PAGE, + (viewer, event) -> { + if (viewer.getPage() < viewer.getPages()) { + viewer.setPage(viewer.getPage() + 1); + menu.open(viewer.getPlayer()); + } + }, + viewer -> viewer.getPage() < viewer.getPages()); + } + + @NotNull + public static ItemHandler forPreviousPage(@NotNull Menu menu) { + return new ItemHandler(PREVIOUS_PAGE, + (viewer, event) -> { + if (viewer.getPage() > 1) { + viewer.setPage(viewer.getPage() - 1); + menu.open(viewer.getPlayer()); + } + }, + viewer -> viewer.getPage() > 1); + } + + @NotNull + public static ItemHandler forClose(@NotNull Menu menu) { + return new ItemHandler(CLOSE, (viewer, event) -> menu.runNextTick(() -> viewer.getPlayer().closeInventory())); + } + + @NotNull + public static ItemHandler forReturn(@NotNull Menu menu, @NotNull ClickAction action) { + return new ItemHandler(RETURN, action); + } + + @NotNull + public String getName() { + return name; + } + + @NotNull + public List getClickActions() { + return clickActions; + } + + @Nullable + public Predicate getVisibilityPolicy() { + return visibilityPolicy; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/menu/item/ItemOptions.java b/src/main/java/su/nightexpress/nightcore/menu/item/ItemOptions.java new file mode 100644 index 0000000..448dee6 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/menu/item/ItemOptions.java @@ -0,0 +1,115 @@ +package su.nightexpress.nightcore.menu.item; + +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.menu.MenuViewer; + +import java.util.function.BiConsumer; +import java.util.function.Predicate; + +public class ItemOptions { + + private Predicate visibilityPolicy; + private Predicate weakPolicy; + private BiConsumer displayModifier; + + public ItemOptions() { + this(null, null, null); + } + + public ItemOptions(@Nullable Predicate visibilityPolicy, + @Nullable Predicate weakPolicy, + @Nullable BiConsumer displayModifier) { + this.setVisibilityPolicy(visibilityPolicy); + this.setWeakPolicy(weakPolicy); + this.setDisplayModifier(displayModifier); + } + + @NotNull + public static ItemOptions personalWeak(@NotNull Player player) { + Predicate visibility = (viewer -> viewer.getPlayer().getUniqueId().equals(player.getUniqueId())); + Predicate weak = (viewer -> viewer.getPlayer().getUniqueId().equals(player.getUniqueId())); + return new ItemOptions(visibility, weak, null); + } + + @NotNull + public static ItemOptions personalPermanent(@NotNull Player player) { + Predicate visibility = (viewer -> viewer.getPlayer().getUniqueId().equals(player.getUniqueId())); + return new ItemOptions(visibility, null, null); + } + + public boolean canSee(@NotNull MenuViewer viewer) { + Predicate policy = this.getVisibilityPolicy(); + return policy == null || policy.test(viewer); + } + + public boolean canBeDestroyed(@NotNull MenuViewer viewer) { + Predicate policy = this.getWeakPolicy(); + return policy != null && policy.test(viewer); + } + + public void modifyDisplay(@NotNull MenuViewer viewer, @NotNull ItemStack item) { + BiConsumer displayModifier = this.getDisplayModifier(); + if (displayModifier != null) { + displayModifier.accept(viewer, item); + } + } + + @Nullable + public Predicate getVisibilityPolicy() { + return visibilityPolicy; + } + + @NotNull + public ItemOptions setVisibilityPolicy(@Nullable Predicate visibilityPolicy) { + this.visibilityPolicy = visibilityPolicy; + return this; + } + + @NotNull + public ItemOptions addVisibilityPolicy(@NotNull Predicate visibilityPolicy) { + if (this.visibilityPolicy == null) { + this.setVisibilityPolicy(visibilityPolicy); + } + else { + this.visibilityPolicy = this.visibilityPolicy.and(visibilityPolicy); + } + + return this; + } + + @Nullable + public Predicate getWeakPolicy() { + return weakPolicy; + } + + @NotNull + public ItemOptions setWeakPolicy(@Nullable Predicate weakPolicy) { + this.weakPolicy = weakPolicy; + return this; + } + + @Nullable + public BiConsumer getDisplayModifier() { + return displayModifier; + } + + @NotNull + public ItemOptions setDisplayModifier(@Nullable BiConsumer displayModifier) { + this.displayModifier = displayModifier; + return this; + } + + @NotNull + public ItemOptions addDisplayModifier(@NotNull BiConsumer displayModifier) { + if (this.displayModifier == null) { + this.setDisplayModifier(displayModifier); + } + else { + this.displayModifier = this.displayModifier.andThen(displayModifier); + } + return this; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/menu/item/MenuItem.java b/src/main/java/su/nightexpress/nightcore/menu/item/MenuItem.java new file mode 100644 index 0000000..9193352 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/menu/item/MenuItem.java @@ -0,0 +1,113 @@ +package su.nightexpress.nightcore.menu.item; + +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.menu.MenuViewer; +import su.nightexpress.nightcore.menu.click.ClickAction; + +public class MenuItem { + + protected ItemStack itemStack; + protected int priority; + protected int[] slots; + + protected ItemOptions options; + protected ItemHandler handler; + + public MenuItem(@NotNull ItemStack itemStack) { + this(itemStack, new int[0]); + } + + public MenuItem(@NotNull ItemStack itemStack, int... slots) { + this(itemStack, 0, slots); + } + + public MenuItem(@NotNull ItemStack itemStack, int priority, int[] slots) { + this(itemStack, priority, slots, new ItemOptions(), new ItemHandler()); + } + + public MenuItem(@NotNull ItemStack itemStack, int priority, int[] slots, @NotNull ItemOptions options, @NotNull ItemHandler handler) { + this.setItemStack(itemStack); + this.setPriority(priority); + this.setSlots(slots); + this.setOptions(options); + this.setHandler(handler); + } + + @NotNull + public MenuItem copy() { + return new MenuItem(this.getItemStack(), this.getPriority(), this.getSlots(), this.getOptions(), this.getHandler()); + } + + @NotNull + public MenuItem resetOptions() { + this.setOptions(new ItemOptions()); + return this; + } + + public boolean canSee(@NotNull MenuViewer viewer) { + if (!this.getOptions().canSee(viewer)) return false; + + var policy = this.getHandler().getVisibilityPolicy(); + return policy == null || policy.test(viewer); + } + + @NotNull + public ItemStack getItemStack() { + return new ItemStack(this.itemStack); + } + + @NotNull + public MenuItem setItemStack(@NotNull ItemStack itemStack) { + this.itemStack = new ItemStack(itemStack); + return this; + } + + public int getPriority() { + return priority; + } + + @NotNull + public MenuItem setPriority(int priority) { + this.priority = priority; + return this; + } + + public int[] getSlots() { + return slots; + } + + @NotNull + public MenuItem setSlots(int... slots) { + this.slots = slots; + return this; + } + + @NotNull + public ItemOptions getOptions() { + return options; + } + + @NotNull + public MenuItem setOptions(@NotNull ItemOptions options) { + this.options = options; + return this; + } + + @NotNull + public ItemHandler getHandler() { + return handler; + } + + @NotNull + public MenuItem setHandler(@NotNull ItemHandler handler) { + this.handler = handler; + return this; + } + + @NotNull + public MenuItem addClick(@NotNull ClickAction click) { + this.getHandler().getClickActions().add(click); + return this; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/menu/link/Linked.java b/src/main/java/su/nightexpress/nightcore/menu/link/Linked.java new file mode 100644 index 0000000..f8af481 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/menu/link/Linked.java @@ -0,0 +1,21 @@ +package su.nightexpress.nightcore.menu.link; + +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.menu.api.Menu; + +public interface Linked extends Menu { + + @NotNull ViewLink getLink(); + + default boolean open(@NotNull Player player, @NotNull T obj) { + this.getLink().set(player, obj); + + if (!this.open(player)) { + this.getLink().clear(player); + return false; + } + + return true; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/menu/link/ViewLink.java b/src/main/java/su/nightexpress/nightcore/menu/link/ViewLink.java new file mode 100644 index 0000000..3965a9d --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/menu/link/ViewLink.java @@ -0,0 +1,41 @@ +package su.nightexpress.nightcore.menu.link; + +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.menu.MenuViewer; + +import java.util.Map; +import java.util.WeakHashMap; + +public class ViewLink { + + private final Map map; + + public ViewLink() { + this.map = new WeakHashMap<>(); + } + + public void set(@NotNull MenuViewer viewer, @NotNull T object) { + this.set(viewer.getPlayer(), object); + } + + public void set(@NotNull Player viewer, @NotNull T object) { + this.map.put(viewer, object); + } + + public T get(@NotNull MenuViewer viewer) { + return this.get(viewer.getPlayer()); + } + + public T get(@NotNull Player viewer) { + return this.map.get(viewer); + } + + public void clear(@NotNull MenuViewer viewer) { + this.clear(viewer.getPlayer()); + } + + public void clear(@NotNull Player viewer) { + this.map.remove(viewer); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/BenchmarkLoop.java b/src/main/java/su/nightexpress/nightcore/util/BenchmarkLoop.java new file mode 100644 index 0000000..c319160 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/BenchmarkLoop.java @@ -0,0 +1,34 @@ +package su.nightexpress.nightcore.util; + +//@BenchmarkMode({Mode.AverageTime}) +//@OutputTimeUnit(TimeUnit.MILLISECONDS) +//@Fork(value = 1, jvmArgs = {"-Xms2G", "-Xmx2G"}) +public class BenchmarkLoop { + + /*private static final int N = 10_000_000; + + public static void main(String[] args) throws RunnerException { + + Options opt = new OptionsBuilder() + .include(BenchmarkLoop.class.getSimpleName()) + .forks(1) + .build(); + + new Runner(opt).run(); + } + + @Benchmark + public static void first(Blackhole blackhole) { + for (int i = 0; i < N; i++) { + + } + } + + @Benchmark + public static void second(Blackhole blackhole) { + for (int i = 0; i < N; i++) { + + } + }*/ + +} diff --git a/src/main/java/su/nightexpress/nightcore/util/Colorizer.java b/src/main/java/su/nightexpress/nightcore/util/Colorizer.java new file mode 100644 index 0000000..d66abf3 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/Colorizer.java @@ -0,0 +1,154 @@ +package su.nightexpress.nightcore.util; + +import net.md_5.bungee.api.ChatColor; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.regex.TimedMatcher; + +import java.util.List; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class Colorizer { + + public static final Pattern PATTERN_HEX = Pattern.compile("#([A-Fa-f0-9]{6})"); + public static final Pattern PATTERN_GRADIENT = Pattern.compile("(.*?)"); + + @NotNull + public static String apply(@NotNull String str) { + return hex(gradient(legacy(str))); + } + + @NotNull + public static List apply(@NotNull List list) { + list.replaceAll(Colorizer::apply); + return list; + } + + @NotNull + public static Set apply(@NotNull Set set) { + return set.stream().map(Colorizer::apply).collect(Collectors.toSet()); + } + + @NotNull + public static String legacyHex(@NotNull String str) { + return hex(legacy(str)); + } + + @NotNull + public static String legacy(@NotNull String str) { + return ChatColor.translateAlternateColorCodes('&', str); + } + + @NotNull + public static String hex(@NotNull String str) { + TimedMatcher timedMatcher = TimedMatcher.create(PATTERN_HEX, str); + //Matcher matcher = PATTERN_HEX.matcher(str); + StringBuilder buffer = new StringBuilder(str.length() + 4 * 8); + while (timedMatcher.find()) { + Matcher matcher = timedMatcher.getMatcher(); + String group = matcher.group(1); + matcher.appendReplacement(buffer, + ChatColor.COLOR_CHAR + "x" + ChatColor.COLOR_CHAR + group.charAt(0) + + ChatColor.COLOR_CHAR + group.charAt(1) + ChatColor.COLOR_CHAR + group.charAt(2) + + ChatColor.COLOR_CHAR + group.charAt(3) + ChatColor.COLOR_CHAR + group.charAt(4) + + ChatColor.COLOR_CHAR + group.charAt(5)); + } + return timedMatcher.getMatcher().appendTail(buffer).toString(); + } + + private static ChatColor[] createGradient(@NotNull java.awt.Color start, @NotNull java.awt.Color end, int length) { + ChatColor[] colors = new ChatColor[length]; + for (int index = 0; index < length; index++) { + double percent = (double) index / (double) length; + + int red = (int) (start.getRed() + percent * (end.getRed() - start.getRed())); + int green = (int) (start.getGreen() + percent * (end.getGreen() - start.getGreen())); + int blue = (int) (start.getBlue() + percent * (end.getBlue() - start.getBlue())); + + java.awt.Color color = new java.awt.Color(red, green, blue); + colors[index] = ChatColor.of(color); + } + return colors; + } + + @NotNull + public static String gradient(@NotNull String string) { + TimedMatcher timedMatcher = TimedMatcher.create(PATTERN_GRADIENT, string); + //Matcher matcher = PATTERN_GRADIENT.matcher(string); + while (timedMatcher.find()) { + Matcher matcher = timedMatcher.getMatcher(); + String start = matcher.group(1); + String end = matcher.group(3); + String content = matcher.group(2); + + java.awt.Color colorStart = new java.awt.Color(Integer.parseInt(start, 16)); + java.awt.Color colorEnd = new java.awt.Color(Integer.parseInt(end, 16)); + ChatColor[] colors = createGradient(colorStart, colorEnd, strip(content).length()); + + StringBuilder gradiented = new StringBuilder(); + StringBuilder specialColors = new StringBuilder(); + char[] characters = content.toCharArray(); + int outIndex = 0; + for (int index = 0; index < characters.length; index++) { + if (characters[index] == ChatColor.COLOR_CHAR) { + if (index + 1 < characters.length) { + if (characters[index + 1] == 'r') { + specialColors.setLength(0); + } + else { + specialColors.append(characters[index]); + specialColors.append(characters[index + 1]); + } + index++; + } + else gradiented.append(colors[outIndex++]).append(specialColors).append(characters[index]); + } + else gradiented.append(colors[outIndex++]).append(specialColors).append(characters[index]); + } + + string = string.replace(matcher.group(0), gradiented.toString()); + } + return string; + } + + @NotNull + public static String plain(@NotNull String str) { + return plainLegacy(plainHex(str)); + } + + @NotNull + public static String plainLegacy(@NotNull String str) { + return str.replace(ChatColor.COLOR_CHAR, '&'); + } + + @NotNull + public static String plainHex(@NotNull String str) { + StringBuilder buffer = new StringBuilder(str); + + int index; + while ((index = buffer.toString().indexOf(ChatColor.COLOR_CHAR + "x")) >= 0) { + int count = 0; + buffer.replace(index, index + 2, "#"); + + for (int point = index + 1; count < 6; point += 1) { + buffer.deleteCharAt(point); + count++; + } + } + + return buffer.toString(); + } + + @NotNull + public static String strip(@NotNull String str) { + String stripped = ChatColor.stripColor(str); + return stripped == null ? "" : stripped; + } + + @NotNull + public static String restrip(@NotNull String str) { + return strip(apply(str)); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/Colors.java b/src/main/java/su/nightexpress/nightcore/util/Colors.java new file mode 100644 index 0000000..5ac3c48 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/Colors.java @@ -0,0 +1,29 @@ +package su.nightexpress.nightcore.util; + +@Deprecated +public class Colors { + + public static final String BOLD = "&l"; + public static final String WHITE = "#e8f2f2"; + public static final String GRAY = "#aaa8a8"; + public static final String GREEN = "#74ea31"; + public static final String YELLOW = "#ead931"; + public static final String ORANGE = "#ea9631"; + public static final String RED = "#ea3131"; + public static final String BLUE = "#3196ea"; + public static final String CYAN = "#31eace"; + public static final String PURPLE = "#bd31ea"; + public static final String PINK = "#ea31b2"; + + public static final String DARK_GRAY = "#6c6c62"; + public static final String LIGHT_GRAY = "#d4d9d8"; + public static final String LIGHT_GREEN = "#aefd5e"; + public static final String LIGHT_YELLOW = "#ffeea2"; + public static final String LIGHT_ORANGE = "#fdba5e"; + public static final String LIGHT_RED = "#fd5e5e"; + public static final String LIGHT_BLUE = "#5e9dfd"; + public static final String LIGHT_CYAN = "#5edefd"; + public static final String LIGHT_PURPLE = "#e39fff"; + public static final String LIGHT_PINK = "#fd8ddb"; + +} diff --git a/src/main/java/su/nightexpress/nightcore/util/CommandUtil.java b/src/main/java/su/nightexpress/nightcore/util/CommandUtil.java new file mode 100644 index 0000000..74f47b0 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/CommandUtil.java @@ -0,0 +1,85 @@ +package su.nightexpress.nightcore.util; + +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.SimpleCommandMap; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.command.api.NightPluginCommand; +import su.nightexpress.nightcore.command.impl.WrappedCommand; + +import java.util.*; + +public class CommandUtil { + + private static final String FIELD_COMMAND_MAP = "commandMap"; + private static final String FIELD_KNOWN_COMMANDS = "knownCommands"; + + private static final SimpleCommandMap COMMAND_MAP = getCommandMap(); + + private static SimpleCommandMap getCommandMap() { + return (SimpleCommandMap) Reflex.getFieldValue(Bukkit.getServer(), FIELD_COMMAND_MAP); + } + + public static void register(@NotNull Plugin plugin, @NotNull NightPluginCommand command) { + WrappedCommand wrappedCommand = new WrappedCommand(plugin, command); + if (COMMAND_MAP.register(plugin.getName(), wrappedCommand)) { + command.setBackend(wrappedCommand); + } + } + + /*public static void syncCommands() { + // Fix tab completer when registerd on runtime + Server server = Bukkit.getServer(); + Method method = Reflex.getMethod(server.getClass(), "syncCommands"); + if (method == null) return; + + Reflex.invokeMethod(method, server); + }*/ + + @SuppressWarnings("unchecked") + public static boolean unregister(@NotNull String name) { + Command command = getCommand(name).orElse(null); + if (command == null) return false; + + Map knownCommands = (HashMap) Reflex.getFieldValue(COMMAND_MAP, FIELD_KNOWN_COMMANDS); + if (knownCommands == null) return false; + if (!command.unregister(COMMAND_MAP)) return false; + + return knownCommands.keySet().removeIf(key -> key.equalsIgnoreCase(command.getName()) || command.getAliases().contains(key)); + } + + @NotNull + public static Set getAliases(@NotNull String name) { + return getAliases(name, false); + } + + @NotNull + public static Set getAliases(@NotNull String name, boolean inclusive) { + Command command = getCommand(name).orElse(null); + if (command == null) return Collections.emptySet(); + + Set aliases = new HashSet<>(command.getAliases()); + if (inclusive) aliases.add(command.getName()); + return aliases; + } + + @NotNull + public static Optional getCommand(@NotNull String name) { + return COMMAND_MAP.getCommands().stream() + .filter(command -> command.getLabel().equalsIgnoreCase(name) || command.getAliases().contains(name)) + .findFirst(); + } + + @NotNull + public static String getCommandName(@NotNull String str) { + String name = Colorizer.strip(str).split(" ")[0].substring(1); + + String[] pluginPrefix = name.split(":"); + if (pluginPrefix.length == 2) { + name = pluginPrefix[1]; + } + + return name; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/EntityUtil.java b/src/main/java/su/nightexpress/nightcore/util/EntityUtil.java new file mode 100644 index 0000000..a1cb8b9 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/EntityUtil.java @@ -0,0 +1,80 @@ +package su.nightexpress.nightcore.util; + +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeInstance; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.inventory.EntityEquipment; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class EntityUtil { + + /*@Deprecated + public static boolean isNPC(@NotNull Entity entity) { + return entity.hasMetadata("NPC"); + }*/ + + public static double getAttribute(@NotNull LivingEntity entity, @NotNull Attribute attribute) { + AttributeInstance instance = entity.getAttribute(attribute); + return instance == null ? 0D : instance.getValue(); + } + + public static double getAttributeBase(@NotNull LivingEntity entity, @NotNull Attribute attribute) { + AttributeInstance instance = entity.getAttribute(attribute); + return instance == null ? 0D : instance.getBaseValue(); + } + + @NotNull + public static Map getEquippedItems(@NotNull LivingEntity entity) { + return getEquippedItems(entity, EquipmentSlot.values()); + } + + @NotNull + public static Map getEquippedItems(@NotNull LivingEntity entity, @NotNull EquipmentSlot... slots) { + EntityEquipment equipment = entity.getEquipment(); + if (equipment == null) return Collections.emptyMap(); + + Map map = new HashMap<>(); + for (EquipmentSlot slot : slots) { + map.put(slot, equipment.getItem(slot)); + } + return map; + } + + @NotNull + public static Map getEquippedHands(@NotNull LivingEntity entity) { + return getEquippedItems(entity, EquipmentSlot.HAND, EquipmentSlot.OFF_HAND); + } + + @NotNull + public static Map getEquippedArmor(@NotNull LivingEntity entity) { + return getEquippedItems(entity, EquipmentSlot.FEET, EquipmentSlot.LEGS, EquipmentSlot.CHEST, EquipmentSlot.HEAD); + } + + @Nullable + public static BlockFace getDirection(@NotNull Entity entity) { + float yaw = Math.round(entity.getLocation().getYaw() / 90F); + + if ((yaw == -4.0F) || (yaw == 0.0F) || (yaw == 4.0F)) { + return BlockFace.SOUTH; + } + if ((yaw == -1.0F) || (yaw == 3.0F)) { + return BlockFace.EAST; + } + if ((yaw == -2.0F) || (yaw == 2.0F)) { + return BlockFace.NORTH; + } + if ((yaw == -3.0F) || (yaw == 1.0F)) { + return BlockFace.WEST; + } + return null; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/FileUtil.java b/src/main/java/su/nightexpress/nightcore/util/FileUtil.java new file mode 100644 index 0000000..8bcccb4 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/FileUtil.java @@ -0,0 +1,91 @@ +package su.nightexpress.nightcore.util; + +import org.jetbrains.annotations.NotNull; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; + +public class FileUtil { + + public static void copy(@NotNull InputStream inputStream, @NotNull File file) { + try { + FileOutputStream outputStream = new FileOutputStream(file); + byte[] array = new byte[1024]; + int read; + while ((read = inputStream.read(array)) > 0) { + outputStream.write(array, 0, read); + } + outputStream.close(); + inputStream.close(); + } + catch (IOException ex) { + ex.printStackTrace(); + } + } + + public static boolean create(@NotNull File file) { + if (file.exists()) return false; + + File parent = file.getParentFile(); + if (parent == null) return false; + + parent.mkdirs(); + try { + return file.createNewFile(); + } + catch (IOException e) { + e.printStackTrace(); + return false; + } + } + + @NotNull + public static List getFiles(@NotNull String path, boolean deep) { + List files = new ArrayList<>(); + + File folder = new File(path); + File[] listOfFiles = folder.listFiles(); + if (listOfFiles == null) return files; + + for (File file : listOfFiles) { + if (file.isFile()) { + files.add(file); + } + else if (file.isDirectory() && deep) { + files.addAll(getFiles(file.getPath(), true)); + } + } + return files; + } + + @NotNull + public static List getFolders(@NotNull String path) { + File folder = new File(path); + File[] listOfFiles = folder.listFiles(); + if (listOfFiles == null) return Collections.emptyList(); + + return Stream.of(listOfFiles).filter(File::isDirectory).toList(); + } + + public static boolean deleteRecursive(@NotNull String path) { + return deleteRecursive(new File(path)); + } + + public static boolean deleteRecursive(@NotNull File dir) { + if (!dir.exists()) return false; + + File[] inside = dir.listFiles(); + if (inside != null) { + for (File file : inside) { + deleteRecursive(file); + } + } + return dir.delete(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/ItemReplacer.java b/src/main/java/su/nightexpress/nightcore/util/ItemReplacer.java new file mode 100644 index 0000000..c5b2514 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/ItemReplacer.java @@ -0,0 +1,246 @@ +package su.nightexpress.nightcore.util; + +import com.google.common.base.Splitter; +import me.clip.placeholderapi.PlaceholderAPI; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.language.entry.LangItem; +import su.nightexpress.nightcore.util.placeholder.PlaceholderMap; +import su.nightexpress.nightcore.util.text.NightMessage; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; + +public class ItemReplacer { + + private final ItemStack item; + private final ItemMeta meta; + private final PlaceholderMap placeholderMap; + + private String displayName; + private String lore; + + private boolean trimLore; + private boolean hideFlags; + + public ItemReplacer(@NotNull ItemStack item) { + this(item, item.getItemMeta()); + } + + public ItemReplacer(@NotNull ItemMeta meta) { + this(null, meta); + } + + public ItemReplacer(@Nullable ItemStack item, @Nullable ItemMeta meta) { + this.item = item; + this.meta = meta; + this.placeholderMap = new PlaceholderMap(); + } + + @NotNull + public ItemReplacer readMeta() { + if (this.hasMeta()) { + this.setDisplayName(this.meta.getDisplayName()); + this.setLore(this.meta.getLore()); + } + return this; + } + + @NotNull + public ItemReplacer readLocale(@NotNull LangItem locale) { + if (this.hasMeta()) { + this.setDisplayName(locale.getLocalizedName()); + this.setLore(locale.getLocalizedLore()); + } + return this; + } + + public void writeMeta() { + if (!this.hasMeta()) return; + + this.replace(this.placeholderMap.replacer()); + + this.meta.setDisplayName(this.getDisplayName() == null ? null : NightMessage.asLegacy(this.getDisplayName())); + this.meta.setLore(NightMessage.asLegacy(this.packTrimmedLore())); + + if (this.isHideFlags()) { + this.meta.addItemFlags(ItemFlag.values()); + } + + if (this.hasItem()) { + this.item.setItemMeta(this.meta); + } + } + + @NotNull + public static ItemReplacer create(@NotNull ItemStack item) { + return new ItemReplacer(item); + } + + @NotNull + public static ItemReplacer create(@NotNull ItemMeta meta) { + return new ItemReplacer(meta); + } + + public static void replace(@NotNull ItemStack item, @NotNull UnaryOperator replacer) { + create(item).trimmed().readMeta().replace(replacer).writeMeta(); + } + + public static void replace(@NotNull ItemMeta meta, @NotNull UnaryOperator replacer) { + create(meta).trimmed().readMeta().replace(replacer).writeMeta(); + } + + public boolean hasMeta() { + return this.meta != null; + } + + public boolean hasItem() { + return this.item != null; + } + + public boolean isTrimLore() { + return trimLore; + } + + public boolean isHideFlags() { + return hideFlags; + } + + @NotNull + public ItemReplacer trimmed() { + this.setTrimLore(true); + return this; + } + + @NotNull + public ItemReplacer hideFlags() { + this.setHideFlags(true); + return this; + } + + @NotNull + public ItemReplacer setHideFlags(boolean hideFlags) { + this.hideFlags = hideFlags; + return this; + } + + @NotNull + public ItemReplacer setTrimLore(boolean trimLore) { + this.trimLore = trimLore; + return this; + } + + @NotNull + public ItemReplacer replace(@NotNull String placeholder, @NotNull String value) { + return this.replace(placeholder, () -> value); + } + + @NotNull + public ItemReplacer replace(@NotNull String placeholder, @NotNull Supplier value) { + this.placeholderMap.add(placeholder, value); + return this; + } + + @NotNull + public ItemReplacer replace(@NotNull PlaceholderMap... placeholderMaps) { + for (PlaceholderMap placeholder : placeholderMaps) { + this.placeholderMap.add(placeholder); + } + return this; + } + + @NotNull + public ItemReplacer replace(@NotNull UnaryOperator replacer) { + if (this.getDisplayName() != null) { + this.setDisplayName(replacer.apply(this.getDisplayName())); + } + + if (this.getLore() != null) { + this.setLore(replacer.apply(this.getLore())); + } + return this; + } + + @NotNull + public ItemReplacer replacePlaceholderAPI(@NotNull Player player) { + if (!Plugins.hasPlaceholderAPI()) return this; + + this.replace(str -> PlaceholderAPI.setPlaceholders(player, str)); + return this; + } + + @NotNull + public ItemReplacer replaceLoreExact(@NotNull String placeholder, @NotNull List replacer) { + if (this.getLore() == null) return this; + + this.setLore(Lists.replace(this.packLore(), placeholder, replacer)); + return this; + } + + @NotNull + public ItemReplacer replaceLoreTrail(@NotNull String placeholder, @NotNull List replacer) { + if (this.getLore() == null) return this; + + List loreReplaced = new ArrayList<>(); + for (String lineHas : this.packLore()) { + if (lineHas.contains(placeholder)) { + replacer.forEach(lineRep -> { + loreReplaced.add(lineHas.replace(placeholder, lineRep)); + }); + continue; + } + loreReplaced.add(lineHas); + } + this.setLore(loreReplaced); + return this; + } + + @NotNull + public List packLore() { + if (this.getLore() == null) return new ArrayList<>(); + + return Splitter.on("\n").splitToList(this.getLore()); + } + + @NotNull + public List packTrimmedLore() { + List lore = this.packLore(); + if (this.isTrimLore()) { + lore = Lists.stripEmpty(lore); + } + return lore; + } + + @Nullable + public String getDisplayName() { + return displayName; + } + + @NotNull + public ItemReplacer setDisplayName(@Nullable String displayName) { + this.displayName = displayName; + return this; + } + + @Nullable + public String getLore() { + return lore; + } + + @NotNull + public ItemReplacer setLore(@Nullable List lore) { + return this.setLore(lore == null ? null : String.join("\n", lore)); + } + + @NotNull + public ItemReplacer setLore(@Nullable String lore) { + this.lore = lore; + return this; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java b/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java new file mode 100644 index 0000000..3452d02 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/ItemUtil.java @@ -0,0 +1,331 @@ +package su.nightexpress.nightcore.util; + +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.Tag; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.SkullMeta; +import org.bukkit.profile.PlayerProfile; +import org.bukkit.profile.PlayerTextures; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.language.LangAssets; + +import java.io.*; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.math.BigInteger; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.*; +import java.util.function.Consumer; + +public class ItemUtil { + + private static final String VERSION = Version.getProtocol(); + private static final String TEXTURES_HOST = "http://textures.minecraft.net/texture/"; + + private static final Class NBT_TAG_COMPOUND = Reflex.getClass("net.minecraft.nbt", "NBTTagCompound"); + private static final Class NMS_ITEM = Reflex.getClass("net.minecraft.world.item", "ItemStack"); + private static final Class CRAFT_ITEM_STACK = Reflex.getClass("org.bukkit.craftbukkit." + VERSION + ".inventory", "CraftItemStack"); + private static final Class NBT_IO = Reflex.getClass("net.minecraft.nbt", "NBTCompressedStreamTools"); + + private static final Constructor NBT_TAG_COMPOUND_NEW = Reflex.getConstructor(NBT_TAG_COMPOUND); + + private static final Method AS_NMS_COPY = Reflex.getMethod(CRAFT_ITEM_STACK, "asNMSCopy", ItemStack.class); + private static final Method AS_BUKKIT_COPY = Reflex.getMethod(CRAFT_ITEM_STACK, "asBukkitCopy", NMS_ITEM); + + private static final Method NMS_ITEM_OF = Reflex.getMethod(NMS_ITEM, "a", NBT_TAG_COMPOUND); + private static final Method NMS_SAVE = Reflex.getMethod(NMS_ITEM, "b", NBT_TAG_COMPOUND); + + private static final Method NBT_IO_WRITE = Reflex.getMethod(NBT_IO, "a", NBT_TAG_COMPOUND, DataOutput.class); + private static final Method NBT_IO_READ = Reflex.getMethod(NBT_IO, "a", DataInput.class); + + @NotNull + public static String getItemName(@NotNull ItemStack item) { + ItemMeta meta = item.getItemMeta(); + return (meta == null || !meta.hasDisplayName()) ? LangAssets.get(item.getType()) : meta.getDisplayName(); + } + + public static void editMeta(@NotNull ItemStack item, @NotNull Consumer function) { + ItemMeta meta = item.getItemMeta(); + if (meta == null) return; + + function.accept(meta); + item.setItemMeta(meta); + } + + @NotNull + public static List getLore(@NotNull ItemStack item) { + ItemMeta meta = item.getItemMeta(); + return (meta == null || meta.getLore() == null) ? new ArrayList<>() : meta.getLore(); + } + + @NotNull + @Deprecated + public static ItemStack createCustomHead(@NotNull String texture) { + ItemStack item = new ItemStack(Material.PLAYER_HEAD); + setSkullTexture(item, texture); + return item; + } + + @NotNull + public static ItemStack getSkinHead(@NotNull String texture) { + ItemStack item = new ItemStack(Material.PLAYER_HEAD); + setHeadSkin(item, texture); + return item; + } + + public static void setHeadSkin(@NotNull ItemStack item, @NotNull String urlData) { + if (item.getType() != Material.PLAYER_HEAD) return; + if (!(item.getItemMeta() instanceof SkullMeta meta)) return; + + UUID uuid = UUID.nameUUIDFromBytes(urlData.getBytes()); + PlayerProfile profile = Bukkit.createPlayerProfile(uuid); + + if (!urlData.startsWith(TEXTURES_HOST)) { + urlData = TEXTURES_HOST + urlData; + } + + try { + URL url = new URL(urlData); + PlayerTextures textures = profile.getTextures(); + textures.setSkin(url); + profile.setTextures(textures); + meta.setOwnerProfile(profile); + } + catch (MalformedURLException exception) { + exception.printStackTrace(); + } + } + + @Nullable + public static String getHeadSkin(@NotNull ItemStack item) { + if (item.getType() != Material.PLAYER_HEAD) return null; + if (!(item.getItemMeta() instanceof SkullMeta meta)) return null; + + PlayerProfile profile = meta.getOwnerProfile(); + if (profile == null) return null; + + URL skin = profile.getTextures().getSkin(); + if (skin == null) return null; + + String raw = skin.toString(); + return raw.substring(TEXTURES_HOST.length()); + } + + @Deprecated + public static void setSkullTexture(@NotNull ItemStack item, @NotNull String value) { + if (item.getType() != Material.PLAYER_HEAD) return; + if (!(item.getItemMeta() instanceof SkullMeta meta)) return; + + UUID uuid = UUID.nameUUIDFromBytes(value.getBytes()); + GameProfile profile = new GameProfile(uuid, "null"); + profile.getProperties().put("textures", new Property("textures", value)); + + Method method = Reflex.getMethod(meta.getClass(), "setProfile", GameProfile.class); + if (method != null) { + Reflex.invokeMethod(method, meta, profile); + } + else { + Reflex.setFieldValue(meta, "profile", profile); + } + + item.setItemMeta(meta); + } + + @Nullable + @Deprecated + public static String getSkullTexture(@NotNull ItemStack item) { + if (item.getType() != Material.PLAYER_HEAD) return null; + + SkullMeta meta = (SkullMeta) item.getItemMeta(); + if (meta == null) return null; + + GameProfile profile = (GameProfile) Reflex.getFieldValue(meta, "profile"); + if (profile == null) return null; + + Collection properties = profile.getProperties().get("textures"); + Optional opt = properties.stream().filter(prop -> { + String name; + if (Version.isAtLeast(Version.V1_20_R2)) { + name = prop.name(); + } + else { + name = (String) Reflex.getFieldValue(profile, "name"); + } + return name != null && name.equalsIgnoreCase("textures"); + }).findFirst(); + + if (opt.isEmpty()) return null; + + if (Version.isAtLeast(Version.V1_20_R2)) { + return opt.get().value(); + } + else { + return (String) Reflex.getFieldValue(opt.get(), "value"); + } + } + + public static boolean isTool(@NotNull ItemStack item) { + return isAxe(item) || isHoe(item) || isPickaxe(item) || isShovel(item); + } + + public static boolean isArmor(@NotNull ItemStack item) { + return isHelmet(item) || isChestplate(item) || isLeggings(item) || isBoots(item); + } + + public static boolean isBow(@NotNull ItemStack item) { + return item.getType() == Material.BOW || item.getType() == Material.CROSSBOW; + } + + public static boolean isSword(@NotNull ItemStack item) { + if (Version.isAtLeast(Version.V1_19_R3)) { + return Tag.ITEMS_SWORDS.isTagged(item.getType()); + } + + Material material = item.getType(); + return material == Material.DIAMOND_SWORD || material == Material.GOLDEN_SWORD + || material == Material.IRON_SWORD || material == Material.NETHERITE_SWORD + || material == Material.STONE_SWORD || material == Material.WOODEN_SWORD; + } + + public static boolean isAxe(@NotNull ItemStack item) { + if (Version.isAtLeast(Version.V1_19_R3)) { + return Tag.ITEMS_AXES.isTagged(item.getType()); + } + + Material material = item.getType(); + return material == Material.DIAMOND_AXE || material == Material.GOLDEN_AXE + || material == Material.IRON_AXE || material == Material.NETHERITE_AXE + || material == Material.STONE_AXE || material == Material.WOODEN_AXE; + } + + public static boolean isTrident(@NotNull ItemStack item) { + return item.getType() == Material.TRIDENT; + } + + public static boolean isPickaxe(@NotNull ItemStack item) { + if (Version.isAtLeast(Version.V1_19_R3)) { + return Tag.ITEMS_PICKAXES.isTagged(item.getType()); + } + + Material material = item.getType(); + return material == Material.DIAMOND_PICKAXE || material == Material.GOLDEN_PICKAXE + || material == Material.IRON_PICKAXE || material == Material.NETHERITE_PICKAXE + || material == Material.STONE_PICKAXE || material == Material.WOODEN_PICKAXE; + } + + public static boolean isShovel(@NotNull ItemStack item) { + if (Version.isAtLeast(Version.V1_19_R3)) { + return Tag.ITEMS_SHOVELS.isTagged(item.getType()); + } + + Material material = item.getType(); + return material == Material.DIAMOND_SHOVEL || material == Material.GOLDEN_SHOVEL + || material == Material.IRON_SHOVEL || material == Material.NETHERITE_SHOVEL + || material == Material.STONE_SHOVEL || material == Material.WOODEN_SHOVEL; + } + + public static boolean isHoe(@NotNull ItemStack item) { + if (Version.isAtLeast(Version.V1_19_R3)) { + return Tag.ITEMS_HOES.isTagged(item.getType()); + } + + Material material = item.getType(); + return material == Material.DIAMOND_HOE || material == Material.GOLDEN_HOE + || material == Material.IRON_HOE || material == Material.NETHERITE_HOE + || material == Material.STONE_HOE || material == Material.WOODEN_HOE; + } + + public static boolean isElytra(@NotNull ItemStack item) { + return item.getType() == Material.ELYTRA; + } + + public static boolean isFishingRod(@NotNull ItemStack item) { + return item.getType() == Material.FISHING_ROD; + } + + public static boolean isHelmet(@NotNull ItemStack item) { + return getEquipmentSlot(item) == EquipmentSlot.HEAD; + } + + public static boolean isChestplate(@NotNull ItemStack item) { + return getEquipmentSlot(item) == EquipmentSlot.CHEST; + } + + public static boolean isLeggings(@NotNull ItemStack item) { + return getEquipmentSlot(item) == EquipmentSlot.LEGS; + } + + public static boolean isBoots(@NotNull ItemStack item) { + return getEquipmentSlot(item) == EquipmentSlot.FEET; + } + + @NotNull + public static EquipmentSlot getEquipmentSlot(@NotNull ItemStack item) { + Material material = item.getType(); + return material.isItem() ? material.getEquipmentSlot() : EquipmentSlot.HAND; + } + + @Nullable + public static String compress(@NotNull ItemStack item) { + if (NBT_TAG_COMPOUND_NEW == null || AS_NMS_COPY == null || NMS_SAVE == null || NBT_IO_WRITE == null) { + throw new UnsupportedOperationException("Unsupported server version!"); + } + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + DataOutputStream dataOutput = new DataOutputStream(outputStream); + + try { + Object nbtTagCompoundItem = NBT_TAG_COMPOUND_NEW.newInstance(); + Object nmsItem = AS_NMS_COPY.invoke(null, item); + NMS_SAVE.invoke(nmsItem, nbtTagCompoundItem); + NBT_IO_WRITE.invoke(null, nbtTagCompoundItem, dataOutput); + return new BigInteger(1, outputStream.toByteArray()).toString(32); + } + catch (ReflectiveOperationException e) { + e.printStackTrace(); + return null; + } + } + + @Nullable + public static ItemStack decompress(@NotNull String compressed) { + if (NBT_IO_READ == null || NMS_ITEM_OF == null || AS_BUKKIT_COPY == null) { + throw new UnsupportedOperationException("Unsupported server version!"); + } + + ByteArrayInputStream inputStream = new ByteArrayInputStream(new BigInteger(compressed, 32).toByteArray()); + + Object nbtTagCompoundRoot; + try { + nbtTagCompoundRoot = NBT_IO_READ.invoke(null, new DataInputStream(inputStream)); + Object nmsItem = NMS_ITEM_OF.invoke(null, nbtTagCompoundRoot); + return (ItemStack) AS_BUKKIT_COPY.invoke(null, nmsItem); + } + catch (ReflectiveOperationException e) { + e.printStackTrace(); + return null; + } + } + + @NotNull + public static List compress(@NotNull ItemStack[] items) { + return compress(Arrays.asList(items)); + } + + @NotNull + public static List compress(@NotNull List items) { + return new ArrayList<>(items.stream().map(ItemUtil::compress).filter(Objects::nonNull).toList()); + } + + public static ItemStack[] decompress(@NotNull List list) { + List items = list.stream().map(ItemUtil::decompress).filter(Objects::nonNull).toList(); + return items.toArray(new ItemStack[list.size()]); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/Lists.java b/src/main/java/su/nightexpress/nightcore/util/Lists.java new file mode 100644 index 0000000..b8d8f44 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/Lists.java @@ -0,0 +1,234 @@ +package su.nightexpress.nightcore.util; + +import org.bukkit.generator.WorldInfo; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.*; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class Lists { + + @NotNull + public static List worldNames() { + return Plugins.CORE.getServer().getWorlds().stream().map(WorldInfo::getName).toList(); + } + + public static int indexOf(Object[] array, @NotNull Object objectToFind) { + return indexOf(array, objectToFind, 0); + } + + public static int indexOf(Object[] array, @NotNull Object objectToFind, int startIndex) { + if (array == null || array.length == 0) return -1; + if (!array.getClass().getComponentType().isInstance(objectToFind)) return -1; + + if (startIndex < 0) startIndex = 0; + + int index; + for (index = startIndex; index < array.length; ++index) { + if (objectToFind.equals(array[index])) { + return index; + } + } + + return -1; + } + + public static boolean contains(Object[] array, Object objectToFind) { + return indexOf(array, objectToFind) != -1; + } + + public static int indexOf(int[] array, int valueToFind) { + return indexOf(array, valueToFind, 0); + } + + public static int indexOf(int[] array, int valueToFind, int startIndex) { + if (array == null || array.length == 0) return -1; + + if (startIndex < 0) startIndex = 0; + + for (int index = startIndex; index < array.length; ++index) { + if (valueToFind == array[index]) { + return index; + } + } + + return -1; + } + + public static boolean contains(int[] array, int valueToFind) { + return indexOf(array, valueToFind) != -1; + } + + @NotNull + public static List> split(@NotNull List list, int targetSize) { + List> lists = new ArrayList<>(); + if (targetSize <= 0) return lists; + + for (int index = 0; index < list.size(); index += targetSize) { + lists.add(list.subList(index, Math.min(index + targetSize, list.size()))); + } + return lists; + } + + @NotNull + public static List replace(@NotNull List origin, @NotNull String var, String... with) { + return replace(origin, var, Arrays.asList(with)); + } + + @NotNull + public static List replace(@NotNull List origin, @NotNull String var, @NotNull List with) { + List replaced = new ArrayList<>(); + for (String line : origin) { + if (line.equalsIgnoreCase(var)) { + replaced.addAll(with); + } + else replaced.add(line); + } + return replaced; + } + + /** + * @param original List to remove empty lines from. + * @return A list with no multiple empty lines in a row. + */ + @NotNull + public static List stripEmpty(@NotNull List original) { + List stripped = new ArrayList<>(); + for (int index = 0; index < original.size(); index++) { + String line = original.get(index); + if (line.isEmpty()) { + String last = stripped.isEmpty() ? null : stripped.get(stripped.size() - 1); + if (last == null || last.isEmpty() || index == (original.size() - 1)) continue; + } + stripped.add(line); + } + return stripped; + } + + @NotNull + public static List getSequentialMatches(@NotNull List results, @NotNull String input) { + char[] chars = input.toCharArray(); + List goods = new ArrayList<>(); + + Result: + for (String sub : results) { + int lastIndex = -1; + + for (char letter : chars) { + int index = sub.indexOf(letter, lastIndex == -1 ? 0 : lastIndex); + if (index <= lastIndex) { + continue Result; + } + lastIndex = index; + } + goods.add(sub); + } + return goods; + } + + @NotNull + public static > Map sortAscent(@NotNull Map map) { + return sort(map, Map.Entry.comparingByValue()); + } + + @NotNull + public static > Map sortDescent(@NotNull Map map) { + return sort(map, Collections.reverseOrder(Map.Entry.comparingByValue())); + } + + @SafeVarargs + @NotNull + public static List newList(T... values) { + List list = new ArrayList<>(); + Collections.addAll(list, values); + return list; + } + + @SafeVarargs + @NotNull + public static Set newSet(T... values) { + Set list = new HashSet<>(); + Collections.addAll(list, values); + return list; + } + + @NotNull + public static > Map sort(@NotNull Map map, @NotNull Comparator> comparator) { + return new LinkedList<>(map.entrySet()).stream().sorted(comparator) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (old, nev) -> nev, LinkedHashMap::new)); + } + + @NotNull + public static List getEnums(@NotNull Class> clazz) { + return new ArrayList<>(Stream.of(clazz.getEnumConstants()).map(Object::toString).toList()); + } + + @NotNull + public static String getEnums(@NotNull Class> clazz, @NotNull String delimiter) { + return String.join(delimiter, getEnums(clazz)); + } + + @NotNull + public static > T next(@NotNull Enum numeration) { + return shifted(numeration, 1); + } + + @NotNull + public static > T next(@NotNull Enum numeration, @NotNull Predicate predicate) { + return shifted(numeration, 1, predicate); + } + + @NotNull + public static > T previous(@NotNull Enum numeration) { + return shifted(numeration, -1); + } + + @NotNull + public static > T previous(@NotNull Enum numeration, @NotNull Predicate predicate) { + return shifted(numeration, -1, predicate); + } + + @NotNull + public static > T shifted(@NotNull Enum numeration, int shift) { + return shifted(numeration, shift, null); + } + + @NotNull + private static > T shifted(@NotNull Enum numeration, int shift, @Nullable Predicate predicate) { + T[] values = numeration.getDeclaringClass().getEnumConstants(); + return shifted(values, numeration/*.ordinal()*/, shift, predicate); + } + + @NotNull + private static > T shifted(T[] values, @NotNull Enum origin, int shift, @Nullable Predicate predicate) { + if (predicate != null) { + T source = origin.getDeclaringClass().cast(origin); + List filtered = new ArrayList<>(Arrays.asList(values)); + filtered.removeIf(num -> !predicate.test(num) && num != source); + + int currentIndex = filtered.indexOf(source); + //List filtered = Stream.of(values).filter(predicate).toList(); + if (currentIndex < 0 | filtered.isEmpty()) return source;//values[currentIndex]; + + return shifted(filtered, currentIndex, shift); + } + return shifted(values, origin.ordinal(), shift); + } + + @NotNull + public static T shifted(T[] values, int currentIndex, int shift) { + int index = currentIndex + shift; + return values[index >= values.length || index < 0 ? 0 : index]; + } + + @NotNull + public static T shifted(@NotNull List values, int currentIndex, int shift) { + int index = currentIndex + shift; + if (index < 0) return values.get(values.size() - 1); + + return values.get(index >= values.size() ? 0 : index); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/LocationUtil.java b/src/main/java/su/nightexpress/nightcore/util/LocationUtil.java new file mode 100644 index 0000000..c99ee07 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/LocationUtil.java @@ -0,0 +1,81 @@ +package su.nightexpress.nightcore.util; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Objects; + +public class LocationUtil { + + @Nullable + public static String serialize(@NotNull Location location) { + World world = location.getWorld(); + if (world == null) return null; + + return location.getX() + "," + location.getY() + "," + location.getZ() + "," + location.getPitch() + "," + location.getYaw() + "," + world.getName(); + } + + @NotNull + public static List serialize(@NotNull Collection list) { + return new ArrayList<>(list.stream().map(LocationUtil::serialize).filter(Objects::nonNull).toList()); + } + + @Nullable + public static Location deserialize(@NotNull String raw) { + String[] split = raw.split(","); + if (split.length != 6) return null; + + World world = Bukkit.getWorld(split[5]); + if (world == null) { + Plugins.CORE.error("Invalid/Unloaded world for: '" + raw + "' location!"); + return null; + } + + double x = NumberUtil.getAnyDouble(split[0], 0); + double y = NumberUtil.getAnyDouble(split[1], 0); + double z = NumberUtil.getAnyDouble(split[2], 0); + float pitch = (float) NumberUtil.getAnyDouble(split[3], 0); + float yaw = (float) NumberUtil.getAnyDouble(split[4], 0); + + return new Location(world, x, y, z, yaw, pitch); + } + + @NotNull + public static List deserialize(@NotNull Collection list) { + return new ArrayList<>(list.stream().map(LocationUtil::deserialize).filter(Objects::nonNull).toList()); + } + + @NotNull + public static String getWorldName(@NotNull Location location) { + World world = location.getWorld(); + return world == null ? "null" : world.getName(); + } + + @NotNull + public static Location getCenter(@NotNull Location location) { + return getCenter(location, true); + } + + @NotNull + public static Location getCenter(@NotNull Location location, boolean doVertical) { + Location centered = location.clone(); + location.setX(location.getBlockX() + 0.5); + location.setY(location.getBlockY() + (doVertical ? 0.5 : 0)); + location.setZ(location.getBlockZ() + 0.5); + return location; + } + + @NotNull + public static Vector getDirection(@NotNull Location from, @NotNull Location to) { + Location origin = from.clone(); + origin.setDirection(to.toVector().subtract(origin.toVector())); + return origin.getDirection(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/NumberUtil.java b/src/main/java/su/nightexpress/nightcore/util/NumberUtil.java new file mode 100644 index 0000000..cef2161 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/NumberUtil.java @@ -0,0 +1,118 @@ +package su.nightexpress.nightcore.util; + +import org.jetbrains.annotations.NotNull; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.Locale; +import java.util.TreeMap; + +public class NumberUtil { + + private static final DecimalFormat FORMAT_ROUND_HUMAN; + private final static TreeMap ROMAN_MAP = new TreeMap<>(); + + static { + FORMAT_ROUND_HUMAN = new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.ENGLISH)); + + ROMAN_MAP.put(1000, "M"); + ROMAN_MAP.put(900, "CM"); + ROMAN_MAP.put(500, "D"); + ROMAN_MAP.put(400, "CD"); + ROMAN_MAP.put(100, "C"); + ROMAN_MAP.put(90, "XC"); + ROMAN_MAP.put(50, "L"); + ROMAN_MAP.put(40, "XL"); + ROMAN_MAP.put(10, "X"); + ROMAN_MAP.put(9, "IX"); + ROMAN_MAP.put(5, "V"); + ROMAN_MAP.put(4, "IV"); + ROMAN_MAP.put(1, "I"); + } + + @NotNull + public static String format(double value) { + return FORMAT_ROUND_HUMAN.format(value); + } + + public static double round(double value) { + return new BigDecimal(value).setScale(2, RoundingMode.HALF_UP).doubleValue(); + } + + @NotNull + public static String toRoman(int number) { + if (number <= 0) return String.valueOf(number); + + int key = ROMAN_MAP.floorKey(number); + if (number == key) { + return ROMAN_MAP.get(number); + } + return ROMAN_MAP.get(key) + toRoman(number - key); + } + + public static int[] splitIntoParts(int whole, int parts) { + int[] arr = new int[parts]; + int remain = whole; + int partsLeft = parts; + for (int i = 0; partsLeft > 0; i++) { + int size = (remain + partsLeft - 1) / partsLeft; // rounded up, aka ceiling + arr[i] = size; + remain -= size; + partsLeft--; + } + return arr; + } + + public static double getDouble(@NotNull String input) { + return getDouble(input, 0D); + } + + public static double getDouble(@NotNull String input, double defaultValue) { + return Math.abs(getAnyDouble(input, defaultValue)); + } + + public static double getAnyDouble(@NotNull String input, double defaultValue) { + try { + double amount = Double.parseDouble(input); + if (!Double.isNaN(amount) && !Double.isInfinite(amount)) { + return amount; + } + } + catch (NumberFormatException ignored) {} + + return defaultValue; + } + + public static int getInteger(@NotNull String input) { + return getInteger(input, 0); + } + + public static int getInteger(@NotNull String input, int defaultValue) { + return Math.abs(getAnyInteger(input, defaultValue)); + } + + public static int getAnyInteger(@NotNull String input, int defaultValue) { + try { + return Integer.parseInt(input); + } + catch (NumberFormatException ignored) {} + + return defaultValue; + } + + public static int[] getIntArray(@NotNull String str) { + String[] split = str.split(","); + int[] array = new int[split.length]; + for (int index = 0; index < split.length; index++) { + try { + array[index] = Integer.parseInt(split[index].trim()); + } + catch (NumberFormatException e) { + array[index] = 0; + } + } + return array; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/PDCUtil.java b/src/main/java/su/nightexpress/nightcore/util/PDCUtil.java new file mode 100644 index 0000000..e26b719 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/PDCUtil.java @@ -0,0 +1,221 @@ +package su.nightexpress.nightcore.util; + +import org.bukkit.NamespacedKey; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.persistence.PersistentDataAdapterContext; +import org.bukkit.persistence.PersistentDataContainer; +import org.bukkit.persistence.PersistentDataHolder; +import org.bukkit.persistence.PersistentDataType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.nio.ByteBuffer; +import java.util.Optional; +import java.util.UUID; + +public class PDCUtil { + + public static final PersistentDataType UUID = new UUIDDataType(); + + @NotNull + public static Optional get(@NotNull ItemStack holder, @NotNull PersistentDataType type, @NotNull NamespacedKey key) { + ItemMeta meta = holder.getItemMeta(); + if (meta == null) return Optional.empty(); + + return get(meta, type, key); + } + + @NotNull + public static Optional get(@NotNull PersistentDataHolder holder, @NotNull PersistentDataType type, @NotNull NamespacedKey key) { + PersistentDataContainer container = holder.getPersistentDataContainer(); + if (container.has(key, type)) { + return Optional.ofNullable(container.get(key, type)); + } + return Optional.empty(); + } + + public static void set(@NotNull ItemStack holder, @NotNull NamespacedKey key, boolean value) { + set(holder, PersistentDataType.INTEGER, key, value ? 1 : 0); + } + + public static void set(@NotNull PersistentDataHolder holder, @NotNull NamespacedKey key, boolean value) { + set(holder, PersistentDataType.INTEGER, key, value ? 1 : 0); + } + + public static void set(@NotNull ItemStack holder, @NotNull NamespacedKey key, double value) { + set(holder, PersistentDataType.DOUBLE, key, value); + } + + public static void set(@NotNull PersistentDataHolder holder, @NotNull NamespacedKey key, double value) { + set(holder, PersistentDataType.DOUBLE, key, value); + } + + public static void set(@NotNull ItemStack holder, @NotNull NamespacedKey key, int value) { + set(holder, PersistentDataType.INTEGER, key, value); + } + + public static void set(@NotNull PersistentDataHolder holder, @NotNull NamespacedKey key, int value) { + set(holder, PersistentDataType.INTEGER, key, value); + } + + public static void set(@NotNull ItemStack holder, @NotNull NamespacedKey key, long value) { + set(holder, PersistentDataType.LONG, key, value); + } + + public static void set(@NotNull PersistentDataHolder holder, @NotNull NamespacedKey key, long value) { + set(holder, PersistentDataType.LONG, key, value); + } + + public static void set(@NotNull ItemStack holder, @NotNull NamespacedKey key, @Nullable String value) { + set(holder, PersistentDataType.STRING, key, value); + } + + public static void set(@NotNull PersistentDataHolder holder, @NotNull NamespacedKey key, @Nullable String value) { + set(holder, PersistentDataType.STRING, key, value); + } + + public static void set(@NotNull ItemStack holder, @NotNull NamespacedKey key, @Nullable UUID value) { + set(holder, UUID, key, value); + } + + public static void set(@NotNull PersistentDataHolder holder, @NotNull NamespacedKey key, @Nullable UUID value) { + set(holder, UUID, key, value); + } + + public static void set(@NotNull ItemStack item, + @NotNull PersistentDataType dataType, + @NotNull NamespacedKey key, + @Nullable Z value) { + ItemUtil.editMeta(item, meta -> set(meta, dataType, key, value)); + /*ItemMeta meta = item.getItemMeta(); + if (meta == null) return; + + set(meta, dataType, key, value); + item.setItemMeta(meta);*/ + } + + public static void set(@NotNull PersistentDataHolder holder, + @NotNull PersistentDataType dataType, + @NotNull NamespacedKey key, + @Nullable Z value) { + if (value == null) { + remove(holder, key); + return; + } + + PersistentDataContainer container = holder.getPersistentDataContainer(); + container.set(key, dataType, value); + + /*if (holder instanceof BlockState state) { + state.update(); + }*/ + } + + public static void remove(@NotNull ItemStack holder, @NotNull NamespacedKey key) { + //ItemMeta meta = holder.getItemMeta(); + //if (meta == null) return; + //remove(meta, key); + ItemUtil.editMeta(holder, meta -> remove(meta, key)); + } + + public static void remove(@NotNull PersistentDataHolder holder, @NotNull NamespacedKey key) { + PersistentDataContainer container = holder.getPersistentDataContainer(); + container.remove(key); + + /*if (holder instanceof BlockState state) { + state.update(); + }*/ + } + + @NotNull + public static Optional getString(@NotNull ItemStack holder, @NotNull NamespacedKey key) { + return get(holder, PersistentDataType.STRING, key); + } + + @NotNull + public static Optional getString(@NotNull PersistentDataHolder holder, @NotNull NamespacedKey key) { + return get(holder, PersistentDataType.STRING, key); + } + + @NotNull + public static Optional getInt(@NotNull ItemStack holder, @NotNull NamespacedKey key) { + return get(holder, PersistentDataType.INTEGER, key); + } + + @NotNull + public static Optional getInt(@NotNull PersistentDataHolder holder, @NotNull NamespacedKey key) { + return get(holder, PersistentDataType.INTEGER, key); + } + + @NotNull + public static Optional getLong(@NotNull ItemStack holder, @NotNull NamespacedKey key) { + return get(holder, PersistentDataType.LONG, key); + } + + @NotNull + public static Optional getLong(@NotNull PersistentDataHolder holder, @NotNull NamespacedKey key) { + return get(holder, PersistentDataType.LONG, key); + } + + @NotNull + public static Optional getDouble(@NotNull ItemStack holder, @NotNull NamespacedKey key) { + return get(holder, PersistentDataType.DOUBLE, key); + } + + @NotNull + public static Optional getDouble(@NotNull PersistentDataHolder holder, @NotNull NamespacedKey key) { + return get(holder, PersistentDataType.DOUBLE, key); + } + + @NotNull + public static Optional getBoolean(@NotNull ItemStack holder, @NotNull NamespacedKey key) { + return get(holder, PersistentDataType.INTEGER, key).map(i -> i != 0); + } + + @NotNull + public static Optional getBoolean(@NotNull PersistentDataHolder holder, @NotNull NamespacedKey key) { + return get(holder, PersistentDataType.INTEGER, key).map(i -> i != 0); + } + + @NotNull + public static Optional getUUID(@NotNull ItemStack holder, @NotNull NamespacedKey key) { + return get(holder, UUID, key); + } + + @NotNull + public static Optional getUUID(@NotNull PersistentDataHolder holder, @NotNull NamespacedKey key) { + return get(holder, UUID, key); + } + + public static class UUIDDataType implements PersistentDataType { + + @NotNull + @Override + public Class getPrimitiveType() { + return byte[].class; + } + + @NotNull + @Override + public Class getComplexType() { + return UUID.class; + } + + @Override + public byte @NotNull [] toPrimitive(UUID complex, @NotNull PersistentDataAdapterContext context) { + ByteBuffer bb = ByteBuffer.wrap(new byte[16]); + bb.putLong(complex.getMostSignificantBits()); + bb.putLong(complex.getLeastSignificantBits()); + return bb.array(); + } + + @Override + public @NotNull UUID fromPrimitive(byte @NotNull [] primitive, @NotNull PersistentDataAdapterContext context) { + ByteBuffer bb = ByteBuffer.wrap(primitive); + long firstLong = bb.getLong(); + long secondLong = bb.getLong(); + return new UUID(firstLong, secondLong); + } + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/Pair.java b/src/main/java/su/nightexpress/nightcore/util/Pair.java new file mode 100644 index 0000000..1701b06 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/Pair.java @@ -0,0 +1,49 @@ +package su.nightexpress.nightcore.util; + +import org.jetbrains.annotations.NotNull; + +import java.util.Objects; + +public class Pair { + + private final F first; + private final S second; + + public Pair(@NotNull F first, @NotNull S second) { + this.first = first; + this.second = second; + } + + @NotNull + public F getFirst() { + return this.first; + } + + @NotNull + public S getSecond() { + return this.second; + } + + @NotNull + public Pair swap() { + return of(this.second, this.first); + } + + @Override + public String toString() { + return "Pair{" + "first=" + first + ", second=" + second + '}'; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Pair other) { + return Objects.equals(this.first, other.first) && Objects.equals(this.second, other.second); + } + return false; + } + + @NotNull + public static Pair of(@NotNull F first, @NotNull S second) { + return new Pair<>(first, second); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/Placeholders.java b/src/main/java/su/nightexpress/nightcore/util/Placeholders.java new file mode 100644 index 0000000..2723c5e --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/Placeholders.java @@ -0,0 +1,72 @@ +package su.nightexpress.nightcore.util; + +import org.bukkit.Location; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.language.tag.MessageTags; +import su.nightexpress.nightcore.util.placeholder.PlaceholderMap; +import su.nightexpress.nightcore.util.text.tag.Tags; + +import java.util.function.UnaryOperator; + +public class Placeholders { + + public static final String GITHUB_URL = "https://github.com/nulli0n/nightcore-spigot/"; + public static final String WIKI_MAIN_URL = GITHUB_URL + "wiki/"; + public static final String WIKI_ITEMS_URL = WIKI_MAIN_URL + "Configuration-Tips#item-sections"; + public static final String WIKI_LANG_URL = WIKI_MAIN_URL + "Language-Config"; + + public static final String DEFAULT = "default"; + public static final String NONE = "none"; + public static final String WILDCARD = "*"; + + public static final String GENERIC_NAME = "%name%"; + public static final String GENERIC_ITEM = "%item%"; + public static final String GENERIC_VALUE = "%value%"; + public static final String GENERIC_AMOUNT = "%amount%"; + public static final String GENERIC_ENTRY = "%entry%"; + + public static final String TAG_NO_PREFIX = MessageTags.NO_PREFIX.getFullName(); + public static final String TAG_LINE_BREAK = Tags.LINE_BREAK.getFullName(); + + public static final String PLAYER_NAME = "%player_name%"; + public static final String PLAYER_DISPLAY_NAME = "%player_display_name%"; + + public static final String LOCATION_X = "%location_x%"; + public static final String LOCATION_Y = "%location_y%"; + public static final String LOCATION_Z = "%location_z%"; + public static final String LOCATION_WORLD = "%location_world%"; + + public static final String COMMAND_USAGE = "%command_usage%"; + public static final String COMMAND_DESCRIPTION = "%command_description%"; + public static final String COMMAND_LABEL = "%command_label%"; + + @NotNull + public static UnaryOperator forLocation(@NotNull Location location) { + return new PlaceholderMap() + .add(LOCATION_X, () -> NumberUtil.format(location.getX())) + .add(LOCATION_Y, () -> NumberUtil.format(location.getY())) + .add(LOCATION_Z, () -> NumberUtil.format(location.getZ())) + .add(LOCATION_WORLD, () -> LocationUtil.getWorldName(location)) + .replacer(); + } + + @NotNull + public static UnaryOperator forPlayer(@NotNull Player player) { + return new PlaceholderMap() + .add(PLAYER_NAME, player::getName) + .add(PLAYER_DISPLAY_NAME, player::getDisplayName) + .replacer(); + } + + @NotNull + public static UnaryOperator forSender(@NotNull CommandSender sender) { + if (sender instanceof Player player) return forPlayer(player); + + return new PlaceholderMap() + .add(PLAYER_NAME, sender::getName) + .add(PLAYER_DISPLAY_NAME, sender::getName) + .replacer(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/Players.java b/src/main/java/su/nightexpress/nightcore/util/Players.java new file mode 100644 index 0000000..bb3c286 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/Players.java @@ -0,0 +1,282 @@ +package su.nightexpress.nightcore.util; + +import me.clip.placeholderapi.PlaceholderAPI; +import net.md_5.bungee.api.ChatMessageType; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.geysermc.floodgate.api.FloodgateApi; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.core.CoreConfig; +import su.nightexpress.nightcore.integration.VaultHook; +import su.nightexpress.nightcore.util.message.NexParser; +import su.nightexpress.nightcore.util.text.NightMessage; +import su.nightexpress.nightcore.util.text.WrappedMessage; + +import java.util.*; +import java.util.function.Predicate; +import java.util.stream.Stream; + +public class Players { + + @NotNull + public static List playerNames() { + return playerNames(null); + } + + @NotNull + public static List playerNames(@Nullable Player viewer) { + return playerNames(viewer, true); + } + + @NotNull + public static List realPlayerNames() { + return realPlayerNames(null); + } + + @NotNull + public static List realPlayerNames(@Nullable Player viewer) { + return playerNames(viewer, false); + } + + @NotNull + public static List playerNames(@Nullable Player viewer, boolean includeCustom) { + Set names = new HashSet<>(); + for (Player player : Bukkit.getServer().getOnlinePlayers()) { + if (viewer != null && !viewer.canSee(player)) continue; + + names.add(player.getName()); + if (includeCustom && CoreConfig.RESPECT_PLAYER_DISPLAYNAME.get()) { + names.add(Colorizer.strip(player.getDisplayName())); + } + } + return names.stream().sorted(String::compareTo).toList(); + } + + @NotNull + public static Optional find(@NotNull String nameOrNick) { + return Optional.ofNullable(getPlayer(nameOrNick)); + } + + @Nullable + public static Player getPlayer(@NotNull String nameOrNick) { + if (!CoreConfig.RESPECT_PLAYER_DISPLAYNAME.get()) { + return Bukkit.getServer().getPlayer(nameOrNick); + } + + Player found = Bukkit.getServer().getPlayerExact(nameOrNick); + if (found != null) { + return found; + } + + String lowerName = nameOrNick.toLowerCase(); + int lowerLength = lowerName.length(); + int delta = Integer.MAX_VALUE; + + for (Player player : Bukkit.getServer().getOnlinePlayers()) { + String nameReal = player.getName().toLowerCase(Locale.ENGLISH); + String nameCustom = player.getDisplayName().toLowerCase(); + + int length; + if (nameReal.startsWith(lowerName)) { + length = player.getName().length(); + } + else if (nameCustom.startsWith(lowerName)) { + length = player.getDisplayName().length(); + } + else continue; + + int curDelta = Math.abs(length - lowerLength); + if (curDelta < delta) { + found = player; + delta = curDelta; + } + + if (curDelta == 0) break; + } + + return found; + } + + public static boolean isBedrock(@NotNull Player player) { + return Plugins.hasFloodgate() && FloodgateApi.getInstance().isFloodgatePlayer(player.getUniqueId()); + } + + public static boolean isReal(@NotNull Player player) { + return Bukkit.getServer().getPlayer(player.getUniqueId()) != null; + } + + @NotNull + public static String getPermissionGroup(@NotNull Player player) { + return Plugins.hasVault() ? VaultHook.getPermissionGroup(player).toLowerCase() : Placeholders.DEFAULT; + } + + @NotNull + public static Set getPermissionGroups(@NotNull Player player) { + return Plugins.hasVault() ? VaultHook.getPermissionGroups(player) : Collections.emptySet(); + } + + @NotNull + public static String getPrefix(@NotNull Player player) { + return Plugins.hasVault() ? VaultHook.getPrefix(player) : ""; + } + + @NotNull + public static String getSuffix(@NotNull Player player) { + return Plugins.hasVault() ? VaultHook.getSuffix(player) : ""; + } + + @Deprecated + public static void sendRichMessage(@NotNull CommandSender sender, @NotNull String message) { + if (!(sender instanceof Player player)) { + sender.sendMessage(Colorizer.apply(NexParser.toPlainText(message))); + return; + } + NexParser.toMessage(message).send(sender); + } + + public static void sendModernMessage(@NotNull CommandSender sender, @NotNull String message) { + NightMessage.create(message).send(sender); + } + + @Deprecated + public static void sendActionBar(@NotNull Player player, @NotNull String msg) { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, NexParser.toMessage(msg).build()); + } + + public static void sendActionBarText(@NotNull Player player, @NotNull String message) { + sendActionBar(player, NightMessage.create(message)); + } + + public static void sendActionBar(@NotNull Player player, @NotNull WrappedMessage message) { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, message.parseIfAbsent()); + } + + public static void dispatchCommands(@NotNull Player player, @NotNull String... commands) { + dispatchCommands(player, Arrays.asList(commands)); + } + + public static void dispatchCommands(@NotNull Player player, @NotNull List commands) { + for (String command : commands) { + dispatchCommand(player, command); + } + } + + public static void dispatchCommand(@NotNull Player player, @NotNull String command) { + command = command.replace("[CONSOLE]", ""); + command = command.trim().replace("%player%", player.getName()); + command = Placeholders.forPlayer(player).apply(command); + if (Plugins.hasPlaceholderAPI()) { + command = PlaceholderAPI.setPlaceholders(player, command); + } + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); + } + + public static boolean hasEmptyInventory(@NotNull Player player) { + return Stream.of(player.getInventory().getContents()).allMatch(item -> item == null || item.getType().isAir()); + } + + public static boolean hasEmptyContents(@NotNull Player player) { + return Stream.of(player.getInventory().getContents()).allMatch(item -> item == null || item.getType().isAir()); + } + + public static int countItemSpace(@NotNull Player player, @NotNull ItemStack item) { + int stackSize = item.getType().getMaxStackSize(); + return Stream.of(player.getInventory().getContents()).mapToInt(itemHas -> { + if (itemHas == null || itemHas.getType().isAir()) { + return stackSize; + } + if (itemHas.isSimilar(item)) { + return (stackSize - itemHas.getAmount()); + } + return 0; + }).sum(); + } + + public static int countItem(@NotNull Player player, @NotNull Predicate predicate) { + return Stream.of(player.getInventory().getContents()) + .filter(item -> item != null && predicate.test(item)) + .mapToInt(ItemStack::getAmount).sum(); + } + + public static int countItem(@NotNull Player player, @NotNull ItemStack item) { + return countItem(player, item::isSimilar); + } + + public static int countItem(@NotNull Player player, @NotNull Material material) { + return countItem(player, itemHas -> itemHas.getType() == material); + } + + public static void takeItem(@NotNull Player player, @NotNull ItemStack item) { + takeItem(player, item, -1); + } + + public static void takeItem(@NotNull Player player, @NotNull ItemStack item, int amount) { + takeItem(player, itemHas -> itemHas.isSimilar(item), amount); + } + + public static void takeItem(@NotNull Player player, @NotNull Material material) { + takeItem(player, material, -1); + } + + public static void takeItem(@NotNull Player player, @NotNull Material material, int amount) { + takeItem(player, itemHas -> itemHas.getType() == material, amount); + } + + public static void takeItem(@NotNull Player player, @NotNull Predicate predicate) { + takeItem(player, predicate, -1); + } + + public static void takeItem(@NotNull Player player, @NotNull Predicate predicate, int amount) { + int takenAmount = 0; + + Inventory inventory = player.getInventory(); + for (ItemStack itemHas : inventory.getContents()) { + if (itemHas == null || !predicate.test(itemHas)) continue; + + if (amount < 0) { + itemHas.setAmount(0); + continue; + } + + int hasAmount = itemHas.getAmount(); + if (takenAmount + hasAmount > amount) { + int diff = (takenAmount + hasAmount) - amount; + itemHas.setAmount(diff); + break; + } + + itemHas.setAmount(0); + if ((takenAmount += hasAmount) == amount) { + break; + } + } + } + + public static void addItem(@NotNull Player player, @NotNull ItemStack... items) { + for (ItemStack item : items) { + addItem(player, item, item.getAmount()); + } + } + + public static void addItem(@NotNull Player player, @NotNull ItemStack item2, int amount) { + if (amount <= 0 || item2.getType().isAir()) return; + + World world = player.getWorld(); + ItemStack item = new ItemStack(item2); + + int realAmount = Math.min(item.getMaxStackSize(), amount); + item.setAmount(realAmount); + player.getInventory().addItem(item).values().forEach(left -> { + world.dropItem(player.getLocation(), left); + }); + + amount -= realAmount; + if (amount > 0) addItem(player, item2, amount); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/Plugins.java b/src/main/java/su/nightexpress/nightcore/util/Plugins.java new file mode 100644 index 0000000..2e6829e --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/Plugins.java @@ -0,0 +1,44 @@ +package su.nightexpress.nightcore.util; + +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.NightCore; + +public class Plugins { + + public static final NightCore CORE = NightCore.getPlugin(NightCore.class); + + public static final String VAULT = "Vault"; + public static final String PLACEHOLDER_API = "PlaceholderAPI"; + public static final String FLOODGATE = "floodgate"; + + private static final boolean HAS_PLACEHOLDER_API = isInstalled(PLACEHOLDER_API); + private static final boolean HAS_VAULT = isInstalled(VAULT); + private static final boolean HAS_FLOODGATE = isInstalled(FLOODGATE); + + public static boolean isInstalled(@NotNull String pluginName) { + Plugin plugin = CORE.getPluginManager().getPlugin(pluginName); + return plugin != null; + } + + public static boolean isLoaded(@NotNull String pluginName) { + Plugin plugin = CORE.getPluginManager().getPlugin(pluginName); + return plugin != null && plugin.isEnabled(); + } + + public static boolean isSpigot() { + return CORE.getServer().getVersion().contains("Spigot"); + } + + public static boolean hasPlaceholderAPI() { + return HAS_PLACEHOLDER_API;//hasPlugin(PLACEHOLDER_API); + } + + public static boolean hasVault() { + return HAS_VAULT;//hasPlugin(VAULT); + } + + public static boolean hasFloodgate() { + return HAS_FLOODGATE;//hasPlugin(FLOODGATE); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/RankMap.java b/src/main/java/su/nightexpress/nightcore/util/RankMap.java new file mode 100644 index 0000000..f1ed483 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/RankMap.java @@ -0,0 +1,147 @@ +package su.nightexpress.nightcore.util; + +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.config.ConfigValue; +import su.nightexpress.nightcore.config.FileConfig; + +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; + +public class RankMap { + + private final Mode mode; + private final String permissionPrefix; + private final T defaultValue; + private final Map values; + + public enum Mode { + RANK, PERMISSION + } + + public RankMap(@NotNull Mode mode, @NotNull String permissionPrefix, @NotNull T defaultValue, @NotNull Map values) { + this.mode = mode; + this.permissionPrefix = permissionPrefix; + this.defaultValue = defaultValue; + this.values = new HashMap<>(values); + } + + @NotNull + public static RankMap readInt(@NotNull FileConfig cfg, @NotNull String path) { + return read(cfg, path, Integer.class); + } + + @NotNull + public static RankMap readDouble(@NotNull FileConfig cfg, @NotNull String path) { + return read(cfg, path, Double.class); + } + + @NotNull + public static RankMap readLong(@NotNull FileConfig cfg, @NotNull String path) { + return read(cfg, path, Long.class); + } + + @NotNull + public static RankMap read(@NotNull FileConfig cfg, @NotNull String path, @NotNull Class clazz) { + if (!cfg.contains(path + ".Mode")) { + for (String rank : cfg.getSection(path)) { + T number; + if (clazz == Double.class) { + number = clazz.cast(cfg.getDouble(path + "." + rank)); + } + else number = clazz.cast(cfg.getInt(path + "." + rank)); + + if (rank.equalsIgnoreCase(Placeholders.DEFAULT)) { + cfg.set(path + ".Default_Value", number); + } + else { + cfg.set(path + ".Values." + rank, number); + } + } + cfg.remove(path); + } + + Mode mode = ConfigValue.create(path + ".Mode", Mode.class, Mode.RANK).read(cfg); + String permissionPrefix = ConfigValue.create(path + ".Permission_Prefix", "sample.prefix.").read(cfg); + + T defaultValue; + if (clazz == Double.class) { + defaultValue = clazz.cast(cfg.getDouble(path + ".Default_Value")); + } + else defaultValue = clazz.cast(cfg.getInt(path + ".Default_Value")); + + Map values = new HashMap<>(); + for (String rank : cfg.getSection(path + ".Values")) { + T number; + if (clazz == Double.class) { + number = clazz.cast(cfg.getDouble(path + ".Values." + rank)); + } + else number = clazz.cast(cfg.getInt(path + ".Values." + rank)); + + values.put(rank.toLowerCase(), number); + } + + return new RankMap<>(mode, permissionPrefix, defaultValue, values); + } + + public void write(@NotNull FileConfig cfg, @NotNull String path) { + cfg.set(path + ".Mode", this.getMode().name()); + cfg.set(path + ".Permission_Prefix", this.getPermissionPrefix()); + this.values.forEach((rank, number) -> { + cfg.set(path + ".Values." + rank, number); + }); + } + + @NotNull + public T getRankValue(@NotNull Player player) { + String group = Players.getPermissionGroup(player); + return this.values.getOrDefault(group, this.getDefaultValue()); + } + + @NotNull + public T getGreatestOrNegative(@NotNull Player player) { + T best = this.getGreatest(player); + T lowest = this.getSmallest(player); + + return lowest.doubleValue() < 0D ? lowest : best; + } + + @NotNull + public T getGreatest(@NotNull Player player) { + if (this.getMode() == Mode.RANK) { + return this.getRankValue(player); + } + return this.values.entrySet().stream() + .filter(entry -> player.hasPermission(this.getPermissionPrefix() + entry.getKey())) + .map(Map.Entry::getValue) + .max(Comparator.comparingDouble(Number::doubleValue)).orElse(this.getDefaultValue()); + } + + @NotNull + public T getSmallest(@NotNull Player player) { + if (this.getMode() == Mode.RANK) { + return this.getRankValue(player); + } + return this.values.entrySet().stream() + .filter(entry -> player.hasPermission(this.getPermissionPrefix() + entry.getKey())) + .map(Map.Entry::getValue) + .min(Comparator.comparingDouble(Number::doubleValue)).orElse(this.getDefaultValue()); + } + + @NotNull + public Mode getMode() { + return mode; + } + + @Nullable + public String getPermissionPrefix() { + return permissionPrefix; + } + + @NotNull + public T getDefaultValue() { + return defaultValue; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/Reflex.java b/src/main/java/su/nightexpress/nightcore/util/Reflex.java new file mode 100644 index 0000000..5f243ac --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/Reflex.java @@ -0,0 +1,158 @@ +package su.nightexpress.nightcore.util; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.lang.reflect.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class Reflex { + + public static Class getClass(@NotNull String path, @NotNull String name) { + return getClass(path + "." + name); + } + + public static Class getInnerClass(@NotNull String path, @NotNull String name) { + return getClass(path + "$" + name); + } + + private static Class getClass(@NotNull String path) { + try { + return Class.forName(path); + } + catch (ClassNotFoundException e) { + e.printStackTrace(); + return null; + } + } + + public static Constructor getConstructor(@NotNull Class clazz, Class... types) { + try { + Constructor constructor = clazz.getDeclaredConstructor(types); + constructor.setAccessible(true); + return constructor; + } + catch (ReflectiveOperationException e) { + e.printStackTrace(); + } + return null; + } + + public static Object invokeConstructor(@NotNull Constructor constructor, Object... obj) { + try { + return constructor.newInstance(obj); + } + catch (ReflectiveOperationException e) { + e.printStackTrace(); + } + return obj; + } + + @NotNull + public static List getFields(@NotNull Class clazz, @NotNull Class type) { + List list = new ArrayList<>(); + + for (Field field : Reflex.getFields(clazz)) { + if (!field.getDeclaringClass().equals(clazz)) continue; + //if (!field.canAccess(null)) continue; + if (!Modifier.isStatic(field.getModifiers())) continue; + if (!Modifier.isFinal(field.getModifiers())) continue; + if (!type.isAssignableFrom(field.getType())) continue; + if (!field.trySetAccessible()) continue; + + try { + list.add(type.cast(field.get(null))); + } + catch (IllegalArgumentException | IllegalAccessException exception) { + exception.printStackTrace(); + } + } + + return list; + } + + @NotNull + public static List getFields(@NotNull Class type) { + List result = new ArrayList<>(); + + Class clazz = type; + while (clazz != null && clazz != Object.class) { + if (!result.isEmpty()) { + result.addAll(0, Arrays.asList(clazz.getDeclaredFields())); + } + else { + Collections.addAll(result, clazz.getDeclaredFields()); + } + clazz = clazz.getSuperclass(); + } + + return result; + } + + public static Field getField(@NotNull Class clazz, @NotNull String fieldName) { + try { + return clazz.getDeclaredField(fieldName); + } + catch (NoSuchFieldException e) { + Class superClass = clazz.getSuperclass(); + return superClass == null ? null : getField(superClass, fieldName); + } + } + + public static Object getFieldValue(@NotNull Object from, @NotNull String fieldName) { + try { + Class clazz = from instanceof Class ? (Class) from : from.getClass(); + Field field = getField(clazz, fieldName); + if (field == null) return null; + + field.setAccessible(true); + return field.get(from); + } + catch (IllegalAccessException e) { + e.printStackTrace(); + } + return null; + } + + public static boolean setFieldValue(@NotNull Object of, @NotNull String fieldName, @Nullable Object value) { + try { + boolean isStatic = of instanceof Class; + Class clazz = isStatic ? (Class) of : of.getClass(); + + Field field = getField(clazz, fieldName); + if (field == null) return false; + + field.setAccessible(true); + field.set(isStatic ? null : of, value); + return true; + } + catch (IllegalAccessException e) { + e.printStackTrace(); + } + return false; + } + + public static Method getMethod(@NotNull Class clazz, @NotNull String fieldName, @NotNull Class... o) { + try { + return clazz.getDeclaredMethod(fieldName, o); + } + catch (NoSuchMethodException e) { + Class superClass = clazz.getSuperclass(); + return superClass == null ? null : getMethod(superClass, fieldName); + } + } + + public static Object invokeMethod(@NotNull Method method, @Nullable Object by, @Nullable Object... param) { + method.setAccessible(true); + try { + return method.invoke(by, param); + } + catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/StringUtil.java b/src/main/java/su/nightexpress/nightcore/util/StringUtil.java new file mode 100644 index 0000000..05b7658 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/StringUtil.java @@ -0,0 +1,201 @@ +package su.nightexpress.nightcore.util; + +import org.bukkit.Color; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.random.Rnd; +import su.nightexpress.nightcore.util.regex.TimedMatcher; + +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; +import java.util.regex.Pattern; + +public class StringUtil { + + private static final Pattern ID_PATTERN = Pattern.compile("[<>\\%\\$\\!\\@\\#\\^\\&\\*\\(\\)\\,\\.\\'\\:\\;\\\"\\}\\]\\{\\[\\=\\+\\`\\~\\\\]");//Pattern.compile("[^a-zA-Zа-яА-Я_0-9]"); + private static final Pattern ID_STRICT_PATTERN = Pattern.compile("[^a-zA-Zа-яА-Я_0-9]"); + + @NotNull + @Deprecated + public static String oneSpace(@NotNull String str) { + return str.trim().replaceAll("\\s+", " "); + } + + @NotNull + @Deprecated + public static String noSpace(@NotNull String str) { + return str.trim().replaceAll("\\s+", ""); + } + + @NotNull + public static String replaceEach(@NotNull String text, @NotNull List>> replacements) { + if (text.isEmpty() || replacements.isEmpty()) { + return text; + } + + final int searchLength = replacements.size(); + // keep track of which still have matches + final boolean[] noMoreMatchesForReplIndex = new boolean[searchLength]; + + // index on index that the match was found + int textIndex = -1; + int replaceIndex = -1; + int tempIndex; + + // index of replace array that will replace the search string found + for (int i = 0; i < searchLength; i++) { + if (noMoreMatchesForReplIndex[i]) { + continue; + } + tempIndex = text.indexOf(replacements.get(i).getFirst()); + + // see if we need to keep searching for this + if (tempIndex == -1) { + noMoreMatchesForReplIndex[i] = true; + } + else if (textIndex == -1 || tempIndex < textIndex) { + textIndex = tempIndex; + replaceIndex = i; + } + } + + // no search strings found, we are done + if (textIndex == -1) { + return text; + } + + int start = 0; + final StringBuilder buf = new StringBuilder(); + while (textIndex != -1) { + for (int i = start; i < textIndex; i++) { + buf.append(text.charAt(i)); + } + buf.append(replacements.get(replaceIndex).getSecond().get()); + + start = textIndex + replacements.get(replaceIndex).getFirst().length(); + + textIndex = -1; + replaceIndex = -1; + // find the next earliest match + for (int i = 0; i < searchLength; i++) { + if (noMoreMatchesForReplIndex[i]) { + continue; + } + tempIndex = text.indexOf(replacements.get(i).getFirst(), start); + + // see if we need to keep searching for this + if (tempIndex == -1) { + noMoreMatchesForReplIndex[i] = true; + } + else if (textIndex == -1 || tempIndex < textIndex) { + textIndex = tempIndex; + replaceIndex = i; + } + } + } + + final int textLength = text.length(); + for (int i = start; i < textLength; i++) { + buf.append(text.charAt(i)); + } + return buf.toString(); + } + + @NotNull + public static > Optional getEnum(String str, @NotNull Class clazz) { + try { + return str == null ? Optional.empty() : Optional.of(Enum.valueOf(clazz, str.toUpperCase())); + } + catch (Exception exception) { + return Optional.empty(); + } + } + + @NotNull + public static Color getColor(@NotNull String str) { + String[] rgb = str.split(","); + int red = NumberUtil.getInteger(rgb[0], 0); + if (red < 0) red = Rnd.get(255); + + int green = rgb.length >= 2 ? NumberUtil.getInteger(rgb[1], 0) : 0; + if (green < 0) green = Rnd.get(255); + + int blue = rgb.length >= 3 ? NumberUtil.getInteger(rgb[2], 0) : 0; + if (blue < 0) blue = Rnd.get(255); + + return Color.fromRGB(red, green, blue); + } + + @NotNull + public static String lowerCaseUnderscore(@NotNull String str) { + return lowerCaseUnderscore(str, -1); + } + + @NotNull + public static String lowerCaseUnderscore(@NotNull String str, int length) { + return lowerCaseAndClean(str, ID_PATTERN, length); + } + + @NotNull + public static String lowerCaseUnderscoreStrict(@NotNull String str) { + return lowerCaseUnderscoreStrict(str, -1); + } + + @NotNull + public static String lowerCaseUnderscoreStrict(@NotNull String str, int length) { + return lowerCaseAndClean(str, ID_STRICT_PATTERN, length); + } + + @NotNull + private static String lowerCaseAndClean(@NotNull String str, @NotNull Pattern pattern, int length) { + String clean = Colorizer.restrip(str).toLowerCase().replace(" ", "_"); + if (length > 0 && clean.length() > length) { + clean = clean.substring(0, length); + } + + TimedMatcher matcher = TimedMatcher.create(pattern, clean, 200); + //Matcher matcher = RegexUtil.getMatcher(ID_STRICT_PATTERN, clean); + return matcher.replaceAll(""); + } + + @NotNull + public static String capitalizeUnderscored(@NotNull String str) { + return capitalizeFully(str.replace("_", " ")); + } + + @NotNull + public static String capitalizeFully(@NotNull String str) { + return capitalize(str.toLowerCase()); + } + + @NotNull + public static String capitalize(@NotNull String str) { + if (str.length() == 0) return str; + + int length = str.length(); + StringBuilder builder = new StringBuilder(length); + boolean capitalizeNext = true; + + for (int index = 0; index < length; ++index) { + char letter = str.charAt(index); + if (Character.isWhitespace(letter)) { + builder.append(letter); + capitalizeNext = true; + } + else if (capitalizeNext) { + builder.append(Character.toTitleCase(letter)); + capitalizeNext = false; + } + else { + builder.append(letter); + } + } + return builder.toString(); + } + + @NotNull + public static String capitalizeFirstLetter(@NotNull String original) { + if (original.isEmpty()) return original; + return original.substring(0, 1).toUpperCase() + original.substring(1); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/TimeUtil.java b/src/main/java/su/nightexpress/nightcore/util/TimeUtil.java new file mode 100644 index 0000000..95a5727 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/TimeUtil.java @@ -0,0 +1,80 @@ +package su.nightexpress.nightcore.util; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.core.CoreLang; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.TimeZone; +import java.util.concurrent.TimeUnit; + +public class TimeUtil { + + @NotNull + public static String formatTime(long time) { + long days = TimeUnit.MILLISECONDS.toDays(time); + long hours = TimeUnit.MILLISECONDS.toHours(time) % 24; + long minutes = TimeUnit.MILLISECONDS.toMinutes(time) % 60; + long seconds = TimeUnit.MILLISECONDS.toSeconds(time) % 60; + String delimiter = CoreLang.TIME_DELIMITER.getString(); + + StringBuilder str = new StringBuilder(); + if (days > 0) { + if (str.length() > 0) { + str.append(delimiter); + } + str.append(CoreLang.TIME_DAY.getString().replace(Placeholders.GENERIC_AMOUNT, String.valueOf(days))); + } + if (hours > 0) { + if (str.length() > 0) { + str.append(delimiter); + } + str.append(CoreLang.TIME_HOUR.getString().replace(Placeholders.GENERIC_AMOUNT, String.valueOf(hours))); + } + if (minutes > 0) { + if (str.length() > 0) { + str.append(delimiter); + } + str.append(CoreLang.TIME_MINUTE.getString().replace(Placeholders.GENERIC_AMOUNT, String.valueOf(minutes))); + } + if (str.length() == 0 || seconds > 0) { + if (str.length() > 0) { + str.append(delimiter); + } + str.append(CoreLang.TIME_SECOND.getString().replace(Placeholders.GENERIC_AMOUNT, String.valueOf(seconds))); + } + + return str.toString(); + } + + @NotNull + public static String formatDuration(long from, long to) { + long time = to - from; + return formatTime(time); + } + + @NotNull + public static String formatDuration(long until) { + return formatTime(until - System.currentTimeMillis()); + } + + @NotNull + public static LocalTime getLocalTimeOf(long ms) { + long hours = TimeUnit.MILLISECONDS.toHours(ms) % 24; + long minutes = TimeUnit.MILLISECONDS.toMinutes(ms) % 60; + long seconds = TimeUnit.MILLISECONDS.toSeconds(ms) % 60; + + return LocalTime.of((int) hours, (int) minutes, (int) seconds); + } + + @NotNull + public static LocalDateTime getLocalDateTimeOf(long ms) { + return LocalDateTime.ofInstant(Instant.ofEpochMilli(ms), TimeZone.getDefault().toZoneId()); + } + + public static long toEpochMillis(@NotNull LocalDateTime dateTime) { + Instant instant = dateTime.atZone(TimeZone.getDefault().toZoneId()).toInstant(); + return instant.toEpochMilli(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/TriFunction.java b/src/main/java/su/nightexpress/nightcore/util/TriFunction.java new file mode 100644 index 0000000..2a6a23c --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/TriFunction.java @@ -0,0 +1,14 @@ +package su.nightexpress.nightcore.util; + +import java.util.Objects; +import java.util.function.Function; + +public interface TriFunction { + + R apply(T t, U u, V v); + + default TriFunction andThen(Function after) { + Objects.requireNonNull(after); + return (T t, U u, V v) -> after.apply(apply(t, u, v)); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/Version.java b/src/main/java/su/nightexpress/nightcore/util/Version.java new file mode 100644 index 0000000..243779d --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/Version.java @@ -0,0 +1,76 @@ +package su.nightexpress.nightcore.util; + +import org.bukkit.Bukkit; +import org.jetbrains.annotations.NotNull; + +public enum Version { + + V1_18_R2("1.18.2"), + V1_19_R3("1.19.4"), + V1_20_R1("1.20.1", true), + V1_20_R2("1.20.2", true), + V1_20_R3("1.20.4"), + UNKNOWN("Unknown"), + ; + + private static Version current; + + private final boolean deprecated; + private final String localized; + + Version(@NotNull String localized) { + this(localized, false); + } + + Version(@NotNull String localized, boolean deprecated) { + this.localized = localized; + this.deprecated = deprecated; + } + + @NotNull + public static String getProtocol() { + String[] split = Bukkit.getServer().getClass().getPackage().getName().split("\\."); + return split[split.length - 1]; + } + + @NotNull + public static Version getCurrent() { + if (current == null) { + current = StringUtil.getEnum(getProtocol(), Version.class).orElse(UNKNOWN); + } + return current; + } + + public boolean isDeprecated() { + return deprecated; + } + + @NotNull + public String getLocalized() { + return localized; + } + + public boolean isLower(@NotNull Version version) { + return this.ordinal() < version.ordinal(); + } + + public boolean isHigher(@NotNull Version version) { + return this.ordinal() > version.ordinal(); + } + + public static boolean isAtLeast(@NotNull Version version) { + return version.isCurrent() || getCurrent().isHigher(version); + } + + public static boolean isAbove(@NotNull Version version) { + return getCurrent().isHigher(version); + } + + public static boolean isBehind(@NotNull Version version) { + return getCurrent().isLower(version); + } + + public boolean isCurrent() { + return this == Version.getCurrent(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/blocktracker/PlayerBlockTracker.java b/src/main/java/su/nightexpress/nightcore/util/blocktracker/PlayerBlockTracker.java new file mode 100644 index 0000000..ca6b0ec --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/blocktracker/PlayerBlockTracker.java @@ -0,0 +1,139 @@ +package su.nightexpress.nightcore.util.blocktracker; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.NamespacedKey; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.Plugins; + +import java.util.*; +import java.util.function.Predicate; + +public final class PlayerBlockTracker { + + public static final Set> BLOCK_FILTERS = new HashSet<>(); + public static final NamespacedKey TRACKED_DATA_KEY = NamespacedKey.minecraft("tracked_chunk_data"); + private static final Map TRACKED_WORLD_MAP = new Object2ObjectOpenHashMap<>(); + + private static TrackListener listener; + + public static void initialize() { + if (listener == null) { + initCurrentlyLoadedWorlds(); + (listener = new TrackListener<>(Plugins.CORE)).registerListeners(); + } + } + + public static void shutdown() { + if (listener != null) { + terminateCurrentlyLoadedWorlds(); + listener.unregisterListeners(); + listener = null; + BLOCK_FILTERS.clear(); + } + } + + public static void initWorld(@NotNull World world) { + TrackedWorld trackedWorld = new TrackedWorld(); + for (Chunk loadedChunk : world.getLoadedChunks()) { + trackedWorld.initChunk(loadedChunk); + } + TRACKED_WORLD_MAP.put(world.getUID(), trackedWorld); + } + + public static void terminateWorld(@NotNull World world) { + TrackedWorld trackedWorld = TRACKED_WORLD_MAP.remove(world.getUID()); + if (trackedWorld == null) { + return; + } + for (Chunk loadedChunk : world.getLoadedChunks()) { + trackedWorld.terminateChunk(loadedChunk); + } + } + + public static void initChunk(@NotNull Chunk chunk) { + TrackedWorld trackedWorld = getTrackedWorldOf(chunk); + if (trackedWorld == null) { + return; + } + trackedWorld.initChunk(chunk); + } + + public static void terminateChunk(@NotNull Chunk chunk) { + TrackedWorld trackedWorld = getTrackedWorldOf(chunk); + if (trackedWorld == null) { + return; + } + trackedWorld.terminateChunk(chunk); + } + + public static void initCurrentlyLoadedWorlds() { + Bukkit.getWorlds().forEach(PlayerBlockTracker::initWorld); + } + + public static void terminateCurrentlyLoadedWorlds() { + Bukkit.getWorlds().forEach(PlayerBlockTracker::terminateWorld); + } + + public static boolean isTracked(@NotNull Block block) { + TrackedWorld trackedWorld = getTrackedWorldOf(block); + if (trackedWorld == null) { + return false; + } + return trackedWorld.isTracked(block); + } + + public static void track(@NotNull Block block) { + if (BLOCK_FILTERS.stream().noneMatch(filter -> filter.test(block))) return; + trackForce(block); + } + + public static void trackForce(@NotNull Block block) { + TrackedWorld trackedWorld = getTrackedWorldOf(block); + if (trackedWorld == null) { + return; + } + trackedWorld.add(block); + } + + public static void unTrack(@NotNull Block block) { + TrackedWorld trackedWorld = getTrackedWorldOf(block); + if (trackedWorld == null) { + return; + } + trackedWorld.remove(block); + } + + public static void track(@NotNull Collection trackedBlocks) { + trackedBlocks.forEach(PlayerBlockTracker::trackForce); + } + + public static void unTrack(@NotNull Collection trackedBlocks) { + trackedBlocks.forEach(PlayerBlockTracker::unTrack); + } + + public static void shift(@NotNull BlockFace direction, @NotNull List blocks) { + unTrack(blocks); + track(blocks.stream().map(block -> block.getRelative(direction)).toList()); + } + + public static void move(@NotNull Block from, @NotNull Block to) { + unTrack(from); + track(to); + } + + @Nullable + private static TrackedWorld getTrackedWorldOf(@NotNull Block block) { + return TRACKED_WORLD_MAP.get(block.getWorld().getUID()); + } + + @Nullable + private static TrackedWorld getTrackedWorldOf(@NotNull Chunk chunk) { + return TRACKED_WORLD_MAP.get(chunk.getWorld().getUID()); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/blocktracker/TrackListener.java b/src/main/java/su/nightexpress/nightcore/util/blocktracker/TrackListener.java new file mode 100644 index 0000000..edaf9bc --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/blocktracker/TrackListener.java @@ -0,0 +1,151 @@ +package su.nightexpress.nightcore.util.blocktracker; + +import org.bukkit.GameMode; +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.block.data.Lightable; +import org.bukkit.entity.Entity; +import org.bukkit.entity.FallingBlock; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.*; +import org.bukkit.event.entity.EntityChangeBlockEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.entity.EntitySpawnEvent; +import org.bukkit.event.world.*; +import org.bukkit.metadata.FixedMetadataValue; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.NightCorePlugin; +import su.nightexpress.nightcore.manager.AbstractListener; + +public class TrackListener

extends AbstractListener

{ + + private static final String META_TRACK_FALLING_BLOCK = "tracker_falling_block"; + + public TrackListener(@NotNull P plugin) { + super(plugin); + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onLoad(WorldLoadEvent event) { + PlayerBlockTracker.initWorld(event.getWorld()); + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onUnload(WorldUnloadEvent event) { + PlayerBlockTracker.terminateWorld(event.getWorld()); + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onLoad(ChunkLoadEvent event) { + PlayerBlockTracker.initChunk(event.getChunk()); + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onUnload(ChunkUnloadEvent event) { + PlayerBlockTracker.terminateChunk(event.getChunk()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlace(BlockPlaceEvent event) { + if (event.getPlayer().getGameMode() == GameMode.CREATIVE) { + return; + } + PlayerBlockTracker.track(event.getBlock()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBreak(BlockBreakEvent event) { + PlayerBlockTracker.unTrack(event.getBlock()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onExplode(BlockExplodeEvent event) { + PlayerBlockTracker.unTrack(event.blockList()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onExplode(EntityExplodeEvent event) { + PlayerBlockTracker.unTrack(event.blockList()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBurn(BlockBurnEvent event) { + PlayerBlockTracker.unTrack(event.getBlock()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onFade(BlockFadeEvent event) { + if (event.getBlock().getBlockData() instanceof Lightable) return; + PlayerBlockTracker.unTrack(event.getBlock()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onForm(BlockFormEvent event) { + PlayerBlockTracker.unTrack(event.getBlock()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onFlow(BlockFromToEvent event) { + PlayerBlockTracker.unTrack(event.getBlock()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onGrow(BlockGrowEvent event) { + PlayerBlockTracker.unTrack(event.getBlock()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onStructureGrow(StructureGrowEvent e) { + if (e.getPlayer() == null) return; + PlayerBlockTracker.track(e.getBlocks().stream().map(BlockState::getBlock).toList()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMultiPlace(BlockMultiPlaceEvent event) { + PlayerBlockTracker.track(event.getReplacedBlockStates().stream().map(BlockState::getBlock).toList()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPistonExtend(BlockPistonExtendEvent event) { + PlayerBlockTracker.shift(event.getDirection(), event.getBlocks()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPistonRetract(BlockPistonRetractEvent event) { + if (!event.isSticky()) { + return; + } + PlayerBlockTracker.shift(event.getDirection(), event.getBlocks()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onSpread(BlockSpreadEvent event) { + PlayerBlockTracker.unTrack(event.getBlock()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onEntityForm(EntityBlockFormEvent event) { + PlayerBlockTracker.unTrack(event.getBlock()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onEntityFallingSpawn(EntitySpawnEvent event) { + Entity entity = event.getEntity(); + if (!(entity instanceof FallingBlock)) return; + + Block block = entity.getLocation().getBlock(); + if (!PlayerBlockTracker.isTracked(block)) return; + + entity.setMetadata(META_TRACK_FALLING_BLOCK, new FixedMetadataValue(plugin, true)); + PlayerBlockTracker.unTrack(block); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onEntityFallingLand(EntityChangeBlockEvent event) { + Entity entity = event.getEntity(); + if (!entity.hasMetadata(META_TRACK_FALLING_BLOCK)) return; + + PlayerBlockTracker.trackForce(event.getBlock()); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/blocktracker/TrackUtil.java b/src/main/java/su/nightexpress/nightcore/util/blocktracker/TrackUtil.java new file mode 100644 index 0000000..1273978 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/blocktracker/TrackUtil.java @@ -0,0 +1,28 @@ +package su.nightexpress.nightcore.util.blocktracker; + +import org.bukkit.Chunk; +import org.bukkit.block.Block; +import org.jetbrains.annotations.NotNull; + +public class TrackUtil { + + public static long getChunkKey(@NotNull Chunk chunk) { + return getChunkKey(chunk.getX(), chunk.getZ()); + } + + public static long getChunkKey(final int chunkX, final int chunkZ) { + return (long) chunkX & 0xFFFFFFFFL | ((long) chunkZ & 0xFFFFFFFFL) << 32; + } + + public static long getChunkKeyOfBlock(@NotNull Block block) { + return getChunkKey(block.getX() >> 4, block.getZ() >> 4); + } + + public static int getRelativeChunkPosition(@NotNull Block block) { + final int relX = (block.getX() % 16 + 16) % 16; + final int relZ = (block.getZ() % 16 + 16) % 16; + final int relY = block.getY(); + return (relY & 0xFFFF) | ((relX & 0xFF) << 16) | ((relZ & 0xFF) << 24); + } + +} \ No newline at end of file diff --git a/src/main/java/su/nightexpress/nightcore/util/blocktracker/TrackedChunk.java b/src/main/java/su/nightexpress/nightcore/util/blocktracker/TrackedChunk.java new file mode 100644 index 0000000..bdb497c --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/blocktracker/TrackedChunk.java @@ -0,0 +1,44 @@ +package su.nightexpress.nightcore.util.blocktracker; + +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntSet; +import org.bukkit.block.Block; +import org.bukkit.persistence.PersistentDataContainer; +import org.bukkit.persistence.PersistentDataType; +import org.jetbrains.annotations.NotNull; + +public class TrackedChunk { + + private final IntSet trackedBlockPositions; + + protected TrackedChunk(@NotNull PersistentDataContainer container) { + final int[] data = container.get(PlayerBlockTracker.TRACKED_DATA_KEY, PersistentDataType.INTEGER_ARRAY); + if (data == null) { + this.trackedBlockPositions = new IntOpenHashSet(); + } + else { + this.trackedBlockPositions = new IntOpenHashSet(data); + } + } + + protected void add(@NotNull Block block) { + this.trackedBlockPositions.add(TrackUtil.getRelativeChunkPosition(block)); + } + + protected void remove(@NotNull Block block) { + this.trackedBlockPositions.remove(TrackUtil.getRelativeChunkPosition(block)); + } + + protected boolean isTracked(@NotNull Block block) { + return this.trackedBlockPositions.contains(TrackUtil.getRelativeChunkPosition(block)); + } + + protected void saveTo(@NotNull PersistentDataContainer container) { + final int[] data = this.trackedBlockPositions.toIntArray(); + container.set(PlayerBlockTracker.TRACKED_DATA_KEY, PersistentDataType.INTEGER_ARRAY, data); + } + + protected boolean isEmpty() { + return this.trackedBlockPositions.isEmpty(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/blocktracker/TrackedWorld.java b/src/main/java/su/nightexpress/nightcore/util/blocktracker/TrackedWorld.java new file mode 100644 index 0000000..3123171 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/blocktracker/TrackedWorld.java @@ -0,0 +1,62 @@ +package su.nightexpress.nightcore.util.blocktracker; + +import it.unimi.dsi.fastutil.longs.Long2ObjectMap; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import org.bukkit.Chunk; +import org.bukkit.block.Block; +import org.bukkit.persistence.PersistentDataContainer; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class TrackedWorld { + + private final Long2ObjectMap chunkMap; + + protected TrackedWorld() { + this.chunkMap = new Long2ObjectOpenHashMap<>(); + } + + protected boolean isTracked(@NotNull Block block) { + TrackedChunk trackedChunk = this.getChunkOf(block); + return trackedChunk != null && trackedChunk.isTracked(block); + } + + protected void add(@NotNull Block block) { + TrackedChunk trackedChunk = this.getChunkOf(block); + if (trackedChunk == null) return; + + trackedChunk.add(block); + } + + protected void remove(@NotNull Block block) { + TrackedChunk trackedChunk = this.getChunkOf(block); + if (trackedChunk == null) return; + + trackedChunk.remove(block); + } + + protected void initChunk(@NotNull Chunk chunk) { + PersistentDataContainer container = chunk.getPersistentDataContainer(); + TrackedChunk trackedChunk = new TrackedChunk(container); + this.chunkMap.put(TrackUtil.getChunkKey(chunk), trackedChunk); + } + + protected void terminateChunk(@NotNull Chunk chunk) { + TrackedChunk trackedChunk = this.chunkMap.remove(TrackUtil.getChunkKey(chunk)); + if (trackedChunk == null) { + return; + } + PersistentDataContainer container = chunk.getPersistentDataContainer(); + if (trackedChunk.isEmpty()) { + container.remove(PlayerBlockTracker.TRACKED_DATA_KEY); + } + else { + trackedChunk.saveTo(container); + } + } + + @Nullable + private TrackedChunk getChunkOf(@NotNull Block block) { + return this.chunkMap.get(TrackUtil.getChunkKeyOfBlock(block)); + } +} \ No newline at end of file diff --git a/src/main/java/su/nightexpress/nightcore/util/message/NexComponent.java b/src/main/java/su/nightexpress/nightcore/util/message/NexComponent.java new file mode 100644 index 0000000..b9cf433 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/message/NexComponent.java @@ -0,0 +1,158 @@ +package su.nightexpress.nightcore.util.message; + +import net.md_5.bungee.api.chat.*; +import net.md_5.bungee.api.chat.hover.content.Item; +import net.md_5.bungee.api.chat.hover.content.Text; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.Colorizer; +import su.nightexpress.nightcore.util.ItemUtil; + +import java.util.List; + +@Deprecated +public class NexComponent { + + private final String text; + + public HoverEvent hoverEvent; + public ClickEvent clickEvent; + + private String font; + private String insertion; + + public NexComponent(@NotNull String text) { + this.text = Colorizer.apply(text); + } + + @NotNull + public String getText() { + return this.text; + } + + @Nullable + public String getFont() { + return font; + } + + public void setFont(@Nullable String font) { + this.font = font; + } + + @Nullable + public String getInsertion() { + return insertion; + } + + public void setInsertion(@Nullable String insertion) { + this.insertion = insertion; + } + + @Nullable + public HoverEvent getHoverEvent() { + return this.hoverEvent; + } + + @Nullable + public ClickEvent getClickEvent() { + return this.clickEvent; + } + + @NotNull + public NexComponent addClickEvent(@NotNull ClickEvent.Action action, @NotNull String value) { + return switch (action) { + case OPEN_URL -> this.openURL(value); + case OPEN_FILE, CHANGE_PAGE -> this; + case RUN_COMMAND -> this.runCommand(value); + case SUGGEST_COMMAND -> this.suggestCommand(value); + case COPY_TO_CLIPBOARD -> this.copyToClipboard(value); + }; + } + + @NotNull + public NexComponent addHoverEvent(@NotNull HoverEvent.Action action, @NotNull String value) { + return switch (action) { + case SHOW_ITEM -> { + ItemStack item = ItemUtil.decompress(value); + yield this.showItem(item == null ? new ItemStack(Material.AIR) : item); + } + case SHOW_TEXT -> this.showText(value); + default -> this; + }; + } + + @NotNull + public NexComponent showText(@NotNull String text) { + return this.showText(text.split(NexParser.TAG_NEWLINE)); + } + + @NotNull + public NexComponent showText(@NotNull List text) { + return this.showText(text.toArray(new String[0])); + } + + @NotNull + public NexComponent showText(@NotNull String... text) { + BaseComponent[] base = NexMessage.fromLegacyText(Colorizer.apply(String.join("\n", text))); + this.hoverEvent = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(base)); + return this; + } + + @NotNull + public NexComponent showItem(@NotNull ItemStack is) { + ItemMeta meta = is.getItemMeta(); + Item item = new Item(is.getType().getKey().getKey(), is.getAmount(), ItemTag.ofNbt(meta == null ? null : meta.getAsString())); + this.hoverEvent = new HoverEvent(HoverEvent.Action.SHOW_ITEM, item); + return this; + } + + @NotNull + public NexComponent runCommand(@NotNull String command) { + this.clickEvent = new ClickEvent(ClickEvent.Action.RUN_COMMAND, command); + return this; + } + + @NotNull + public NexComponent suggestCommand(@NotNull String command) { + this.clickEvent = new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, command); + return this; + } + + @NotNull + public NexComponent openURL(@NotNull String url) { + this.clickEvent = new ClickEvent(ClickEvent.Action.OPEN_URL, url); + return this; + } + + @NotNull + public NexComponent copyToClipboard(@NotNull String text) { + this.clickEvent = new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, text); + return this; + } + + @NotNull + public TextComponent build() { + TextComponent component = new TextComponent(NexMessage.fromLegacyText(this.getText())); + if (this.hoverEvent != null) { + component.setHoverEvent(this.getHoverEvent()); + } + if (this.clickEvent != null) { + component.setClickEvent(this.getClickEvent()); + } + component.setFont(this.getFont()); + component.setInsertion(this.getInsertion()); + return component; + } + + @Override + public String toString() { + return "NexComponent{" + + "text='" + text + '\'' + + ", hoverEvent=" + hoverEvent + + ", clickEvent=" + clickEvent + + '}'; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/message/NexMessage.java b/src/main/java/su/nightexpress/nightcore/util/message/NexMessage.java new file mode 100644 index 0000000..d3b74d1 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/message/NexMessage.java @@ -0,0 +1,230 @@ +package su.nightexpress.nightcore.util.message; + +import com.google.common.base.Preconditions; +import net.md_5.bungee.api.ChatColor; +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.util.Colorizer; +import su.nightexpress.nightcore.util.Reflex; + +import java.lang.reflect.Method; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +@Deprecated +public class NexMessage { + + //private static final Pattern URL = Pattern.compile("(?:(https?)://)?([-\\w_\\.]{2,}\\.[a-z]{2,4})(/\\S*)?$"); + + private String message; + private final Map components; + + public NexMessage(@NotNull String message) { + this.message = Colorizer.apply(message); + this.components = new HashMap<>(); + + // Originally was in 'fromLegacyText' method of the TextComponent class. + /*Matcher matcher = RegexUtil.getMatcher(URL, Colorizer.strip(this.message)); + while (RegexUtil.matcherFind(matcher)) { + String url = matcher.group(0); + String link = url.startsWith("http") ? url : "http://" + url; + + this.addComponent(url, url).openURL(link); + }*/ + } + + @NotNull + public NexComponent addComponent(@NotNull String placeholder, @NotNull String text) { + NexComponent component = new NexComponent(text); + String tag = "{@" + this.components.size() + "}"; + + this.components.put(tag, component); + this.message = this.message.replaceFirst(Pattern.quote(placeholder) + "(?!\\w)", tag); + return component; + } + + @NotNull + public BaseComponent[] build() { + return this.build(this.message); + } + + @NotNull + private BaseComponent[] build(@NotNull String line) { + ComponentBuilder builder = new ComponentBuilder(); + + StringBuilder text = new StringBuilder(); + for (int index = 0; index < line.length(); index++) { + char letter = line.charAt(index); + if (letter == '{') { + int indexEnd = line.indexOf("}", index); + if (indexEnd > index && ++indexEnd <= line.length()) { + String varRaw = line.substring(index, indexEnd); + if (varRaw.charAt(1) == '@') { + if (!text.isEmpty()) { + append(builder, fromLegacyText(text.toString()), ComponentBuilder.FormatRetention.ALL); + text = new StringBuilder(); + } + + index += varRaw.length() - 1; + + NexComponent component = this.components.get(varRaw); + if (component == null) continue; + + append(builder, component.build(), ComponentBuilder.FormatRetention.ALL); + continue; + } + } + } + text.append(letter); + } + if (!text.isEmpty()) { + append(builder, fromLegacyText(text.toString()), ComponentBuilder.FormatRetention.ALL); + } + TO_RETAIN.clear(); + return builder.create(); + } + + public void send(@NotNull CommandSender sender) { + if (sender instanceof Player player) { + for (String line : this.message.split("\n")) { + player.spigot().sendMessage(this.build(line)); + } + } + } + + public void send(@NotNull CommandSender... senders) { + Stream.of(senders).forEach(this::send); + } + + public void send(@NotNull Collection senders) { + senders.forEach(this::send); + } + + // Фикс форматирования компонентов на основе https://github.com/SpigotMC/BungeeCord/pull/3344/ + // Так как этот фикс не встроен в API спигота, и все равно работает не так, как нужно, будем использовать свой. + + private static final Set TO_RETAIN = ConcurrentHashMap.newKeySet(); + private static final Method GET_DUMMY = Reflex.getMethod(ComponentBuilder.class, "getDummy"); + + @NotNull + public static ComponentBuilder append(@NotNull ComponentBuilder orig, + @NotNull BaseComponent[] components, + @NotNull ComponentBuilder.FormatRetention retention) { + Preconditions.checkArgument(components.length != 0, "No components to append"); + for (BaseComponent component : components) { + append(orig, component, retention); + } + return orig; + } + + @NotNull + public static ComponentBuilder append(@NotNull ComponentBuilder orig, + @NotNull BaseComponent component, + @NotNull ComponentBuilder.FormatRetention retention) { + List parts = orig.getParts(); + BaseComponent previous = parts.isEmpty() ? null : parts.get(parts.size() - 1); + if (previous == null) { + previous = GET_DUMMY == null ? null : (BaseComponent) Reflex.invokeMethod(GET_DUMMY, orig); + Reflex.setFieldValue(orig, "dummy", null); + } + + BaseComponent inheritance = TO_RETAIN.stream().filter(has -> has.equals(component)).findFirst().orElse(null); + if (previous != null && inheritance != null) { + component.copyFormatting(previous, retention, false); + TO_RETAIN.remove(inheritance); + } + + parts.add(component); + orig.resetCursor(); + return orig; + } + + public static BaseComponent[] fromLegacyText(@NotNull String message) { + return fromLegacyText(message, ChatColor.WHITE); + } + + public static BaseComponent[] fromLegacyText(@NotNull String message, @NotNull ChatColor defaultColor) { + ArrayList components = new ArrayList<>(); + StringBuilder builder = new StringBuilder(); + TextComponent component = new TextComponent(); + + for (int index = 0; index < message.length(); index++) { + char letter = message.charAt(index); + if (letter == ChatColor.COLOR_CHAR) { + if (++index >= message.length()) break; + + letter = message.charAt(index); + if (letter >= 'A' && letter <= 'Z') { + letter += 32; + } + + ChatColor format; + if (letter == 'x' && index + 12 < message.length()) { + StringBuilder hex = new StringBuilder("#"); + for (int indexHex = 0; indexHex < 6; indexHex++) { + hex.append(message.charAt(index + 2 + (indexHex * 2))); + } + try { + format = ChatColor.of(hex.toString()); + } + catch (IllegalArgumentException ex) { + format = null; + } + + index += 12; + } + else { + format = ChatColor.getByChar( letter ); + } + if (format == null) continue; + + if (builder.length() > 0) { + TextComponent old = component; + component = new TextComponent(old); + old.setText(builder.toString()); + builder = new StringBuilder(); + components.add(old); + } + + if (format == ChatColor.BOLD) { + component.setBold( true ); + } + else if (format == ChatColor.ITALIC) { + component.setItalic(true); + } + else if (format == ChatColor.UNDERLINE) { + component.setUnderlined(true); + } + else if (format == ChatColor.STRIKETHROUGH) { + component.setStrikethrough(true); + } + else if (format == ChatColor.MAGIC) { + component.setObfuscated(true); + } + else { + if (format == ChatColor.RESET) { + format = defaultColor; + } + component = new TextComponent(); + component.setColor(format); + } + continue; + } + builder.append(letter); + } + + if (!component.hasFormatting()) { + TO_RETAIN.add(component); + } + + component.setText(builder.toString()); + components.add(component); + return components.toArray(new BaseComponent[0]); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/message/NexParser.java b/src/main/java/su/nightexpress/nightcore/util/message/NexParser.java new file mode 100644 index 0000000..49ba9a2 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/message/NexParser.java @@ -0,0 +1,136 @@ +package su.nightexpress.nightcore.util.message; + +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.HoverEvent; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.Colorizer; +import su.nightexpress.nightcore.util.regex.TimedMatcher; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@Deprecated +public class NexParser { + + private static final String OPTION_PATTERN = ":(?:'|\")(.*?)(?:'|\")(?=>|\\s|$)"; + + private static final Pattern PATTERN_OPTIONS = Pattern.compile("<\\?(.*?)\\?>(.*?)(?:<\\/>)+"); + private static final Map PATTERN_CLICKS = new HashMap<>(); + private static final Map PATTERN_HOVERS = new HashMap<>(); + private static final Pattern PATTERN_FONT = Pattern.compile("font" + OPTION_PATTERN); + private static final Pattern PATTERN_INSERTION = Pattern.compile("insertion" + OPTION_PATTERN); + + public static final String TAG_NEWLINE = ""; + + static { + for (ClickEvent.Action action : ClickEvent.Action.values()) { + PATTERN_CLICKS.put(action, Pattern.compile(action.name().toLowerCase() + OPTION_PATTERN)); + } + for (HoverEvent.Action action : HoverEvent.Action.values()) { + PATTERN_HOVERS.put(action, Pattern.compile(action.name().toLowerCase() + OPTION_PATTERN)); + } + } + + public static boolean contains(@NotNull String message) { + TimedMatcher matcher = TimedMatcher.create(PATTERN_OPTIONS, message); + return matcher.find(); + } + + @NotNull + public static String removeFrom(@NotNull String message) { + return strip(message, false); + } + + @NotNull + public static String toPlainText(@NotNull String message) { + return strip(message, true); + } + + @NotNull + private static String strip(@NotNull String message, boolean toPlain) { + TimedMatcher timedMatcher = TimedMatcher.create(PATTERN_OPTIONS, message); + while (timedMatcher.find()) { + Matcher matcher = timedMatcher.getMatcher(); + String matchFull = matcher.group(0); + if (toPlain) { + String matchOptions = matcher.group(1).trim(); + String matchText = matcher.group(2); + message = message.replace(matchFull, matchText); + } + else message = message.replace(matchFull, ""); + } + return message; + } + + public static String[] getPlainParts(@NotNull String message) { + //message = StringUtil.color(message.replace("\n", " ")); + return PATTERN_OPTIONS.split(message); + } + + public static String[] getComponentParts(@NotNull String message) { + List components = new ArrayList<>(); + + TimedMatcher timedMatcher = TimedMatcher.create(PATTERN_OPTIONS, message); + while (timedMatcher.find()) { + components.add(timedMatcher.getMatcher().group(0)); + } + + return components.toArray(new String[0]); + } + + @NotNull + public static NexMessage toMessage(@NotNull String message) { + message = Colorizer.apply(message); + + TimedMatcher timedMatcher = TimedMatcher.create(PATTERN_OPTIONS, message); + Map parameters = new HashMap<>(); + while (timedMatcher.find()) { + Matcher matcher = timedMatcher.getMatcher(); + String matchFull = matcher.group(0); + String matchOptions = matcher.group(1).trim(); + String matchText = matcher.group(2); + + message = message.replace(matchFull, matchText); + parameters.put(matchText, matchOptions); + } + + NexMessage nexMessage = new NexMessage(message); + for (Map.Entry entry : parameters.entrySet()) { + String text = entry.getKey(); + String options = entry.getValue(); + + NexComponent component = nexMessage.addComponent(text, text); + for (Map.Entry entryParams : PATTERN_CLICKS.entrySet()) { + String paramValue = getOption(entryParams.getValue(), options); + if (paramValue == null) continue; + + component.addClickEvent(entryParams.getKey(), paramValue); + break; + } + for (Map.Entry entryParams : PATTERN_HOVERS.entrySet()) { + String paramValue = getOption(entryParams.getValue(), options); + if (paramValue == null) continue; + + component.addHoverEvent(entryParams.getKey(), paramValue); + break; + } + component.setFont(getOption(PATTERN_FONT, options)); + component.setInsertion(getOption(PATTERN_INSERTION, options)); + } + + return nexMessage; + } + + @Nullable + private static String getOption(@NotNull Pattern pattern, @NotNull String from) { + TimedMatcher timedMatcher = TimedMatcher.create(pattern, from); + if (!timedMatcher.find()) return null; + + return timedMatcher.getMatcher().group(1).stripLeading(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/placeholder/Placeholder.java b/src/main/java/su/nightexpress/nightcore/util/placeholder/Placeholder.java new file mode 100644 index 0000000..416074b --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/placeholder/Placeholder.java @@ -0,0 +1,15 @@ +package su.nightexpress.nightcore.util.placeholder; + +import org.jetbrains.annotations.NotNull; + +import java.util.function.UnaryOperator; + +public interface Placeholder { + + @NotNull PlaceholderMap getPlaceholders(); + + @NotNull + default UnaryOperator replacePlaceholders() { + return this.getPlaceholders().replacer(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/placeholder/PlaceholderMap.java b/src/main/java/su/nightexpress/nightcore/util/placeholder/PlaceholderMap.java new file mode 100644 index 0000000..2b38b97 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/placeholder/PlaceholderMap.java @@ -0,0 +1,77 @@ +package su.nightexpress.nightcore.util.placeholder; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.Pair; +import su.nightexpress.nightcore.util.StringUtil; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; + +public class PlaceholderMap { + + private final List>> keys; + + public PlaceholderMap() { + this(new ArrayList<>()); + } + + public PlaceholderMap(@NotNull PlaceholderMap other) { + this(other.getKeys()); + } + + public PlaceholderMap(@NotNull List>> keys) { + this.keys = new ArrayList<>(keys); + } + + @NotNull + public static PlaceholderMap fusion(@NotNull PlaceholderMap... others) { + PlaceholderMap map = new PlaceholderMap(); + for (PlaceholderMap other : others) { + map.add(other); + } + return map; + } + + @NotNull + public static PlaceholderMap fusion(@NotNull Placeholder... others) { + PlaceholderMap map = new PlaceholderMap(); + for (Placeholder other : others) { + map.add(other.getPlaceholders()); + } + return map; + } + + @NotNull + public List>> getKeys() { + return keys; + } + + @NotNull + public PlaceholderMap add(@NotNull PlaceholderMap other) { + this.getKeys().addAll(other.getKeys()); + return this; + } + + @NotNull + public PlaceholderMap add(@NotNull String key, @NotNull String replacer) { + this.add(key, () -> replacer); + return this; + } + + @NotNull + public PlaceholderMap add(@NotNull String key, @NotNull Supplier replacer) { + this.getKeys().add(Pair.of(key, replacer)); + return this; + } + + public void clear() { + this.getKeys().clear(); + } + + @NotNull + public UnaryOperator replacer() { + return str -> StringUtil.replaceEach(str, this.getKeys()); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/random/MTRandom.java b/src/main/java/su/nightexpress/nightcore/util/random/MTRandom.java new file mode 100644 index 0000000..fc28dc6 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/random/MTRandom.java @@ -0,0 +1,111 @@ +package su.nightexpress.nightcore.util.random; + +import java.util.Random; + +public class MTRandom extends Random { + + private final static int UPPER_MASK = 0x80000000; + private final static int LOWER_MASK = 0x7fffffff; + + private final static int N = 624; + private final static int M = 397; + private final static int[] MAGIC = {0x0, 0x9908b0df}; + private final static int MAGIC_FACTOR1 = 1812433253; + private final static int MAGIC_FACTOR2 = 1664525; + private final static int MAGIC_FACTOR3 = 1566083941; + private final static int MAGIC_MASK1 = 0x9d2c5680; + private final static int MAGIC_MASK2 = 0xefc60000; + private final static int MAGIC_SEED = 19650218; + private final static long DEFAULT_SEED = 5489L; + + // Internal state + private transient int[] mt; + private transient int mti; + + // Temporary buffer used during setSeed(long) + private transient int[] ibuf; + + public MTRandom() { + + } + + private void setSeed() { + if (mt == null) mt = new int[N]; + + // ---- Begin Mersenne Twister Algorithm ---- + mt[0] = MTRandom.MAGIC_SEED; + for (mti = 1; mti < N; mti++) { + mt[mti] = (MAGIC_FACTOR1 * (mt[mti - 1] ^ (mt[mti - 1] >>> 30)) + mti); + } + // ---- End Mersenne Twister Algorithm ---- + } + + public final synchronized void setSeed(long seed) { + if (ibuf == null) ibuf = new int[2]; + + ibuf[0] = (int) seed; + ibuf[1] = (int) (seed >>> 32); + setSeed(ibuf); + } + + protected final synchronized int next(int bits) { + // ---- Begin Mersenne Twister Algorithm ---- + int y, kk; + if (mti >= N) { + + for (kk = 0; kk < N - M; kk++) { + y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); + mt[kk] = mt[kk + M] ^ (y >>> 1) ^ MAGIC[y & 0x1]; + } + for (; kk < N - 1; kk++) { + y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); + mt[kk] = mt[kk + (M - N)] ^ (y >>> 1) ^ MAGIC[y & 0x1]; + } + y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); + mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ MAGIC[y & 0x1]; + + mti = 0; + } + + y = mt[mti++]; + + // Tempering + y ^= (y >>> 11); + y ^= (y << 7) & MAGIC_MASK1; + y ^= (y << 15) & MAGIC_MASK2; + y ^= (y >>> 18); + // ---- End Mersenne Twister Algorithm ---- + return (y >>> (32 - bits)); + } + + // This is a fairly obscure little code section to pack a + // byte[] into an int[] in little endian ordering. + + public final synchronized void setSeed(int[] buf) { + int length = buf.length; + if (length == 0) throw new IllegalArgumentException("Seed buffer may not be empty"); + // ---- Begin Mersenne Twister Algorithm ---- + int i = 1, j = 0, k = (Math.max(N, length)); + setSeed(); + for (; k > 0; k--) { + mt[i] = (mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >>> 30)) * MAGIC_FACTOR2)) + buf[j] + j; + i++; + j++; + if (i >= N) { + mt[0] = mt[N - 1]; + i = 1; + } + if (j >= length) j = 0; + } + for (k = N - 1; k > 0; k--) { + mt[i] = (mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >>> 30)) * MAGIC_FACTOR3)) - i; + i++; + if (i >= N) { + mt[0] = mt[N - 1]; + i = 1; + } + } + mt[0] = UPPER_MASK; // MSB is 1; assuring non-zero initial array + // ---- End Mersenne Twister Algorithm ---- + } +} \ No newline at end of file diff --git a/src/main/java/su/nightexpress/nightcore/util/random/Rnd.java b/src/main/java/su/nightexpress/nightcore/util/random/Rnd.java new file mode 100644 index 0000000..9b3c241 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/random/Rnd.java @@ -0,0 +1,101 @@ +package su.nightexpress.nightcore.util.random; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.Pair; + +import java.util.*; + +public class Rnd { + + public static final MTRandom RANDOM = new MTRandom(); + + public static float getChance() { + return nextFloat() * 100f; + } + + public static int get(int n) { + return nextInt(n); + } + + public static int get(int min, int max) { + return min + (int) Math.floor(RANDOM.nextDouble() * (max - min + 1)); + } + + public static double getDouble(double max) { + return getDouble(0, max); + } + + public static double getDouble(double min, double max) { + return min + (max - min) * RANDOM.nextDouble(); + } + + @NotNull + public static E get(@NotNull E[] list) { + return list[get(list.length)]; + } + + public static int get(int[] list) { + return list[get(list.length)]; + } + + @NotNull + public static E get(@NotNull List list) { + if (list.isEmpty()) throw new NoSuchElementException("Empty list provided!"); + + return list.get(get(list.size())); + } + + @NotNull + public static E get(@NotNull Set list) { + return get(new ArrayList<>(list)); + } + + @NotNull + public static T getByWeight(@NotNull Map itemsMap) { + List> items = itemsMap.entrySet().stream() + .filter(entry -> entry.getValue() > 0D) + .map(entry -> Pair.of(entry.getKey(), entry.getValue())) + .sorted(Comparator.comparing(Pair::getSecond)) + .toList(); + double totalWeight = items.stream().mapToDouble(Pair::getSecond).sum(); + + int index = 0; + for (double roll = nextDouble() * totalWeight; index < items.size() - 1; ++index) { + roll -= items.get(index).getSecond(); + if (roll <= 0D) break; + } + return items.get(index).getFirst(); + } + + public static boolean chance(int chance) { + return chance >= 1 && (chance > 99 || nextInt(99) + 1 <= chance); + } + + public static boolean chance(double chance) { + return nextDouble() <= chance / 100.0; + } + + public static int nextInt(int n) { + return (int) Math.floor(RANDOM.nextDouble() * n); + } + + public static int nextInt() { + return RANDOM.nextInt(); + } + + public static double nextDouble() { + return RANDOM.nextDouble(); + } + + public static float nextFloat() { + return RANDOM.nextFloat(); + } + + public static double nextGaussian() { + return RANDOM.nextGaussian(); + } + + public static boolean nextBoolean() { + return RANDOM.nextBoolean(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/regex/MatcherTimeoutException.java b/src/main/java/su/nightexpress/nightcore/util/regex/MatcherTimeoutException.java new file mode 100644 index 0000000..193fc4f --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/regex/MatcherTimeoutException.java @@ -0,0 +1,23 @@ +package su.nightexpress.nightcore.util.regex; + +import org.jetbrains.annotations.NotNull; + +public class MatcherTimeoutException extends RuntimeException { + + private final String chars; + private final long timeout; + + MatcherTimeoutException(@NotNull CharSequence chars, long timeout) { + this.chars = chars.toString(); + this.timeout = timeout; + } + + @NotNull + public String getString() { + return this.chars; + } + + public long getTimeout() { + return this.timeout; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/regex/TimedMatcher.java b/src/main/java/su/nightexpress/nightcore/util/regex/TimedMatcher.java new file mode 100644 index 0000000..79d92ff --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/regex/TimedMatcher.java @@ -0,0 +1,95 @@ +package su.nightexpress.nightcore.util.regex; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.Plugins; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class TimedMatcher { + + private final Matcher matcher; + private boolean debug; + + public TimedMatcher(@NotNull Matcher matcher) { + this.matcher = matcher; + } + + @NotNull + public static TimedMatcher create(@NotNull String pattern, @NotNull String str) { + return create(pattern, str, 200); + } + + @NotNull + public static TimedMatcher create(@NotNull Pattern pattern, @NotNull String str) { + return new TimedMatcher(getMatcher(pattern, str, 200)); + } + + @NotNull + public static TimedMatcher create(@NotNull String rawPattern, @NotNull String str, long timeout) { + return create(Pattern.compile(rawPattern), str, timeout); + } + + @NotNull + public static TimedMatcher create(@NotNull Pattern pattern, @NotNull String str, long timeout) { + return new TimedMatcher(getMatcher(pattern, str, timeout)); + } + + @NotNull + private static Matcher getMatcher(@NotNull Pattern pattern, @NotNull String text, long timeout) { + if (timeout <= 0) { + return pattern.matcher(text); + } + return pattern.matcher(new TimeoutCharSequence(text, timeout)); + } + + @NotNull + public Matcher getMatcher() { + return matcher; + } + + public boolean isDebug() { + return debug; + } + + public void setDebug(boolean debug) { + this.debug = debug; + } + + @NotNull + public String replaceAll(@NotNull String with) { + try { + return this.matcher.replaceAll(with); + } + catch (MatcherTimeoutException exception) { + if (this.isDebug()) { + Plugins.CORE.warn("Matcher " + exception.getTimeout() + "ms timeout error for replaceAll: '" + matcher.pattern().pattern() + "'."); + } + return ""; + } + } + + public boolean matches() { + try { + return this.matcher.matches(); + } + catch (MatcherTimeoutException exception) { + if (this.isDebug()) { + Plugins.CORE.warn("Matcher " + exception.getTimeout() + "ms timeout error for: '" + matcher.pattern().pattern() + "'."); + } + return false; + } + } + + public boolean find() { + try { + return this.matcher.find(); + } + catch (MatcherTimeoutException exception) { + if (this.isDebug()) { + Plugins.CORE.warn("Matcher " + exception.getTimeout() + "ms timeout error for: '" + matcher.pattern().pattern() + "'."); + } + return false; + } + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/regex/TimeoutCharSequence.java b/src/main/java/su/nightexpress/nightcore/util/regex/TimeoutCharSequence.java new file mode 100644 index 0000000..290e876 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/regex/TimeoutCharSequence.java @@ -0,0 +1,39 @@ +package su.nightexpress.nightcore.util.regex; + +import org.jetbrains.annotations.NotNull; + +public class TimeoutCharSequence implements CharSequence { + + private final CharSequence chars; + private final long timeout; + private final long maxTime; + + public TimeoutCharSequence(@NotNull CharSequence chars, long timeout) { + this.chars = chars; + this.timeout = timeout; + this.maxTime = (System.currentTimeMillis() + timeout); + } + + @Override + public char charAt(int index) { + if (System.currentTimeMillis() > this.maxTime) { + throw new MatcherTimeoutException(this.chars, this.timeout); + } + return this.chars.charAt(index); + } + + @Override + public int length() { + return this.chars.length(); + } + + @Override + public CharSequence subSequence(int start, int end) { + return new TimeoutCharSequence(this.chars.subSequence(start, end), this.timeout); + } + + @Override + public String toString() { + return this.chars.toString(); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/NightMessage.java b/src/main/java/su/nightexpress/nightcore/util/text/NightMessage.java new file mode 100644 index 0000000..92937d7 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/NightMessage.java @@ -0,0 +1,350 @@ +package su.nightexpress.nightcore.util.text; + +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.ComponentBuilder; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.Pair; +import su.nightexpress.nightcore.util.Placeholders; +import su.nightexpress.nightcore.util.text.decoration.*; +import su.nightexpress.nightcore.util.text.tag.*; +import su.nightexpress.nightcore.util.text.tag.api.DynamicTag; +import su.nightexpress.nightcore.util.text.tag.api.Tag; +import su.nightexpress.nightcore.util.text.tag.impl.*; + +import java.awt.*; +import java.util.List; +import java.util.*; + +public class NightMessage { + + private static final Map TAG_MAP = new HashMap<>(); + + static { + registerTags( + Tags.WHITE, Tags.GRAY, Tags.GREEN, + Tags.YELLOW, Tags.ORANGE, Tags.RED, + Tags.BLUE, Tags.CYAN, Tags.PURPLE, Tags.PINK, + + Tags.DARK_GRAY, Tags.LIGHT_GRAY, Tags.LIGHT_GREEN, + Tags.LIGHT_YELLOW, Tags.LIGHT_ORANGE, Tags.LIGHT_RED, + Tags.LIGHT_BLUE, Tags.LIGHT_CYAN, Tags.LIGHT_PURPLE, Tags.LIGHT_PINK + ); + + registerTags(Tags.BOLD, Tags.ITALIC, Tags.OBFUSCATED, Tags.STRIKETHROUGH, Tags.UNDERLINED); + + registerTags( + Tags.FONT, Tags.HEX_COLOR, Tags.GRADIENT, + Tags.HOVER, Tags.CLICK, + Tags.LINE_BREAK, Tags.RESET + ); + } + + @NotNull + public static Collection getTags() { + return TAG_MAP.values(); + } + + 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); + } + } + + @Nullable + public static Tag getTag(@NotNull String name) { + return TAG_MAP.get(name.toLowerCase()); + } + + @NotNull + public static String asLegacy(@NotNull String string) { + return create(string).toLegacy(); + } + + @NotNull + public static List asLegacy(@NotNull List string) { + List list = new ArrayList<>(); + for (String str : string) { + for (String br : str.split(Placeholders.TAG_LINE_BREAK)) { + list.add(asLegacy(br)); + } + } + return list; + } + + /** + * + * @param string Text to deserialize. + * @return Precompiled WrappedMessage object. + */ + @NotNull + public static WrappedMessage create(@NotNull String string) { + return create(string, TagPool.ALL); + } + + @NotNull + public static WrappedMessage from(@NotNull String string) { + return from(string, TagPool.ALL); + } + + @NotNull + public static WrappedMessage create(@NotNull String string, @NotNull TagPool tagPool) { + return from(string, tagPool).compile(); + } + + @NotNull + public static WrappedMessage from(@NotNull String string, @NotNull TagPool tagPool) { + return new WrappedMessage(string, tagPool); + } + + + + public static BaseComponent[] parse(@NotNull String string) { + return parse(string, TagPool.ALL); + } + + public static BaseComponent[] parse(@NotNull String string, @NotNull TagPool tagPool) { + List parts = new ArrayList<>(); + + WrappedText currentText = new WrappedText(); + parts.add(currentText); + + Tag lastTag = null; + + 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; + + boolean closeTag = false; + if (next == Tag.CLOSE_MARK) { + closeTag = true; + index++; + } + + String leading = string.substring(index + 1); + String brackets = string.substring(index + 1, indexEnd); + + Tag tag = getTag(brackets); + Decorator decorator = null; + //System.out.println("brackets = " + brackets); + + if (tag == null) { + for (Tag registered : getTags()) { + String tagName = registered.getName(); + if (leading.startsWith(tagName)) { + char latest = leading.charAt(tagName.length()); + + if (latest == Tag.CLOSE_BRACKET || registered instanceof DecoratorParser) { + tag = registered; + break; + } + } + } + } + //System.out.println("found tag = " + tag); + + //if (tag == null) break Tag; + /*if (tag != null && !tagPool.isGoodTag(tag)) { + break Tag; + }*/ + + if (!closeTag) { + // If tag is variable like hex codes or hover/click events. + if (tag instanceof DecoratorParser parser) { + // If tag has no dynamic content, strip it to the next close bracket. + if (!(tag instanceof DynamicTag)) { + leading = brackets; + } + //System.out.println("tag = " + tag.getName()); + //System.out.println("content = " + leading); + ParsedDecorator parsedDecorator = parser.parse(leading); + if (parsedDecorator != null) { + decorator = parsedDecorator.getDecorator(); + indexEnd = index + parsedDecorator.getLength() + 1; // 1 for close bracket + } + } + else if (tag instanceof Decorator textDecorator) { + decorator = textDecorator; + } + } + + if (tag != null) { + if (tagPool.isGoodTag(tag)) { + if (tag == Tags.LINE_BREAK) { + if (currentText.getTextBuilder().isEmpty()) { + currentText.getTextBuilder().append("\n"); + } + else { + currentText = currentText.nested(); + currentText.setText("\n"); + parts.add(currentText); + } + currentText = currentText.nested(); + parts.add(currentText); + } + + // Если был текст ДО текущего тега и не было ДРУГИХ тегов прямо перед ним, + // то вставляем новую часть текста + if (lastTag == null && !currentText.getTextBuilder().isEmpty()) { + currentText = currentText.nested(); + parts.add(currentText); + } + + if (closeTag) { + currentText.removeLatestTag(tag); + } + else if (tag != Tags.LINE_BREAK) { + currentText.addTag(tag, decorator); + } + + lastTag = tag; + } + index = indexEnd; + continue; + } + + // Move cursor back to '/' of invalid closing tag. + if (closeTag) { + index--; + } + } + currentText.getTextBuilder().append(letter); + lastTag = null; + } + + //System.out.println("parsedTexts = " + parts); + + fixGradients(parts); + + ComponentBuilder builder = new ComponentBuilder(); + for (WrappedText wrappedText : parts) { + builder.append(wrappedText.toComponent(), ComponentBuilder.FormatRetention.NONE); + } + + return builder.create(); + } + + // Fix gradient smoothness when multiple WrappedTexts have the same gradient colors, but different tag lists. + private static void fixGradients(@NotNull List parts) { + if (parts.size() < 2) return; + + List>> pairs = new ArrayList<>(); + + Pair> currentList = null; + GradientDecorator lastGradient = null; + int lastIndex = -1; + + // Create a list of sequental parts with the same gradient. + for (int index = 0; index < parts.size(); index++) { + WrappedText text = parts.get(index); + GradientDecorator gradient = (GradientDecorator) text.getDecorator(GradientTag.NAME); + + // Check for next list + if (gradient != null) { + boolean bigStep = (index - lastIndex) > 1; + boolean sameGradient = lastGradient != null && gradient.isSimilar(lastGradient); + boolean lastElement = (index == parts.size() - 1); + if (bigStep || !sameGradient || lastElement) { + if (currentList != null && currentList.getSecond().size() > 1) { + pairs.add(currentList); + } + currentList = Pair.of(gradient, new ArrayList<>()); + } + currentList.getSecond().add(text); + } + else if (currentList != null) { + pairs.add(currentList); + currentList = null; + } + + lastGradient = gradient; + lastIndex = index; + } + //System.out.println("pairs = " + pairs); + + // Recreate Gradient Decorator with shifted colors depends on text length. + for (var pair : pairs) { + GradientDecorator gradient = pair.getFirst(); + List texts = pair.getSecond(); + + int length = texts.stream().mapToInt(text -> text.getText().length()).sum(); + + Color[] colors = gradient.createGradient(length); + int shift = 0; + + for (WrappedText text : texts) { + if (shift >= colors.length) break; + + int textLength = text.getText().length(); + + Color start = colors[shift]; + Color end = colors[textLength + shift - 1]; + + GradientDecorator decorator = new GradientDecorator(start, end); + text.getDecoratorMap().put(GradientTag.NAME, decorator); + + shift += textLength; + } + } + } + + @NotNull + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + private final List texts; + + public Builder() { + this.texts = new ArrayList<>(); + } + + public BaseComponent[] create() { + ComponentBuilder builder = new ComponentBuilder(); + for (WrappedText wrappedText : this.texts) { + builder.append(wrappedText.toComponent(), ComponentBuilder.FormatRetention.NONE); + } + return builder.create(); + } + + public void send(@NotNull CommandSender sender) { + sender.spigot().sendMessage(this.create()); + } + + public Builder append(@NotNull WrappedText.Builder textBuilder) { + this.texts.add(textBuilder.getText()); + return this; + } + + public WrappedText.Builder append(@NotNull String text, @NotNull Tag... tags) { + WrappedText.Builder builder = WrappedText.builder(text); + this.texts.add(builder.getText()); + for (Tag tag : tags) { + builder.tag(tag); + } + return builder; + } + + public Builder appendLineBreak() { + return this.append(WrappedText.builder("\n")); + } + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/WrappedMessage.java b/src/main/java/su/nightexpress/nightcore/util/text/WrappedMessage.java new file mode 100644 index 0000000..7559ad6 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/WrappedMessage.java @@ -0,0 +1,127 @@ +package su.nightexpress.nightcore.util.text; + +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.text.tag.TagPool; + +import java.util.function.UnaryOperator; + +public class WrappedMessage { + + private final TagPool tagPool; + + private String string; + private BaseComponent[] components; + + public WrappedMessage(@NotNull String string, @NotNull TagPool tagPool) { + this.tagPool = tagPool; + this.string = string; + } + + @NotNull + public WrappedMessage copy() { + WrappedMessage copy = new WrappedMessage(this.string, this.tagPool); + if (this.components != null) { + BaseComponent[] components = new BaseComponent[this.components.length]; + for (int index = 0; index < components.length; index++) { + components[index] = this.components[index].duplicate(); + } + copy.components = components; + } + return copy; + } + + @NotNull + public WrappedMessage compile() { + this.parseIfAbsent(); + return this; + } + + @NotNull + public WrappedMessage recompile() { + this.parse(); + return this; + } + + @NotNull + public String toLegacy() { + return TextComponent.toLegacyText(this.parseIfAbsent()); + } + + @NotNull + public WrappedMessage replace(@NotNull String what, @NotNull Object object) { + return this.replace(str -> str.replace(what, String.valueOf(object))); + //return this.replace(what, String.valueOf(object)); + } + + @NotNull + public WrappedMessage replace(@NotNull UnaryOperator operator) { + this.string = operator.apply(this.string); + this.components = null; + return this; + + + /*if (this.components == null) { + this.string = operator.apply(this.string); + return this; + } + + for (BaseComponent component : this.components) { + if (component instanceof TextComponent textComponent) { + textComponent.setText(operator.apply(textComponent.getText())); + } + } + return this;*/ + } + + /*@NotNull + public WrappedMessage replace(@NotNull String var, @NotNull String value) { + if (this.components == null) { + this.string = this.string.replace(var, value); + return this; + } + + WrappedMessage message = NightMessage.create(value); + + ComponentBuilder builder = new ComponentBuilder(); + for (BaseComponent component : this.components) { + if (component instanceof TextComponent textComponent) { + String text = textComponent.getText(); + String[] split = text.split(var); + + ComponentBuilder replacer = new ComponentBuilder(); + for (String part : split) { + if (!replacer.getParts().isEmpty()) { + replacer.append(message.parseIfAbsent()); + } + + TextComponent origin = new TextComponent(part); + origin.copyFormatting(textComponent); + replacer.append(origin); + } + builder.append(replacer.create()); + } + else builder.append(component); + } + + return this; + }*/ + + public void send(@NotNull CommandSender... senders) { + this.parseIfAbsent(); + for (CommandSender sender : senders) { + sender.spigot().sendMessage(this.components); + } + } + + public BaseComponent[] parseIfAbsent() { + return this.components == null ? this.parse() : this.components; + } + + public BaseComponent[] parse() { + this.components = NightMessage.parse(this.string, this.tagPool); + return this.components; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/WrappedText.java b/src/main/java/su/nightexpress/nightcore/util/text/WrappedText.java new file mode 100644 index 0000000..cb3aafe --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/WrappedText.java @@ -0,0 +1,197 @@ +package su.nightexpress.nightcore.util.text; + +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.text.decoration.*; +import su.nightexpress.nightcore.util.text.tag.api.Tag; +import su.nightexpress.nightcore.util.text.tag.Tags; +import su.nightexpress.nightcore.util.text.tag.impl.ColorTag; +import su.nightexpress.nightcore.util.text.tag.impl.FontStyleTag; + +import java.awt.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class WrappedText { + + private final StringBuilder textBuilder; + private final List tags; + private final Map decoratorMap; + + public WrappedText() { + this.textBuilder = new StringBuilder(); + this.tags = new ArrayList<>(); + this.decoratorMap = new HashMap<>(); + } + + public WrappedText(@NotNull String text) { + this(); + this.setText(text); + } + + @NotNull + public WrappedText nested() { + WrappedText nested = new WrappedText(); + nested.getTags().addAll(this.getTags()); + nested.getDecoratorMap().putAll(this.getDecoratorMap()); + return nested; + } + + @Nullable + public Decorator getDecorator(@NotNull Tag tag) { + return this.getDecorator(tag.getName()); + } + + @Nullable + public Decorator getDecorator(@NotNull String tagName) { + return this.getDecoratorMap().get(tagName.toLowerCase()); + } + + @NotNull + public BaseComponent toComponent() { + TextComponent component = new TextComponent(this.getText()); + + for (Tag tag : this.getTags()) { + Decorator decorator = this.getDecorator(tag); + if (decorator == null) continue; + + decorator.decorate(component); + } + + return component; + } + + public void addTag(@NotNull Tag tag, @Nullable Decorator decorator) { + //this.getTags().removeIf(tag::conflictsWith); + this.getTags().removeIf(other -> other.getName().equals(tag.getName())); + this.getTags().add(tag); + if (decorator != null) { + this.decoratorMap.put(tag.getName(), decorator); + } + } + + public void removeLatestTag(@NotNull Tag tag) { + for (int indexTag = this.getTags().size() - 1; indexTag > -1; indexTag--) { + Tag has = this.getTags().get(indexTag); + if (has.getName().equalsIgnoreCase(tag.getName())) { + this.getTags().remove(indexTag); + this.getDecoratorMap().remove(tag.getName()); + break ; + } + } + } + + public void removeTag(@NotNull Tag tag) { + this.getTags().remove(tag); + this.getDecoratorMap().remove(tag.getName()); + } + + @NotNull + public List getTags() { + return tags; + } + + @NotNull + public Map getDecoratorMap() { + return decoratorMap; + } + + @NotNull + public StringBuilder getTextBuilder() { + return textBuilder; + } + + @NotNull + public String getText() { + return this.getTextBuilder().toString(); + } + + public void setText(@NotNull String text) { + this.textBuilder.setLength(0); + this.textBuilder.append(text); + } + + @Override + public String toString() { + return "ParsedText{" + + "tags=" + tags + + ", text=" + textBuilder + + '}'; + } + + @NotNull + public static Builder builder(@NotNull String text) { + return new Builder(new WrappedText(text)); + } + + public static class Builder { + + private final WrappedText text; + + public Builder(@NotNull WrappedText text) { + this.text = text; + } + + @NotNull + public WrappedText getText() { + return text; + } + + @NotNull + public Builder tag(@NotNull Tag tag) { + return this.tag(tag, tag instanceof Decorator decorator ? decorator : null); + } + + @NotNull + public Builder tag(@NotNull Tag tag, @Nullable Decorator decorator) { + this.getText().addTag(tag, decorator); + return this; + } + + public Builder color(@NotNull Color color) { + return this.color(new ColorTag(color)); + } + + public Builder color(@NotNull ColorTag tag) { + return this.tag(tag); + } + + public Builder bold() { + return style(Tags.BOLD); + } + + public Builder style(@NotNull FontStyleTag tag) { + return this.tag(tag); + } + + public Builder gradient(@NotNull Color from, @NotNull Color to) { + return this.tag(Tags.GRADIENT, new GradientDecorator(from, to)); + } + + public Builder showText(@NotNull String... text) { + return this.tag(Tags.HOVER, new ShowTextDecorator(text)); + } + + public Builder showItem(@NotNull ItemStack itemStack) { + return this.tag(Tags.HOVER, new ShowItemDecorator(itemStack)); + } + + public Builder runCommand(@NotNull String value) { + return this.clickEvent(ClickEvent.Action.RUN_COMMAND, value); + } + + public Builder suggestCommand(@NotNull String value) { + return this.clickEvent(ClickEvent.Action.SUGGEST_COMMAND, value); + } + + public Builder clickEvent(@NotNull ClickEvent.Action action, @NotNull String value) { + return this.tag(Tags.CLICK, new ClickEventDecorator(action, value)); + } + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/decoration/ClickEventDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/decoration/ClickEventDecorator.java new file mode 100644 index 0000000..f21d1ef --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/decoration/ClickEventDecorator.java @@ -0,0 +1,26 @@ +package su.nightexpress.nightcore.util.text.decoration; + +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.ClickEvent; +import org.jetbrains.annotations.NotNull; + +public class ClickEventDecorator implements Decorator { + + private final ClickEvent.Action action; + private final String value; + + public ClickEventDecorator(@NotNull ClickEvent.Action action, @NotNull String value) { + this.action = action; + this.value = value; + } + + @NotNull + public ClickEvent createEvent() { + return new ClickEvent(this.action, this.value); + } + + @Override + public void decorate(@NotNull BaseComponent component) { + component.setClickEvent(this.createEvent()); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/decoration/Decorator.java b/src/main/java/su/nightexpress/nightcore/util/text/decoration/Decorator.java new file mode 100644 index 0000000..d6912bf --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/decoration/Decorator.java @@ -0,0 +1,9 @@ +package su.nightexpress.nightcore.util.text.decoration; + +import net.md_5.bungee.api.chat.BaseComponent; +import org.jetbrains.annotations.NotNull; + +public interface Decorator { + + void decorate(@NotNull BaseComponent component); +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/decoration/DecoratorParser.java b/src/main/java/su/nightexpress/nightcore/util/text/decoration/DecoratorParser.java new file mode 100644 index 0000000..7713fe2 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/decoration/DecoratorParser.java @@ -0,0 +1,9 @@ +package su.nightexpress.nightcore.util.text.decoration; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public interface DecoratorParser { + + @Nullable ParsedDecorator parse(@NotNull String str); +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/decoration/FontDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/decoration/FontDecorator.java new file mode 100644 index 0000000..2f8569a --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/decoration/FontDecorator.java @@ -0,0 +1,18 @@ +package su.nightexpress.nightcore.util.text.decoration; + +import net.md_5.bungee.api.chat.BaseComponent; +import org.jetbrains.annotations.NotNull; + +public class FontDecorator implements Decorator { + + private final String font; + + public FontDecorator(@NotNull String font) { + this.font = font; + } + + @Override + public void decorate(@NotNull BaseComponent component) { + component.setFont(this.font); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/decoration/GradientDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/decoration/GradientDecorator.java new file mode 100644 index 0000000..3b49427 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/decoration/GradientDecorator.java @@ -0,0 +1,79 @@ +package su.nightexpress.nightcore.util.text.decoration; + +import net.md_5.bungee.api.ChatColor; +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.TextComponent; +import org.jetbrains.annotations.NotNull; + +import java.awt.*; + +public class GradientDecorator implements Decorator { + + private final Color color; + private final Color colorEnd; + + public GradientDecorator(@NotNull Color color, @NotNull Color colorEnd) { + this.color = color; + this.colorEnd = colorEnd; + } + + public boolean isSimilar(@NotNull GradientDecorator other) { + return this.getColor().equals(other.getColor()) && this.getColorEnd().equals(other.getColorEnd()); + } + + public Color getColor() { + return color; + } + + @NotNull + public Color getColorEnd() { + return colorEnd; + } + + public Color[] createGradient(int length) { + Color[] colors = new Color[length]; + for (int index = 0; index < length; index++) { + double percent = (double) index / (double) length; + + int red = (int) (color.getRed() + percent * (colorEnd.getRed() - color.getRed())); + int green = (int) (color.getGreen() + percent * (colorEnd.getGreen() - color.getGreen())); + int blue = (int) (color.getBlue() + percent * (colorEnd.getBlue() - color.getBlue())); + + java.awt.Color color = new java.awt.Color(red, green, blue); + colors[index] = color; + } + return colors; + } + + /*@NotNull + public List> gradient(@NotNull String string) { + List> list = new ArrayList<>(); + + Color[] colors = createGradient(string.length()); + char[] characters = string.toCharArray(); + + for (int index = 0; index < characters.length; index++) { + list.add(Pair.of(String.valueOf(characters[index]), colors[index])); + } + + return list; + }*/ + + @Override + public void decorate(@NotNull BaseComponent component) { + if (!(component instanceof TextComponent textComponent)) return; + + String text = textComponent.getText(); + + Color[] colors = createGradient(text.length()); + char[] characters = text.toCharArray(); + + for (int index = 0; index < characters.length; index++) { + TextComponent extra = new TextComponent(String.valueOf(characters[index])); + extra.copyFormatting(textComponent); + extra.setColor(ChatColor.of(colors[index])); + textComponent.addExtra(extra); + } + textComponent.setText(""); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/decoration/ParsedDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/decoration/ParsedDecorator.java new file mode 100644 index 0000000..cf36a78 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/decoration/ParsedDecorator.java @@ -0,0 +1,29 @@ +package su.nightexpress.nightcore.util.text.decoration; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.text.decoration.Decorator; + +public class ParsedDecorator { + + private final Decorator tag; + + private int length; + + public ParsedDecorator(@NotNull Decorator tag, int length) { + this.tag = tag; + this.length = length; + } + + @NotNull + public Decorator getDecorator() { + return tag; + } + + public void setLength(int length) { + this.length = length; + } + + public int getLength() { + return length; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/decoration/ShowItemDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/decoration/ShowItemDecorator.java new file mode 100644 index 0000000..ace5854 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/decoration/ShowItemDecorator.java @@ -0,0 +1,38 @@ +package su.nightexpress.nightcore.util.text.decoration; + +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.ItemTag; +import net.md_5.bungee.api.chat.hover.content.Item; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.ItemUtil; + +public class ShowItemDecorator implements Decorator { + + private final ItemStack item; + + public ShowItemDecorator(@NotNull String string) { + this(ItemUtil.decompress(string)); + } + + public ShowItemDecorator(ItemStack item) { + this.item = item == null ? new ItemStack(Material.AIR) : new ItemStack(item); + } + + @NotNull + public HoverEvent createEvent() { + String key = item.getType().getKey().getKey(); + ItemMeta meta = item.getItemMeta(); + Item item = new Item(key, this.item.getAmount(), ItemTag.ofNbt(meta == null ? null : meta.getAsString())); + + return new HoverEvent(HoverEvent.Action.SHOW_ITEM, item); + } + + @Override + public void decorate(@NotNull BaseComponent component) { + component.setHoverEvent(this.createEvent()); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/decoration/ShowTextDecorator.java b/src/main/java/su/nightexpress/nightcore/util/text/decoration/ShowTextDecorator.java new file mode 100644 index 0000000..3d186e7 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/decoration/ShowTextDecorator.java @@ -0,0 +1,37 @@ +package su.nightexpress.nightcore.util.text.decoration; + +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.hover.content.Text; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.Lists; +import su.nightexpress.nightcore.util.text.NightMessage; +import su.nightexpress.nightcore.util.text.tag.Tags; + +import java.util.List; + +public class ShowTextDecorator implements Decorator { + + private final List text; + + public ShowTextDecorator(@NotNull String... strings) { + this(Lists.newList(strings)); + } + + public ShowTextDecorator(@NotNull List text) { + this.text = text; + } + + @NotNull + public HoverEvent createEvent() { + String fused = String.join(Tags.LINE_BREAK.getFullName(), this.text); + Text text = new Text(NightMessage.parse(fused)); + + return new HoverEvent(HoverEvent.Action.SHOW_TEXT, text); + } + + @Override + public void decorate(@NotNull BaseComponent component) { + component.setHoverEvent(this.createEvent()); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/StandardTags.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/StandardTags.java new file mode 100644 index 0000000..ea13422 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/StandardTags.java @@ -0,0 +1,27 @@ +package su.nightexpress.nightcore.util.text.tag; + +@Deprecated +public class StandardTags { + + /*public static final String WHITE = Tags.WHITE.getFullName(); + public static final String GRAY = Tags.GRAY.getFullName(); + public static final String GREEN = Tags.GREEN.getFullName(); + public static final String YELLOW = Tags.YELLOW.getFullName(); + public static final String ORANGE = Tags.ORANGE.getFullName(); + public static final String RED = Tags.RED.getFullName(); + public static final String BLUE = Tags.BLUE.getFullName(); + public static final String CYAN = Tags.CYAN.getFullName(); + public static final String PURPLE = Tags.PURPLE.getFullName(); + public static final String PINK = Tags.PINK.getFullName(); + + public static final String DARK_GRAY = Tags.DARK_GRAY.getFullName(); + public static final String LIGHT_GRAY = Tags.LIGHT_GRAY.getFullName(); + public static final String LIGHT_GREEN = Tags.LIGHT_GREEN.getFullName(); + public static final String LIGHT_YELLOW = Tags.LIGHT_YELLOW.getFullName(); + public static final String LIGHT_ORANGE = Tags.LIGHT_ORANGE.getFullName(); + public static final String LIGHT_RED = Tags.LIGHT_RED.getFullName(); + public static final String LIGHT_BLUE = Tags.LIGHT_BLUE.getFullName(); + public static final String LIGHT_CYAN = Tags.LIGHT_CYAN.getFullName(); + public static final String LIGHT_PURPLE = Tags.LIGHT_PURPLE.getFullName(); + public static final String LIGHT_PINK = Tags.LIGHT_PINK.getFullName();*/ +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/TagPool.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/TagPool.java new file mode 100644 index 0000000..7f7a172 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/TagPool.java @@ -0,0 +1,77 @@ +package su.nightexpress.nightcore.util.text.tag; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.Placeholders; +import su.nightexpress.nightcore.util.text.tag.api.Tag; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class TagPool { + + public static final TagPool ALL = new TagPool(Mode.BLACKLIST, Collections.emptySet()); + public static final TagPool NONE = new TagPool(Mode.WHITELIST, Collections.emptySet()); + + private final Mode mode; + private final Set tags; + + @NotNull + public static TagPool whitelisted(@NotNull Tag... tags) { + return create(Mode.WHITELIST, tags); + } + + @NotNull + public static TagPool blacklisted(@NotNull Tag... tags) { + return create(Mode.BLACKLIST, tags); + } + + @NotNull + public static TagPool create(@NotNull Mode mode, @NotNull Tag... tags) { + return new TagPool(mode, Stream.of(tags).map(Tag::getName).collect(Collectors.toSet())); + } + + public TagPool(@NotNull Mode mode, @NotNull Set tags) { + this.mode = mode; + this.tags = new HashSet<>(tags); + } + + public enum Mode { + WHITELIST, BLACKLIST + } + + public boolean isWhitelist() { + return this.getMode() == Mode.WHITELIST; + } + + public boolean isBlacklist() { + return this.getMode() == Mode.BLACKLIST; + } + + public boolean isGoodTag(@NotNull Tag tag) { + return this.isGoodTag(tag.getName()); + } + + public boolean isGoodTag(@NotNull String name) { + name = name.toLowerCase(); + + if (this.isWhitelist()) { + return this.getTags().contains(name) || this.getTags().contains(Placeholders.WILDCARD); + } + else { + return !this.getTags().contains(name); + } + } + + @NotNull + public Mode getMode() { + return mode; + } + + @NotNull + public Set getTags() { + return tags; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java new file mode 100644 index 0000000..1d014e0 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/Tags.java @@ -0,0 +1,42 @@ +package su.nightexpress.nightcore.util.text.tag; + +import su.nightexpress.nightcore.util.text.tag.impl.*; + +public class Tags { + + public static final ClickTag CLICK = new ClickTag(); + public static final FontTag FONT = new FontTag(); + public static final GradientTag GRADIENT = new GradientTag(); + public static final HexColorTag HEX_COLOR = new HexColorTag(); + public static final HoverTag HOVER = new HoverTag(); + public static final LineBreakTag LINE_BREAK = new LineBreakTag(); + public static final ResetTag RESET = new ResetTag(); + + public static final FontStyleTag BOLD = new FontStyleTag("b", FontStyleTag.Style.BOLD); + public static final FontStyleTag ITALIC = new FontStyleTag("i", FontStyleTag.Style.ITALIC); + public static final FontStyleTag OBFUSCATED = new FontStyleTag("o", FontStyleTag.Style.OBFUSCATED); + public static final FontStyleTag STRIKETHROUGH = new FontStyleTag("s", FontStyleTag.Style.STRIKETHROUGH); + public static final FontStyleTag UNDERLINED = new FontStyleTag("u", FontStyleTag.Style.UNDERLINED); + + public static final ColorTag WHITE = new ColorTag("white", "#e8f2f2"); + public static final ColorTag GRAY = new ColorTag("gray", "#aaa8a8"); + public static final ColorTag GREEN = new ColorTag("green", "#74ea31"); + public static final ColorTag YELLOW = new ColorTag("yellow", "#ead931"); + public static final ColorTag ORANGE = new ColorTag("orange", "#ea9631"); + public static final ColorTag RED = new ColorTag("red", "#ea3131"); + public static final ColorTag BLUE = new ColorTag("blue", "#3196ea"); + public static final ColorTag CYAN = new ColorTag("cyan", "#31eace"); + public static final ColorTag PURPLE = new ColorTag("purple", "#bd31ea"); + public static final ColorTag PINK = new ColorTag("pink", "#ea31b2"); + + public static final ColorTag DARK_GRAY = new ColorTag("dark_gray", "#6c6c62"); + public static final ColorTag LIGHT_GRAY = new ColorTag("light_gray", "#d4d9d8"); + public static final ColorTag LIGHT_GREEN = new ColorTag("light_green", "#aefd5e"); + public static final ColorTag LIGHT_YELLOW = new ColorTag("light_yellow", "#ffeea2"); + public static final ColorTag LIGHT_ORANGE = new ColorTag("light_orange", "#fdba5e"); + public static final ColorTag LIGHT_RED = new ColorTag("light_red", "#fd5e5e"); + public static final ColorTag LIGHT_BLUE = new ColorTag("light_blue", "#5e9dfd"); + public static final ColorTag LIGHT_CYAN = new ColorTag("light_cyan", "#5edefd"); + public static final ColorTag LIGHT_PURPLE = new ColorTag("light_purple", "#e39fff"); + public static final ColorTag LIGHT_PINK = new ColorTag("light_pink", "#fd8ddb"); +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ContentTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ContentTag.java new file mode 100644 index 0000000..a9cba84 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/ContentTag.java @@ -0,0 +1,34 @@ +package su.nightexpress.nightcore.util.text.tag.api; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.text.decoration.DecoratorParser; +import su.nightexpress.nightcore.util.text.decoration.ParsedDecorator; + +public abstract class ContentTag extends DynamicTag implements DecoratorParser { + + public ContentTag(@NotNull String name) { + super(name); + } + + @Override + @Nullable + public final ParsedDecorator parse(@NotNull String str) { + int tagLength = this.getName().length(); + String sub = str.substring(tagLength); + + if (sub.charAt(0) == ':') { + sub = sub.substring(1); + tagLength += 1; + } + + ParsedDecorator decorator = this.onParse(sub); + if (decorator != null) { + decorator.setLength(decorator.getLength() + tagLength + 2); // 2 for quotes + } + return decorator; + } + + @Nullable + protected abstract ParsedDecorator onParse(@NotNull String sub); +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/DynamicTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/DynamicTag.java new file mode 100644 index 0000000..074bdb2 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/DynamicTag.java @@ -0,0 +1,57 @@ +package su.nightexpress.nightcore.util.text.tag.api; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public abstract class DynamicTag extends Tag { + + public DynamicTag(@NotNull String name) { + super(name); + } + + @NotNull + protected final String leading(@Nullable String prefix, @NotNull String content) { + if (prefix != null) prefix += ":"; + + StringBuilder builder = new StringBuilder(); + builder.append(this.getName()).append(":"); + if (prefix != null) { + builder.append(prefix); + } + builder.append("'").append(content).append("'"); + + return brackets(builder.toString()); + } + + @NotNull + protected final String enclose(@Nullable String prefix, @NotNull String content, @NotNull String text) { + return leading(prefix, content) + text + this.getClosingName(); + } + + @Nullable + public static String parseQuotedContent(@NotNull String string) { + char quote = string.charAt(0); + if (quote != '\'' && quote != '"') return null; + + int indexEnd = -1; + for (int index = 0; index < string.length(); index++) { + if (index == (string.length() - 1) || index == 0) continue; + + char letter = string.charAt(index); + if (letter == '\\') { // TODO Replace/remove it + index++; + continue; + } + if (letter != quote) continue; + + char next = string.charAt(index + 1); + if (next == Tag.CLOSE_BRACKET) { + indexEnd = index; + break; + } + } + if (indexEnd == -1) return null; + + return string.substring(1, indexEnd); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/api/Tag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/Tag.java new file mode 100644 index 0000000..4edcb9b --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/api/Tag.java @@ -0,0 +1,54 @@ +package su.nightexpress.nightcore.util.text.tag.api; + +import org.jetbrains.annotations.NotNull; + +public abstract class Tag { + + public static final char OPEN_BRACKET = '<'; + public static final char CLOSE_BRACKET = '>'; + public static final char CLOSE_MARK = '/'; + + protected final String name; + + public Tag(@NotNull String name) { + this.name = name.toLowerCase(); + } + + @NotNull + public static String brackets(@NotNull String str) { + return OPEN_BRACKET + str + CLOSE_BRACKET; + } + + @NotNull + public String getName() { + return name; + } + + @NotNull + public String enclose(@NotNull String text) { + return this.getFullName() + text + this.getClosingName(); + } + + public abstract int getWeight(); + + @NotNull + public final String getFullName() { + return brackets(this.getName()); + } + + @NotNull + public final String getClosingName() { + return brackets(CLOSE_MARK + this.getName()); + } + + public boolean conflictsWith(@NotNull Tag tag) { + return tag.getName().equalsIgnoreCase(this.getName()); + } + + @Override + public String toString() { + return "Tag{" + + "name='" + name + '\'' + + '}'; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ClickTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ClickTag.java new file mode 100644 index 0000000..c558e24 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ClickTag.java @@ -0,0 +1,55 @@ +package su.nightexpress.nightcore.util.text.tag.impl; + +import net.md_5.bungee.api.chat.ClickEvent; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.text.decoration.ClickEventDecorator; +import su.nightexpress.nightcore.util.text.decoration.Decorator; +import su.nightexpress.nightcore.util.text.decoration.ParsedDecorator; +import su.nightexpress.nightcore.util.text.tag.api.DynamicTag; +import su.nightexpress.nightcore.util.text.tag.api.ContentTag; + +public class ClickTag extends ContentTag { + + public static final String NAME = "click"; + + public ClickTag() { + super(NAME); + } + + @Override + public int getWeight() { + return 50; + } + + @NotNull + public String enclose(@NotNull ClickEvent.Action action, @NotNull String text, @NotNull String command) { + String actionName = action.name().toLowerCase(); + return this.enclose(actionName, command, text); + } + + @Override + @Nullable + public ParsedDecorator onParse(@NotNull String sub) { + ClickEvent.Action action = null; + for (ClickEvent.Action global : ClickEvent.Action.values()) { + if (sub.startsWith(global.name().toLowerCase())) { + action = global; + break; + } + } + if (action == null) return null; + + int prefixSize = action.name().toLowerCase().length() + 1; // 1 for ':', like "run_command:" + sub = sub.substring(prefixSize); + + String content = DynamicTag.parseQuotedContent(sub); + if (content == null) return null; + + int length = prefixSize + content.length();// + 2; // 2 for quotes + + Decorator decorator = new ClickEventDecorator(action, content); + + return new ParsedDecorator(decorator, length); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ColorTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ColorTag.java new file mode 100644 index 0000000..01d8ac6 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ColorTag.java @@ -0,0 +1,47 @@ +package su.nightexpress.nightcore.util.text.tag.impl; + +import net.md_5.bungee.api.ChatColor; +import net.md_5.bungee.api.chat.BaseComponent; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.text.decoration.Decorator; +import su.nightexpress.nightcore.util.text.tag.api.Tag; + +import java.awt.*; + +public class ColorTag extends Tag implements Decorator { + + protected final Color color; + + public ColorTag(@NotNull String name, @NotNull String hex) { + this(name, Color.decode(hex)); + } + + public ColorTag(@NotNull Color color) { + this(Integer.toHexString(color.getRGB()).substring(2), color); + } + + public ColorTag(@NotNull String name, @NotNull Color color) { + super(name); + this.color = color; + } + + @Override + public int getWeight() { + return 10; + } + + @NotNull + public Color getColor() { + return color; + } + + @Override + public boolean conflictsWith(@NotNull Tag tag) { + return tag instanceof ColorTag; + } + + @Override + public void decorate(@NotNull BaseComponent component) { + component.setColor(ChatColor.of(this.getColor())); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontStyleTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontStyleTag.java new file mode 100644 index 0000000..707deee --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontStyleTag.java @@ -0,0 +1,41 @@ +package su.nightexpress.nightcore.util.text.tag.impl; + +import net.md_5.bungee.api.chat.BaseComponent; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.text.decoration.Decorator; +import su.nightexpress.nightcore.util.text.tag.api.Tag; + +public class FontStyleTag extends Tag implements Decorator { + + public enum Style { + BOLD, ITALIC, UNDERLINED, STRIKETHROUGH, OBFUSCATED + } + + private final Style style; + + public FontStyleTag(@NotNull String name, @NotNull Style style) { + super(name); + this.style = style; + } + + @Override + public int getWeight() { + return 0; + } + + @NotNull + public Style getStyle() { + return style; + } + + @Override + public void decorate(@NotNull BaseComponent component) { + switch (this.getStyle()) { + case BOLD -> component.setBold(true); + case ITALIC -> component.setItalic(true); + case OBFUSCATED -> component.setObfuscated(true); + case UNDERLINED -> component.setUnderlined(true); + case STRIKETHROUGH -> component.setStrikethrough(true); + } + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontTag.java new file mode 100644 index 0000000..ce92d82 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/FontTag.java @@ -0,0 +1,33 @@ +package su.nightexpress.nightcore.util.text.tag.impl; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.text.decoration.FontDecorator; +import su.nightexpress.nightcore.util.text.decoration.ParsedDecorator; +import su.nightexpress.nightcore.util.text.tag.api.DynamicTag; +import su.nightexpress.nightcore.util.text.tag.api.ContentTag; + +public class FontTag extends ContentTag { + + public static final String NAME = "font"; + + public FontTag() { + super(NAME); + } + + @Override + @Nullable + public ParsedDecorator onParse(@NotNull String str) { + String content = DynamicTag.parseQuotedContent(str); + if (content == null) return null; + + int length = content.length();// + 2; // 2 for quotes + + return new ParsedDecorator(new FontDecorator(content), length); + } + + @Override + public int getWeight() { + return 0; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java new file mode 100644 index 0000000..28afed5 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/GradientTag.java @@ -0,0 +1,60 @@ +package su.nightexpress.nightcore.util.text.tag.impl; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.text.decoration.DecoratorParser; +import su.nightexpress.nightcore.util.text.decoration.GradientDecorator; +import su.nightexpress.nightcore.util.text.decoration.ParsedDecorator; +import su.nightexpress.nightcore.util.text.tag.api.Tag; + +import java.awt.*; + +public class GradientTag extends Tag implements DecoratorParser { + + public static final String NAME = "gradient"; + + public GradientTag() { + super(NAME); + } + + @Override + public int getWeight() { + return Integer.MAX_VALUE - 1; + } + + @Override + public boolean conflictsWith(@NotNull Tag tag) { + return super.conflictsWith(tag) || tag instanceof ColorTag || tag instanceof HexColorTag; + } + + @Override + @Nullable + public ParsedDecorator parse(@NotNull String content) { + int tagLength = this.getName().length() + 1; // 1 for semicolon + content = content.substring(tagLength); + + String[] split = content.split(":"); + if (split.length < 2) return null; + + String code1 = split[0]; + String code2 = split[1]; + //if (!code1.startsWith("#")) code1 = "#" + code1; + //if (!code2.startsWith("#")) code2 = "#" + code2; + //if (code1.length() != 7 || code2.length() != 7) return null; + + Color from; + Color to; + + try { + from = Color.decode(code1); + to = Color.decode(code2); + } + catch (NumberFormatException exception) { + return null; + } + + GradientDecorator decorator = new GradientDecorator(from, to); + + return new ParsedDecorator(decorator, 15 + tagLength); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HexColorTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HexColorTag.java new file mode 100644 index 0000000..6fc52d6 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HexColorTag.java @@ -0,0 +1,41 @@ +package su.nightexpress.nightcore.util.text.tag.impl; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.text.decoration.DecoratorParser; +import su.nightexpress.nightcore.util.text.decoration.ParsedDecorator; +import su.nightexpress.nightcore.util.text.tag.api.Tag; + +import java.awt.*; + +public class HexColorTag extends Tag implements DecoratorParser { + + public HexColorTag() { + super("#"); + } + + @Override + public int getWeight() { + return 10; + } + + @Override + public boolean conflictsWith(@NotNull Tag tag) { + return super.conflictsWith(tag) || tag instanceof ColorTag || tag instanceof GradientTag; + } + + @Override + @Nullable + public ParsedDecorator parse(@NotNull String content) { + Color color; + + try { + color = Color.decode(content); + } + catch (NumberFormatException exception) { + return null; + } + + return new ParsedDecorator(new ColorTag(color), 7); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HoverTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HoverTag.java new file mode 100644 index 0000000..8e0ac35 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/HoverTag.java @@ -0,0 +1,79 @@ +package su.nightexpress.nightcore.util.text.tag.impl; + +import net.md_5.bungee.api.chat.HoverEvent; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.util.ItemUtil; +import su.nightexpress.nightcore.util.text.decoration.Decorator; +import su.nightexpress.nightcore.util.text.decoration.ParsedDecorator; +import su.nightexpress.nightcore.util.text.decoration.ShowItemDecorator; +import su.nightexpress.nightcore.util.text.decoration.ShowTextDecorator; +import su.nightexpress.nightcore.util.text.tag.api.DynamicTag; +import su.nightexpress.nightcore.util.text.tag.api.ContentTag; + +public class HoverTag extends ContentTag { + + public static final String NAME = "hover"; + + public HoverTag() { + super(NAME); + } + + @Override + public int getWeight() { + return 50; + } + + /*@Override + public boolean isDynamicSize() { + return true; + }*/ + + @NotNull + public String enclose(@NotNull String text, @NotNull String hint) { + String action = HoverEvent.Action.SHOW_TEXT.name().toLowerCase(); + return this.enclose(action, hint, text); + } + + @Override + @Nullable + public ParsedDecorator onParse(@NotNull String sub) { + HoverEvent.Action action = null; + for (HoverEvent.Action global : HoverEvent.Action.values()) { + if (sub.startsWith(global.name().toLowerCase())) { + action = global; + break; + } + } + if (action == null) return null; + + int prefixSize = action.name().toLowerCase().length() + 1; // 1 for ':', like "show_text:" + sub = sub.substring(prefixSize); + + String content = DynamicTag.parseQuotedContent(sub); + if (content == null) return null; + + int length = prefixSize + content.length();// + 2; // 2 for quotes + + Decorator decorator; + if (action == HoverEvent.Action.SHOW_TEXT) { + decorator = new ShowTextDecorator(content); + } + else if (action == HoverEvent.Action.SHOW_ITEM) { + ItemStack item; + + Material material = Material.getMaterial(content.toUpperCase()); + if (material != null) { + item = new ItemStack(material); + } + else item = ItemUtil.decompress(content); + + decorator = new ShowItemDecorator(item); + } + else return null; + + return new ParsedDecorator(decorator, length); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/LineBreakTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/LineBreakTag.java new file mode 100644 index 0000000..49c674c --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/LineBreakTag.java @@ -0,0 +1,15 @@ +package su.nightexpress.nightcore.util.text.tag.impl; + +import su.nightexpress.nightcore.util.text.tag.api.Tag; + +public class LineBreakTag extends Tag { + + public LineBreakTag() { + super("br"); + } + + @Override + public int getWeight() { + return 0; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ResetTag.java b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ResetTag.java new file mode 100644 index 0000000..ece94e1 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/text/tag/impl/ResetTag.java @@ -0,0 +1,32 @@ +package su.nightexpress.nightcore.util.text.tag.impl; + +import net.md_5.bungee.api.chat.BaseComponent; +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.util.text.decoration.Decorator; +import su.nightexpress.nightcore.util.text.tag.api.Tag; + +public class ResetTag extends Tag implements Decorator { + + public ResetTag() { + super("r"); + } + + @Override + public int getWeight() { + return Integer.MAX_VALUE; + } + + @Override + public void decorate(@NotNull BaseComponent component) { + component.setColor(null); + component.setBold(false); + component.setItalic(false); + component.setObfuscated(false); + component.setUnderlined(false); + component.setStrikethrough(false); + component.setFont(null); + component.setInsertion(null); + component.setHoverEvent(null); + component.setClickEvent(null); + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniDouble.java b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniDouble.java new file mode 100644 index 0000000..158bf03 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniDouble.java @@ -0,0 +1,55 @@ +package su.nightexpress.nightcore.util.wrapper; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.config.FileConfig; +import su.nightexpress.nightcore.util.random.Rnd; + +public final class UniDouble { + + private final double minInclusive; + private final double maxInclusive; + + private UniDouble(double min, double max) { + this.minInclusive = min; + this.maxInclusive = max; + } + + @NotNull + public static UniDouble of(double min, double max) { + return new UniDouble(min, max); + } + + @NotNull + public static UniDouble read(@NotNull FileConfig cfg, @NotNull String path) { + double min = cfg.getDouble(path + ".Min"); + double max = cfg.getDouble(path + ".Max"); + return of(min, max); + } + + public void write(@NotNull FileConfig cfg, @NotNull String path) { + cfg.set(path + ".Min", this.getMinValue()); + cfg.set(path + ".Max", this.getMaxValue()); + } + + @NotNull + public UniInt asInt() { + return UniInt.of((int) this.getMinValue(), (int) this.getMaxValue()); + } + + public double roll() { + return Rnd.getDouble(this.minInclusive, this.maxInclusive); + } + + public double getMinValue() { + return this.minInclusive; + } + + public double getMaxValue() { + return this.maxInclusive; + } + + @Override + public String toString() { + return "[" + this.minInclusive + "-" + this.maxInclusive + "]"; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniInt.java b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniInt.java new file mode 100644 index 0000000..edcb0b1 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniInt.java @@ -0,0 +1,50 @@ +package su.nightexpress.nightcore.util.wrapper; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.config.FileConfig; +import su.nightexpress.nightcore.util.random.Rnd; + +public final class UniInt { + + private final int minInclusive; + private final int maxInclusive; + + private UniInt(int var0, int var1) { + this.minInclusive = var0; + this.maxInclusive = var1; + } + + @NotNull + public static UniInt of(int var0, int var1) { + return new UniInt(var0, var1); + } + + @NotNull + public static UniInt read(@NotNull FileConfig cfg, @NotNull String path) { + int min = cfg.getInt(path + ".Min"); + int max = cfg.getInt(path + ".Max"); + return of(min, max); + } + + public void write(@NotNull FileConfig cfg, @NotNull String path) { + cfg.set(path + ".Min", this.getMinValue()); + cfg.set(path + ".Max", this.getMaxValue()); + } + + public int roll() { + return Rnd.get(this.minInclusive, this.maxInclusive); + } + + public int getMinValue() { + return this.minInclusive; + } + + public int getMaxValue() { + return this.maxInclusive; + } + + @Override + public String toString() { + return "[" + this.minInclusive + "-" + this.maxInclusive + "]"; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniParticle.java b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniParticle.java new file mode 100644 index 0000000..bbeede6 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniParticle.java @@ -0,0 +1,205 @@ +package su.nightexpress.nightcore.util.wrapper; + +import org.bukkit.*; +import org.bukkit.block.data.BlockData; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.config.FileConfig; +import su.nightexpress.nightcore.util.NumberUtil; +import su.nightexpress.nightcore.util.StringUtil; + +public class UniParticle { + + private final Particle particle; + private final Object data; + + public UniParticle(@Nullable Particle particle, @Nullable Object data) { + this.particle = particle; + this.data = data; + } + + @NotNull + public static UniParticle of(@Nullable Particle particle) { + return UniParticle.of(particle, null); + } + + @NotNull + public static UniParticle of(@Nullable Particle particle, @Nullable Object data) { + return new UniParticle(particle, data); + } + + @NotNull + public static UniParticle itemCrack(@NotNull ItemStack item) { + return new UniParticle(Particle.ITEM_CRACK, new ItemStack(item)); + } + + @NotNull + public static UniParticle itemCrack(@NotNull Material material) { + return new UniParticle(Particle.ITEM_CRACK, new ItemStack(material)); + } + + @NotNull + public static UniParticle blockCrack(@NotNull Material material) { + return new UniParticle(Particle.BLOCK_CRACK, material.createBlockData()); + } + + @NotNull + public static UniParticle blockDust(@NotNull Material material) { + return new UniParticle(Particle.BLOCK_DUST, material.createBlockData()); + } + + @NotNull + public static UniParticle blockMarker(@NotNull Material material) { + return new UniParticle(Particle.BLOCK_MARKER, material.createBlockData()); + } + + @NotNull + public static UniParticle fallingDust(@NotNull Material material) { + return new UniParticle(Particle.FALLING_DUST, material.createBlockData()); + } + + @NotNull + public static UniParticle redstone(@NotNull Color color, float size) { + return new UniParticle(Particle.REDSTONE, new Particle.DustOptions(color, size)); + } + + @NotNull + public static UniParticle read(@NotNull FileConfig cfg, @NotNull String path) { + String name = cfg.getString(path + ".Name", ""); + Particle particle = StringUtil.getEnum(name, Particle.class).orElse(null); + if (particle == null) return UniParticle.of(null); + + Class dataType = particle.getDataType(); + Object data = null; + if (dataType == BlockData.class) { + Material material = Material.getMaterial(cfg.getString(path + ".Material", "")); + data = material != null ? material.createBlockData() : Material.STONE.createBlockData(); + } + else if (dataType == Particle.DustOptions.class) { + Color color = StringUtil.getColor(cfg.getString(path + ".Color", "")); + double size = cfg.getDouble(path + ".Size", 1D); + data = new Particle.DustOptions(color, (float) size); + } + else if (dataType == Particle.DustTransition.class) { + Color colorStart = StringUtil.getColor(cfg.getString(path + ".Color_From", "")); + Color colorEnd = StringUtil.getColor(cfg.getString(path + ".Color_To", "")); + double size = cfg.getDouble(path + ".Size", 1D); + data = new Particle.DustTransition(colorStart, colorEnd, 1.0f); + } + else if (dataType == ItemStack.class) { + ItemStack item = cfg.getItem(path + ".Item"); + data = item.getType().isAir() ? new ItemStack(Material.STONE) : item; + } + else if (dataType != Void.class) return UniParticle.of(Particle.REDSTONE); + + return UniParticle.of(particle, data); + } + + public void write(@NotNull FileConfig cfg, @NotNull String path) { + cfg.set(path + ".Name", this.isEmpty() ? "null" : this.getParticle().name()); + + Object data = this.getData(); + if (data instanceof BlockData blockData) { + cfg.set(path + ".Material", blockData.getMaterial().name()); + } + else if (data instanceof Particle.DustTransition dustTransition) { + Color colorStart = dustTransition.getColor(); + Color colorEnd = dustTransition.getToColor(); + cfg.set(path + ".Color_From", colorStart.getRed() + "," + colorStart.getGreen() + "," + colorStart.getBlue()); + cfg.set(path + ".Color_To", colorEnd.getRed() + "," + colorEnd.getGreen() + "," + colorEnd.getBlue()); + cfg.set(path + ".Size", dustTransition.getSize()); + } + else if (data instanceof Particle.DustOptions dustOptions) { + Color color = dustOptions.getColor(); + cfg.set(path + ".Color", color.getRed() + "," + color.getGreen() + "," + color.getBlue()); + cfg.set(path + ".Size", dustOptions.getSize()); + } + else if (data instanceof ItemStack item) { + cfg.setItem(path + ".Item", item); + } + } + + public boolean isEmpty() { + return this.particle == null; + } + + public Particle getParticle() { + return particle; + } + + @Nullable + public Object getData() { + return data; + } + + @NotNull + @Deprecated + public UniParticle parseData(@NotNull String from) { + if (this.isEmpty()) return this; + + String[] split = from.split(" "); + Class dataType = this.getParticle().getDataType(); + Object data = null; + if (dataType == BlockData.class) { + Material material = Material.getMaterial(from.toUpperCase()); + data = material != null ? material.createBlockData() : Material.STONE.createBlockData(); + } + else if (dataType == Particle.DustOptions.class) { + Color color = StringUtil.getColor(split[0]); + double size = split.length >= 2 ? NumberUtil.getDouble(split[1], 1D) : 1D; + data = new Particle.DustOptions(color, (float) size); + } + else if (dataType == Particle.DustTransition.class) { + Color colorStart = StringUtil.getColor(split[0]); + Color colorEnd = split.length >= 2 ? StringUtil.getColor(split[1]) : colorStart; + double size = split.length >= 3 ? NumberUtil.getDouble(split[2], 1D) : 1D; + data = new Particle.DustTransition(colorStart, colorEnd, 1.0f); + } + else if (dataType == ItemStack.class) { + Material material = Material.getMaterial(from.toUpperCase()); + if (material != null && !material.isAir()) data = new ItemStack(material); + else data = new ItemStack(Material.STONE); + } + else if (dataType != Void.class) return UniParticle.of(Particle.REDSTONE); + + return UniParticle.of(this.getParticle(), data); + } + + public void play(@NotNull Location location, double speed, int amount) { + this.play(location, 0D, speed, amount); + } + + public void play(@NotNull Location location, double offsetAll, double speed, int amount) { + this.play(location, offsetAll, offsetAll, offsetAll, speed, amount); + } + + public void play(@NotNull Location location, double xOffset, double yOffset, double zOffset, double speed, int amount) { + this.play(null, location, xOffset, yOffset, zOffset, speed, amount); + } + + public void play(@NotNull Player player, @NotNull Location location, double speed, int amount) { + this.play(player, location, 0D, speed, amount); + } + + public void play(@NotNull Player player, @NotNull Location location, double offsetAll, double speed, int amount) { + this.play(player, location, offsetAll, offsetAll, offsetAll, speed, amount); + } + + public void play(@Nullable Player player, @NotNull Location location, double xOffset, double yOffset, double zOffset, double speed, int amount) { + if (this.isEmpty()) return; + + if (player == null) { + World world = location.getWorld(); + if (world == null) return; + + world.spawnParticle(this.getParticle(), location, amount, xOffset, yOffset, zOffset, speed, this.getData()); + //EffectUtil.playParticle(location, this.getParticle(), this.getData(), xOffset, yOffset, zOffset, speed, amount); + } + else { + player.spawnParticle(this.getParticle(), location, amount, xOffset, yOffset, zOffset, speed, this.getData()); + //EffectUtil.playParticle(player, location, this.getParticle(), this.getData(), xOffset, yOffset, zOffset, speed, amount); + } + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniPermission.java b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniPermission.java new file mode 100644 index 0000000..eddd032 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniPermission.java @@ -0,0 +1,37 @@ +package su.nightexpress.nightcore.util.wrapper; + +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class UniPermission extends Permission { + + public UniPermission(@NotNull String name) { + this(name, null, null); + } + + public UniPermission(@NotNull String name, @Nullable PermissionDefault defaultValue) { + this(name, null, defaultValue); + } + + public UniPermission(@NotNull String name, @Nullable String description) { + this(name, description, PermissionDefault.OP); + } + + public UniPermission(@NotNull String name, @Nullable String description, @Nullable PermissionDefault defaultValue) { + super(name, description, defaultValue); + } + + @NotNull + public UniPermission description(String... desc) { + this.setDescription(String.join(" ", desc)); + return this; + } + + public void addChildren(@NotNull Permission... childrens) { + for (Permission children : childrens) { + children.addParent(this, true); + } + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniSound.java b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniSound.java new file mode 100644 index 0000000..b8856f0 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniSound.java @@ -0,0 +1,112 @@ +package su.nightexpress.nightcore.util.wrapper; + +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import su.nightexpress.nightcore.config.ConfigValue; +import su.nightexpress.nightcore.config.FileConfig; +import su.nightexpress.nightcore.util.StringUtil; + +public class UniSound { + + private final String soundName; + private final Sound soundType; + private final float volume; + private final float pitch; + + public UniSound(@NotNull String soundName, @Nullable Sound soundType, float volume, float pitch) { + this.soundName = soundName; + this.soundType = soundType; + this.volume = volume; + this.pitch = pitch; + } + + @NotNull + public static UniSound of(@NotNull Sound sound) { + return of(sound, 0.8F); + } + + @NotNull + public static UniSound of(@NotNull Sound sound, float volume) { + return of(sound, volume, 1F); + } + + @NotNull + public static UniSound of(@NotNull Sound sound, float volume, float pitch) { + return new UniSound(sound.name(), sound, volume, pitch); + } + + @NotNull + public static UniSound read(@NotNull FileConfig cfg, @NotNull String path) { + String soundName = ConfigValue.create(path + ".Name", "null", + "Sound name. You can use Spigot sound names, or ones from your resource pack.", + "Spigot Sounds: https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Sound.html").read(cfg); + + float volume = ConfigValue.create(path + ".Volume", 0.8F, + "Sound volume. From 0.0 to 1.0.").read(cfg).floatValue(); + + float pitch = ConfigValue.create(path + ".Pitch", 1D, + "Sound speed. From 0.5 to 2.0").read(cfg).floatValue(); + + Sound soundType = StringUtil.getEnum(soundName, Sound.class).orElse(null); + + return new UniSound(soundName, soundType, volume, pitch); + } + + public void write(@NotNull FileConfig cfg, @NotNull String path) { + cfg.set(path + ".Name", this.getSoundName()); + cfg.set(path + ".Volume", this.getVolume()); + cfg.set(path + ".Pitch", this.getPitch()); + } + + public boolean isEmpty() { + return this.getVolume() <= 0F || this.getSoundName().isEmpty(); + } + + public void play(@NotNull Player player) { + if (this.isEmpty()) return; + + Location location = player.getLocation(); + if (this.getSoundType() == null) { + player.playSound(location, this.getSoundName(), this.getVolume(), this.getPitch()); + } + else { + player.playSound(location, this.getSoundType(), this.getVolume(), this.getPitch()); + } + } + + public void play(@NotNull Location location) { + if (this.isEmpty()) return; + + World world = location.getWorld(); + if (world == null) return; + + if (this.getSoundType() == null) { + world.playSound(location, this.getSoundName(), this.getVolume(), this.getPitch()); + } + else { + world.playSound(location, this.getSoundType(), this.getVolume(), this.getPitch()); + } + } + + @NotNull + public String getSoundName() { + return soundName; + } + + @Nullable + public Sound getSoundType() { + return soundType; + } + + public float getVolume() { + return volume; + } + + public float getPitch() { + return pitch; + } +} diff --git a/src/main/java/su/nightexpress/nightcore/util/wrapper/UniTask.java b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniTask.java new file mode 100644 index 0000000..c443172 --- /dev/null +++ b/src/main/java/su/nightexpress/nightcore/util/wrapper/UniTask.java @@ -0,0 +1,78 @@ +package su.nightexpress.nightcore.util.wrapper; + +import org.jetbrains.annotations.NotNull; +import su.nightexpress.nightcore.NightCorePlugin; + +public class UniTask { + + private final NightCorePlugin plugin; + private final Runnable runnable; + + private long interval; + private boolean async; + private int taskId; + + public UniTask(@NotNull NightCorePlugin plugin, @NotNull Runnable runnable) { + this(plugin, runnable, 0L); + } + + public UniTask(@NotNull NightCorePlugin plugin, @NotNull Runnable runnable, long interval) { + this(plugin, runnable, interval, false); + } + + public UniTask(@NotNull NightCorePlugin plugin, @NotNull Runnable runnable, long interval, boolean async) { + this.plugin = plugin; + this.runnable = runnable; + this.setTicksInterval(interval); + this.setAsync(async); + + this.taskId = -1; + } + + public UniTask setSecondsInterval(int interval) { + return this.setTicksInterval(interval * 20L); + } + + public UniTask setTicksInterval(long interval) { + this.interval = interval; + return this; + } + + public UniTask setAsync() { + return this.setAsync(true); + } + + public UniTask setAsync(boolean async) { + this.async = async; + return this; + } + + public boolean isRunning() { + return this.taskId >= 0 && this.plugin.getScheduler().isCurrentlyRunning(this.taskId); + } + + public final void restart() { + this.stop(); + this.start(); + } + + public UniTask start() { + if (this.taskId >= 0 || this.interval <= 0L) return this; + + if (this.async) { + this.taskId = plugin.getScheduler().runTaskTimerAsynchronously(plugin, runnable, 0L, interval).getTaskId(); + } + else { + this.taskId = plugin.getScheduler().runTaskTimer(plugin, runnable, 0L, interval).getTaskId(); + } + return this; + } + + public boolean stop() { + if (this.taskId < 0) return false; + + this.plugin.getServer().getScheduler().cancelTask(this.taskId); + this.taskId = -1; + return true; + } +} diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml new file mode 100644 index 0000000..2854e12 --- /dev/null +++ b/src/main/resources/plugin.yml @@ -0,0 +1,11 @@ +name: nightcore +main: su.nightexpress.nightcore.NightCore +version: '${project.version}' +description: Plugin Creation Kit. +author: NightExpress +softdepend: [ Vault] +api-version: 1.18 +load: STARTUP +libraries: + - com.zaxxer:HikariCP:5.0.1 + - it.unimi.dsi:fastutil:8.5.11 \ No newline at end of file