├── .gitignore ├── LICENSE ├── README.md ├── pom.xml ├── res ├── ._BeastTokensAPI.jar ├── ._EssentialsX-2.18.0.0.jar ├── ._Factions.jar ├── ._PlayerPointsNew.jar ├── ._TokenManager.jar ├── BeastTokensAPI.jar ├── CrazyCrates.jar ├── EnjinMinecraftPlugin.jar ├── EssentialsX-2.18.0.0.jar ├── Factions.jar ├── GriefPrevention.jar ├── PlayerPoints.jar ├── PlayerPointsNew.jar ├── TokenEnchantAPI.jar ├── TokenManager.jar └── VotingPlugin.jar └── src └── main ├── java └── com │ └── trophonix │ └── tradeplus │ ├── TradePlus.java │ ├── commands │ ├── Command.java │ ├── CommandHandler.java │ ├── TradeCommand.java │ └── TradePlusCommand.java │ ├── config │ ├── ConfigMessage.java │ └── TradePlusConfig.java │ ├── events │ ├── ExcessChestListener.java │ ├── TradeAcceptEvent.java │ ├── TradeCompleteEvent.java │ └── TradeRequestEvent.java │ ├── extras │ ├── BeastTokensExtra.java │ ├── EconomyExtra.java │ ├── EnjinPointsExtra.java │ ├── ExperienceExtra.java │ ├── Extra.java │ ├── GriefPreventionExtra.java │ ├── LandsExtra.java │ ├── PlayerPointsExtra.java │ ├── TokenEnchantExtra.java │ ├── TokenManagerExtra.java │ └── VotingPluginExtra.java │ ├── gui │ ├── MenuAction.java │ ├── MenuButton.java │ ├── MenuInventoryHolder.java │ └── TradeMenu.java │ ├── hooks │ ├── EssentialsHook.java │ ├── FactionsHook.java │ ├── WorldGuardHook.java │ └── factions │ │ └── MassiveCraftFactionsHook.java │ ├── logging │ ├── Logs.java │ ├── NullEmptyListAdapter.java │ ├── NullZeroNumberAdapter.java │ ├── PostProcessingEnabler.java │ ├── PostProcessor.java │ └── TradeLog.java │ ├── trade │ ├── EntityPickupItemEventListener.java │ ├── InteractListener.java │ ├── Trade.java │ └── TradeRequest.java │ └── util │ ├── InvUtils.java │ ├── ItemFactory.java │ ├── ItemUtils1_14.java │ ├── MsgUtils.java │ ├── MsgUtils1_8.java │ ├── NMSManager.java │ ├── PDCUtils.java │ ├── PlayerUtil.java │ ├── Procedure.java │ ├── Sounds.java │ └── XP.java └── resources └── plugin.yml /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.war 8 | *.ear 9 | 10 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 11 | hs_err_pid* 12 | 13 | out/ 14 | target/ 15 | .idea 16 | .project 17 | *.iml 18 | 19 | .DS_Store 20 | .classpath 21 | org.eclipse.* 22 | *.lst 23 | pom.properties 24 | dependency-reduced-pom.xml 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 | Trade+ is a trading plugin for Spigot servers versions 1.7.10 and up. I opened sourced it because I didn't have a ton of time to work on it anymore, and I hope to let other developers contribute and make it better if they can find issues before I can :) 4 | 5 | If you feel like 'donating'/paying for it, you can do so on the SpigotMC resource page: https://www.spigotmc.org/resources/23138/ 6 | 7 | But if you want to download it from the [releases page](https://github.com/Trophonix/TradePlus/releases) that's totally fine too. 8 | 9 | If you find bugs or want to add features, you are, of course, more than welcome to submit pull requests. Thanks! 10 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.trophonix 8 | TradePlus 9 | 3.84 10 | 11 | 12 | ${project.basedir}/res/ 13 | 3.84.5 14 | 15 | 16 | 17 | 18 | spigot-repo 19 | https://hub.spigotmc.org/nexus/content/repositories/snapshots/ 20 | 21 | 22 | 23 | bungeecord-repo 24 | https://oss.sonatype.org/content/repositories/snapshots 25 | 26 | 27 | 28 | vault-repo 29 | http://nexus.hc.to/content/repositories/pub_releases 30 | 31 | 32 | 33 | dakani 34 | https://repo.dakanilabs.com/repository/maven-public/ 35 | 36 | 37 | 38 | minebench-repo 39 | https://repo.minebench.de/ 40 | 41 | 42 | 43 | jitpack.io 44 | https://jitpack.io 45 | 46 | 47 | 48 | savagefactions-repo 49 | https://cdn.jsdelivr.net/gh/ProSavage/SavageFactions@1.6.x/ 50 | 51 | 52 | 53 | aikar 54 | https://repo.aikar.co/content/groups/aikar/ 55 | 56 | 57 | 58 | codemc-repo 59 | https://repo.codemc.org/repository/maven-public/ 60 | 61 | 62 | 63 | 64 | 65 | org.spigotmc 66 | spigot-api 67 | 1.17.1-R0.1-SNAPSHOT 68 | provided 69 | 70 | 71 | 72 | com.google.guava 73 | guava 74 | 21.0 75 | compile 76 | 77 | 78 | 79 | com.google.code.gson 80 | gson 81 | 2.8.5 82 | compile 83 | 84 | 85 | 86 | com.github.WesJD.AnvilGUI 87 | anvilgui 88 | 478e0c196e 89 | compile 90 | 91 | 92 | 93 | co.aikar 94 | taskchain-bukkit 95 | 3.7.2 96 | compile 97 | 98 | 99 | 100 | org.projectlombok 101 | lombok 102 | 1.18.20 103 | provided 104 | 105 | 106 | 107 | net.milkbowl.vault 108 | VaultAPI 109 | 1.7 110 | provided 111 | 112 | 113 | 114 | com.github.TechFortress 115 | GriefPrevention 116 | 16.7.1 117 | system 118 | ${res}/GriefPrevention.jar 119 | 120 | 121 | 122 | org.black_ixx 123 | PlayerPoints 124 | 3.1.0 125 | system 126 | ${res}/PlayerPointsNew.jar 127 | 128 | 129 | 130 | BeastTokens 131 | BeastTokens 132 | 2.0 133 | system 134 | ${res}/BeastTokensAPI.jar 135 | 136 | 137 | 138 | com.enjin.mc 139 | enjin-mc-plugin 140 | 3.4.3 141 | system 142 | ${res}/EnjinMinecraftPlugin.jar 143 | 144 | 145 | 146 | com.vk2gpz.tokenenchant 147 | api 148 | 10.0.0 149 | system 150 | ${res}/TokenEnchantAPI.jar 151 | 152 | 153 | 154 | com.github.kicjow 155 | Crazy-Crates 156 | v1.8.5 157 | system 158 | ${res}/CrazyCrates.jar 159 | 160 | 161 | 162 | com.github.Realizedd 163 | TokenManager 164 | 3.2.2 165 | system 166 | ${res}/TokenManager.jar 167 | 168 | 169 | 170 | com.github.ProSavage 171 | SavageFactions 172 | 1.6.3-RC 173 | provided 174 | 175 | 176 | 177 | org.codemc.worldguardwrapper 178 | worldguardwrapper 179 | 1.1.6-SNAPSHOT 180 | 181 | 182 | 183 | com.github.Angeschossen 184 | LandsAPI 185 | 4.5.2.0 186 | provided 187 | 188 | 189 | 190 | com.github.Ben12345rocks 191 | VotingPlugin 192 | 6.6.2 193 | system 194 | ${res}/VotingPlugin.jar 195 | 196 | 197 | 198 | com.earth2me 199 | essentials 200 | 2.18.0.0 201 | system 202 | ${res}/EssentialsX-2.18.0.0.jar 203 | 204 | 205 | 206 | 207 | ${basedir}/src/main/java/ 208 | ${project.artifactId}-${revision} 209 | 210 | 211 | . 212 | true 213 | ${basedir}/src/main/resources/ 214 | 215 | 216 | 217 | 218 | 219 | org.projectlombok 220 | lombok-maven-plugin 221 | 1.18.12.0 222 | 223 | 224 | generate-sources 225 | 226 | 227 | 228 | 229 | 230 | org.apache.maven.plugins 231 | maven-compiler-plugin 232 | 3.2 233 | 234 | 1.8 235 | 1.8 236 | 237 | 238 | 239 | 240 | org.apache.maven.plugins 241 | maven-shade-plugin 242 | 3.2.0 243 | 244 | 245 | package 246 | 247 | shade 248 | 249 | 250 | 251 | 252 | *:* 253 | 254 | META-INF/*.SF 255 | META-INF/*.DSA 256 | META-INF/*.RSA 257 | 258 | 259 | 260 | 261 | 262 | com.google.common 263 | com.trophonix.tradeplus.shaded.guava 264 | 265 | 266 | co.aikar.taskchain 267 | com.trophonix.tradeplus.shaded.taskchain 268 | 269 | 270 | net.wesjd.anvilgui 271 | com.trophonix.tradeplus.shaded.anvilgui 272 | 273 | 274 | org.codemc.worldguardwrapper 275 | com.trophonix.tradeplus.shaded.worldguardwrapper 276 | 277 | 278 | true 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | -------------------------------------------------------------------------------- /res/._BeastTokensAPI.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Trophonix/TradePlus/655cf856724cb162ee3dee7342563565f9729e65/res/._BeastTokensAPI.jar -------------------------------------------------------------------------------- /res/._EssentialsX-2.18.0.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Trophonix/TradePlus/655cf856724cb162ee3dee7342563565f9729e65/res/._EssentialsX-2.18.0.0.jar -------------------------------------------------------------------------------- /res/._Factions.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Trophonix/TradePlus/655cf856724cb162ee3dee7342563565f9729e65/res/._Factions.jar -------------------------------------------------------------------------------- /res/._PlayerPointsNew.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Trophonix/TradePlus/655cf856724cb162ee3dee7342563565f9729e65/res/._PlayerPointsNew.jar -------------------------------------------------------------------------------- /res/._TokenManager.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Trophonix/TradePlus/655cf856724cb162ee3dee7342563565f9729e65/res/._TokenManager.jar -------------------------------------------------------------------------------- /res/BeastTokensAPI.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Trophonix/TradePlus/655cf856724cb162ee3dee7342563565f9729e65/res/BeastTokensAPI.jar -------------------------------------------------------------------------------- /res/CrazyCrates.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Trophonix/TradePlus/655cf856724cb162ee3dee7342563565f9729e65/res/CrazyCrates.jar -------------------------------------------------------------------------------- /res/EnjinMinecraftPlugin.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Trophonix/TradePlus/655cf856724cb162ee3dee7342563565f9729e65/res/EnjinMinecraftPlugin.jar -------------------------------------------------------------------------------- /res/EssentialsX-2.18.0.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Trophonix/TradePlus/655cf856724cb162ee3dee7342563565f9729e65/res/EssentialsX-2.18.0.0.jar -------------------------------------------------------------------------------- /res/Factions.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Trophonix/TradePlus/655cf856724cb162ee3dee7342563565f9729e65/res/Factions.jar -------------------------------------------------------------------------------- /res/GriefPrevention.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Trophonix/TradePlus/655cf856724cb162ee3dee7342563565f9729e65/res/GriefPrevention.jar -------------------------------------------------------------------------------- /res/PlayerPoints.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Trophonix/TradePlus/655cf856724cb162ee3dee7342563565f9729e65/res/PlayerPoints.jar -------------------------------------------------------------------------------- /res/PlayerPointsNew.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Trophonix/TradePlus/655cf856724cb162ee3dee7342563565f9729e65/res/PlayerPointsNew.jar -------------------------------------------------------------------------------- /res/TokenEnchantAPI.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Trophonix/TradePlus/655cf856724cb162ee3dee7342563565f9729e65/res/TokenEnchantAPI.jar -------------------------------------------------------------------------------- /res/TokenManager.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Trophonix/TradePlus/655cf856724cb162ee3dee7342563565f9729e65/res/TokenManager.jar -------------------------------------------------------------------------------- /res/VotingPlugin.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Trophonix/TradePlus/655cf856724cb162ee3dee7342563565f9729e65/res/VotingPlugin.jar -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/TradePlus.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus; 2 | 3 | import co.aikar.taskchain.BukkitTaskChainFactory; 4 | import co.aikar.taskchain.TaskChainFactory; 5 | import com.trophonix.tradeplus.commands.CommandHandler; 6 | import com.trophonix.tradeplus.commands.TradeCommand; 7 | import com.trophonix.tradeplus.commands.TradePlusCommand; 8 | import com.trophonix.tradeplus.config.TradePlusConfig; 9 | import com.trophonix.tradeplus.events.ExcessChestListener; 10 | import com.trophonix.tradeplus.hooks.WorldGuardHook; 11 | import com.trophonix.tradeplus.logging.Logs; 12 | import com.trophonix.tradeplus.trade.InteractListener; 13 | import com.trophonix.tradeplus.trade.Trade; 14 | import com.trophonix.tradeplus.util.InvUtils; 15 | import com.trophonix.tradeplus.util.PlayerUtil; 16 | import com.trophonix.tradeplus.util.Sounds; 17 | import lombok.Getter; 18 | import org.bukkit.entity.Player; 19 | import org.bukkit.event.EventHandler; 20 | import org.bukkit.event.Listener; 21 | import org.bukkit.event.player.PlayerJoinEvent; 22 | import org.bukkit.event.player.PlayerQuitEvent; 23 | import org.bukkit.inventory.Inventory; 24 | import org.bukkit.plugin.java.JavaPlugin; 25 | import org.bukkit.scheduler.BukkitRunnable; 26 | 27 | import java.io.File; 28 | import java.util.ArrayList; 29 | import java.util.List; 30 | import java.util.concurrent.ConcurrentLinkedQueue; 31 | 32 | public class TradePlus extends JavaPlugin implements Listener { 33 | 34 | public ConcurrentLinkedQueue ongoingTrades = new ConcurrentLinkedQueue<>(); 35 | @Getter private TaskChainFactory taskFactory; 36 | 37 | @Getter private TradePlusConfig tradeConfig; 38 | 39 | // private CommandHandler commandHandler; 40 | 41 | @Getter private List excessChests; 42 | 43 | private Logs logs; 44 | 45 | public Trade getTrade(Player player) { 46 | for (Trade trade : ongoingTrades) { 47 | if (trade.player1.equals(player) || trade.player2.equals(player)) return trade; 48 | } 49 | return null; 50 | } 51 | 52 | public Trade getTrade(Player player1, Player player2) { 53 | for (Trade trade : ongoingTrades) { 54 | if (trade.player1.equals(player1) && trade.player2.equals(player2)) return trade; 55 | if (trade.player2.equals(player1) && trade.player1.equals(player2)) return trade; 56 | } 57 | return null; 58 | } 59 | 60 | @Override 61 | public void onLoad() { 62 | try { 63 | WorldGuardHook.init(); 64 | } catch (Throwable ignored) { 65 | getLogger().info("Failed to hook into worldguard. Ignore this if you don't have worldguard."); 66 | } 67 | } 68 | 69 | @Override 70 | public void onEnable() { 71 | tradeConfig = new TradePlusConfig(this); 72 | taskFactory = BukkitTaskChainFactory.create(this); 73 | taskFactory 74 | .newChain() 75 | .async(tradeConfig::load) 76 | .async(tradeConfig::update) 77 | .async(tradeConfig::save) 78 | .sync( 79 | () -> { 80 | excessChests = new ArrayList<>(); 81 | setupCommands(); 82 | reload(); 83 | if (Sounds.version > 17) { 84 | getServer().getPluginManager().registerEvents(new InteractListener(this), this); 85 | } 86 | new ExcessChestListener(this); 87 | }) 88 | .execute(); 89 | getServer().getPluginManager().registerEvents(this, this); 90 | } 91 | 92 | @Override 93 | public void onDisable() { 94 | if (logs != null) { 95 | logs.save(); 96 | } 97 | } 98 | 99 | private void setupCommands() { 100 | getCommand("trade").setExecutor(new TradeCommand(this)); 101 | getCommand("tradeplus").setExecutor(new TradePlusCommand(this)); 102 | } 103 | 104 | public void reload() { 105 | tradeConfig.reload(); 106 | if (logs == null && tradeConfig.isTradeLogs()) { 107 | try { 108 | logs = new Logs(this, new File(getDataFolder(), "logs")); 109 | new BukkitRunnable() { 110 | @Override 111 | public void run() { 112 | try { 113 | logs.save(); 114 | } catch (Exception | Error ex) { 115 | getLogger().info("The trade logger crashed."); 116 | cancel(); 117 | logs = null; 118 | } 119 | } 120 | }.runTaskTimer(this, 5 * 60 * 20, 5 * 60 * 20); 121 | log("Initialized trade logger."); 122 | } catch (Exception | Error ex) { 123 | log("Failed to load trade logger."); 124 | ex.printStackTrace(); 125 | } 126 | } 127 | InvUtils.reloadItems(this); 128 | } 129 | 130 | @EventHandler 131 | public void onJoin(PlayerJoinEvent event) { 132 | if (!getTradeConfig().isAllowSameIpTrade()) { 133 | PlayerUtil.registerIP(event.getPlayer()); 134 | } 135 | } 136 | 137 | @EventHandler 138 | public void onQuit(PlayerQuitEvent event) { 139 | PlayerUtil.removeIP(event.getPlayer()); 140 | } 141 | 142 | public void log(String message) { 143 | if (tradeConfig.isDebugMode()) { 144 | getLogger().info(message); 145 | } 146 | } 147 | 148 | public Logs getLogs() { 149 | return logs; 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/commands/Command.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.commands; 2 | 3 | import lombok.Getter; 4 | import org.bukkit.command.CommandSender; 5 | 6 | import java.util.Collections; 7 | import java.util.List; 8 | 9 | public abstract class Command { 10 | 11 | @Getter private List aliases; 12 | 13 | Command(List aliases) { 14 | this.aliases = aliases; 15 | } 16 | 17 | public boolean isAlias(String command) { 18 | return aliases.contains(command.toLowerCase()); 19 | } 20 | 21 | public abstract void onCommand(CommandSender sender, String[] args); 22 | 23 | public List onTabComplete(CommandSender sender, String[] args, String full) { 24 | return Collections.emptyList(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/commands/CommandHandler.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.commands; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import lombok.Getter; 5 | import org.bukkit.Bukkit; 6 | import org.bukkit.command.CommandExecutor; 7 | import org.bukkit.command.CommandSender; 8 | import org.bukkit.event.Cancellable; 9 | import org.bukkit.event.EventHandler; 10 | import org.bukkit.event.Listener; 11 | import org.bukkit.event.player.PlayerCommandPreprocessEvent; 12 | import org.bukkit.event.server.ServerCommandEvent; 13 | 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | 17 | public class CommandHandler implements Listener, CommandExecutor { 18 | 19 | @Getter private List commands = new ArrayList<>(); 20 | 21 | public CommandHandler(TradePlus pl, boolean compatMode) { 22 | try { 23 | Class.forName("org.bukkit.event.server.TabCompleteEvent"); 24 | Bukkit.getPluginManager() 25 | .registerEvents( 26 | new CommandHandler.TabCompleter() { 27 | @Override 28 | public List getCompletions( 29 | CommandSender sender, String cmd, String[] args, String buffer) { 30 | Command command = 31 | commands.stream().filter(c -> c.isAlias(cmd)).findFirst().orElse(null); 32 | return command != null ? command.onTabComplete(sender, args, buffer) : null; 33 | } 34 | }, 35 | pl); 36 | } catch (ClassNotFoundException ignored) { 37 | } 38 | } 39 | 40 | public void add(Command command) { 41 | commands.add(command); 42 | } 43 | 44 | public void clear() { 45 | commands.clear(); 46 | } 47 | 48 | @Override 49 | public boolean onCommand( 50 | CommandSender sender, org.bukkit.command.Command command, String label, String[] args) { 51 | String[] cmd = new String[args.length + 1]; 52 | cmd[0] = label; 53 | for (int i = 0; i < args.length; i++) { 54 | cmd[i+1] = args[i]; 55 | } 56 | testAndRun(null, sender, cmd); 57 | return true; 58 | } 59 | 60 | // @EventHandler(ignoreCancelled = true) 61 | // public void onCommandEvent(PlayerCommandPreprocessEvent event) { 62 | // String[] cmd = event.getMessage().substring(1).split("\\s+"); 63 | // testAndRun(event, event.getPlayer(), cmd); 64 | // } 65 | // 66 | // @EventHandler(ignoreCancelled = true) 67 | // public void onServerCommand(ServerCommandEvent event) { 68 | // String[] cmd = event.getCommand().split("\\s+"); 69 | // testAndRun(event, event.getSender(), cmd); 70 | // } 71 | 72 | private void testAndRun(Cancellable event, CommandSender sender, String[] cmd) { 73 | if (cmd.length > 0) { 74 | String[] args = new String[cmd.length - 1]; 75 | System.arraycopy(cmd, 1, args, 0, cmd.length - 1); 76 | commands.stream() 77 | .filter(command -> command.isAlias(cmd[0])) 78 | .findFirst() 79 | .ifPresent( 80 | command -> { 81 | command.onCommand(sender, args); 82 | if (event != null) event.setCancelled(true); 83 | }); 84 | } 85 | } 86 | 87 | private abstract class TabCompleter implements Listener { 88 | 89 | @EventHandler 90 | public void onTabComplete(org.bukkit.event.server.TabCompleteEvent event) { 91 | String[] cmd = event.getBuffer().split("\\s+"); 92 | if (cmd.length > 0) { 93 | String[] args = new String[cmd.length - 1]; 94 | System.arraycopy(cmd, 1, args, 0, cmd.length - 1); 95 | List completions = 96 | getCompletions(event.getSender(), cmd[0], args, event.getBuffer()); 97 | if (completions != null) event.setCompletions(completions); 98 | } 99 | } 100 | 101 | protected abstract List getCompletions( 102 | CommandSender sender, String command, String[] args, String buffer); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/commands/TradeCommand.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.commands; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import com.trophonix.tradeplus.events.TradeAcceptEvent; 5 | import com.trophonix.tradeplus.events.TradeRequestEvent; 6 | import com.trophonix.tradeplus.hooks.FactionsHook; 7 | import com.trophonix.tradeplus.hooks.WorldGuardHook; 8 | import com.trophonix.tradeplus.trade.Trade; 9 | import com.trophonix.tradeplus.trade.TradeRequest; 10 | import com.trophonix.tradeplus.util.MsgUtils; 11 | import com.trophonix.tradeplus.util.PDCUtils; 12 | import com.trophonix.tradeplus.util.PlayerUtil; 13 | import org.bukkit.Bukkit; 14 | import org.bukkit.GameMode; 15 | import org.bukkit.Location; 16 | import org.bukkit.command.Command; 17 | import org.bukkit.command.CommandExecutor; 18 | import org.bukkit.command.CommandSender; 19 | import org.bukkit.command.TabCompleter; 20 | import org.bukkit.entity.Player; 21 | 22 | import java.net.InetSocketAddress; 23 | import java.text.DecimalFormat; 24 | import java.util.ArrayList; 25 | import java.util.List; 26 | import java.util.concurrent.ConcurrentLinkedQueue; 27 | import java.util.stream.Collectors; 28 | 29 | public class TradeCommand implements TabCompleter, CommandExecutor { 30 | 31 | private static final DecimalFormat format = new DecimalFormat("0.##"); 32 | 33 | private final ConcurrentLinkedQueue requests = new ConcurrentLinkedQueue<>(); 34 | 35 | private final TradePlus pl; 36 | 37 | private boolean pdc; 38 | 39 | public TradeCommand(TradePlus pl) { 40 | // super( 41 | // new ArrayList() { 42 | // { 43 | // add("trade"); 44 | // if (pl.getTradeConfig().getAliases() != null) { 45 | // addAll(pl.getTradeConfig().getAliases()); 46 | // } 47 | // } 48 | // }); 49 | this.pl = pl; 50 | try { 51 | Class.forName("org.bukkit.persistence.PersistentDataContainer"); 52 | PDCUtils.initialize(pl); 53 | pdc = true; 54 | } catch (ClassNotFoundException ignored) { 55 | } 56 | } 57 | 58 | @Override 59 | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { 60 | if (!(sender instanceof Player)) { 61 | MsgUtils.send(sender, "&cThis command can only be executed by players!"); 62 | return true; 63 | } 64 | final Player player = (Player) sender; 65 | 66 | if (pdc && args.length == 1 && args[0].equalsIgnoreCase("toggle")) { 67 | boolean allowed = PDCUtils.toggleTrading(player); 68 | (allowed ? pl.getTradeConfig().getTradingEnabled() : pl.getTradeConfig().getTradingDisabled()).send(sender); 69 | return true; 70 | } 71 | 72 | try { 73 | if (pl.getTradeConfig().isWorldguardTradingFlag()) { 74 | if (Bukkit.getServer().getPluginManager().isPluginEnabled("WorldGuard")) { 75 | if (!WorldGuardHook.isTradingAllowed(player, player.getLocation())) { 76 | pl.getTradeConfig().getWorldguardTradingNotAllowed().send(player); 77 | return true; 78 | } 79 | } 80 | } 81 | } catch (Throwable ignored) { 82 | 83 | } 84 | 85 | try { 86 | if (!pl.getTradeConfig().isFactionsAllowTradeInEnemyTerritory()) { 87 | if (FactionsHook.isPlayerInEnemyTerritory(player)) { 88 | pl.getTradeConfig().getFactionsEnemyTerritory().send(player); 89 | return true; 90 | } 91 | } 92 | } catch (Throwable ignored) { 93 | } 94 | 95 | boolean permissionRequired = pl.getConfig().getBoolean("permissions.required", false); 96 | 97 | if (args.length == 1) { 98 | final Player receiver = Bukkit.getPlayer(args[0]); 99 | if (receiver == null || PlayerUtil.isVanished(receiver)) { 100 | if (args[0].equalsIgnoreCase("deny")) { 101 | requests.forEach( 102 | req -> { 103 | if (req.receiver == player) { 104 | requests.remove(req); 105 | if (req.sender.isOnline()) { 106 | pl.getTradeConfig() 107 | .getTheyDenied() 108 | .send(req.sender, "%PLAYER%", player.getName()); 109 | } 110 | } 111 | }); 112 | pl.getTradeConfig().getYouDenied().send(player); 113 | return true; 114 | } 115 | pl.getTradeConfig().getErrorsPlayerNotFound().send(player); 116 | return true; 117 | } 118 | 119 | if (player == receiver) { 120 | pl.getTradeConfig().getErrorsSelfTrade().send(player); 121 | return true; 122 | } 123 | 124 | if (!pl.getTradeConfig().isAllowSameIpTrade()) { 125 | if (PlayerUtil.sameIP(player, receiver)) { 126 | pl.getTradeConfig().getErrorsSameIp().send(player); 127 | return true; 128 | } 129 | } 130 | 131 | if (!pl.getTradeConfig().isAllowTradeInCreative()) { 132 | if (player.getGameMode().equals(GameMode.CREATIVE) || player.getGameMode().equals(GameMode.SPECTATOR)) { 133 | pl.getTradeConfig().getErrorsCreative().send(player); 134 | return true; 135 | } else if (receiver.getGameMode().equals(GameMode.CREATIVE) || receiver.getGameMode().equals(GameMode.SPECTATOR)) { 136 | pl.getTradeConfig().getErrorsCreativeThem().send(player, "%PLAYER%", receiver.getName()); 137 | return true; 138 | } 139 | } 140 | 141 | if (pl.getTradeConfig().getBlockedWorlds().contains(player.getWorld().getName())) { 142 | pl.getTradeConfig().getErrorsBlockedWorld().send(player, "%WORLD%", player.getWorld().getName()); 143 | return true; 144 | } 145 | 146 | if (player.getWorld().equals(receiver.getWorld())) { 147 | double amount = pl.getTradeConfig().getSameWorldRange(); 148 | if (amount != 0.0 149 | && player.getLocation().distanceSquared(receiver.getLocation()) > Math.pow(amount, 2)) { 150 | pl.getTradeConfig() 151 | .getErrorsSameWorldRange() 152 | .send(player, "%PLAYER%", receiver.getName(), "%AMOUNT%", format.format(amount)); 153 | return true; 154 | } 155 | } else { 156 | if (pl.getTradeConfig().isAllowCrossWorld()) { 157 | double amount = Math.pow(pl.getTradeConfig().getCrossWorldRange(), 2); 158 | Location test = receiver.getLocation().clone(); 159 | test.setWorld(player.getWorld()); 160 | if (amount != 0.0 && player.getLocation().distanceSquared(test) > amount) { 161 | pl.getTradeConfig() 162 | .getErrorsCrossWorldRange() 163 | .send(player, "%PLAYER%", receiver.getName(), "%AMOUNT%", format.format(amount)); 164 | return true; 165 | } 166 | } else { 167 | pl.getTradeConfig().getErrorsNoCrossWorld().send(player, "%PLAYER%", receiver.getName()); 168 | return true; 169 | } 170 | } 171 | 172 | for (TradeRequest req : requests) { 173 | if (req.sender == player) { 174 | pl.getTradeConfig().getErrorsWaitForExpire().send(player, "%PLAYER%", receiver.getName()); 175 | return true; 176 | } 177 | } 178 | 179 | boolean accept = false; 180 | for (TradeRequest req : requests) { 181 | if (req.contains(player) && req.contains(receiver)) accept = true; 182 | } 183 | if (accept) { 184 | TradeAcceptEvent tradeAcceptEvent = new TradeAcceptEvent(receiver, player); 185 | Bukkit.getPluginManager().callEvent(tradeAcceptEvent); 186 | if (tradeAcceptEvent.isCancelled()) return true; 187 | pl.getTradeConfig().getAcceptSender().send(receiver, "%PLAYER%", player.getName()); 188 | pl.getTradeConfig().getAcceptReceiver().send(player, "%PLAYER%", receiver.getName()); 189 | new Trade(receiver, player); 190 | requests.removeIf(req -> req.contains(player) && req.contains(receiver)); 191 | } else { 192 | if (pdc && !PDCUtils.allowTrading(receiver)) { 193 | pl.getTradeConfig().getErrorsTradingDisabled().send(sender, "%PLAYER%", receiver.getName()); 194 | return true; 195 | } 196 | 197 | String sendPermission = pl.getTradeConfig().getSendPermission(); 198 | if (permissionRequired) { 199 | if (!sender.hasPermission(sendPermission)) { 200 | pl.getTradeConfig().getErrorsNoPermsAccept().send(player); 201 | return true; 202 | } 203 | } 204 | 205 | String acceptPermission = pl.getTradeConfig().getAcceptPermission(); 206 | if (permissionRequired && !receiver.hasPermission(acceptPermission)) { 207 | pl.getTradeConfig() 208 | .getErrorsNoPermsReceive() 209 | .send(player, "%PLAYER%", receiver.getName()); 210 | return true; 211 | } 212 | 213 | TradeRequestEvent event = new TradeRequestEvent(player, receiver); 214 | Bukkit.getPluginManager().callEvent(event); 215 | if (event.isCancelled()) return true; 216 | final TradeRequest request = new TradeRequest(player, receiver); 217 | requests.add(request); 218 | pl.getTradeConfig().getRequestSent().send(player, "%PLAYER%", receiver.getName()); 219 | pl.getTradeConfig() 220 | .getRequestReceived() 221 | .setOnClick("/trade " + player.getName()) 222 | .send(receiver, "%PLAYER%", player.getName()); 223 | Bukkit.getScheduler() 224 | .runTaskLater( 225 | pl, 226 | () -> { 227 | boolean was = requests.remove(request); 228 | if (player.isOnline() && was) { 229 | pl.getTradeConfig().getExpired().send(player, "%PLAYER%", receiver.getName()); 230 | } 231 | }, 232 | 20 * (long)pl.getTradeConfig().getRequestCooldownSeconds()); 233 | } 234 | return true; 235 | } 236 | pl.getTradeConfig().getErrorsInvalidUsage().send(player); 237 | return true; 238 | } 239 | 240 | @Override 241 | public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { 242 | List args0 = new ArrayList<>(); 243 | args0.add("deny"); 244 | args0.addAll( 245 | Bukkit.getOnlinePlayers().stream() 246 | .filter(p -> !PlayerUtil.isVanished(p)) 247 | .map(Player::getName) 248 | .collect(Collectors.toList())); 249 | if (args.length == 0) { 250 | return args0; 251 | } else if (args.length == 1) { 252 | return args0.stream() 253 | .filter( 254 | name -> 255 | !name.equalsIgnoreCase(args[0]) 256 | && name.toLowerCase().startsWith(args[0].toLowerCase())) 257 | .collect(Collectors.toList()); 258 | } 259 | return null; 260 | } 261 | } 262 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/commands/TradePlusCommand.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.commands; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import com.trophonix.tradeplus.trade.Trade; 5 | import com.trophonix.tradeplus.util.MsgUtils; 6 | import com.trophonix.tradeplus.util.PlayerUtil; 7 | import org.bukkit.Bukkit; 8 | import org.bukkit.command.Command; 9 | import org.bukkit.command.CommandExecutor; 10 | import org.bukkit.command.CommandSender; 11 | import org.bukkit.command.TabCompleter; 12 | import org.bukkit.entity.Player; 13 | 14 | import java.util.Arrays; 15 | import java.util.Collections; 16 | import java.util.List; 17 | import java.util.stream.Collectors; 18 | 19 | public class TradePlusCommand implements CommandExecutor, TabCompleter { 20 | 21 | private final TradePlus pl; 22 | private List arg0 = Arrays.asList("reload", "rl", "force", "spectate"); 23 | 24 | public TradePlusCommand(TradePlus pl) { 25 | // super(Collections.singletonList("tradeplus")); 26 | this.pl = pl; 27 | } 28 | 29 | @Override 30 | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { 31 | if (!sender.hasPermission("tradeplus.admin")) { 32 | pl.getTradeConfig().getErrorsNoPermsAdmin().send(sender); 33 | return true; 34 | } 35 | 36 | switch (args.length) { 37 | case 1: 38 | if (args[0].equalsIgnoreCase("reload") || args[0].equalsIgnoreCase("rl")) { 39 | pl.reload(); 40 | pl.getTradeConfig().getAdminConfigReloaded().send(sender); 41 | return true; 42 | } 43 | break; 44 | case 2: 45 | if (pl.getTradeConfig().isSpectateEnabled() && args[0].equalsIgnoreCase("spectate")) { 46 | Player player = Bukkit.getPlayer(args[1]); 47 | if (player == null || !player.isOnline()) { 48 | pl.getTradeConfig().getAdminInvalidPlayers().send(sender); 49 | return true; 50 | } 51 | Trade trade = pl.getTrade(player); 52 | if (trade == null) { 53 | pl.getTradeConfig().getAdminNoTrade().send(player); 54 | } else { 55 | player.openInventory(trade.getSpectatorInv()); 56 | } 57 | return true; 58 | } 59 | break; 60 | case 3: 61 | if (args[0].equalsIgnoreCase("force")) { 62 | Player p1 = Bukkit.getPlayer(args[1]); 63 | Player p2 = Bukkit.getPlayer(args[2]); 64 | if (p1 == null || p2 == null || !p1.isOnline() || !p2.isOnline() || p1.equals(p2)) { 65 | pl.getTradeConfig().getAdminInvalidPlayers().send(sender); 66 | return true; 67 | } 68 | pl.getTradeConfig() 69 | .getAdminForcedTrade() 70 | .send(sender, "%PLAYER1%", p1.getName(), "%PLAYER2%", p2.getName()); 71 | pl.getTradeConfig().getForcedTrade().send(p1, "%PLAYER%", p2.getName()); 72 | pl.getTradeConfig().getForcedTrade().send(p2, "%PLAYER%", p1.getName()); 73 | Trade trade = new Trade(p1, p2); 74 | if (sender instanceof Player && !(sender.equals(p1) || sender.equals(p2))) 75 | ((Player) sender).openInventory(trade.getSpectatorInv()); 76 | return true; 77 | } else if (args[0].equalsIgnoreCase("spectate")) { 78 | if (!(sender instanceof Player)) { 79 | pl.getTradeConfig().getAdminPlayersOnly().send(sender); 80 | return true; 81 | } 82 | Player player = (Player) sender; 83 | Player p1 = Bukkit.getPlayer(args[1]); 84 | Player p2 = Bukkit.getPlayer(args[2]); 85 | if (p1 == null || p2 == null || !p1.isOnline() || !p2.isOnline() || p1.equals(p2)) { 86 | pl.getTradeConfig().getAdminInvalidPlayers().send(sender); 87 | return true; 88 | } 89 | Trade trade = pl.getTrade(p1, p2); 90 | if (trade == null) { 91 | pl.getTradeConfig().getAdminNoTrade().send(player); 92 | } else { 93 | player.openInventory(trade.getSpectatorInv()); 94 | } 95 | return true; 96 | } 97 | break; 98 | } 99 | MsgUtils.send( 100 | sender, 101 | new String[] { 102 | "&6&l<----- Trade+ by Trophonix ----->", 103 | "&e/trade &fSend a trade request", 104 | "&e/tradeplus reload &fReload config files", 105 | "&e/tradeplus force &fForce 2 players to trade" 106 | }); 107 | if (pl.getTradeConfig().isSpectateEnabled()) 108 | MsgUtils.send(sender, "&e/tradeplus spectate &fSpectate an ongoing trade"); 109 | return true; 110 | } 111 | 112 | @Override 113 | public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { 114 | StringBuilder builder = new StringBuilder(alias.toLowerCase()); 115 | for (String arg : args) { 116 | builder.append(" ").append(arg); 117 | } 118 | String full = builder.toString(); 119 | if (args.length == 0) { 120 | return arg0; 121 | } else if (args.length == 1 && !full.endsWith(" ")) { 122 | return arg0.stream() 123 | .filter(name -> !name.equalsIgnoreCase(args[0]) && name.startsWith(args[0].toLowerCase())) 124 | .collect(Collectors.toList()); 125 | } else if (args.length > 1 126 | && !full.endsWith(" ") 127 | && (args[0].equalsIgnoreCase("force") || args[0].equalsIgnoreCase("spectate"))) { 128 | return Bukkit.getOnlinePlayers().stream() 129 | .filter(p -> !PlayerUtil.isVanished(p)) 130 | .map(Player::getName) 131 | .filter( 132 | name -> 133 | !name.equalsIgnoreCase(args[args.length - 1]) 134 | && name.toLowerCase().startsWith(args[args.length - 1])) 135 | .collect(Collectors.toList()); 136 | } 137 | return null; 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/config/ConfigMessage.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.config; 2 | 3 | import com.trophonix.tradeplus.util.MsgUtils; 4 | import org.bukkit.ChatColor; 5 | import org.bukkit.command.CommandSender; 6 | import org.bukkit.configuration.ConfigurationSection; 7 | import org.bukkit.entity.Player; 8 | 9 | public class ConfigMessage { 10 | 11 | private String[] message; 12 | private String onHover; 13 | private String onClick; 14 | 15 | public ConfigMessage(ConfigurationSection yml, String key, String defaultText) { 16 | String text = null; 17 | if (yml.isString(key)) { 18 | text = yml.getString(key); 19 | } else if (yml.isConfigurationSection(key)) { 20 | text = yml.getString(key + ".text"); 21 | onHover = yml.getString(key + ".hover"); 22 | } 23 | if (text == null) text = defaultText; 24 | if (text.contains("%NEWLINE%")) { 25 | message = text.split("%NEWLINE%"); 26 | for (int i = 0; i < message.length; i++) { 27 | message[i] = MsgUtils.color(message[i]); 28 | } 29 | } else { 30 | message = new String[] {MsgUtils.color(text)}; 31 | } 32 | } 33 | 34 | public void send(CommandSender player, String... replacements) { 35 | String hover = this.onHover; 36 | if (hover != null) 37 | for (int i = 0; i < replacements.length - 1; i += 2) { 38 | hover = hover.replace(replacements[i], replacements[i + 1]); 39 | } 40 | for (String line : message) { 41 | for (int i = 0; i < replacements.length - 1; i += 2) { 42 | line = line.replace(replacements[i], replacements[i + 1]); 43 | } 44 | if (onHover == null && onClick == null) { 45 | player.sendMessage(line); 46 | } else { 47 | MsgUtils.send((Player) player, hover, onClick, line); 48 | } 49 | } 50 | } 51 | 52 | public ConfigMessage setOnClick(String command) { 53 | onClick = command; 54 | return this; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/events/ExcessChestListener.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.events; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import org.bukkit.Material; 5 | import org.bukkit.event.EventHandler; 6 | import org.bukkit.event.Listener; 7 | import org.bukkit.event.inventory.InventoryCloseEvent; 8 | import org.bukkit.inventory.Inventory; 9 | import org.bukkit.inventory.ItemStack; 10 | 11 | public class ExcessChestListener implements Listener { 12 | 13 | private TradePlus pl; 14 | 15 | public ExcessChestListener(TradePlus pl) { 16 | this.pl = pl; 17 | pl.getServer().getPluginManager().registerEvents(this, pl); 18 | } 19 | 20 | @EventHandler 21 | public void onClose(InventoryCloseEvent event) { 22 | Inventory closed = event.getInventory(); 23 | 24 | if (pl.getExcessChests().contains(closed)) { 25 | for (ItemStack i : event.getInventory()) { 26 | if (i == null || i.getType() == Material.AIR) continue; 27 | event.getPlayer().getWorld().dropItemNaturally(event.getPlayer().getLocation(), i); 28 | } 29 | pl.getExcessChests().remove(closed); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/events/TradeAcceptEvent.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.events; 2 | 3 | import org.bukkit.entity.Player; 4 | import org.bukkit.event.Cancellable; 5 | import org.bukkit.event.Event; 6 | import org.bukkit.event.HandlerList; 7 | 8 | /** Created by Lucas on 5/20/17. */ 9 | public class TradeAcceptEvent extends Event implements Cancellable { 10 | 11 | private static final HandlerList handlers = new HandlerList(); 12 | 13 | private final Player sender; 14 | private final Player receiver; 15 | 16 | private boolean cancelled; 17 | 18 | public TradeAcceptEvent(Player sender, Player receiver) { 19 | this.sender = sender; 20 | this.receiver = receiver; 21 | } 22 | 23 | public static HandlerList getHandlerList() { 24 | return handlers; 25 | } 26 | 27 | @Override 28 | public boolean isCancelled() { 29 | return cancelled; 30 | } 31 | 32 | @Override 33 | public void setCancelled(boolean cancelled) { 34 | this.cancelled = cancelled; 35 | } 36 | 37 | public Player getSender() { 38 | return sender; 39 | } 40 | 41 | public Player getReceiver() { 42 | return receiver; 43 | } 44 | 45 | @Override 46 | public HandlerList getHandlers() { 47 | return handlers; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/events/TradeCompleteEvent.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.events; 2 | 3 | import com.trophonix.tradeplus.logging.TradeLog; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Getter; 6 | import org.bukkit.entity.Player; 7 | import org.bukkit.event.Event; 8 | import org.bukkit.event.HandlerList; 9 | 10 | @AllArgsConstructor 11 | @Getter 12 | public class TradeCompleteEvent extends Event { 13 | 14 | private static final HandlerList handlers = new HandlerList(); 15 | 16 | private final TradeLog trade; 17 | private final Player playerOne; 18 | private final Player playerTwo; 19 | 20 | public static HandlerList getHandlerList() { 21 | return handlers; 22 | } 23 | 24 | @Override 25 | public HandlerList getHandlers() { 26 | return handlers; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/events/TradeRequestEvent.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.events; 2 | 3 | import org.bukkit.entity.Player; 4 | import org.bukkit.event.Cancellable; 5 | import org.bukkit.event.Event; 6 | import org.bukkit.event.HandlerList; 7 | 8 | /** Created by Lucas on 5/20/17. */ 9 | public class TradeRequestEvent extends Event implements Cancellable { 10 | 11 | private static final HandlerList handlers = new HandlerList(); 12 | 13 | private final Player sender; 14 | private final Player receiver; 15 | 16 | private boolean cancelled; 17 | 18 | public TradeRequestEvent(Player sender, Player receiver) { 19 | this.sender = sender; 20 | this.receiver = receiver; 21 | } 22 | 23 | public static HandlerList getHandlerList() { 24 | return handlers; 25 | } 26 | 27 | public Player getSender() { 28 | return sender; 29 | } 30 | 31 | public Player getReceiver() { 32 | return receiver; 33 | } 34 | 35 | @Override 36 | public boolean isCancelled() { 37 | return cancelled; 38 | } 39 | 40 | @Override 41 | public void setCancelled(boolean cancelled) { 42 | this.cancelled = cancelled; 43 | } 44 | 45 | @Override 46 | public HandlerList getHandlers() { 47 | return handlers; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/extras/BeastTokensExtra.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.extras; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import com.trophonix.tradeplus.trade.Trade; 5 | import com.trophonix.tradeplus.util.ItemFactory; 6 | import me.mraxetv.beasttokens.BeastTokensAPI; 7 | import me.mraxetv.beasttokens.api.handlers.PlayersManager; 8 | import me.mraxetv.beasttokens.api.handlers.TokensManager; 9 | import me.realized.tokenmanager.api.TokenManager; 10 | import org.bukkit.entity.Player; 11 | import org.bukkit.inventory.ItemStack; 12 | 13 | public class BeastTokensExtra extends Extra { 14 | 15 | private TokensManager api; 16 | 17 | public BeastTokensExtra(Player player1, Player player2, TradePlus pl, Trade trade) { 18 | super("beasttokens", player1, player2, pl, trade); 19 | api = BeastTokensAPI.getTokensManager(); 20 | } 21 | 22 | @Override 23 | public double getMax(Player player) { return api.getTokens(player); } 24 | 25 | @Override 26 | public void onTradeEnd() { 27 | if (value1 > 0) { 28 | api.setTokens(player1, api.getTokens(player1) - (long) value1); 29 | api.setTokens(player2, api.getTokens(player2) + (long) value1); 30 | } 31 | if (value2 > 0) { 32 | api.setTokens(player2, api.getTokens(player2) - (long) value2); 33 | api.setTokens(player1, api.getTokens(player1) + (long) value2); 34 | } 35 | } 36 | 37 | @Override 38 | public ItemStack _getIcon(Player player) { 39 | return ItemFactory.replaceInMeta( 40 | icon, 41 | "%AMOUNT%", 42 | Long.toString((long) (player.equals(player1) ? value1 : value2)), 43 | "%INCREMENT%", 44 | Long.toString((long) increment), 45 | "%PLAYERINCREMENT%", 46 | Long.toString((long) (player.equals(player1) ? increment1 : increment2))); 47 | } 48 | 49 | @Override 50 | public ItemStack _getTheirIcon(Player player) { 51 | return ItemFactory.replaceInMeta( 52 | theirIcon, "%AMOUNT%", Long.toString((long) (player.equals(player1) ? value1 : value2))); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/extras/EconomyExtra.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.extras; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import com.trophonix.tradeplus.trade.Trade; 5 | import com.trophonix.tradeplus.util.ItemFactory; 6 | import net.milkbowl.vault.economy.Economy; 7 | import net.milkbowl.vault.economy.EconomyResponse; 8 | import org.bukkit.entity.Player; 9 | import org.bukkit.inventory.ItemStack; 10 | 11 | public class EconomyExtra extends Extra { 12 | 13 | private final Economy economy; 14 | 15 | public EconomyExtra(Player player1, Player player2, TradePlus pl, Trade trade) { 16 | super("economy", player1, player2, pl, trade); 17 | this.economy = pl.getServer().getServicesManager().getRegistration(Economy.class).getProvider(); 18 | } 19 | 20 | @Override 21 | public double getMax(Player player) { 22 | return economy.getBalance(player); 23 | } 24 | 25 | @Override 26 | public void onTradeEnd() { 27 | if (value1 > 0) { 28 | if (economy.withdrawPlayer(player1, value1).type.equals(EconomyResponse.ResponseType.SUCCESS)) 29 | economy.depositPlayer(player2, value1 - ((value1 / 100) * taxPercent)); 30 | } 31 | if (value2 > 0) { 32 | if (economy.withdrawPlayer(player2, value2).type.equals(EconomyResponse.ResponseType.SUCCESS)) 33 | economy.depositPlayer(player1, value2 - ((value2 / 100) * taxPercent)); 34 | } 35 | } 36 | 37 | @Override 38 | public ItemStack _getIcon(Player player) { 39 | return ItemFactory.replaceInMeta( 40 | icon, 41 | "%AMOUNT%", 42 | decimalFormat.format(player.equals(player1) ? value1 : value2), 43 | "%CURRENCY%", 44 | economy.getBalance(player) == 1 45 | ? economy.currencyNameSingular() 46 | : economy.currencyNamePlural(), 47 | "%INCREMENT%", 48 | decimalFormat.format(increment), 49 | "%PLAYERINCREMENT%", 50 | decimalFormat.format(player.equals(player1) ? increment1 : increment2)); 51 | } 52 | 53 | @Override 54 | public ItemStack _getTheirIcon(Player player) { 55 | return ItemFactory.replaceInMeta( 56 | theirIcon, 57 | "%AMOUNT%", 58 | decimalFormat.format(player.equals(player1) ? value1 : value2), 59 | "%CURRENCY%", 60 | economy.getBalance(player) == 1 61 | ? economy.currencyNameSingular() 62 | : economy.currencyNamePlural()); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/extras/EnjinPointsExtra.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.extras; 2 | 3 | import com.enjin.core.EnjinServices; 4 | import com.enjin.rpc.mappings.mappings.general.RPCData; 5 | import com.enjin.rpc.mappings.services.PointService; 6 | import com.trophonix.tradeplus.TradePlus; 7 | import com.trophonix.tradeplus.trade.Trade; 8 | import com.trophonix.tradeplus.util.ItemFactory; 9 | import org.bukkit.entity.Player; 10 | import org.bukkit.inventory.ItemStack; 11 | 12 | public class EnjinPointsExtra extends Extra { 13 | 14 | private TradePlus pl; 15 | 16 | public EnjinPointsExtra(Player player1, Player player2, TradePlus pl, Trade trade) { 17 | super("enjinpoints", player1, player2, pl, trade); 18 | this.pl = pl; 19 | } 20 | 21 | @Override 22 | public double getMax(Player player) { 23 | try { 24 | return EnjinServices.getService(PointService.class).get(player.getName()).getResult(); 25 | } catch (Exception ex) { 26 | pl.getLogger().warning("Failed to get enjinpoints for player: " + player.getName()); 27 | return 0; 28 | } 29 | } 30 | 31 | @Override 32 | public void onTradeEnd() { 33 | if (value1 > 0) { 34 | transact(player1, player2, value1); 35 | } 36 | if (value2 > 0) { 37 | transact(player2, player1, value2); 38 | } 39 | } 40 | 41 | @Override 42 | public ItemStack _getIcon(Player player) { 43 | return ItemFactory.replaceInMeta( 44 | icon, 45 | "%AMOUNT%", 46 | decimalFormat.format(player.equals(player1) ? value1 : value2), 47 | "%CURRENCY%", 48 | "Enjin points", 49 | "%INCREMENT%", 50 | decimalFormat.format(increment), 51 | "%PLAYERINCREMENT%", 52 | decimalFormat.format(player.equals(player1) ? increment1 : increment2)); 53 | } 54 | 55 | @Override 56 | public ItemStack _getTheirIcon(Player player) { 57 | return ItemFactory.replaceInMeta( 58 | theirIcon, 59 | "%AMOUNT%", 60 | decimalFormat.format(player.equals(player1) ? value1 : value2), 61 | "%CURRENCY%", 62 | "Enjin points"); 63 | } 64 | 65 | private void transact(Player take, Player give, double points) { 66 | PointService pointService = EnjinServices.getService(PointService.class); 67 | RPCData withdrawResponse = pointService.remove(take.getName(), (int) points); 68 | if (withdrawResponse == null) { 69 | pl.getLogger() 70 | .warning("Failed to withdraw " + points + " points from " + take.getName() + ":"); 71 | pl.getLogger().warning("Couldn't connect to enjin points api"); 72 | } else if (withdrawResponse.getError() != null) { 73 | pl.getLogger() 74 | .warning("Failed to withdraw " + points + " points from " + take.getName() + ":"); 75 | pl.getLogger().warning(withdrawResponse.getError().getMessage()); 76 | } else { 77 | RPCData depositResponse = pointService.add(give.getName(), (int) points); 78 | if (depositResponse == null) { 79 | pl.getLogger().warning("Failed to give " + points + " points to " + give.getName() + ":"); 80 | pl.getLogger().warning("Couldn't connect to enjin points api"); 81 | } else if (depositResponse.getError() != null) { 82 | pl.getLogger().warning("Failed to give " + points + " points to " + give.getName() + ":"); 83 | pl.getLogger().warning(depositResponse.getError().getMessage()); 84 | } 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/extras/ExperienceExtra.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.extras; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import com.trophonix.tradeplus.trade.Trade; 5 | import com.trophonix.tradeplus.util.ItemFactory; 6 | import com.trophonix.tradeplus.util.XP; 7 | import org.bukkit.entity.Player; 8 | import org.bukkit.inventory.ItemStack; 9 | 10 | public class ExperienceExtra extends Extra { 11 | 12 | private boolean levelMode; 13 | 14 | public ExperienceExtra(Player player1, Player player2, TradePlus pl, Trade trade) { 15 | super("experience", player1, player2, pl, trade); 16 | levelMode = pl.getConfig().getBoolean("extras.experience.levelMode", false); 17 | } 18 | 19 | @Override 20 | public double getMax(Player player) { 21 | // if (levelMode) return player.getLevel(); 22 | // else 23 | return XP.getExp(player); 24 | } 25 | 26 | @Override 27 | public void onTradeEnd() { 28 | if (taxPercent > 0) { 29 | value1 -= (value1 * taxPercent) / 100; 30 | value2 -= (value2 * taxPercent) / 100; 31 | } 32 | if (value1 > 0) { 33 | changeXp(player1, -value1); 34 | changeXp(player2, value1); 35 | } 36 | if (value2 > 0) { 37 | changeXp(player2, -value2); 38 | changeXp(player1, value2); 39 | } 40 | } 41 | 42 | @Override 43 | public ItemStack _getIcon(Player player) { 44 | return ItemFactory.replaceInMeta( 45 | icon, 46 | "%AMOUNT%", 47 | decimalFormat.format(player.equals(player1) ? value1 : value2), 48 | "%INCREMENT%", 49 | decimalFormat.format(increment), 50 | "%PLAYERINCREMENT%", 51 | decimalFormat.format(player.equals(player1) ? increment1 : increment2), 52 | "%LEVELS%", 53 | Integer.toString( 54 | player.equals(player1) 55 | ? getLevelChangeFromXp(player1, -value1) 56 | : getLevelChangeFromXp(player2, -value2))); 57 | } 58 | 59 | @Override 60 | public ItemStack _getTheirIcon(Player player) { 61 | return ItemFactory.replaceInMeta( 62 | theirIcon, 63 | "%AMOUNT%", 64 | decimalFormat.format(player.equals(player1) ? value1 : value2), 65 | "%LEVELS%", 66 | Integer.toString( 67 | player.equals(player1) 68 | ? getLevelChangeFromXp(player2, value1) 69 | : getLevelChangeFromXp(player1, value2))); 70 | } 71 | 72 | private int getLevelChangeFromXp(Player receiver, double amount) { 73 | int currentXp = XP.getExp(receiver); 74 | double currentLevel = XP.getLevelFromExp(currentXp); 75 | return (int) (XP.getLevelFromExp(currentXp + (int) amount) - currentLevel); 76 | } 77 | 78 | private void changeXp(Player player, Number amount) { 79 | XP.changeExp(player, amount.intValue()); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/extras/Extra.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.extras; 2 | 3 | import com.google.common.base.Preconditions; 4 | import com.trophonix.tradeplus.TradePlus; 5 | import com.trophonix.tradeplus.trade.Trade; 6 | import com.trophonix.tradeplus.util.ItemFactory; 7 | import com.trophonix.tradeplus.util.MsgUtils; 8 | import com.trophonix.tradeplus.util.Sounds; 9 | import lombok.Getter; 10 | import org.bukkit.ChatColor; 11 | import org.bukkit.Material; 12 | import org.bukkit.configuration.ConfigurationSection; 13 | import org.bukkit.conversations.*; 14 | import org.bukkit.entity.Player; 15 | import org.bukkit.event.Listener; 16 | import org.bukkit.event.inventory.ClickType; 17 | import org.bukkit.inventory.ItemStack; 18 | 19 | import java.text.DecimalFormat; 20 | 21 | public abstract class Extra implements Listener { 22 | 23 | static final DecimalFormat decimalFormat = new DecimalFormat("###,##0.##"); 24 | public final String name; 25 | final ItemStack icon; 26 | final Player player1; 27 | private Conversation convo1, convo2; 28 | final Player player2; 29 | final double increment; 30 | final ItemStack theirIcon; 31 | final double taxPercent; 32 | public double value1 = 0, value2 = 0; 33 | double increment1; 34 | double increment2; 35 | @Getter private String displayName; 36 | private TradePlus pl; 37 | private double max1; 38 | private double max2; 39 | private long lastUpdatedMax = System.currentTimeMillis(); 40 | private String mode; 41 | private Trade trade; 42 | 43 | Extra(String name, Player player1, Player player2, TradePlus pl, Trade trade) { 44 | pl.getServer().getPluginManager().registerEvents(this, pl); 45 | this.pl = pl; 46 | this.name = name; 47 | ConfigurationSection section = 48 | Preconditions.checkNotNull(pl.getConfig().getConfigurationSection("extras." + name)); 49 | this.displayName = section.getString("name"); 50 | this.player1 = player1; 51 | this.player2 = player2; 52 | this.increment = section.getDouble("increment", 1D); 53 | this.increment1 = increment; 54 | this.increment2 = increment; 55 | ItemFactory factory = 56 | new ItemFactory(section.getString("material", "PAPER"), Material.PAPER) 57 | .display(section.getString("display", "&4ERROR")) 58 | .customModelData(section.getInt("customModelData", 0)); 59 | if (section.contains("lore")) factory.lore(section.getStringList("lore")); 60 | this.icon = factory.flag("HIDE_ATTRIBUTES").build(); 61 | this.theirIcon = 62 | new ItemFactory(section.getString("material", "PAPER"), Material.PAPER) 63 | .display(section.getString("theirdisplay", "&4ERROR")) 64 | .customModelData(section.getInt("customModelData", 0)) 65 | .build(); 66 | this.taxPercent = section.getDouble("taxpercent", 0); 67 | this.mode = section.getString("mode", "chat").toLowerCase(); 68 | if (mode.equals("type") || mode.equals("anvil")) { 69 | mode = "chat"; 70 | section.set("mode", "chat"); 71 | pl.saveConfig(); 72 | } 73 | this.trade = trade; 74 | } 75 | 76 | public void init() { 77 | this.max1 = getMax(player1); 78 | this.max2 = getMax(player2); 79 | this.pl.log("'" + name + "' extra initialized. Balances: [" + max1 + ", " + max2 + "]"); 80 | } 81 | 82 | public void onClick(Player player, ClickType click) { 83 | double offer = player1.equals(player) ? value1 : value2; 84 | if (mode.equals("chat")) { 85 | trade.setCancelOnClose(player, false); 86 | player.closeInventory(); 87 | Conversation convo = 88 | new ConversationFactory(pl) 89 | .withPrefix( 90 | conversationContext -> 91 | MsgUtils.color(pl.getTradeConfig().getExtrasTypePrefix())) 92 | .withFirstPrompt( 93 | new StringPrompt() { 94 | @Override 95 | public Prompt acceptInput( 96 | ConversationContext conversationContext, String input) { 97 | if (trade.isCancelled()) return null; 98 | if (input == null || input.equalsIgnoreCase("cancel")) return null; 99 | Number number; 100 | try { 101 | number = Double.parseDouble(input); 102 | } catch (NumberFormatException ignored) { 103 | player.sendMessage(pl.getTradeConfig().getExtrasTypePrefix() + pl.getTradeConfig().getExtrasTypeInvalid()); 104 | return this; 105 | } 106 | if (number.doubleValue() < 0 || number.doubleValue() > getMax(player)) { 107 | return new StringPrompt() { 108 | @Override 109 | public Prompt acceptInput( 110 | ConversationContext conversationContext, String input) { 111 | if (trade.isCancelled()) return null; 112 | if (input == null || input.equalsIgnoreCase("cancel")) return null; 113 | Number number; 114 | try { 115 | number = Double.parseDouble(input); 116 | } catch (NumberFormatException ignored) { 117 | return this; 118 | } 119 | if (number.doubleValue() < 0 || number.doubleValue() > getMax(player)) { 120 | return this; 121 | } 122 | if (player1.equals(player)) { 123 | setValue1(number.doubleValue()); 124 | } else if (player2.equals(player)) { 125 | setValue2(number.doubleValue()); 126 | } 127 | updateMax(false); 128 | return null; 129 | } 130 | 131 | @Override 132 | public String getPromptText(ConversationContext conversationContext) { 133 | return pl.getTradeConfig() 134 | .getExtrasTypeMaximum() 135 | .replace("%BALANCE%", decimalFormat.format(getMax(player))) 136 | .replace("%EXTRA%", displayName); 137 | } 138 | }; 139 | } 140 | if (player1.equals(player)) { 141 | setValue1(number.doubleValue()); 142 | } else if (player2.equals(player)) { 143 | setValue2(number.doubleValue()); 144 | } 145 | updateMax(false); 146 | return null; 147 | } 148 | 149 | @Override 150 | public String getPromptText(ConversationContext conversationContext) { 151 | return pl.getTradeConfig() 152 | .getExtrasTypeEmpty() 153 | .replace("%BALANCE%", decimalFormat.format(getMax(player))) 154 | .replace("%AMOUNT%", decimalFormat.format(offer)) 155 | .replace("%EXTRA%", displayName); 156 | } 157 | }) 158 | .withTimeout(30) 159 | .addConversationAbandonedListener( 160 | event -> { 161 | if (trade.isCancelled()) return; 162 | if (!event.gracefulExit()) Sounds.villagerHmm(player, 1f); 163 | trade.open(player); 164 | trade.updateExtras(); 165 | trade.setCancelOnClose(player, true); 166 | }) 167 | .buildConversation(player); 168 | if (player.equals(player1)) { 169 | convo1 = convo; 170 | } else { 171 | convo2 = convo; 172 | } 173 | convo.begin(); 174 | } else { 175 | if (click.isLeftClick()) { 176 | if (click.isShiftClick()) { 177 | if (player.equals(player1)) { 178 | increment1 -= increment; 179 | } else if (player.equals(player2)) { 180 | increment2 -= increment; 181 | } 182 | } else { 183 | if (player.equals(player1)) { 184 | value1 -= increment1; 185 | } else if (player.equals(player2)) { 186 | value2 -= increment2; 187 | } 188 | } 189 | } else if (click.isRightClick()) { 190 | if (click.isShiftClick()) { 191 | if (player.equals(player1)) { 192 | increment1 += increment; 193 | } else if (player.equals(player2)) { 194 | increment2 += increment; 195 | } 196 | } else { 197 | if (player.equals(player1)) { 198 | value1 += increment1; 199 | } else if (player.equals(player2)) { 200 | value2 += increment2; 201 | } 202 | } 203 | } 204 | } 205 | if (increment1 < 0) increment1 = 0; 206 | if (increment2 < 0) increment2 = 0; 207 | 208 | if (value1 < 0) value1 = 0; 209 | if (value2 < 0) value2 = 0; 210 | 211 | updateMax(true); 212 | } 213 | 214 | public void setValue1(double value1) { 215 | this.value1 = value1; 216 | } 217 | 218 | public void setValue2(double value2) { 219 | this.value2 = value2; 220 | } 221 | 222 | public boolean updateMax(boolean delay) { 223 | long now = System.currentTimeMillis(); 224 | if (!delay || now > lastUpdatedMax + 5000) { 225 | max1 = getMax(player1); 226 | max2 = getMax(player2); 227 | lastUpdatedMax = now; 228 | } 229 | boolean updated = false; 230 | if (value1 > max1) { 231 | value1 = max1; 232 | updated = true; 233 | } 234 | if (value2 > max2) { 235 | value2 = max2; 236 | updated = true; 237 | } 238 | return updated; 239 | } 240 | 241 | public abstract double getMax(Player player); 242 | 243 | public abstract void onTradeEnd(); 244 | 245 | public void onCancel() { 246 | if (convo1 != null && player1.isConversing()) player1.abandonConversation(convo1); 247 | if (convo2 != null && player2.isConversing()) player2.abandonConversation(convo2); 248 | } 249 | 250 | public ItemStack getIcon(Player player) { 251 | return ItemFactory.replaceInMeta( 252 | _getIcon(player), 253 | "%BALANCE%", 254 | decimalFormat.format(getMax(player)), 255 | "%EXTRA%", 256 | displayName); 257 | } 258 | 259 | public ItemStack getTheirIcon(Player player) { 260 | return ItemFactory.replaceInMeta( 261 | _getTheirIcon(player), 262 | "%BALANCE%", 263 | decimalFormat.format(getMax(player1.equals(player) ? player2 : player1)), 264 | "%EXTRA%", 265 | displayName); 266 | } 267 | 268 | protected abstract ItemStack _getIcon(Player player); 269 | 270 | protected abstract ItemStack _getTheirIcon(Player player); 271 | } 272 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/extras/GriefPreventionExtra.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.extras; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import com.trophonix.tradeplus.trade.Trade; 5 | import com.trophonix.tradeplus.util.ItemFactory; 6 | import me.ryanhamshire.GriefPrevention.GriefPrevention; 7 | import me.ryanhamshire.GriefPrevention.PlayerData; 8 | import org.bukkit.entity.Player; 9 | import org.bukkit.inventory.ItemStack; 10 | 11 | public class GriefPreventionExtra extends Extra { 12 | 13 | public GriefPreventionExtra(Player player1, Player player2, TradePlus pl, Trade trade) { 14 | super("griefprevention", player1, player2, pl, trade); 15 | } 16 | 17 | @Override 18 | public double getMax(Player player) { 19 | PlayerData data = GriefPrevention.instance.dataStore.getPlayerData(player.getUniqueId()); 20 | return data.getRemainingClaimBlocks(); 21 | } 22 | 23 | @Override 24 | public void onTradeEnd() { 25 | GriefPrevention inst = GriefPrevention.instance; 26 | PlayerData data1 = inst.dataStore.getPlayerData(player1.getUniqueId()); 27 | PlayerData data2 = inst.dataStore.getPlayerData(player2.getUniqueId()); 28 | if (value1 > 0) { 29 | data1.setBonusClaimBlocks(data1.getBonusClaimBlocks() - (int) value1); 30 | data2.setBonusClaimBlocks( 31 | data2.getBonusClaimBlocks() + (int) (value1 - ((value1 / 100) * taxPercent))); 32 | } 33 | if (value2 > 0) { 34 | data2.setBonusClaimBlocks(data2.getBonusClaimBlocks() - (int) value2); 35 | data1.setBonusClaimBlocks( 36 | data1.getBonusClaimBlocks() + (int) (value2 - ((value2 / 100) * taxPercent))); 37 | } 38 | inst.dataStore.savePlayerData(player1.getUniqueId(), data1); 39 | inst.dataStore.savePlayerData(player2.getUniqueId(), data2); 40 | } 41 | 42 | @Override 43 | public ItemStack _getIcon(Player player) { 44 | return ItemFactory.replaceInMeta( 45 | icon, 46 | "%AMOUNT%", 47 | decimalFormat.format(player.equals(player1) ? value1 : value2), 48 | "%INCREMENT%", 49 | decimalFormat.format(increment), 50 | "%PLAYERINCREMENT%", 51 | decimalFormat.format(player.equals(player1) ? increment1 : increment2)); 52 | } 53 | 54 | @Override 55 | public ItemStack _getTheirIcon(Player player) { 56 | return ItemFactory.replaceInMeta( 57 | theirIcon, "%AMOUNT%", decimalFormat.format(player.equals(player1) ? value1 : value2)); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/extras/LandsExtra.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.extras; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import com.trophonix.tradeplus.trade.Trade; 5 | import me.angeschossen.lands.api.integration.LandsIntegration; 6 | import me.angeschossen.lands.api.land.Land; 7 | import me.angeschossen.lands.api.player.LandPlayer; 8 | import org.bukkit.entity.Player; 9 | import org.bukkit.inventory.ItemStack; 10 | 11 | public class LandsExtra extends Extra { 12 | 13 | private LandsIntegration landsApi; 14 | private String selectedLand1, selectedLand2; 15 | 16 | public LandsExtra(Player player1, Player player2, TradePlus pl, Trade trade) { 17 | super("lands", player1, player2, pl, trade); 18 | this.landsApi = new LandsIntegration(pl, false); 19 | } 20 | 21 | private Land getSelectedLand(Player player) { 22 | LandPlayer landPlayer = landsApi.getLandPlayer(player.getUniqueId()); 23 | if (landPlayer == null) return null; 24 | 25 | Land land; 26 | if (player1.equals(player)) { 27 | land = landPlayer.getLand(selectedLand1); 28 | if (land == null) selectedLand1 = null; 29 | } else if (player2.equals(player)) { 30 | land = landPlayer.getLand(selectedLand2); 31 | if (land == null) selectedLand2 = null; 32 | } else return null; 33 | return land; 34 | } 35 | 36 | @Override 37 | public double getMax(Player player) { 38 | Land land = getSelectedLand(player); 39 | if (land == null) { 40 | return 0; 41 | } 42 | return land.getMaxChunks() - land.getSize(); 43 | } 44 | 45 | @Override 46 | public void onTradeEnd() { 47 | Land land1 = getSelectedLand(player1); 48 | Land land2 = getSelectedLand(player2); 49 | } 50 | 51 | @Override 52 | protected ItemStack _getIcon(Player player) { 53 | return null; 54 | } 55 | 56 | @Override 57 | protected ItemStack _getTheirIcon(Player player) { 58 | return null; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/extras/PlayerPointsExtra.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.extras; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import com.trophonix.tradeplus.trade.Trade; 5 | import com.trophonix.tradeplus.util.ItemFactory; 6 | import org.black_ixx.playerpoints.PlayerPoints; 7 | import org.black_ixx.playerpoints.PlayerPointsAPI; 8 | import org.bukkit.entity.Player; 9 | import org.bukkit.inventory.ItemStack; 10 | 11 | public class PlayerPointsExtra extends Extra { 12 | 13 | private final PlayerPointsAPI playerPointsAPI; 14 | 15 | public PlayerPointsExtra(Player player1, Player player2, TradePlus pl, Trade trade) { 16 | super("playerpoints", player1, player2, pl, trade); 17 | this.playerPointsAPI = 18 | new PlayerPointsAPI( 19 | (PlayerPoints) pl.getServer().getPluginManager().getPlugin("PlayerPoints")); 20 | } 21 | 22 | @Override 23 | public double getMax(Player player) { 24 | return playerPointsAPI.look(player.getUniqueId()); 25 | } 26 | 27 | @Override 28 | public void onTradeEnd() { 29 | if (value1 > 0) { 30 | playerPointsAPI.take(player1.getUniqueId(), (int) value1); 31 | playerPointsAPI.give(player2.getUniqueId(), (int) (value1 - ((value1 / 100) * taxPercent))); 32 | } 33 | if (value2 > 0) { 34 | playerPointsAPI.take(player2.getUniqueId(), (int) value2); 35 | playerPointsAPI.give(player1.getUniqueId(), (int) (value2 - ((value2 / 100) * taxPercent))); 36 | } 37 | } 38 | 39 | @Override 40 | public ItemStack _getIcon(Player player) { 41 | return ItemFactory.replaceInMeta( 42 | icon, 43 | "%AMOUNT%", 44 | decimalFormat.format(player.equals(player1) ? value1 : value2), 45 | "%INCREMENT%", 46 | decimalFormat.format(increment), 47 | "%PLAYERINCREMENT%", 48 | decimalFormat.format(player.equals(player1) ? increment1 : increment2)); 49 | } 50 | 51 | @Override 52 | public ItemStack _getTheirIcon(Player player) { 53 | return ItemFactory.replaceInMeta( 54 | theirIcon, "%AMOUNT%", decimalFormat.format(player.equals(player1) ? value1 : value2)); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/extras/TokenEnchantExtra.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.extras; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import com.trophonix.tradeplus.trade.Trade; 5 | import com.trophonix.tradeplus.util.ItemFactory; 6 | import com.vk2gpz.tokenenchant.api.TokenEnchantAPI; 7 | import org.bukkit.entity.Player; 8 | import org.bukkit.inventory.ItemStack; 9 | 10 | public class TokenEnchantExtra extends Extra { 11 | 12 | public TokenEnchantExtra(Player player1, Player player2, TradePlus pl, Trade trade) { 13 | super("tokenenchant", player1, player2, pl, trade); 14 | } 15 | 16 | @Override 17 | public double getMax(Player player) { 18 | return TokenEnchantAPI.getInstance().getTokens(player); 19 | } 20 | 21 | @Override 22 | public void onTradeEnd() { 23 | if (value1 > 0) { 24 | TokenEnchantAPI.getInstance().removeTokens(player1, value1); 25 | TokenEnchantAPI.getInstance().addTokens(player2, value1); 26 | } 27 | if (value2 > 0) { 28 | TokenEnchantAPI.getInstance().removeTokens(player2, value2); 29 | TokenEnchantAPI.getInstance().addTokens(player1, value2); 30 | } 31 | } 32 | 33 | @Override 34 | public ItemStack _getIcon(Player player) { 35 | return ItemFactory.replaceInMeta( 36 | icon, 37 | "%AMOUNT%", 38 | decimalFormat.format(player.equals(player1) ? value1 : value2), 39 | "%INCREMENT%", 40 | decimalFormat.format(increment), 41 | "%PLAYERINCREMENT%", 42 | decimalFormat.format(player.equals(player1) ? increment1 : increment2)); 43 | } 44 | 45 | @Override 46 | public ItemStack _getTheirIcon(Player player) { 47 | return ItemFactory.replaceInMeta( 48 | theirIcon, "%AMOUNT%", decimalFormat.format(player.equals(player1) ? value1 : value2)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/extras/TokenManagerExtra.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.extras; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import com.trophonix.tradeplus.trade.Trade; 5 | import com.trophonix.tradeplus.util.ItemFactory; 6 | import me.realized.tokenmanager.api.TokenManager; 7 | import org.bukkit.entity.Player; 8 | import org.bukkit.inventory.ItemStack; 9 | 10 | public class TokenManagerExtra extends Extra { 11 | 12 | private TokenManager api; 13 | 14 | public TokenManagerExtra(Player player1, Player player2, TradePlus pl, Trade trade) { 15 | super("tokenmanager", player1, player2, pl, trade); 16 | api = (TokenManager) pl.getServer().getPluginManager().getPlugin("TokenManager"); 17 | } 18 | 19 | @Override 20 | public double getMax(Player player) { 21 | return api.getTokens(player).orElse(0); 22 | } 23 | 24 | @Override 25 | public void onTradeEnd() { 26 | if (value1 > 0) { 27 | api.setTokens(player1, api.getTokens(player1).orElse((long) value1) - (long) value1); 28 | api.setTokens(player2, api.getTokens(player2).orElse(0L) + (long) value1); 29 | } 30 | if (value2 > 0) { 31 | api.setTokens(player2, api.getTokens(player2).orElse((long) value2) - (long) value2); 32 | api.setTokens(player1, api.getTokens(player1).orElse(0L) + (long) value2); 33 | } 34 | } 35 | 36 | @Override 37 | public ItemStack _getIcon(Player player) { 38 | return ItemFactory.replaceInMeta( 39 | icon, 40 | "%AMOUNT%", 41 | Long.toString((long) (player.equals(player1) ? value1 : value2)), 42 | "%INCREMENT%", 43 | Long.toString((long) increment), 44 | "%PLAYERINCREMENT%", 45 | Long.toString((long) (player.equals(player1) ? increment1 : increment2))); 46 | } 47 | 48 | @Override 49 | public ItemStack _getTheirIcon(Player player) { 50 | return ItemFactory.replaceInMeta( 51 | theirIcon, "%AMOUNT%", Long.toString((long) (player.equals(player1) ? value1 : value2))); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/extras/VotingPluginExtra.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.extras; 2 | 3 | import com.bencodez.votingplugin.user.UserManager; 4 | import com.bencodez.votingplugin.user.VotingPluginUser; 5 | import com.trophonix.tradeplus.TradePlus; 6 | import com.trophonix.tradeplus.trade.Trade; 7 | import com.trophonix.tradeplus.util.ItemFactory; 8 | import org.bukkit.entity.Player; 9 | import org.bukkit.inventory.ItemStack; 10 | 11 | public class VotingPluginExtra extends Extra { 12 | 13 | public VotingPluginExtra(Player player1, Player player2, TradePlus pl, Trade trade) { 14 | super("votingplugin", player1, player2, pl, trade); 15 | } 16 | 17 | @Override 18 | public double getMax(Player player) { 19 | VotingPluginUser user = UserManager.getInstance().getVotingPluginUser(player.getUniqueId()); 20 | return user.getPoints(); 21 | } 22 | 23 | @Override 24 | public void onTradeEnd() { 25 | VotingPluginUser user1 = UserManager.getInstance().getVotingPluginUser(player1); 26 | VotingPluginUser user2 = UserManager.getInstance().getVotingPluginUser(player2); 27 | if (value1 > 0) { 28 | user1.setPoints(user1.getPoints() - (int) value1); 29 | user2.setPoints(user2.getPoints() + (int) value1); 30 | } 31 | if (value2 > 0) { 32 | user2.setPoints(user2.getPoints() - (int) value2); 33 | user1.setPoints(user1.getPoints() + (int) value2); 34 | } 35 | } 36 | 37 | @Override 38 | protected ItemStack _getIcon(Player player) { 39 | return ItemFactory.replaceInMeta( 40 | icon, 41 | "%AMOUNT%", 42 | Integer.toString((int) (player.equals(player1) ? value1 : value2)), 43 | "%INCREMENT%", 44 | Integer.toString((int) increment), 45 | "%PLAYERINCREMENT%", 46 | Integer.toString((int) (player.equals(player1) ? increment1 : increment2))); 47 | } 48 | 49 | @Override 50 | protected ItemStack _getTheirIcon(Player player) { 51 | return ItemFactory.replaceInMeta( 52 | theirIcon, "%AMOUNT%", Integer.toString((int) (player.equals(player1) ? value1 : value2))); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/gui/MenuAction.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.gui; 2 | 3 | import com.trophonix.tradeplus.util.ItemFactory; 4 | import org.bukkit.configuration.ConfigurationSection; 5 | 6 | public enum MenuAction { 7 | ACCEPT, 8 | CANCEL, 9 | THEY_ACCEPT, 10 | THEY_CANCEL, 11 | 12 | MY_HEAD, 13 | THEIR_HEAD, 14 | 15 | MY_ITEM_SLOTS, 16 | THEIR_ITEM_SLOTS, 17 | 18 | EXTRA_ECONOMY, 19 | EXTRA_EXPERIENCE, 20 | EXTRA_GRIEF_PREVENTION, 21 | EXTRA_ENJIN_POINTS, 22 | EXTRA_PLAYER_POINTS, 23 | EXTRA_TOKEN_ENCHANT, 24 | EXTRA_TOKEN_MANAGER, 25 | EXTRA_VOTING_PLUGIN; 26 | 27 | private ItemFactory factory; 28 | private boolean enabled = true; 29 | 30 | public void load(ConfigurationSection section) { 31 | enabled = section.getBoolean("enabled", true); 32 | factory = 33 | new ItemFactory(section.getString("material")) 34 | .amount(section.getInt("amount", 1)) 35 | .customModelData(section.getInt("customModelData", 0)) 36 | .display(section.getString("display", "&4ERROR")) 37 | .lore(section.getStringList("lore")) 38 | .flag("HIDE_ATTRIBUTES"); 39 | } 40 | 41 | public boolean isEnabled() { 42 | return enabled; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/gui/MenuButton.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.gui; 2 | 3 | import com.trophonix.tradeplus.util.ItemFactory; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Getter; 6 | 7 | @Getter 8 | @AllArgsConstructor 9 | public class MenuButton { 10 | 11 | private MenuAction action; 12 | private ItemFactory icon; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/gui/MenuInventoryHolder.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.gui; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | import org.bukkit.inventory.Inventory; 7 | import org.bukkit.inventory.InventoryHolder; 8 | 9 | public class MenuInventoryHolder implements InventoryHolder { 10 | 11 | @Getter @Setter private Inventory current; 12 | 13 | @Override 14 | public Inventory getInventory() { 15 | return current; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/gui/TradeMenu.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.gui; 2 | 3 | import lombok.Getter; 4 | import org.bukkit.entity.Player; 5 | import org.bukkit.inventory.Inventory; 6 | 7 | import java.util.Map; 8 | 9 | @Getter 10 | public class TradeMenu { 11 | 12 | private Inventory inventory; 13 | private Player player; 14 | private TradeMenu partner; 15 | 16 | private Map buttons; 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/hooks/EssentialsHook.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.hooks; 2 | 3 | import com.earth2me.essentials.Essentials; 4 | import com.earth2me.essentials.User; 5 | import org.bukkit.Bukkit; 6 | import org.bukkit.entity.Player; 7 | 8 | public class EssentialsHook { 9 | 10 | public static boolean isVanished(Player player) { 11 | Essentials essentials = (Essentials) Bukkit.getPluginManager().getPlugin("Essentials"); 12 | User user = essentials.getUser(player); 13 | return user.isVanished(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/hooks/FactionsHook.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.hooks; 2 | 3 | import com.trophonix.tradeplus.hooks.factions.MassiveCraftFactionsHook; 4 | import org.bukkit.entity.Player; 5 | 6 | public class FactionsHook { 7 | 8 | private static boolean massiveCraft; 9 | 10 | static { 11 | try { 12 | Class.forName("com.massivecraft.factions.FPlayers"); 13 | massiveCraft = true; 14 | } catch (Exception ignored) { 15 | massiveCraft = false; 16 | } 17 | } 18 | 19 | public static boolean isPlayerInEnemyTerritory(Player player) { 20 | if (massiveCraft) { 21 | return MassiveCraftFactionsHook.isPlayerInEnemyTerritory(player); 22 | } 23 | return false; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/hooks/WorldGuardHook.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.hooks; 2 | 3 | import org.bukkit.Location; 4 | import org.bukkit.entity.Player; 5 | import org.codemc.worldguardwrapper.WorldGuardWrapper; 6 | import org.codemc.worldguardwrapper.flag.IWrappedFlag; 7 | 8 | public class WorldGuardHook { 9 | 10 | private static IWrappedFlag tradingFlag; 11 | 12 | public static void init() { 13 | tradingFlag = 14 | WorldGuardWrapper.getInstance() 15 | .registerFlag("trading", Boolean.TYPE, true) 16 | .orElse(WorldGuardWrapper.getInstance().getFlag("trading", Boolean.TYPE).orElse(null)); 17 | } 18 | 19 | public static boolean isTradingAllowed(Player player, Location location) { 20 | if (tradingFlag == null) return true; 21 | return WorldGuardWrapper.getInstance().queryFlag(player, location, tradingFlag).orElse(true); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/hooks/factions/MassiveCraftFactionsHook.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.hooks.factions; 2 | 3 | import com.massivecraft.factions.*; 4 | import org.bukkit.entity.Player; 5 | 6 | public class MassiveCraftFactionsHook { 7 | 8 | public static boolean isPlayerInEnemyTerritory(Player player) { 9 | FPlayer me = FPlayers.getInstance().getByPlayer(player); 10 | Faction faction = Board.getInstance().getFactionAt(new FLocation(player.getLocation())); 11 | return me.getRelationTo(faction).isEnemy(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/logging/Logs.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.logging; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.GsonBuilder; 5 | import com.google.gson.TypeAdapter; 6 | import com.google.gson.stream.JsonReader; 7 | import com.google.gson.stream.JsonWriter; 8 | import com.trophonix.tradeplus.TradePlus; 9 | 10 | import java.io.File; 11 | import java.io.FileWriter; 12 | import java.io.IOException; 13 | import java.text.DateFormat; 14 | import java.text.SimpleDateFormat; 15 | import java.util.*; 16 | import java.util.function.UnaryOperator; 17 | 18 | public class Logs implements List { 19 | 20 | private static final DateFormat folderNameFormat = 21 | new SimpleDateFormat("'session_'yyyy-MM-dd'_'HH:mm:ss"); 22 | 23 | private static final DateFormat fileNameFormat = 24 | new SimpleDateFormat("'{player1}-{player2}_'HH:mm:ss'.json'"); 25 | 26 | private TradePlus plugin; 27 | 28 | private File folder; 29 | private List logs = new ArrayList<>(); 30 | 31 | private Gson gson; 32 | 33 | public Logs(TradePlus plugin, File parent, String file) { 34 | this.plugin = plugin; 35 | if (!parent.exists()) { 36 | parent.mkdirs(); 37 | } 38 | folder = new File(parent, file); 39 | gson = 40 | new GsonBuilder() 41 | .registerTypeAdapter( 42 | UUID.class, 43 | new TypeAdapter() { 44 | @Override 45 | public void write(JsonWriter jsonWriter, UUID uuid) throws IOException { 46 | jsonWriter.value(uuid.toString()); 47 | } 48 | 49 | @Override 50 | public UUID read(JsonReader jsonReader) throws IOException { 51 | return UUID.fromString(jsonReader.nextString()); 52 | } 53 | }) 54 | .registerTypeAdapterFactory(new PostProcessingEnabler()) 55 | .registerTypeHierarchyAdapter(List.class, new NullEmptyListAdapter()) 56 | .registerTypeHierarchyAdapter(Number.class, new NullZeroNumberAdapter()) 57 | .setPrettyPrinting() 58 | .create(); 59 | // File[] contents; 60 | // if (folder.exists() && (contents = folder.listFiles()) != null) { 61 | // for (File child : contents) { 62 | // FileReader reader = new FileReader(child); 63 | // add(gson.fromJson(reader, TradeLog.class)); 64 | // reader.close(); 65 | // } 66 | // } 67 | } 68 | 69 | public Logs(TradePlus plugin, File parent) { 70 | this(plugin, parent, folderNameFormat.format(new Date())); 71 | } 72 | 73 | public void log(TradeLog log) { 74 | logs.add(log); 75 | } 76 | 77 | public void save() { 78 | try { 79 | if (!logs.isEmpty()) { 80 | if (!folder.exists()) folder.mkdirs(); 81 | Iterator iter = iterator(); 82 | while (iter.hasNext()) { 83 | TradeLog log = iter.next(); 84 | try { 85 | File file = 86 | new File( 87 | folder, 88 | fileNameFormat 89 | .format(log.getTime()) 90 | .replace("{player1}", log.getPlayer1().getLastKnownName()) 91 | .replace("{player2}", log.getPlayer2().getLastKnownName())); 92 | if (!file.exists()) file.createNewFile(); 93 | FileWriter writer = new FileWriter(file); 94 | gson.toJson(log, TradeLog.class, writer); 95 | writer.close(); 96 | } catch (Exception | Error ex) { 97 | plugin.getLogger().warning( 98 | "Failed to save trade log for trade between " 99 | + log.getPlayer1().getLastKnownName() 100 | + " and " 101 | + log.getPlayer2().getLastKnownName()); 102 | plugin.getLogger().warning(ex.getLocalizedMessage()); 103 | } 104 | iter.remove(); 105 | } 106 | } 107 | } catch (Exception | Error ex) { 108 | plugin.getLogger().warning("Failed to save trade logs."); 109 | logs.clear(); 110 | } 111 | } 112 | 113 | @Override 114 | public int size() { 115 | return logs.size(); 116 | } 117 | 118 | @Override 119 | public boolean isEmpty() { 120 | return logs.isEmpty(); 121 | } 122 | 123 | @Override 124 | public boolean contains(Object o) { 125 | return logs.contains(o); 126 | } 127 | 128 | @Override 129 | public Iterator iterator() { 130 | return logs.iterator(); 131 | } 132 | 133 | @Override 134 | public Object[] toArray() { 135 | return logs.toArray(); 136 | } 137 | 138 | @Override 139 | public T[] toArray(T[] a) { 140 | return logs.toArray(a); 141 | } 142 | 143 | @Override 144 | public boolean add(TradeLog tradeLog) { 145 | return logs.add(tradeLog); 146 | } 147 | 148 | @Override 149 | public boolean remove(Object o) { 150 | return logs.remove(o); 151 | } 152 | 153 | @Override 154 | public boolean containsAll(Collection c) { 155 | return logs.containsAll(c); 156 | } 157 | 158 | @Override 159 | public boolean addAll(Collection c) { 160 | return logs.addAll(c); 161 | } 162 | 163 | @Override 164 | public boolean addAll(int index, Collection c) { 165 | return logs.addAll(index, c); 166 | } 167 | 168 | @Override 169 | public boolean removeAll(Collection c) { 170 | return logs.removeAll(c); 171 | } 172 | 173 | @Override 174 | public boolean retainAll(Collection c) { 175 | return logs.retainAll(c); 176 | } 177 | 178 | @Override 179 | public void replaceAll(UnaryOperator operator) { 180 | logs.replaceAll(operator); 181 | } 182 | 183 | @Override 184 | public void sort(Comparator c) { 185 | logs.sort(c); 186 | } 187 | 188 | @Override 189 | public void clear() { 190 | logs.clear(); 191 | } 192 | 193 | @Override 194 | public boolean equals(Object o) { 195 | if (o == null || getClass() != o.getClass()) { 196 | return false; 197 | } 198 | return logs.equals(o); 199 | } 200 | 201 | @Override 202 | public int hashCode() { 203 | return logs.hashCode(); 204 | } 205 | 206 | @Override 207 | public TradeLog get(int index) { 208 | return logs.get(index); 209 | } 210 | 211 | @Override 212 | public TradeLog set(int index, TradeLog element) { 213 | return logs.set(index, element); 214 | } 215 | 216 | @Override 217 | public void add(int index, TradeLog element) { 218 | logs.add(index, element); 219 | } 220 | 221 | @Override 222 | public TradeLog remove(int index) { 223 | return logs.remove(index); 224 | } 225 | 226 | @Override 227 | public int indexOf(Object o) { 228 | return logs.indexOf(o); 229 | } 230 | 231 | @Override 232 | public int lastIndexOf(Object o) { 233 | return logs.lastIndexOf(o); 234 | } 235 | 236 | @Override 237 | public ListIterator listIterator() { 238 | return logs.listIterator(); 239 | } 240 | 241 | @Override 242 | public ListIterator listIterator(int index) { 243 | return logs.listIterator(index); 244 | } 245 | 246 | @Override 247 | public List subList(int fromIndex, int toIndex) { 248 | return logs.subList(fromIndex, toIndex); 249 | } 250 | 251 | @Override 252 | public Spliterator spliterator() { 253 | return logs.spliterator(); 254 | } 255 | } 256 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/logging/NullEmptyListAdapter.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.logging; 2 | 3 | import com.google.gson.*; 4 | 5 | import java.lang.reflect.Type; 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | class NullEmptyListAdapter implements JsonSerializer>, JsonDeserializer> { 10 | 11 | @Override 12 | public JsonElement serialize(List src, Type type, JsonSerializationContext context) { 13 | if (src == null || src.isEmpty()) return null; 14 | JsonArray array = new JsonArray(); 15 | for (Object obj : src) { 16 | array.add(context.serialize(obj)); 17 | } 18 | return array; 19 | } 20 | 21 | @Override 22 | public List deserialize(JsonElement src, Type type, JsonDeserializationContext context) 23 | throws JsonParseException { 24 | List list = new ArrayList<>(); 25 | if (src == null) return list; 26 | if (!(src instanceof JsonArray)) throw new JsonParseException("Invalid list"); 27 | for (JsonElement elem : (JsonArray) src) { 28 | list.add(context.deserialize(elem, type)); 29 | } 30 | return list; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/logging/NullZeroNumberAdapter.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.logging; 2 | 3 | import com.google.gson.*; 4 | 5 | import java.lang.reflect.Type; 6 | 7 | class NullZeroNumberAdapter implements JsonSerializer, JsonDeserializer { 8 | 9 | @Override 10 | public JsonElement serialize(Number number, Type type, JsonSerializationContext context) { 11 | return number.doubleValue() != 0 ? new JsonPrimitive(number) : null; 12 | } 13 | 14 | @Override 15 | public Number deserialize(JsonElement elem, Type type, JsonDeserializationContext context) 16 | throws JsonParseException { 17 | if (elem == null) return 0; 18 | return elem.getAsJsonPrimitive().getAsNumber(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/logging/PostProcessingEnabler.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.logging; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.TypeAdapter; 5 | import com.google.gson.TypeAdapterFactory; 6 | import com.google.gson.reflect.TypeToken; 7 | import com.google.gson.stream.JsonReader; 8 | import com.google.gson.stream.JsonWriter; 9 | 10 | import java.io.IOException; 11 | 12 | class PostProcessingEnabler implements TypeAdapterFactory { 13 | 14 | @Override 15 | public TypeAdapter create(Gson gson, TypeToken type) { 16 | TypeAdapter delegate = gson.getDelegateAdapter(this, type); 17 | return new TypeAdapter() { 18 | @Override 19 | public void write(JsonWriter writer, T obj) throws IOException { 20 | delegate.write(writer, obj); 21 | } 22 | 23 | @Override 24 | public T read(JsonReader reader) throws IOException { 25 | T obj = delegate.read(reader); 26 | if (obj instanceof PostProcessor) { 27 | ((PostProcessor) obj).doPostProcessing(); 28 | } 29 | return obj; 30 | } 31 | }; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/logging/PostProcessor.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.logging; 2 | 3 | interface PostProcessor { 4 | 5 | void doPostProcessing(); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/logging/TradeLog.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.logging; 2 | 3 | import com.trophonix.tradeplus.util.ItemFactory; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Getter; 6 | import org.bukkit.Bukkit; 7 | import org.bukkit.OfflinePlayer; 8 | 9 | import java.util.Date; 10 | import java.util.List; 11 | import java.util.UUID; 12 | 13 | @Getter 14 | public class TradeLog implements PostProcessor { 15 | 16 | private Trader player1, player2; 17 | private List player1Items, player2Items; 18 | private List player1ExtraOffers, player2ExtraOffers; 19 | private Date time; 20 | 21 | public TradeLog() {} 22 | 23 | public TradeLog( 24 | OfflinePlayer player1, 25 | OfflinePlayer player2, 26 | List player1Items, 27 | List player2Items, 28 | List player1ExtraOffers, 29 | List player2ExtraOffers) { 30 | this.player1 = new Trader(player1.getUniqueId(), player1.getName()); 31 | this.player2 = new Trader(player2.getUniqueId(), player2.getName()); 32 | player1Items.sort((o1, o2) -> Integer.compare(o2.getAmount(), o1.getAmount())); 33 | this.player1Items = player1Items; 34 | player2Items.sort((o1, o2) -> Integer.compare(o2.getAmount(), o1.getAmount())); 35 | this.player2Items = player2Items; 36 | this.player1ExtraOffers = player1ExtraOffers; 37 | this.player2ExtraOffers = player2ExtraOffers; 38 | this.time = new Date(); 39 | } 40 | 41 | @Override 42 | public void doPostProcessing() { 43 | player1.updateName(); 44 | player2.updateName(); 45 | } 46 | 47 | @Getter 48 | @AllArgsConstructor 49 | public static class Trader { 50 | 51 | private UUID uniqueId; 52 | private String lastKnownName; 53 | 54 | void updateName() { 55 | OfflinePlayer op = Bukkit.getOfflinePlayer(uniqueId); 56 | if (op.getName() == null) lastKnownName = "unknown"; 57 | else lastKnownName = op.getName(); 58 | } 59 | } 60 | 61 | @Getter 62 | public static class ExtraOffer { 63 | 64 | private String id; 65 | private double value; 66 | 67 | public ExtraOffer() {} 68 | 69 | public ExtraOffer(String id, double value) { 70 | this.id = id; 71 | this.value = value; 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/trade/EntityPickupItemEventListener.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.trade; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import org.bukkit.entity.Player; 5 | import org.bukkit.event.EventHandler; 6 | import org.bukkit.event.Listener; 7 | import org.bukkit.event.entity.EntityPickupItemEvent; 8 | 9 | public class EntityPickupItemEventListener implements Listener { 10 | 11 | private final Trade trade; 12 | 13 | public EntityPickupItemEventListener(Trade trade) { 14 | this.trade = trade; 15 | } 16 | 17 | @EventHandler 18 | public void onPickup(EntityPickupItemEvent event) { 19 | if (trade.isCancelled()) return; 20 | if (!(event.getEntity() instanceof Player)) return; 21 | Player player = (Player) event.getEntity(); 22 | if (player.equals(trade.getPlayer1()) || player.equals(trade.getPlayer2())) { 23 | event.setCancelled(true); 24 | } 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/trade/InteractListener.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.trade; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import com.trophonix.tradeplus.util.PlayerUtil; 5 | import org.bukkit.Bukkit; 6 | import org.bukkit.entity.Player; 7 | import org.bukkit.event.EventHandler; 8 | import org.bukkit.event.Listener; 9 | import org.bukkit.event.entity.EntityDamageByEntityEvent; 10 | import org.bukkit.event.player.PlayerCommandPreprocessEvent; 11 | import org.bukkit.event.player.PlayerInteractAtEntityEvent; 12 | import org.bukkit.event.player.PlayerQuitEvent; 13 | 14 | import java.util.HashMap; 15 | import java.util.Map; 16 | import java.util.UUID; 17 | 18 | public class InteractListener implements Listener { 19 | 20 | private final TradePlus pl; 21 | 22 | private Map lastTrigger = new HashMap<>(); 23 | 24 | public InteractListener(TradePlus pl) { 25 | this.pl = pl; 26 | } 27 | 28 | @EventHandler 29 | public void onInteract(PlayerInteractAtEntityEvent event) { 30 | if (event.getRightClicked() instanceof Player && pl.getTradeConfig().isAllowShiftRightClick()) { 31 | Long last = lastTrigger.get(event.getPlayer().getUniqueId()); 32 | if (last != null && System.currentTimeMillis() < last + 5000L) return; 33 | Player player = event.getPlayer(); 34 | Player interacted = (Player) event.getRightClicked(); 35 | if (PlayerUtil.isVanished(interacted)) { 36 | return; 37 | } 38 | String action = pl.getTradeConfig().getAction(); 39 | if ((action.contains("sneak") || action.contains("crouch") || action.contains("shift")) 40 | && !player.isSneaking()) return; 41 | if (action.contains("right")) { 42 | event.setCancelled(true); 43 | event.getPlayer().performCommand("trade " + interacted.getName()); 44 | lastTrigger.put(event.getPlayer().getUniqueId(), System.currentTimeMillis()); 45 | } 46 | } 47 | } 48 | 49 | @EventHandler(ignoreCancelled = true) 50 | public void onDamage(EntityDamageByEntityEvent event) { 51 | if (event.getDamager() instanceof Player && event.getEntity() instanceof Player) { 52 | Long last = lastTrigger.get(event.getEntity().getUniqueId()); 53 | if (last != null && System.currentTimeMillis() < last + 5000L) return; 54 | Player player = (Player) event.getDamager(); 55 | Player interacted = (Player) event.getEntity(); 56 | if (PlayerUtil.isVanished(interacted)) { 57 | return; 58 | } 59 | String action = pl.getTradeConfig().getAction(); 60 | if ((action.contains("sneak") || action.contains("crouch") || action.contains("shift")) 61 | && !player.isSneaking()) return; 62 | if (action.contains("left")) { 63 | event.setCancelled(true); 64 | player.performCommand("trade " + interacted.getName()); 65 | lastTrigger.put(player.getUniqueId(), System.currentTimeMillis()); 66 | } 67 | } 68 | } 69 | 70 | @EventHandler 71 | public void onQuit(PlayerQuitEvent event) { 72 | lastTrigger.remove(event.getPlayer().getUniqueId()); 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/trade/Trade.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.trade; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import com.trophonix.tradeplus.events.TradeCompleteEvent; 5 | import com.trophonix.tradeplus.extras.*; 6 | import com.trophonix.tradeplus.logging.TradeLog; 7 | import com.trophonix.tradeplus.util.InvUtils; 8 | import com.trophonix.tradeplus.util.ItemFactory; 9 | import com.trophonix.tradeplus.util.MsgUtils; 10 | import com.trophonix.tradeplus.util.Sounds; 11 | import lombok.Getter; 12 | import org.bukkit.Bukkit; 13 | import org.bukkit.ChatColor; 14 | import org.bukkit.Location; 15 | import org.bukkit.Material; 16 | import org.bukkit.entity.Player; 17 | import org.bukkit.event.EventHandler; 18 | import org.bukkit.event.HandlerList; 19 | import org.bukkit.event.Listener; 20 | import org.bukkit.event.inventory.*; 21 | import org.bukkit.event.player.*; 22 | import org.bukkit.event.server.PluginDisableEvent; 23 | import org.bukkit.inventory.Inventory; 24 | import org.bukkit.inventory.ItemStack; 25 | import org.bukkit.scheduler.BukkitRunnable; 26 | import org.bukkit.scheduler.BukkitTask; 27 | 28 | import java.util.ArrayList; 29 | import java.util.HashMap; 30 | import java.util.List; 31 | import java.util.Map; 32 | import java.util.regex.Pattern; 33 | import java.util.regex.PatternSyntaxException; 34 | import java.util.stream.Collectors; 35 | 36 | public class Trade implements Listener { 37 | 38 | @Getter public final Player player1, player2; 39 | private final TradePlus pl = TradePlus.getPlugin(TradePlus.class); 40 | private List mySlots, theirSlots, myExtraSlots, theirExtraSlots; 41 | private final List extras = new ArrayList<>(); 42 | private final Map placedExtras = new HashMap<>(); 43 | private final long startTime = System.currentTimeMillis(); 44 | private boolean cancelOnClose1 = true, cancelOnClose2 = true; 45 | @Getter private Inventory spectatorInv, inv1, inv2; 46 | private boolean accept1, accept2; 47 | private Location location1, location2; 48 | private ItemStack[] accepted1, accepted2; 49 | private boolean forced = false; 50 | private BukkitTask task; 51 | @Getter private boolean cancelled; 52 | private EntityPickupItemEventListener entityPickupListener; 53 | 54 | public Trade(Player p1, Player p2) { 55 | player1 = p1; 56 | player2 = p2; 57 | location1 = p1.getLocation(); 58 | location2 = p2.getLocation(); 59 | pl.getTaskFactory() 60 | .newChain() 61 | .sync( 62 | () -> { 63 | inv1 = InvUtils.getTradeInventory(player1, player2); 64 | inv2 = InvUtils.getTradeInventory(player2, player1); 65 | spectatorInv = InvUtils.getSpectatorInventory(player1, player2); 66 | }) 67 | .async( 68 | () -> { 69 | if (pl.getTradeConfig().isSpectateEnabled() 70 | && pl.getTradeConfig().isSpectateBroadcast()) 71 | Bukkit.getOnlinePlayers() 72 | .forEach( 73 | p -> { 74 | if (p.hasPermission("tradeplus.admin") 75 | && !p.hasPermission("tradeplus.admin.silent")) { 76 | pl.getTradeConfig() 77 | .getSpectateMessage() 78 | .setOnClick( 79 | "/tradeplus spectate " 80 | + player1.getName() 81 | + " " 82 | + player2.getName()) 83 | .send( 84 | p, 85 | "%PLAYER1%", 86 | player1.getName(), 87 | "%PLAYER2%", 88 | player2.getName()); 89 | } 90 | }); 91 | if (pl.getConfig().getBoolean("extras.economy.enabled", true) 92 | && pl.getServer().getPluginManager().isPluginEnabled("Vault")) { 93 | try { 94 | if (pl.getServer() 95 | .getServicesManager() 96 | .getRegistration(Class.forName("net.milkbowl.vault.economy.Economy")) 97 | != null) { 98 | extras.add(new EconomyExtra(player1, player2, pl, this)); 99 | } 100 | } catch (Exception ignored) { 101 | } 102 | } 103 | if (pl.getConfig().getBoolean("extras.experience.enabled", true)) { 104 | extras.add(new ExperienceExtra(player1, player2, pl, this)); 105 | } 106 | if (pl.getConfig().getBoolean("extras.playerpoints.enabled", true) 107 | && pl.getServer().getPluginManager().isPluginEnabled("PlayerPoints")) { 108 | extras.add(new PlayerPointsExtra(player1, player2, pl, this)); 109 | } 110 | if (pl.getConfig().getBoolean("extras.griefprevention.enabled", true) 111 | && pl.getServer().getPluginManager().isPluginEnabled("GriefPrevention")) { 112 | extras.add(new GriefPreventionExtra(player1, player2, pl, this)); 113 | } 114 | if (pl.getConfig().getBoolean("extras.enjinpoints.enabled", false) 115 | && pl.getServer().getPluginManager().isPluginEnabled("EnjinMinecraftPlugin")) { 116 | extras.add(new EnjinPointsExtra(player1, player2, pl, this)); 117 | } 118 | if (pl.getConfig().getBoolean("extras.tokenenchant.enabled", true) 119 | && pl.getServer().getPluginManager().isPluginEnabled("TokenEnchant")) { 120 | extras.add(new TokenEnchantExtra(player1, player2, pl, this)); 121 | } 122 | if (pl.getConfig().getBoolean("extras.tokenmanager.enabled", true) 123 | && pl.getServer().getPluginManager().isPluginEnabled("TokenManager")) { 124 | extras.add(new TokenManagerExtra(player1, player2, pl, this)); 125 | } 126 | if (pl.getConfig().getBoolean("extras.beasttoken.enabled", true) 127 | && pl.getServer().getPluginManager().isPluginEnabled("BeastToken")) { 128 | extras.add(new BeastTokensExtra(player1, player2, pl, this)); 129 | } 130 | if (pl.getConfig().getBoolean("extras.votingplugin.enabled", false) 131 | && pl.getServer().getPluginManager().isPluginEnabled("VotingPlugin")) { 132 | extras.add(new VotingPluginExtra(player1, player2, pl, this)); 133 | } 134 | }) 135 | .sync( 136 | () -> { 137 | Bukkit.getServer().getPluginManager().registerEvents(this, pl); 138 | try { 139 | Class.forName("org.bukkit.event.entity.EntityPickupItemEvent"); 140 | entityPickupListener = new EntityPickupItemEventListener(this); 141 | Bukkit.getServer().getPluginManager().registerEvents(entityPickupListener, pl); 142 | } catch (ClassNotFoundException ignored) { 143 | } 144 | 145 | this.mySlots = pl.getTradeConfig().getMySlots(); 146 | this.theirSlots = pl.getTradeConfig().getTheirSlots(); 147 | this.myExtraSlots = pl.getTradeConfig().getMyExtraSlots(); 148 | this.theirExtraSlots = pl.getTradeConfig().getTheirExtraSlots(); 149 | 150 | for (Extra extra : extras) { 151 | extra.init(); 152 | } 153 | updateExtras(); 154 | 155 | updateAcceptance(); 156 | }) 157 | .sync( 158 | () -> { 159 | pl.ongoingTrades.add(this); 160 | player1.openInventory(inv1); 161 | player2.openInventory(inv2); 162 | }) 163 | .execute(); 164 | } 165 | 166 | private static List combine(ItemStack[] items) { 167 | List result = new ArrayList<>(); 168 | for (int i = 0; i < items.length; i++) { 169 | ItemStack item = items[i]; 170 | if (item == null) continue; 171 | item = item.clone(); 172 | for (int j = i + 1; j < items.length; j++) { 173 | ItemStack dupe = items[j]; 174 | if (item.isSimilar(dupe)) { 175 | item.setAmount(item.getAmount() + dupe.getAmount()); 176 | items[j] = null; 177 | } 178 | } 179 | result.add(item); 180 | } 181 | return result; 182 | } 183 | 184 | @EventHandler 185 | public void onDrag(InventoryDragEvent event) { 186 | if (!(event.getWhoClicked() instanceof Player)) { 187 | return; 188 | } 189 | Player player = (Player) event.getWhoClicked(); 190 | Inventory inv = event.getInventory(); 191 | if (inv1.getViewers().contains(player) || inv2.getViewers().contains(player)) { 192 | if (accept1 && accept2) { 193 | event.setCancelled(true); 194 | return; 195 | } 196 | 197 | for (int slot : event.getInventorySlots()) { 198 | if (!mySlots.contains(slot)) { 199 | event.setCancelled(true); 200 | return; 201 | } 202 | } 203 | if (event.getInventorySlots().size() > 0) { 204 | if (pl.getTradeConfig().isPreventChangeOnAccept() 205 | && ((player.equals(player1) && accept1) || (player.equals(player2) && accept2))) { 206 | event.setCancelled(true); 207 | return; 208 | } 209 | Bukkit.getScheduler().runTaskLater(pl, this::updateInventories, 1L); 210 | click(); 211 | } 212 | } else if (inv.equals(spectatorInv)) { 213 | event.setCancelled(true); 214 | } 215 | } 216 | 217 | @EventHandler 218 | public void onClick(InventoryClickEvent event) { 219 | if (!(event.getWhoClicked() instanceof Player)) { 220 | return; 221 | } 222 | 223 | Player player = (Player) event.getWhoClicked(); 224 | Inventory inv = event.getClickedInventory(); 225 | if (inv == null) return; 226 | 227 | ClickType click = event.getClick(); 228 | 229 | if (spectatorInv.equals(inv)) { 230 | event.setCancelled(true); 231 | return; 232 | } 233 | 234 | if (!(inv1.getViewers().contains(player) || inv2.getViewers().contains(player))) { 235 | return; 236 | } 237 | 238 | int slot = event.getSlot(); 239 | 240 | if (event.getRawSlot() < event.getView().getTopInventory().getSize()) { 241 | if (click.equals(ClickType.DOUBLE_CLICK)) { 242 | event.setCancelled(true); 243 | return; 244 | } 245 | 246 | if (!mySlots.contains(slot) && 247 | (click.equals(ClickType.SHIFT_LEFT) 248 | || click.equals(ClickType.SHIFT_RIGHT))) { 249 | event.setCancelled(true); 250 | } 251 | 252 | // don't let players interact 253 | // with a cancelled trade window 254 | if (cancelled) { 255 | event.setCancelled(true); 256 | return; 257 | } 258 | 259 | // if it's in the left side, 260 | // the event will affect the 261 | // player's trade 262 | if (slot != pl.getTradeConfig().getAcceptSlot() 263 | && mySlots.contains(slot) 264 | && getExtra(slot) == null) { 265 | if (accept1 && accept2) { 266 | event.setCancelled(true); 267 | return; 268 | } 269 | 270 | if (pl.getTradeConfig().isPreventChangeOnAccept() 271 | && ((player.equals(player1) && accept1) || (player.equals(player2) && accept2))) { 272 | event.setCancelled(true); 273 | event.setResult(InventoryClickEvent.Result.DENY); 274 | return; 275 | } 276 | if (pl.getTradeConfig().isAntiscamCancelOnChange()) { 277 | accept1 = false; 278 | accept2 = false; 279 | updateAcceptance(); 280 | } 281 | Bukkit.getScheduler().runTaskLater(pl, this::updateInventories, 1L); 282 | click(); 283 | } else { 284 | event.setCancelled(true); 285 | event.setResult(InventoryClickEvent.Result.DENY); 286 | ItemStack item = inv.getItem(slot); 287 | if (item != null) { 288 | // toggle button 289 | if (slot == pl.getTradeConfig().getAcceptSlot()) { 290 | if (!forced) { 291 | ItemStack cursor = player.getItemOnCursor(); 292 | if (cursor == null || cursor.getType() == Material.AIR) { 293 | if (player.equals(player1)) { 294 | accept1 = !accept1; 295 | } else { 296 | accept2 = !accept2; 297 | } 298 | } 299 | 300 | updateAcceptance(); 301 | checkAcceptance(); 302 | } 303 | // force trade button 304 | } else if (slot == 49 && player.hasPermission("tradeplus.admin")) { 305 | if (forced) { 306 | forced = false; 307 | accept1 = false; 308 | accept2 = false; 309 | updateAcceptance(); 310 | checkAcceptance(); 311 | } else { 312 | forced = true; 313 | accept1 = true; 314 | accept2 = true; 315 | updateAcceptance(); 316 | checkAcceptance(); 317 | } 318 | // extras, or cancel 319 | } else { 320 | Extra extra = getExtra(slot); 321 | if (extra != null) { 322 | if (pl.getTradeConfig().isPreventChangeOnAccept() 323 | && ((player.equals(player1) && accept1) || (player.equals(player2) && accept2))) { 324 | return; 325 | } 326 | if (task != null) { 327 | return; 328 | } 329 | extra.onClick(player, event.getClick()); 330 | updateExtras(); 331 | click(); 332 | } 333 | } 334 | } 335 | } 336 | // if they click in the bottom 337 | } else if (player.getInventory().equals(inv)) { 338 | if (cancelled) { 339 | event.setCancelled(true); 340 | return; 341 | } 342 | Inventory open = player.getOpenInventory().getTopInventory(); 343 | // Using my own double click 344 | // code so items only collect 345 | // from the left side 346 | if (click.equals(ClickType.DOUBLE_CLICK)) { 347 | event.setCancelled(true); 348 | if (accept1 && accept2) { 349 | return; 350 | } 351 | 352 | ItemStack item = event.getCurrentItem(); 353 | ItemStack cursor = player.getItemOnCursor(); 354 | if ((item == null || item.getType().equals(Material.AIR)) 355 | && !cursor.getType().equals(Material.AIR)) { 356 | for (int j : mySlots) { 357 | if (j == pl.getTradeConfig().getAcceptSlot() || getExtra(j) != null) continue; 358 | ItemStack i = open.getItem(j); 359 | if (i != null && cursor.isSimilar(i)) { 360 | int amount = cursor.getAmount() + i.getAmount(); 361 | if (amount <= cursor.getMaxStackSize()) { 362 | open.setItem(j, null); 363 | cursor.setAmount(amount); 364 | } else { 365 | int remaining = amount - cursor.getMaxStackSize(); 366 | i.setAmount(remaining); 367 | cursor.setAmount(cursor.getMaxStackSize()); 368 | break; 369 | } 370 | } 371 | } 372 | } 373 | 374 | if (pl.getTradeConfig().isAntiscamCancelOnChange()) { 375 | accept1 = false; 376 | accept2 = false; 377 | updateAcceptance(); 378 | } 379 | 380 | // Using my own shift click 381 | // code so items only go in 382 | // the left side 383 | } else if (click.name().contains("SHIFT")) { 384 | event.setCancelled(true); 385 | if (isBlocked(event.getCurrentItem())) { 386 | Sounds.villagerHit(player, 1); 387 | return; 388 | } 389 | 390 | if (accept1 && accept2) { 391 | return; 392 | } 393 | if (pl.getTradeConfig().isAntiscamCancelOnChange()) { 394 | accept1 = false; 395 | accept2 = false; 396 | updateAcceptance(); 397 | } 398 | ItemStack current = event.getCurrentItem(); 399 | if (current != null) { 400 | int amount = click.name().contains("LEFT") ? current.getMaxStackSize() : 1; 401 | player 402 | .getInventory() 403 | .setItem( 404 | event.getSlot(), 405 | putOnLeft(player.equals(player1) ? inv1 : inv2, current, amount)); 406 | click(); 407 | } 408 | } 409 | // don't allow changing 410 | // after cancellation 411 | if (pl.getTradeConfig().isPreventChangeOnAccept() 412 | && ((player.equals(player1) && accept1) || (player.equals(player2) && accept2))) { 413 | event.setCancelled(true); 414 | return; 415 | } 416 | // cancel on change 417 | //if (pl.getTradeConfig().isAntiscamCancelOnChange()) { 418 | accept1 = false; 419 | accept2 = false; 420 | updateAcceptance(); 421 | //} 422 | Bukkit.getScheduler().runTaskLater(pl, this::updateInventories, 1L); 423 | } 424 | } 425 | 426 | // plays a click sound effect to all viewers 427 | private void click() { 428 | if (pl.getTradeConfig().isSoundEffectsEnabled() && pl.getTradeConfig().isSoundOnChange()) { 429 | Sounds.click(player1, 2); 430 | Sounds.click(player2, 2); 431 | spectatorInv.getViewers().stream() 432 | .filter(Player.class::isInstance) 433 | .forEach(p -> Sounds.click((Player) p, 2)); 434 | } 435 | } 436 | 437 | @EventHandler 438 | public void onQuit(PlayerQuitEvent event){ 439 | if (!(event.getPlayer().equals(player1) || event.getPlayer().equals(player2))) return; 440 | if (cancelled) return; 441 | cancelled = true; 442 | Player otherPlayer = event.getPlayer().equals(player1) ? player2 : player1; 443 | Inventory otherInv = event.getPlayer().equals(player1) ? inv2 : inv1; 444 | Inventory inv = event.getPlayer().equals(player1) ? inv1 : inv2; 445 | giveItemsOnLeft(inv, event.getPlayer()); 446 | giveItemsOnLeft(otherInv, otherPlayer); 447 | pl.getTradeConfig().getCancelledMessage().send(otherPlayer, "%PLAYER%", event.getPlayer().getName()); 448 | if (otherInv.getViewers().contains(otherPlayer)) { 449 | otherPlayer.closeInventory(); 450 | } 451 | } 452 | 453 | @EventHandler 454 | public void onClose(InventoryCloseEvent event) { 455 | Inventory closed = event.getInventory(); 456 | if (closed == null || closed.getSize() < 54) { 457 | return; 458 | } 459 | 460 | // I keep having issues with 461 | // identifying inventories so 462 | // trying to make sure it catches 463 | // all events 464 | if (closed.equals(inv1) 465 | || closed.equals(inv2) 466 | || inv1.getViewers().contains(event.getPlayer()) 467 | || inv2.getViewers().contains(event.getPlayer())) { 468 | if ((event.getPlayer().equals(player1) && !cancelOnClose1) 469 | || (event.getPlayer().equals(player2) && !cancelOnClose2)) { 470 | return; 471 | } 472 | 473 | giveOnCursor((Player) event.getPlayer()); 474 | 475 | // Return items to them 476 | giveItemsOnLeft(closed, (Player) event.getPlayer()); 477 | 478 | Bukkit.getScheduler() 479 | .runTaskLater( 480 | pl, 481 | () -> { 482 | if (inv1.getViewers().isEmpty() 483 | && inv2.getViewers().isEmpty() 484 | && spectatorInv.getViewers().isEmpty()) { 485 | HandlerList.unregisterAll(this); 486 | if (entityPickupListener != null) 487 | HandlerList.unregisterAll(entityPickupListener); 488 | } 489 | }, 490 | 1L); 491 | 492 | if (cancelled) { 493 | return; 494 | } 495 | 496 | cancel(false); 497 | 498 | pl.ongoingTrades.remove(this); 499 | if (task != null) { 500 | task.cancel(); 501 | task = null; 502 | } 503 | 504 | pl.getTradeConfig().getCancelledMessage().send(player1, "%PLAYER%", player2.getName()); 505 | pl.getTradeConfig().getCancelledMessage().send(player2, "%PLAYER%", player1.getName()); 506 | } else if (closed.equals(spectatorInv) 507 | || spectatorInv.getViewers().contains(event.getPlayer())) { 508 | Bukkit.getScheduler() 509 | .runTaskLater( 510 | pl, 511 | () -> { 512 | if (inv1.getViewers().isEmpty() 513 | && inv2.getViewers().isEmpty() 514 | && spectatorInv.getViewers().isEmpty()) { 515 | HandlerList.unregisterAll(this); 516 | if (entityPickupListener != null) 517 | HandlerList.unregisterAll(entityPickupListener); 518 | } 519 | }, 520 | 1L); 521 | } 522 | } 523 | 524 | @EventHandler 525 | public void onMove(PlayerMoveEvent event) { 526 | if (cancelled || event.getTo() == null) return; 527 | Player player = event.getPlayer(); 528 | if (player.equals(player1) || player.equals(player2)) { 529 | if (event.getFrom().distanceSquared(event.getTo()) < 0.01) return; 530 | if (System.currentTimeMillis() < startTime + 1000) { 531 | return; 532 | } 533 | event.setCancelled(true); 534 | } 535 | } 536 | 537 | @EventHandler 538 | public void onInventoryPickupEvent(InventoryPickupItemEvent event) { 539 | if (cancelled) return; 540 | if (accept1 && accept2 && (event.getInventory() == inv1 || event.getInventory() == inv2)) { 541 | event.setCancelled(true); 542 | } 543 | } 544 | 545 | @EventHandler 546 | public void onInventoryInteract(InventoryInteractEvent event) { 547 | if ((event.getInventory() == inv1 || event.getInventory() == inv2)) { 548 | if (accept1 && accept2) { 549 | event.setCancelled(true); 550 | return; 551 | } 552 | if (event.getWhoClicked() == player1 || event.getWhoClicked() == player2) { 553 | event.setCancelled(true); 554 | } 555 | } 556 | } 557 | 558 | @EventHandler 559 | public void onDropItem(PlayerDropItemEvent event) { 560 | if (cancelled) return; 561 | if (player1.equals(event.getPlayer()) || player2.equals(event.getPlayer())) { 562 | event.setCancelled(true); 563 | if (accept1 && accept2) { 564 | giveOnCursor(event.getPlayer()); 565 | } 566 | } 567 | } 568 | 569 | private void giveOnCursor(Player player) { 570 | if (player.getItemOnCursor().getType() != Material.AIR) { 571 | player 572 | .getInventory() 573 | .addItem(player.getItemOnCursor()) 574 | .forEach((i, j) -> player.getWorld().dropItemNaturally(player.getLocation(), j)); 575 | player.setItemOnCursor(null); 576 | } 577 | } 578 | 579 | @EventHandler 580 | public void onDisable(PluginDisableEvent event) { 581 | if (event.getPlugin().getName().equalsIgnoreCase("TradePlus")) { 582 | player1.closeInventory(); 583 | } 584 | } 585 | 586 | @EventHandler 587 | public void onInteract(PlayerInteractAtEntityEvent event) { 588 | if (event.getPlayer() == player1 || event.getPlayer() == player2) { 589 | event.setCancelled(true); 590 | } 591 | } 592 | 593 | private void giveItemsOnLeft(Inventory inv, Player player) { 594 | List dropoff = new ArrayList<>(); 595 | for (int slot : mySlots) { 596 | if (slot == pl.getTradeConfig().getAcceptSlot() || getExtra(slot) != null) continue; 597 | ItemStack item = inv.getItem(slot); 598 | if (item == null || item.getType() == Material.AIR) continue; 599 | dropoff.addAll(player.getInventory().addItem(item).values()); 600 | inv.setItem(slot, null); 601 | } 602 | if (!dropoff.isEmpty()) { 603 | int size = dropoff.size() / 9; 604 | if (dropoff.size() % 9 > 0) { 605 | size++; 606 | } 607 | size *= 9; 608 | Inventory excessChest = 609 | Bukkit.createInventory(null, size, pl.getTradeConfig().getExcessTitle()); 610 | dropoff.forEach(excessChest::addItem); 611 | pl.getExcessChests().add(excessChest); 612 | Bukkit.getScheduler().runTaskLater(pl, () -> player.openInventory(excessChest), 1L); 613 | } 614 | } 615 | 616 | private List getItemsOnLeft(Inventory inv) { 617 | List items = new ArrayList<>(); 618 | pl.getTradeConfig() 619 | .getMySlots() 620 | .forEach( 621 | slot -> { 622 | if (slot != pl.getTradeConfig().getAcceptSlot() && getExtra(slot) == null) { 623 | ItemStack item = inv.getItem(slot); 624 | if (item != null) { 625 | items.add(item); 626 | } 627 | } 628 | }); 629 | return items; 630 | } 631 | 632 | private int getRight(int left) { 633 | return theirSlots.get(mySlots.indexOf(left)); 634 | } 635 | 636 | private int getRightExtra(int left) { 637 | return theirExtraSlots.get(myExtraSlots.indexOf(left)); 638 | } 639 | 640 | private void updateInventories() { 641 | pl.getTradeConfig() 642 | .getMySlots() 643 | .forEach( 644 | slot -> { 645 | if (getExtra(slot) == null && slot != pl.getTradeConfig().getAcceptSlot()) { 646 | ItemStack item1 = inv1.getItem(slot); 647 | if (isBlocked(item1)) { 648 | Sounds.villagerHit(player1, 1); 649 | inv1.setItem(slot, null); 650 | player1.getInventory().addItem(item1).values().stream() 651 | .findFirst() 652 | .ifPresent( 653 | i -> player1.getWorld().dropItemNaturally(player1.getLocation(), i)); 654 | } else { 655 | inv2.setItem(getRight(slot), item1); 656 | spectatorInv.setItem(slot, item1); 657 | } 658 | 659 | ItemStack item2 = inv2.getItem(slot); 660 | if (isBlocked(item2)) { 661 | Sounds.villagerHit(player2, 1); 662 | inv2.setItem(slot, null); 663 | player2.getInventory().addItem(item2).values().stream() 664 | .findFirst() 665 | .ifPresent( 666 | i -> player2.getWorld().dropItemNaturally(player2.getLocation(), i)); 667 | } else { 668 | inv1.setItem(getRight(slot), item2); 669 | spectatorInv.setItem(getRight(slot), item2); 670 | } 671 | } 672 | }); 673 | player1.updateInventory(); 674 | player2.updateInventory(); 675 | } 676 | 677 | public void updateExtras() { 678 | int slot1 = 0, slot2a = 0, slot2b = 0; 679 | ItemStack placeholder = 680 | pl.getTradeConfig().getPlaceholder().copy().replace("%PLAYER%", player2.getName()).build(); 681 | for (int i = 0; i < myExtraSlots.size(); i++) { 682 | if (i >= extras.size()) { 683 | break; 684 | } 685 | int mySlot = myExtraSlots.get(i); 686 | int theirSlot = theirExtraSlots.get(i); 687 | inv1.setItem(mySlot, placeholder); 688 | inv1.setItem(theirSlot, placeholder); 689 | inv2.setItem(mySlot, placeholder); 690 | inv2.setItem(theirSlot, placeholder); 691 | } 692 | placedExtras.clear(); 693 | for (Extra extra : extras) { 694 | inv1.setItem(myExtraSlots.get(slot1), extra.getIcon(player1)); 695 | inv2.setItem(myExtraSlots.get(slot1), extra.getIcon(player2)); 696 | placedExtras.put(myExtraSlots.get(slot1), extra); 697 | slot1++; 698 | if (extra.value1 > 0) { 699 | inv2.setItem(theirExtraSlots.get(slot2a), extra.getTheirIcon(player1)); 700 | spectatorInv.setItem(myExtraSlots.get(slot2a), extra.getTheirIcon(player1)); 701 | slot2a++; 702 | } 703 | if (extra.value2 > 0) { 704 | inv1.setItem(theirExtraSlots.get(slot2b), extra.getTheirIcon(player2)); 705 | spectatorInv.setItem(theirExtraSlots.get(slot2b), extra.getTheirIcon(player2)); 706 | slot2b++; 707 | } 708 | } 709 | player1.updateInventory(); 710 | player2.updateInventory(); 711 | } 712 | 713 | private void updateAcceptance() { 714 | if (pl.getTradeConfig().isAcceptEnabled()) { 715 | inv1.setItem( 716 | pl.getTradeConfig().getAcceptSlot(), 717 | accept1 718 | ? pl.getTradeConfig().getCancel().build() 719 | : pl.getTradeConfig().getAccept().build()); 720 | inv1.setItem( 721 | pl.getTradeConfig().getTheirAcceptSlot(), 722 | accept2 723 | ? pl.getTradeConfig().getTheirAccept().build() 724 | : pl.getTradeConfig().getTheirCancel().build()); 725 | inv2.setItem( 726 | pl.getTradeConfig().getAcceptSlot(), 727 | accept2 728 | ? pl.getTradeConfig().getCancel().build() 729 | : pl.getTradeConfig().getAccept().build()); 730 | inv2.setItem( 731 | pl.getTradeConfig().getTheirAcceptSlot(), 732 | accept1 733 | ? pl.getTradeConfig().getTheirAccept().build() 734 | : pl.getTradeConfig().getTheirCancel().build()); 735 | 736 | inv1.getItem(pl.getTradeConfig().getAcceptSlot()) 737 | .setAmount(pl.getTradeConfig().getAntiscamCountdown()); 738 | inv1.getItem(pl.getTradeConfig().getTheirAcceptSlot()) 739 | .setAmount(pl.getTradeConfig().getAntiscamCountdown()); 740 | inv2.getItem(pl.getTradeConfig().getAcceptSlot()) 741 | .setAmount(pl.getTradeConfig().getAntiscamCountdown()); 742 | inv2.getItem(pl.getTradeConfig().getTheirAcceptSlot()) 743 | .setAmount(pl.getTradeConfig().getAntiscamCountdown()); 744 | 745 | spectatorInv.setItem( 746 | 4, 747 | accept1 && accept2 748 | ? pl.getTradeConfig().getTheirAccept().build() 749 | : pl.getTradeConfig().getTheirCancel().build()); 750 | } 751 | } 752 | 753 | private void checkAcceptance() { 754 | if (pl.getTradeConfig().isAcceptEnabled()) { 755 | if (accept1 && accept2) { 756 | for (Extra extra : extras) { 757 | if (extra.updateMax(false)) { 758 | accept1 = false; 759 | accept2 = false; 760 | updateAcceptance(); 761 | updateExtras(); 762 | return; 763 | } 764 | } 765 | 766 | if (task != null) { 767 | return; 768 | } 769 | 770 | giveOnCursor(player1); 771 | giveOnCursor(player2); 772 | 773 | accepted1 = getItemsOnLeft(inv1).toArray(new ItemStack[0]); 774 | 775 | accepted2 = getItemsOnLeft(inv2).toArray(new ItemStack[0]); 776 | 777 | if (pl.getTradeConfig().isSoundEffectsEnabled() && pl.getTradeConfig().isSoundOnAccept()) { 778 | Sounds.pling(player1, 1); 779 | Sounds.pling(player2, 1); 780 | spectatorInv.getViewers().stream() 781 | .filter(Player.class::isInstance) 782 | .forEach(p -> Sounds.pling((Player) p, 1)); 783 | } 784 | 785 | task = 786 | Bukkit.getScheduler() 787 | .runTaskTimer( 788 | pl, 789 | () -> { 790 | int current = inv1.getItem(pl.getTradeConfig().getAcceptSlot()).getAmount(); 791 | if (current > 1) { 792 | countAcceptSlots(current - 1); 793 | } else { 794 | if (task != null) { 795 | pl.ongoingTrades.remove(this); 796 | task.cancel(); 797 | task = null; 798 | 799 | for (Extra extra : extras) { 800 | if (extra.updateMax(false)) { 801 | pl.getTradeConfig() 802 | .getDiscrepancyDetected() 803 | .send(player1, "%PLAYER%", player2.getName()); 804 | pl.getTradeConfig() 805 | .getDiscrepancyDetected() 806 | .send(player2, "%PLAYER%", player1.getName()); 807 | cancel(false); 808 | return; 809 | } 810 | } 811 | 812 | for (Extra extra : extras) { 813 | if (extra.value1 > extra.getMax(player1) || extra.value2 > extra.getMax(player2)) { 814 | pl.getTradeConfig() 815 | .getDiscrepancyDetected() 816 | .send(player1, "%PLAYER%", player2.getName()); 817 | pl.getTradeConfig() 818 | .getDiscrepancyDetected() 819 | .send(player2, "%PLAYER%", player1.getName()); 820 | cancel(false); 821 | return; 822 | } 823 | } 824 | 825 | if (pl.getTradeConfig().isDiscrepancyDetection()) { 826 | boolean discrepancy = false; 827 | int i = 0; 828 | for (ItemStack item : getItemsOnLeft(inv1)) { 829 | if (item == null) continue; 830 | if (accepted1.length <= i || !item.isSimilar(accepted1[i++])) { 831 | discrepancy = true; 832 | break; 833 | } 834 | } 835 | 836 | if (!discrepancy) { 837 | i = 0; 838 | for (ItemStack item : getItemsOnLeft(inv2)) { 839 | if (item == null) continue; 840 | if (accepted2.length <= i || !item.isSimilar(accepted2[i++])) { 841 | discrepancy = true; 842 | } 843 | } 844 | } 845 | 846 | if (discrepancy) { 847 | cancelled = true; 848 | pl.log( 849 | "Found discrepancy in trade between " 850 | + player1.getName() 851 | + " and " 852 | + player2.getName()); 853 | pl.getTradeConfig() 854 | .getDiscrepancyDetected() 855 | .send(player1, "%PLAYER%", player2.getName()); 856 | pl.getTradeConfig() 857 | .getDiscrepancyDetected() 858 | .send(player2, "%PLAYER%", player1.getName()); 859 | cancel(false); 860 | return; 861 | } 862 | } 863 | 864 | for (int leftSlot : mySlots) { 865 | if (leftSlot == pl.getTradeConfig().getAcceptSlot()) continue; 866 | if (getExtra(leftSlot) != null) continue; 867 | int rightSlot = getRight(leftSlot); 868 | inv1.setItem(leftSlot, inv1.getItem(rightSlot)); 869 | inv2.setItem(leftSlot, inv2.getItem(rightSlot)); 870 | } 871 | 872 | for (int leftSlot : myExtraSlots) { 873 | if (leftSlot == pl.getTradeConfig().getAcceptSlot()) continue; 874 | if (getExtra(leftSlot) == null) continue; 875 | int rightSlot = getRightExtra(leftSlot); 876 | inv1.setItem(leftSlot, inv1.getItem(rightSlot)); 877 | inv2.setItem(leftSlot, inv2.getItem(rightSlot)); 878 | } 879 | 880 | cancel(true); 881 | 882 | for (Extra extra : extras) { 883 | extra.onTradeEnd(); 884 | } 885 | 886 | if (pl.getTradeConfig().isSoundEffectsEnabled() 887 | && pl.getTradeConfig().isSoundOnComplete()) { 888 | Sounds.levelUp(player1, 1); 889 | Sounds.levelUp(player2, 1); 890 | spectatorInv.getViewers().stream() 891 | .filter(Player.class::isInstance) 892 | .map(Player.class::cast) 893 | .forEach(p -> Sounds.levelUp(p, 1)); 894 | } 895 | 896 | pl.getTradeConfig() 897 | .getTradeComplete() 898 | .send(player1, "%PLAYER%", player2.getName()); 899 | pl.getTradeConfig() 900 | .getTradeComplete() 901 | .send(player2, "%PLAYER%", player1.getName()); 902 | 903 | if (pl.getLogs() != null) { 904 | try { 905 | TradeLog trade = 906 | new TradeLog( 907 | player1, 908 | player2, 909 | combine(accepted1).stream() 910 | .map(ItemFactory::new) 911 | .collect(Collectors.toList()), 912 | combine(accepted2).stream() 913 | .map(ItemFactory::new) 914 | .collect(Collectors.toList()), 915 | extras.stream() 916 | .filter(e -> e.value1 > 0) 917 | .map(e -> new TradeLog.ExtraOffer(e.name, e.value1)) 918 | .collect(Collectors.toList()), 919 | extras.stream() 920 | .filter(e -> e.value2 > 0) 921 | .map(e -> new TradeLog.ExtraOffer(e.name, e.value2)) 922 | .collect(Collectors.toList())); 923 | 924 | TradeCompleteEvent completeEvent = 925 | new TradeCompleteEvent(trade, player1, player2); 926 | Bukkit.getPluginManager().callEvent(completeEvent); 927 | 928 | pl.getLogs().log(trade); 929 | } catch (Exception ex) { 930 | pl.log("Failed to save trade log. " + ex.getMessage()); 931 | } 932 | } 933 | } else { 934 | updateAcceptance(); 935 | } 936 | } 937 | }, 938 | 20L, 939 | 20L); 940 | } else { 941 | if (task != null) { 942 | task.cancel(); 943 | accept1 = false; 944 | accept2 = false; 945 | task = null; 946 | click(); 947 | } 948 | } 949 | } 950 | } 951 | 952 | private Extra getExtra(int slot) { 953 | return placedExtras.get(slot); 954 | } 955 | 956 | private ItemStack putOnLeft(Inventory inventory, ItemStack toMove, int amountToMove) { 957 | int moved = 0; 958 | for (int slot : mySlots) { 959 | if (getExtra(slot) != null || slot == pl.getTradeConfig().getAcceptSlot()) continue; 960 | ItemStack inInventory = inventory.getItem(slot); 961 | if (inInventory != null 962 | && inInventory.isSimilar(toMove) 963 | && inInventory.getAmount() < inInventory.getType().getMaxStackSize()) { 964 | while (inInventory.getAmount() < inInventory.getType().getMaxStackSize() 965 | && toMove.getAmount() > 0 966 | && moved++ < amountToMove) { 967 | inInventory.setAmount(inInventory.getAmount() + 1); 968 | toMove.setAmount(toMove.getAmount() - 1); 969 | } 970 | if (toMove.getAmount() <= 0 || moved == amountToMove) { 971 | return null; 972 | } 973 | } 974 | } 975 | for (int slot : mySlots) { 976 | if (getExtra(slot) != null || slot == pl.getTradeConfig().getAcceptSlot()) continue; 977 | ItemStack i = inventory.getItem(slot); 978 | if (!(i == null || i.getType().equals(Material.AIR))) { 979 | continue; 980 | } 981 | inventory.setItem(slot, toMove); 982 | toMove = null; 983 | } 984 | return toMove; 985 | } 986 | 987 | private boolean isBlocked(ItemStack item) { 988 | if (item == null || item.getType().equals(Material.AIR)) { 989 | return false; 990 | } 991 | 992 | if (item.hasItemMeta()) { 993 | if (pl.getTradeConfig().isDenyNamedItems() 994 | && item.getItemMeta().hasDisplayName()) { 995 | return true; 996 | } 997 | 998 | String regex = pl.getConfig().getString("blocked.regex", ""); 999 | if (!regex.isEmpty()) { 1000 | try { 1001 | Pattern pattern = Pattern.compile(regex); 1002 | if (item.getItemMeta().hasDisplayName()) { 1003 | String displayName = item.getItemMeta().getDisplayName(); 1004 | if (pattern.matcher(displayName).find()) { 1005 | return true; 1006 | } 1007 | } 1008 | if (item.getItemMeta().hasLore()) { 1009 | List lore = item.getItemMeta().getLore(); 1010 | if (lore.stream().anyMatch(s -> pattern.matcher(s).find())) { 1011 | return true; 1012 | } 1013 | } 1014 | } catch (PatternSyntaxException ex) { 1015 | Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "Your blocked.regex is invalid!"); 1016 | } 1017 | } 1018 | List blockedLore = pl.getTradeConfig().getLoreBlacklist(); 1019 | if (!blockedLore.isEmpty()) { 1020 | for (int i = 0; i < blockedLore.size(); i++) { 1021 | String line = MsgUtils.color(blockedLore.get(i)); 1022 | if (line.length() > 2) { 1023 | line = line.substring(1, line.length() - 1); 1024 | } 1025 | blockedLore.set(i, line); 1026 | } 1027 | if (item.getItemMeta().hasDisplayName()) { 1028 | String displayName = item.getItemMeta().getDisplayName(); 1029 | if (blockedLore.stream().anyMatch(displayName::contains)) { 1030 | return true; 1031 | } 1032 | } 1033 | if (item.getItemMeta().hasLore()) { 1034 | List lore = item.getItemMeta().getLore(); 1035 | for (String blocked : blockedLore) { 1036 | for (String line : lore) { 1037 | if (line.contains(blocked)) { 1038 | return true; 1039 | } 1040 | } 1041 | } 1042 | } 1043 | } 1044 | } 1045 | List blocked = pl.getTradeConfig().getItemBlacklist(); 1046 | if (blocked.isEmpty()) { 1047 | return false; 1048 | } 1049 | String type = item.getType().toString(); 1050 | List checks = new ArrayList<>(); 1051 | if (Sounds.version < 113) { 1052 | byte data = item.getData().getData(); 1053 | checks.add(type + ":" + data); 1054 | checks.add(type.replace("_", "") + ":" + data); 1055 | checks.add(type.replace("_", " ") + ":" + data); 1056 | try { // Throws exception for materials added after the flattening 1057 | checks.add(item.getType().getId() + ":" + data); 1058 | checks.add(Integer.toString(item.getType().getId())); 1059 | } catch (IllegalArgumentException ignored) { 1060 | } 1061 | } 1062 | checks.add(type); 1063 | checks.add(type.replace("_", "")); 1064 | checks.add(type.replace("_", " ")); 1065 | for (String block : blocked) { 1066 | for (String check : checks) { 1067 | if (block.equalsIgnoreCase(check)) { 1068 | return true; 1069 | } 1070 | } 1071 | } 1072 | return false; 1073 | } 1074 | 1075 | public void open(Player player) { 1076 | if (cancelled) { 1077 | player.closeInventory(); 1078 | } else { 1079 | if (player1.equals(player)) { 1080 | player.openInventory(inv1); 1081 | } else if (player2.equals(player)) { 1082 | player.openInventory(inv2); 1083 | } 1084 | } 1085 | } 1086 | 1087 | public void setCancelOnClose(Player player, boolean cancelOnClose) { 1088 | if (player1.equals(player)) { 1089 | cancelOnClose1 = cancelOnClose; 1090 | } else if (player2.equals(player)) { 1091 | cancelOnClose2 = cancelOnClose; 1092 | } 1093 | } 1094 | 1095 | private void cancel(boolean success) { 1096 | if (inv1.getViewers().isEmpty()) player1.openInventory(inv1); 1097 | if (inv2.getViewers().isEmpty()) player2.openInventory(inv2); 1098 | for (Extra extra : extras) { 1099 | extra.onCancel(); 1100 | } 1101 | cancelled = true; 1102 | 1103 | ItemStack acceptItem = success ? pl.getTradeConfig().getComplete().build() : pl.getTradeConfig().getCancelled().build(); 1104 | 1105 | inv1.setItem(pl.getTradeConfig().getAcceptSlot(), acceptItem); 1106 | inv2.setItem(pl.getTradeConfig().getAcceptSlot(), acceptItem); 1107 | inv1.setItem(pl.getTradeConfig().getTheirAcceptSlot(), acceptItem); 1108 | inv2.setItem(pl.getTradeConfig().getTheirAcceptSlot(), acceptItem); 1109 | if (pl.getTradeConfig().isEndDisplayEnabled()) { 1110 | for (int slot : theirSlots) { 1111 | inv1.setItem(slot, pl.getTradeConfig().getPlaceholder().build()); 1112 | inv2.setItem(slot, pl.getTradeConfig().getPlaceholder().build()); 1113 | } 1114 | 1115 | if (pl.getTradeConfig().getEndDisplayTimer() > 0) { 1116 | int closeTimer = pl.getTradeConfig().getEndDisplayTimer(); 1117 | countAcceptSlots(closeTimer); 1118 | new BukkitRunnable() { 1119 | @Override 1120 | public void run() { 1121 | int count = inv1.getItem(pl.getTradeConfig().getAcceptSlot()).getAmount(); 1122 | if (--count == 0) { 1123 | cancel(); 1124 | if (inv1.getViewers().contains(player1)) player1.closeInventory(); 1125 | if (inv2.getViewers().contains(player2)) player2.closeInventory(); 1126 | } else { 1127 | countAcceptSlots(count); 1128 | } 1129 | } 1130 | }.runTaskTimer(pl, 0, 20); 1131 | } 1132 | } else { 1133 | player1.closeInventory(); 1134 | player2.closeInventory(); 1135 | } 1136 | } 1137 | 1138 | private void countAcceptSlots(int count) { 1139 | inv1.getItem(pl.getTradeConfig().getAcceptSlot()).setAmount(count); 1140 | inv2.getItem(pl.getTradeConfig().getAcceptSlot()).setAmount(count); 1141 | inv1.getItem(pl.getTradeConfig().getTheirAcceptSlot()).setAmount(count); 1142 | inv2.getItem(pl.getTradeConfig().getTheirAcceptSlot()).setAmount(count); 1143 | spectatorInv.getItem(4).setAmount(count); 1144 | if (pl.getTradeConfig().isSoundEffectsEnabled() && pl.getTradeConfig().isSoundOnCountdown()) { 1145 | Sounds.click(player1, 2); 1146 | Sounds.click(player2, 2); 1147 | spectatorInv.getViewers().stream() 1148 | .filter(Player.class::isInstance) 1149 | .forEach(p -> Sounds.click((Player) p, 2)); 1150 | } 1151 | } 1152 | } 1153 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/trade/TradeRequest.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.trade; 2 | 3 | import org.bukkit.entity.Player; 4 | 5 | /** Created by lucas on 5/26/16. */ 6 | public class TradeRequest { 7 | 8 | public final Player sender; 9 | public final Player receiver; 10 | 11 | public TradeRequest(Player sender, Player receiver) { 12 | this.sender = sender; 13 | this.receiver = receiver; 14 | } 15 | 16 | public boolean contains(Player player) { 17 | return sender.equals(player) || receiver.equals(player); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/util/InvUtils.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.util; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import com.trophonix.tradeplus.gui.MenuInventoryHolder; 5 | import org.bukkit.Bukkit; 6 | import org.bukkit.ChatColor; 7 | import org.bukkit.entity.Player; 8 | import org.bukkit.inventory.Inventory; 9 | import org.bukkit.inventory.ItemStack; 10 | 11 | public class InvUtils { 12 | // public static final List leftSlots = 13 | // new LinkedList<>( 14 | // Arrays.asList(0, 15 | // 1, 2, 3, 9, 10, 11, 12, 18, 19, 20, 21, 27, 28, 29, 30, 36, 37, 38, 16 | // 39, 45, 46, 47, 17 | // 48)); 18 | 19 | private static TradePlus pl; 20 | 21 | public static void reloadItems(TradePlus pl) { 22 | InvUtils.pl = pl; 23 | } 24 | 25 | public static Inventory getTradeInventory(Player player1, Player player2) { 26 | MenuInventoryHolder holder = new MenuInventoryHolder(); 27 | Inventory inv = 28 | Bukkit.createInventory( 29 | holder, 30 | 54, 31 | pl.getTradeConfig().getGuiTitle().replace("%PLAYER%", player2.getName())); 32 | holder.setCurrent(inv); 33 | ItemStack separator = 34 | pl.getTradeConfig().getSeparator().copy().replace("%PLAYER%", player2.getName()).build(); 35 | for (int i = 4; i <= 49; i += 9) inv.setItem(i, separator); 36 | if (pl.getTradeConfig().isAcceptEnabled()) { 37 | if (pl.getTradeConfig().isForceEnabled() && player1.hasPermission("tradeplus.admin")) { 38 | inv.setItem(49, pl.getTradeConfig().getForce().build()); 39 | } 40 | } else { 41 | inv.setItem(pl.getTradeConfig().getAcceptSlot(), separator); 42 | inv.setItem(pl.getTradeConfig().getTheirAcceptSlot(), separator); 43 | } 44 | if (pl.getTradeConfig().isHeadEnabled()) try { 45 | inv.setItem( 46 | 4, 47 | ItemFactory.getPlayerSkull( 48 | player2, 49 | pl.getTradeConfig().getHeadDisplayName().replace("%PLAYER%", player2.getName()))); 50 | } catch (Exception | Error ignored) { 51 | inv.setItem(4, separator); 52 | } 53 | return inv; 54 | } 55 | 56 | public static Inventory getSpectatorInventory(Player player1, Player player2) { 57 | String title = 58 | MsgUtils.color(pl.getTradeConfig().getSpectatorTitle()); 59 | if (Sounds.version > 1.8) 60 | title = title.replace("%PLAYER1%", player1.getName()).replace("%PLAYER2%", player2.getName()); 61 | Inventory inv = Bukkit.createInventory(new MenuInventoryHolder(), 54, title); 62 | ItemStack separator = pl.getTradeConfig().getSeparator().build(); 63 | for (int i = 4; i <= 49; i += 9) inv.setItem(i, separator); 64 | for (int i = 45; i <= 53; i++) inv.setItem(i, separator); 65 | if (pl.getTradeConfig().isHeadEnabled()){ 66 | try { 67 | inv.setItem( 68 | pl.getTradeConfig().getAcceptSlot(), 69 | ItemFactory.getPlayerSkull(player1, "&f" + player1.getName())); 70 | inv.setItem( 71 | pl.getTradeConfig().getTheirAcceptSlot(), 72 | ItemFactory.getPlayerSkull(player2, "&f" + player2.getName())); 73 | } catch (Exception | Error ignored) { 74 | } 75 | } 76 | 77 | return inv; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/util/ItemFactory.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.util; 2 | 3 | import com.google.common.base.Preconditions; 4 | import com.trophonix.tradeplus.TradePlus; 5 | import lombok.Getter; 6 | import org.bukkit.ChatColor; 7 | import org.bukkit.Material; 8 | import org.bukkit.configuration.ConfigurationSection; 9 | import org.bukkit.entity.Player; 10 | import org.bukkit.inventory.ItemStack; 11 | import org.bukkit.inventory.meta.ItemMeta; 12 | import org.bukkit.inventory.meta.SkullMeta; 13 | 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | import java.util.stream.Collectors; 17 | 18 | public class ItemFactory { 19 | 20 | @Getter 21 | private ItemStack stack; 22 | 23 | public ItemFactory(Material material) { 24 | this.stack = new ItemStack(material); 25 | } 26 | 27 | public ItemFactory(String parsable, Material fallback) { 28 | if (parsable == null) { 29 | this.stack = new ItemStack(fallback); 30 | } else { 31 | byte data = -1; 32 | if (parsable.contains(":")) { 33 | String[] split = parsable.split(":"); 34 | data = Byte.parseByte(split[1]); 35 | parsable = split[0]; 36 | } 37 | parsable = parsable.toUpperCase().replace(" ", "_"); 38 | 39 | Material mat = Material.getMaterial(parsable); 40 | if (mat == null) { 41 | mat = fallback; 42 | TradePlus.getPlugin(TradePlus.class) 43 | .getLogger() 44 | .warning( 45 | "Unknown material [" 46 | + parsable 47 | + "]." 48 | + (Sounds.version >= 113 49 | ? " Make sure you've updated to the new 1.13 standard. Numerical item IDs are no longer supported. Using fallback: " 50 | + fallback.name() 51 | : "")); 52 | } 53 | 54 | if (data > 0) { 55 | this.stack = new ItemStack(mat, 1, data, data); 56 | } else { 57 | this.stack = new ItemStack(mat); 58 | } 59 | } 60 | } 61 | 62 | public ItemFactory damage(short damage) { 63 | stack.setDurability(damage); 64 | return this; 65 | } 66 | 67 | public ItemFactory(String parsable) { 68 | this(parsable, Material.PAPER); 69 | // Preconditions.checkNotNull(parsable, "Material cannot be null."); 70 | // byte data = -1; 71 | // if (parsable.contains(":")) { 72 | // String[] split = parsable.split(":"); 73 | // data = Byte.parseByte(split[1]); 74 | // parsable = split[0]; 75 | // } 76 | // parsable = parsable.toUpperCase().replace(" ", "_"); 77 | // Material mat = Material.getMaterial(parsable); 78 | // this.material = Preconditions.checkNotNull(mat, "Unknown material [%s]", parsable); 79 | // ; 80 | // this.data = data; 81 | } 82 | 83 | public ItemFactory(ItemStack stack) { 84 | this.stack = stack.clone(); 85 | } 86 | 87 | public ItemFactory(ConfigurationSection yml, String key) { 88 | this.stack = yml.getItemStack(key); 89 | if (stack != null && stack.hasItemMeta()) { 90 | ItemMeta meta = stack.getItemMeta(); 91 | String displayName = null; 92 | List lore = null; 93 | 94 | if (meta.hasDisplayName()) { 95 | displayName = MsgUtils.color(meta.getDisplayName()); 96 | } 97 | 98 | if (meta.hasLore()) { 99 | lore = 100 | meta.getLore().stream() 101 | .map(s -> MsgUtils.color(s)) 102 | .collect(Collectors.toList()); 103 | } 104 | 105 | meta.setDisplayName(displayName); 106 | meta.setLore(lore); 107 | 108 | stack.setItemMeta(meta); 109 | } 110 | } 111 | 112 | public ItemFactory save(ConfigurationSection yml, String key) { 113 | ItemStack stack = this.stack.clone(); 114 | ItemMeta meta = stack.getItemMeta(); 115 | if (meta != null) { 116 | if (meta.hasDisplayName()) meta.setDisplayName(meta.getDisplayName().replace(ChatColor.COLOR_CHAR, '&')); 117 | if (meta.hasLore()) meta.setLore(meta.getLore().stream().map(s -> s.replace(ChatColor.COLOR_CHAR, '&')).collect(Collectors.toList())); 118 | } 119 | yml.set(key, stack); 120 | return this; 121 | } 122 | 123 | static ItemStack getPlayerSkull(Player player, String displayName) { 124 | ItemStack skull = 125 | new ItemStack(Material.getMaterial(Sounds.version > 112 ? "PLAYER_HEAD" : "SKULL_ITEM")); 126 | Preconditions.checkNotNull(skull, "Failed to load skull."); 127 | if (Sounds.version < 113) skull.getData().setData((byte) 3); 128 | SkullMeta meta = (SkullMeta) skull.getItemMeta(); 129 | meta.setDisplayName(MsgUtils.color(displayName)); 130 | if (Sounds.version >= 112) meta.setOwningPlayer(player); 131 | else meta.setOwner(player.getName()); 132 | skull.setItemMeta(meta); 133 | return skull; 134 | } 135 | 136 | public static ItemStack replaceInMeta(ItemStack item, String... replace) { 137 | item = item.clone(); 138 | if (!item.hasItemMeta()) { 139 | return item; 140 | } 141 | ItemMeta meta = item.getItemMeta(); 142 | if (meta != null) { 143 | try { 144 | for (int i = 0; i < replace.length - 1; i += 2) { 145 | String toReplace = replace[i]; 146 | String replaceWith = replace[i + 1]; 147 | if (meta.hasDisplayName()) { 148 | meta.setDisplayName(meta.getDisplayName().replace(toReplace, replaceWith)); 149 | } 150 | if (meta.hasLore()) { 151 | List lore = meta.getLore(); 152 | assert lore != null; 153 | for (int j = 0; j < lore.size(); j++) { 154 | lore.set(j, lore.get(j).replace(toReplace, replaceWith)); 155 | } 156 | meta.setLore(lore); 157 | } 158 | } 159 | } catch (Exception ignored) { 160 | } 161 | } 162 | item.setItemMeta(meta); 163 | return item; 164 | } 165 | 166 | public ItemFactory replace(String... replace) { 167 | if (stack.hasItemMeta()) { 168 | ItemMeta meta = stack.getItemMeta(); 169 | String display = meta.getDisplayName(); 170 | List lore = meta.getLore(); 171 | for (int i = 0; i < replace.length - 1; i += 2) { 172 | if (display != null) display = display.replace(replace[i], replace[i + 1]); 173 | if (lore != null) { 174 | int n = i; 175 | lore = 176 | lore.stream() 177 | .map(str -> str.replace(replace[n], replace[n + 1])) 178 | .collect(Collectors.toList()); 179 | } 180 | } 181 | meta.setDisplayName(display); 182 | meta.setLore(lore); 183 | stack.setItemMeta(meta); 184 | } 185 | return this; 186 | } 187 | 188 | public ItemStack build() { 189 | return stack.clone(); 190 | } 191 | 192 | public ItemFactory copy() { 193 | return new ItemFactory(stack); 194 | } 195 | 196 | public ItemFactory amount(int amount) { 197 | this.stack.setAmount(amount); 198 | return this; 199 | } 200 | 201 | public ItemFactory display(String display) { 202 | ItemMeta meta = stack.getItemMeta(); 203 | if (display.contains("%NEWLINE%")) { 204 | String[] split = display.split("%NEWLINE%"); 205 | display = split[0]; 206 | List lore = new ArrayList<>(); 207 | for (int i = 1; i < split.length; i++) { 208 | lore.add(split[i]); 209 | } 210 | this.lore(lore); 211 | } 212 | meta.setDisplayName(MsgUtils.color(display)); 213 | stack.setItemMeta(meta); 214 | return this; 215 | } 216 | 217 | public ItemFactory lore(List lore) { 218 | for (int i = 0; i < lore.size(); i++) { 219 | String line = lore.get(i); 220 | if (line != null) { 221 | line = MsgUtils.color(line); 222 | lore.set(i, line); 223 | } 224 | } 225 | ItemMeta meta = stack.getItemMeta(); 226 | List current = meta.getLore(); 227 | if (current == null) current = new ArrayList<>(); 228 | current.addAll(lore); 229 | meta.setLore(current); 230 | stack.setItemMeta(meta); 231 | return this; 232 | } 233 | 234 | public ItemFactory flag(String flag) { 235 | if (Sounds.version == 17) return this; 236 | ItemMeta meta = stack.getItemMeta(); 237 | meta.addItemFlags(org.bukkit.inventory.ItemFlag.valueOf(flag)); 238 | stack.setItemMeta(meta); 239 | return this; 240 | } 241 | 242 | public ItemFactory customModelData(int customModelData) { 243 | if (Sounds.version < 114) return this; 244 | ItemMeta meta = stack.getItemMeta(); 245 | ItemUtils1_14.applyCustomModelData(meta, customModelData); 246 | stack.setItemMeta(meta); 247 | return this; 248 | } 249 | 250 | public int getAmount() { 251 | return stack.getAmount(); 252 | } 253 | } 254 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/util/ItemUtils1_14.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.util; 2 | 3 | import org.bukkit.NamespacedKey; 4 | import org.bukkit.enchantments.Enchantment; 5 | import org.bukkit.inventory.ItemStack; 6 | import org.bukkit.inventory.meta.ItemMeta; 7 | 8 | public class ItemUtils1_14 { 9 | 10 | public static int getCustomModelData(ItemStack stack) { 11 | if (!stack.hasItemMeta()) return 0; 12 | return stack.getItemMeta().getCustomModelData(); 13 | } 14 | 15 | public static void applyCustomModelData(ItemMeta meta, int customModelData) { 16 | meta.setCustomModelData(customModelData); 17 | } 18 | 19 | public static String getName(Enchantment enchantment) { 20 | return enchantment.getKey().getKey(); 21 | } 22 | 23 | public static Enchantment getEnchantment(String key) { 24 | return Enchantment.getByKey(NamespacedKey.minecraft(key)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/util/MsgUtils.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.util; 2 | 3 | import org.bukkit.ChatColor; 4 | import org.bukkit.command.CommandSender; 5 | import org.bukkit.entity.Player; 6 | 7 | import java.util.regex.Matcher; 8 | import java.util.regex.Pattern; 9 | 10 | import static org.bukkit.ChatColor.COLOR_CHAR; 11 | 12 | public class MsgUtils { 13 | 14 | private static boolean clickableMessages; 15 | 16 | static { 17 | try { 18 | clickableMessages = Class.forName("net.md_5.bungee.api.chat.TextComponent") != null; 19 | } catch (ClassNotFoundException ignored) { 20 | clickableMessages = false; 21 | } 22 | } 23 | 24 | public static void send(Player player, String onHover, String onClick, String[] messages) { 25 | if (clickableMessages) { 26 | MsgUtils1_8.send(player, onHover, onClick, messages); 27 | } else { 28 | send(player, messages); 29 | } 30 | } 31 | 32 | public static void send(Player player, String onHover, String onClick, String message) { 33 | if (message.contains("%NEWLINE%")) { 34 | send(player, onHover, onClick, message.split("%NEWLINE%")); 35 | } else { 36 | send(player, onHover, onClick, new String[] {message}); 37 | } 38 | } 39 | 40 | public static void send(CommandSender sender, String[] messages) { 41 | for (String message : messages) { 42 | send(sender, message); 43 | } 44 | } 45 | 46 | public static void send(CommandSender sender, String message) { 47 | sender.sendMessage(color(message)); 48 | } 49 | 50 | public static final String startTag = "&\\{"; 51 | public static final String endTag = "}"; 52 | 53 | public static String color(String string) { 54 | final Pattern hexPattern = Pattern.compile(startTag + "([A-Fa-f0-9]{6})" + endTag); 55 | Matcher matcher = hexPattern.matcher(string); 56 | StringBuffer buffer = new StringBuffer(string.length() + 4 * 8); 57 | while (matcher.find()) 58 | { 59 | String group = matcher.group(1); 60 | matcher.appendReplacement(buffer, COLOR_CHAR + "x" 61 | + COLOR_CHAR + group.charAt(0) + COLOR_CHAR + group.charAt(1) 62 | + COLOR_CHAR + group.charAt(2) + COLOR_CHAR + group.charAt(3) 63 | + COLOR_CHAR + group.charAt(4) + COLOR_CHAR + group.charAt(5) 64 | ); 65 | } 66 | return ChatColor.translateAlternateColorCodes('&', matcher.appendTail(buffer).toString()); 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/util/MsgUtils1_8.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.util; 2 | 3 | import net.md_5.bungee.api.chat.BaseComponent; 4 | import net.md_5.bungee.api.chat.ClickEvent; 5 | import net.md_5.bungee.api.chat.HoverEvent; 6 | import net.md_5.bungee.api.chat.TextComponent; 7 | import org.bukkit.ChatColor; 8 | import org.bukkit.entity.Player; 9 | 10 | class MsgUtils1_8 { 11 | 12 | public static void send(Player player, String onHover, String onClick, String[] messages) { 13 | for (String m : messages) { 14 | BaseComponent[] comps = 15 | TextComponent.fromLegacyText(MsgUtils.color(m)); 16 | for (BaseComponent comp : comps) { 17 | if (onHover != null) 18 | comp.setHoverEvent( 19 | new HoverEvent( 20 | HoverEvent.Action.SHOW_TEXT, 21 | TextComponent.fromLegacyText( 22 | MsgUtils.color(onHover)))); 23 | if (onClick != null) 24 | comp.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, onClick)); 25 | } 26 | player.spigot().sendMessage(comps); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/util/NMSManager.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.util; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.entity.Player; 5 | 6 | import java.lang.reflect.Field; 7 | import java.lang.reflect.InvocationTargetException; 8 | import java.lang.reflect.Method; 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | 12 | /** 13 | * Created by PhilipsNostrum 14 | * 15 | *

Cleaned up & useNewVersion-added by Gecolay 16 | */ 17 | public class NMSManager { 18 | 19 | public static final Map, Class> CORRESPONDING_TYPES = 20 | new HashMap, Class>(); 21 | 22 | public static Class getPrimitiveType(Class Class) { 23 | return CORRESPONDING_TYPES.containsKey(Class) ? CORRESPONDING_TYPES.get(Class) : Class; 24 | } 25 | 26 | public static Class[] toPrimitiveTypeArray(Class[] Classes) { 27 | int L = Classes != null ? Classes.length : 0; 28 | Class[] T = new Class[L]; 29 | for (int i = 0; i < L; i++) T[i] = getPrimitiveType(Classes[i]); 30 | return T; 31 | } 32 | 33 | public static boolean equalsTypeArray(Class[] Value1, Class[] Value2) { 34 | if (Value1.length != Value2.length) return false; 35 | for (int i = 0; i < Value1.length; i++) 36 | if (!Value1[i].equals(Value2[i]) && !Value1[i].isAssignableFrom(Value2[i])) return false; 37 | return true; 38 | } 39 | 40 | public static boolean classListEqual(Class[] Value1, Class[] Value2) { 41 | if (Value1.length != Value2.length) return false; 42 | for (int i = 0; i < Value1.length; i++) if (Value1[i] != Value2[i]) return false; 43 | return true; 44 | } 45 | 46 | public static String getVersion() { 47 | String V = Bukkit.getServer().getClass().getPackage().getName(); 48 | return V.substring(V.lastIndexOf('.') + 1) + "."; 49 | } 50 | 51 | public static boolean useNewVersion() { 52 | try { 53 | Class.forName("net.minecraft.server." + getVersion() + "ContainerAccess"); 54 | return true; 55 | } catch (Exception e) { 56 | return false; 57 | } 58 | } 59 | 60 | public static Field getField(Class Class, String Field) { 61 | try { 62 | Field F = Class.getDeclaredField(Field); 63 | F.setAccessible(true); 64 | return F; 65 | } catch (Exception e) { 66 | e.printStackTrace(); 67 | return null; 68 | } 69 | } 70 | 71 | public static Class getNMSClass(String ClassName) { 72 | Class C = null; 73 | try { 74 | return Class.forName("net.minecraft.server." + getVersion() + ClassName); 75 | } catch (Exception e) { 76 | e.printStackTrace(); 77 | } 78 | return C; 79 | } 80 | 81 | public static Method getMethod(Class Class, String ClassName, Class... Parameters) { 82 | for (Method M : Class.getMethods()) 83 | if (M.getName().equals(ClassName) 84 | && (Parameters.length == 0 || classListEqual(Parameters, M.getParameterTypes()))) { 85 | M.setAccessible(true); 86 | return M; 87 | } 88 | return null; 89 | } 90 | 91 | public static Method getMethod(String MethodName, Class Class, Class... Parameters) { 92 | Class[] T = toPrimitiveTypeArray(Parameters); 93 | for (Method M : Class.getMethods()) 94 | if (M.getName().equals(MethodName) 95 | && equalsTypeArray(toPrimitiveTypeArray(M.getParameterTypes()), T)) return M; 96 | return null; 97 | } 98 | 99 | public static Object getHandle(Object Object) { 100 | try { 101 | return getMethod("getHandle", Object.getClass()).invoke(Object); 102 | } catch (Exception e) { 103 | e.printStackTrace(); 104 | return null; 105 | } 106 | } 107 | 108 | public static Object getPlayerField(Player Player, String Field) 109 | throws SecurityException, NoSuchMethodException, NoSuchFieldException, 110 | IllegalArgumentException, IllegalAccessException, InvocationTargetException { 111 | Object P = Player.getClass().getMethod("getHandle").invoke(Player); 112 | return P.getClass().getField(Field).get(P); 113 | } 114 | 115 | public static Object invokeMethod(String MethodName, Object Parameter) { 116 | try { 117 | return getMethod(MethodName, Parameter.getClass()).invoke(Parameter); 118 | } catch (Exception e) { 119 | e.printStackTrace(); 120 | return null; 121 | } 122 | } 123 | 124 | public static Object invokeMethodWithArgs( 125 | String MethodName, Object Object, Object... Parameters) { 126 | try { 127 | return getMethod(MethodName, Object.getClass()).invoke(Object, Parameters); 128 | } catch (Exception e) { 129 | e.printStackTrace(); 130 | return null; 131 | } 132 | } 133 | 134 | public static boolean set(Object Object, String Field, Object Value) { 135 | Class C = Object.getClass(); 136 | while (C != null) { 137 | try { 138 | Field F = C.getDeclaredField(Field); 139 | F.setAccessible(true); 140 | F.set(Object, Value); 141 | return true; 142 | } catch (NoSuchFieldException e) { 143 | C = C.getSuperclass(); 144 | } catch (Exception e) { 145 | throw new IllegalStateException(e); 146 | } 147 | } 148 | return false; 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/util/PDCUtils.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.util; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import org.bukkit.NamespacedKey; 5 | import org.bukkit.entity.Player; 6 | import org.bukkit.persistence.PersistentDataContainer; 7 | import org.bukkit.persistence.PersistentDataType; 8 | 9 | public class PDCUtils { 10 | 11 | private static NamespacedKey ALLOW_TRADING; 12 | 13 | public static boolean allowTrading(Player player) { 14 | PersistentDataContainer pdc = player.getPersistentDataContainer(); 15 | return pdc.getOrDefault(ALLOW_TRADING, PersistentDataType.BYTE, (byte)1) == 1; 16 | } 17 | 18 | public static boolean toggleTrading(Player player) { 19 | PersistentDataContainer pdc = player.getPersistentDataContainer(); 20 | boolean allow = allowTrading(player); 21 | pdc.set(ALLOW_TRADING, PersistentDataType.BYTE, allow ? (byte)0 : (byte)1); 22 | return !allow; 23 | } 24 | 25 | public static void initialize(TradePlus plugin) { 26 | ALLOW_TRADING = new NamespacedKey(plugin, "allow_trading"); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/util/PlayerUtil.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.util; 2 | 3 | import com.trophonix.tradeplus.TradePlus; 4 | import com.trophonix.tradeplus.hooks.EssentialsHook; 5 | import org.bukkit.Bukkit; 6 | import org.bukkit.entity.Player; 7 | import org.bukkit.metadata.MetadataValue; 8 | 9 | import java.net.InetSocketAddress; 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | import java.util.Objects; 13 | import java.util.UUID; 14 | 15 | public class PlayerUtil { 16 | 17 | private static final Map ipAddresses = new HashMap<>(); 18 | 19 | public static void registerIP(Player player) { 20 | InetSocketAddress address = player.getAddress(); 21 | if (address != null) { 22 | String ip = player.getAddress().getHostString(); 23 | if (ip != null) ipAddresses.put(player.getUniqueId(), ip); 24 | } 25 | } 26 | 27 | public static void removeIP(Player player) { 28 | ipAddresses.remove(player.getUniqueId()); 29 | } 30 | 31 | public static boolean sameIP(Player player1, Player player2) { 32 | String ip1 = ipAddresses.get(player1.getUniqueId()); 33 | String ip2 = ipAddresses.get(player2.getUniqueId()); 34 | if (ip1 == null || ip2 == null) return false; 35 | return ip1.equals(ip2); 36 | } 37 | 38 | public static boolean isVanished(Player player) { 39 | if (Bukkit.getPluginManager().isPluginEnabled("Essentials")) { 40 | if (EssentialsHook.isVanished(player)) return true; 41 | } 42 | 43 | for (MetadataValue meta : player.getMetadata("vanished")) { 44 | if (meta.asBoolean()) return true; 45 | } 46 | return false; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/util/Procedure.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.util; 2 | 3 | public interface Procedure { 4 | void invoke(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/util/Sounds.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.util; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.ChatColor; 5 | import org.bukkit.Sound; 6 | import org.bukkit.entity.Player; 7 | 8 | public class Sounds { 9 | 10 | public static final int version; 11 | private static Sound pling; 12 | private static Sound click; 13 | private static Sound levelUp; 14 | private static Sound villagerHit; 15 | private static Sound villagerHmm; 16 | 17 | static { 18 | String[] split = 19 | Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3].split("_"); 20 | version = Integer.parseInt(split[0].replace("v", "") + split[1]); 21 | // System.out.println("You appear to be running version " + version); 22 | } 23 | 24 | public static void loadSounds() { 25 | try { 26 | if (version < 19) { 27 | pling = Sound.valueOf("NOTE_PLING"); 28 | click = Sound.valueOf("CLICK"); 29 | levelUp = Sound.valueOf("LEVEL_UP"); 30 | villagerHit = Sound.valueOf("VILLAGER_HIT"); 31 | villagerHmm = Sound.valueOf("VILLAGER_IDLE"); 32 | } else if (version < 113) { 33 | pling = Sound.valueOf("BLOCK_NOTE_PLING"); 34 | click = Sound.valueOf("UI_BUTTON_CLICK"); 35 | levelUp = Sound.valueOf("ENTITY_PLAYER_LEVELUP"); 36 | villagerHit = Sound.valueOf("ENTITY_VILLAGER_HURT"); 37 | villagerHmm = Sound.valueOf("ENTITY_VILLAGER_AMBIENT"); 38 | } else { 39 | pling = Sound.valueOf("BLOCK_NOTE_BLOCK_PLING"); 40 | click = Sound.valueOf("UI_BUTTON_CLICK"); 41 | levelUp = Sound.valueOf("ENTITY_PLAYER_LEVELUP"); 42 | villagerHit = Sound.valueOf("ENTITY_VILLAGER_HURT"); 43 | villagerHmm = Sound.valueOf("ENTITY_VILLAGER_AMBIENT"); 44 | } 45 | } catch (IllegalArgumentException | NullPointerException | NoSuchFieldError ex) { 46 | Bukkit.getConsoleSender() 47 | .sendMessage( 48 | ChatColor.DARK_RED + "Unable to load sounds! Sound effects will be disabled."); 49 | } 50 | } 51 | 52 | public static void pling(Player player, float v1) { 53 | if (pling != null) player.playSound(player.getEyeLocation(), pling, 1, v1); 54 | } 55 | 56 | public static void click(Player player, float v1) { 57 | if (click != null) player.playSound(player.getEyeLocation(), click, 1, v1); 58 | } 59 | 60 | public static void levelUp(Player player, float v1) { 61 | if (levelUp != null) player.playSound(player.getEyeLocation(), levelUp, 1, v1); 62 | } 63 | 64 | public static void villagerHit(Player player, float v1) { 65 | if (villagerHit != null) player.playSound(player.getEyeLocation(), villagerHit, 1, v1); 66 | } 67 | 68 | public static void villagerHmm(Player player, float v1) {} 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/trophonix/tradeplus/util/XP.java: -------------------------------------------------------------------------------- 1 | package com.trophonix.tradeplus.util; 2 | 3 | import org.bukkit.entity.Player; 4 | 5 | public class XP { 6 | 7 | /** 8 | * Calculates a player's total exp based on level and progress to next. 9 | * http://minecraft.gamepedia.com/Experience#Leveling_up 10 | * 11 | * @param player the Player 12 | * @return the amount of exp the Player has 13 | */ 14 | public static int getExp(Player player) { 15 | return getExpFromLevel(player.getLevel()) 16 | + Math.round(getExpToNext(player.getLevel()) * player.getExp()); 17 | } 18 | 19 | /** 20 | * Calculates total experience based on level. 21 | * 22 | *

http://minecraft.gamepedia.com/Experience#Leveling_up 23 | * 24 | *

"One can determine how much experience has been collected to reach a level using the 25 | * equations: 26 | * 27 | *

Total Experience = [Level]2 + 6[Level] (at levels 0-15) 2.5[Level]2 - 40.5[Level] + 360 (at 28 | * levels 16-30) 4.5[Level]2 - 162.5[Level] + 2220 (at level 31+)" 29 | * 30 | * @param level the level 31 | * @return the total experience calculated 32 | */ 33 | public static int getExpFromLevel(int level) { 34 | if (level > 30) { 35 | return (int) (4.5 * level * level - 162.5 * level + 2220); 36 | } 37 | if (level > 15) { 38 | return (int) (2.5 * level * level - 40.5 * level + 360); 39 | } 40 | return level * level + 6 * level; 41 | } 42 | 43 | /** 44 | * Calculates level based on total experience. 45 | * 46 | * @param exp the total experience 47 | * @return the level calculated 48 | */ 49 | public static double getLevelFromExp(long exp) { 50 | if (exp > 1395) { 51 | return (Math.sqrt(72 * exp - 54215) + 325) / 18; 52 | } 53 | if (exp > 315) { 54 | return Math.sqrt(40 * exp - 7839) / 10 + 8.1; 55 | } 56 | if (exp > 0) { 57 | return Math.sqrt(exp + 9) - 3; 58 | } 59 | return 0; 60 | } 61 | 62 | /** 63 | * http://minecraft.gamepedia.com/Experience#Leveling_up 64 | * 65 | *

"The formulas for figuring out how many experience orbs you need to get to the next level 66 | * are as follows: Experience Required = 2[Current Level] + 7 (at levels 0-15) 5[Current Level] - 67 | * 38 (at levels 16-30) 9[Current Level] - 158 (at level 31+)" 68 | */ 69 | private static int getExpToNext(int level) { 70 | if (level > 30) { 71 | return 9 * level - 158; 72 | } 73 | if (level > 15) { 74 | return 5 * level - 38; 75 | } 76 | return 2 * level + 7; 77 | } 78 | 79 | /** 80 | * Change a Player's exp. 81 | * 82 | *

This method should be used in place of {@link Player#giveExp(int)}, which does not properly 83 | * account for different levels requiring different amounts of experience. 84 | * 85 | * @param player the Player affected 86 | * @param exp the amount of experience to add or remove 87 | */ 88 | public static void changeExp(Player player, int exp) { 89 | exp += getExp(player); 90 | 91 | if (exp < 0) { 92 | exp = 0; 93 | } 94 | 95 | double levelAndExp = getLevelFromExp(exp); 96 | 97 | int level = (int) levelAndExp; 98 | player.setLevel(level); 99 | player.setExp((float) (levelAndExp - level)); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/resources/plugin.yml: -------------------------------------------------------------------------------- 1 | name: TradePlus 2 | version: ${project.version} 3 | author: Trophonix 4 | main: com.trophonix.tradeplus.TradePlus 5 | softdepend: [Vault,EnjinMinecraftPlugin,GriefPrevention,PlayerPoints,TokenManager,BeastTokens,TokenEnchant,WorldGuard,VotingPlugin] 6 | api-version: "1.16" 7 | commands: 8 | trade: 9 | description: Trade command 10 | tradeplus: 11 | description: TradePlus admin command 12 | permission: tradeplus.admin 13 | permissions: 14 | tradeplus.admin: 15 | description: TradePlus admin permission 16 | default: op 17 | children: 18 | tradeplus.trade: true 19 | tradeplus.admin.silent: 20 | description: Silence admin trade notifications 21 | default: false --------------------------------------------------------------------------------