Compare commits

...

185 commits

Author SHA1 Message Date
Telesphoreo 1609476188 Merge https://github.com/lishid/OpenInv 2021-09-29 15:13:28 -05:00
Telesphoreo f329da29a4 Merge https://github.com/AtlasMediaGroup/OpenInv 2021-09-29 15:11:48 -05:00
Jikoo 1c579564bc
Add reading assistant 2021-07-12 21:07:45 -04:00
Adam eae4021138
Add relocation notice 2021-04-11 18:29:37 -04:00
Nathan Curran be534df766
Merge branch 'master' of https://github.com/lishid/OpenInv 2021-03-21 21:50:18 +11:00
Jikoo 6563b4f6ce
Migrate API-only functions out of PlayerDataManager
With the update to 1.16 there's no need to maintain multiple copies of the same code. Additionally, in 1.16 the action bar now supports JSON text.
2021-03-18 20:31:45 -04:00
Jikoo 1d5a836fd0
Partially automate release changelog 2021-03-18 16:38:41 -04:00
Jikoo 3ba82683ec
Fix double chest custom names not displaying
Closes #175
2021-03-17 00:09:10 -04:00
Jikoo 6e5c332272
Extract player implementation 2021-03-16 23:49:17 -04:00
Jikoo 1c9d133ed1
Fix item delete in own inventory
Dragging items across top and bottom inventories with own inventory open resulted in the overlapping content being deleted.
2021-03-16 23:49:10 -04:00
Jikoo dad1e16c18
Fix item dupe in own inventory
Reduce desync for other actions in own inventory

Closes #182
2021-03-16 12:14:47 -04:00
Jikoo 519dd7da33
Fix cache breaking build on Spigot version change 2021-03-16 09:45:29 -04:00
Adam 1bd7932cc5
Drop 1.8/1.15/1.16.3 support (#185)
With the recent uptick in requests for support by people running 1.12 who have recently updated past Java 9, I revisited the supported versions.

First, the "modern" versions: 1.15 is run by 2.9% of servers, 1.16.3 by 5%. Since all of these versions are supported to ease the transition of updating servers and servers have updated, there's no real reason to keep them around. It's a lot easier if you can update a plugin and just have it work on both versions rather than push all the plugin updates to master with the server update, but none of these versions have any reason for long-term support.

Regarding heavily outdated server software: As of the time of writing, 1.8 and 1.12 have market shares of 8.6% and 8.5% of servers respectively.
Regarding 1.8: 1.8 support is already a bit wonky - with the changes made to inventory names, it's not (easily) possible to bridge the gap, and future changes will make that more and more difficult. People use 1.8 because they disliked the 1.9 combat changes, but there are plugins that fully rework combat to how it used to be. I have yet to hear a compelling argument that cannot be resolved with plugins. In the interest of my own sanity (handling and backporting the inventory name change in particular was a real humdinger) I will no longer be backporting changes to 1.8.
Regarding 1.12: I am honestly not sure why people are not updating. I get it, 1.13 and the flattening was a rough transition, but pretty much every developer active at the time bridged the gap. If your server is heavily dependent on some software only available at that time, you can live with other software available at that time. At the time of 1.12's release, Java 9 was not released. Either update your server, downgrade Java, or fork OpenInv and backport Java 9 support yourself.
2021-03-16 09:34:41 -04:00
Telesphoreo c8d16a590f
Merge https://github.com/lishid/OpenInv 2020-12-19 14:15:48 -06:00
speed 352dd1bbc2
Merge lishid/master 2020-12-04 13:40:38 -05:00
Adam dad00d2d9c
build: Add action to build and automatically release files (#170)
Auto-release is gonna get a nice live test at a later date.
2020-11-26 11:05:45 -05:00
Jikoo 502f661be3
fix: Update 1.15 adapter to 1.15.2 2020-11-26 10:47:51 -05:00
Jikoo 804d30bcc7
tpyo 2020-11-15 14:33:28 -05:00
Jikoo db8b67082b
Fix up .gitignore a bit 2020-11-15 13:25:50 -05:00
Jikoo b2156edcc7
Fix mistake in InventoryAccess grabbing ender chest 2020-11-15 12:59:59 -05:00
Jikoo 45de495699
Simplify command executor assignment a little more 2020-11-15 12:26:36 -05:00
Jikoo f45d332727
Clarify download locations for older versions
Hopefully this will help people figure out where they've gone wrong. Maybe I should be stating supported versions in release notes too.
2020-11-15 12:22:25 -05:00
Telesphoreo 41c085c4d7 br 2020-11-08 19:14:08 -06:00
Telesphoreo 3f9f382af1 Merge https://github.com/lishid/OpenInv 2020-11-08 19:10:05 -06:00
Jikoo 9705cb156b
Bump version to 4.1.6-SNAPSHOT for development 2020-11-03 18:32:43 -05:00
Jikoo 1c45ef517f
Bump version to 4.1.5 for release 2020-11-03 18:32:11 -05:00
Jikoo 3fee84fc58
Add support for 1.16.4, drop 1.16.1 2020-11-03 18:19:34 -05:00
Telesphoreo 41693b5db0 thank you video, very cool! 2020-09-28 09:15:07 -05:00
Jikoo 00113cc4d4 These are my favorite version bumps 2020-09-15 13:47:12 -04:00
Jikoo 788f022e74 Mitigate some permissions confusion
For some reason, certain permissions plugins seem to not respect our declared default false nodes. To alleviate user confusion, these nodes will not be allowed to be used via wildcard internally.
2020-09-15 13:44:50 -04:00
Jikoo da55790fd2 Allow spectators to edit inventories
Requires permission OpenInv.spectate
Closes #155
2020-09-15 13:35:04 -04:00
Jikoo 1a6d513603 Reduce technical debt
* Reduce duplicate code
* Use more specific functional interfaces where available
* Fix some potential NPEs
* Remove some unnecessary/nonfunctional code
* Merge inventory listeners - no longer need to keep separate due to event availability
* Removed TODO items that probably won't ever be implemented. Good ideas, too drastic changes or too much work to maintain.
2020-09-15 12:51:49 -04:00
Jikoo a5b02ab26a Bump version to 4.1.5-SNAPSHOT for development 2020-08-22 12:22:00 -04:00
Jikoo 0c3ce2dfb3 Bump version to 4.1.4 for release 2020-08-22 12:21:22 -04:00
Jikoo a1f4649a09 Reword invalid version message, include releases link 2020-08-22 12:00:08 -04:00
Jikoo 100d0e12cd Update to 1.16.2 2020-08-12 00:06:20 -04:00
Jikoo 3e629798e5 Bump version to 4.1.4-SNAPSHOT for development 2020-07-15 23:23:31 -04:00
Jikoo 7c1f15974c Bump version to 4.1.3 for release 2020-07-15 23:23:03 -04:00
mfnalex d992237766
Add support for 3rd party plugins firing PlayerInteractEvent (#146)
* Add support for InvUnload

* generalize 3rd party plugins' event check
2020-07-15 22:38:38 -04:00
Jikoo c93464e643 Fix double chest loot generation with AnyContainer (#142) 2020-07-08 20:44:15 -04:00
Jikoo 56afefc82b Bump version to 4.1.3-SNAPSHOT for development 2020-06-25 19:40:07 -04:00
Jikoo f0a66570d2 Bump version to 4.1.2 for release 2020-06-25 19:39:38 -04:00
Jikoo 201a3578bf Add 1.16 support, drop 1.14 (#141) 2020-06-25 19:38:38 -04:00
Nathaniel Freeman 1228fc2de2 es_ES translation 2020-06-24 07:12:20 -04:00
NotMyFault 2561e75ae5 Fix typo 2020-06-02 19:01:33 -04:00
N0tMyFaultOG 80661b9465 Add german translation 2020-06-02 17:59:31 -04:00
Jikoo 53701da34f Bump version to 4.1.2-SNAPSHOT for development 2020-05-29 10:32:32 -04:00
Jikoo 9cf4712813 Bump version to 4.1.1 for release 2020-05-29 10:32:03 -04:00
Jikoo abe8fccdb5 Document new nodes 2020-05-29 10:27:50 -04:00
Jikoo 4499bb5453 Don't break behavior on existing setups
Permission to use /openinv and /openender will grant online/offline access so that existing permissions configurations do not have to be redone. Users looking to implement the new permissions will need to deny them.
2020-05-29 10:22:40 -04:00
Phoenix616 5405b7d7b9 Add permission for online/offline opening (Resolves #129) 2020-05-29 10:08:26 -04:00
129fc5e32c631b5007cb2cd8d45d416002b42bab 34199d12a4 Add localization for Brazilian Portuguese 2020-04-30 17:42:10 -04:00
Jikoo 67131ab9f9 Save after adding new keys 2020-04-24 10:47:51 -04:00
Jikoo 723381cb2b Fix IndexOutOfBounds on no args
Closes #128
2020-04-22 12:07:19 -04:00
Jikoo 34e7252d77 Correct lang + replacement mistake with inventory names 2020-04-19 18:04:10 -04:00
Jikoo a1b2df74cc Save existing vehicles if we had to load player (#22) 2020-04-19 17:54:45 -04:00
Jikoo 7210f9153e Bump version to 4.1.1-SNAPSHOT for development 2020-04-18 08:05:09 -04:00
Jikoo dcdfac0d3b Bump version to 4.1.0 for release 2020-04-18 08:04:38 -04:00
Jikoo c7b4554a6c It's been over 3 years :)
The common module was designed to prevent the internal modules depending on the core plugin. With the introduction of localization, this overcomplication became ever more exacerbated.
Probably will play around a bit more to remove freshly introduced static abuse before release.
Closes #61
2020-03-24 21:01:59 -04:00
Jikoo c51acb4e72 Add basic /searchcontainer
May be subject to change as I (very slowly) work towards console support for commands.
Closes #113
2020-03-15 10:43:08 -04:00
Jikoo 23d41cd6c8 Simplify and expand tab completion 2020-03-15 09:50:51 -04:00
Jikoo 8bc389496b Update cache for Java 8 2020-03-15 09:49:11 -04:00
Jikoo 1cc36d08bd Modify players before other plugins access them
Closes #123
2020-03-11 09:17:17 -04:00
Jikoo c8938f451d Update copyright 2020-02-01 08:03:15 -05:00
Jikoo 4f2665fedc Improve any/silent container commands
* Merged duplicate code
* Added on/off parameters - closes #120
* Added tab completion for parameters
2020-02-01 08:00:03 -05:00
unixminecraft 7d93bb06ad Updated /sc check command to correctly display if SilentChest is active or not. 2020-01-14 22:40:01 -05:00
Jikoo 19c491411f Bump version to 4.0.9-SNAPSHOT for development 2019-12-12 14:37:03 -05:00
Jikoo 65c6eb2693 Bump version to 4.0.8 for release 2019-12-12 14:36:38 -05:00
Jikoo ab1f4ace8a Fix AnyContainer breaking modified ender chest sizes 2019-12-12 14:33:42 -05:00
Jikoo e7dc52bee4 Drop support for 1.13, latest 2 versions only. 2019-12-12 14:21:33 -05:00
Jikoo a9c5799677 Merge branch 'master' of https://github.com/lishid/OpenInv 2019-12-12 13:59:38 -05:00
Andre LeBlanc 6d6257720a add support for 1.15 2019-12-12 13:59:12 -05:00
Andre LeBlanc 3e235fa688 add support for 1.15 2019-12-12 12:49:21 -05:00
Jikoo dd02355ac2 Properly remove SilentContainer viewers
Closes #115
2019-12-03 13:50:27 -05:00
Jikoo 4d3f5d67a8 Update copyright
Practically should make it 2020 at this rate, whoops

(cherry picked from commit ff76f2b95a)
2019-12-03 13:32:41 -05:00
Jikoo 7ad5faa2ce Clean up maven instructions
(cherry picked from commit b92543e078)
2019-12-03 13:32:37 -05:00
Jikoo c28383ef36 Work around 1.14 tab completion issues 2019-10-01 08:30:28 -04:00
Jikoo 5fbab1ab8f Bump version to 4.0.8-SNAPSHOT for development 2019-09-29 19:43:14 -04:00
Jikoo d97b092978 Bump version to 4.0.7 for release 2019-09-29 19:42:59 -04:00
Jikoo 154bf56c2a Include api-version in plugin.yml
Closes #111, #112
2019-09-29 19:40:06 -04:00
William Blake Galbreath d65a9caeb2 Add support for varying sizes of inventories 2019-08-01 21:04:23 -04:00
Jikoo b3c4253606 Bump version to 4.0.7-SNAPSHOT for development 2019-07-21 13:30:02 -04:00
Jikoo b64000e89b Bump version to 4.0.6 for release 2019-07-21 13:29:45 -04:00
Jikoo 3faf41ef18 More clear error when loot is not generated 2019-07-19 18:16:36 -04:00
Jikoo db27d25a93 More Bukkit API, less breaking with new versions 2019-07-19 18:14:14 -04:00
Jikoo 0f02e6fe66 Right, 1.13 is a thing 2019-07-19 18:12:06 -04:00
Jikoo ec07637e9f Bump version to 4.0.6-SNAPSHOT for development 2019-07-19 16:26:24 -04:00
Jikoo b269f3509c Bump version to 4.0.5 for release 2019-07-19 16:26:03 -04:00
Jikoo f2e4c8a3ad Fix barrel triggering AnyContainer (#108) 2019-07-19 16:24:58 -04:00
Jikoo 35839f1548 Bump version to 4.0.5-SNAPSHOT for development 2019-07-19 07:21:37 -04:00
Jikoo a4a462a1fa Bump version to 4.0.4 for release 2019-07-19 07:21:16 -04:00
Jikoo b9f901af66 Add silent barrels - fixes #106 2019-07-19 07:18:23 -04:00
Jikoo 1333056613 Correct item order - fixes #107 2019-07-19 07:13:11 -04:00
Jikoo fb23df313a Bump version to 4.0.4-SNAPSHOT for development 2019-05-27 20:53:44 -04:00
Jikoo 96dc400c83 Bump version to 4.0.3 for release 2019-05-27 20:53:02 -04:00
Jikoo b801d36f12 Turns out api-version below 1.13 is unsupported.
Compiling for 1.8, no api-version.
2019-05-27 20:52:49 -04:00
Jikoo 4c27599dd9 Bump version to 4.0.3-SNAPSHOT for development 2019-05-27 20:23:16 -04:00
Jikoo 64ad0a5267 Bump version to 4.0.2 for release 2019-05-27 20:22:50 -04:00
Jikoo cba7f44192 Include api-version in plugin.yml (Closes #102) 2019-05-27 20:22:02 -04:00
Jikoo e8ace6bd06 Update to 1.14.2 2019-05-27 20:12:39 -04:00
Jikoo fd70f260ba Fix mistake in string comparison utility 2019-05-27 20:05:58 -04:00
Jikoo be9874ba1d Fix pom changes causing Spigot API to be shaded into final jar 2019-05-27 20:05:06 -04:00
Jikoo 096faef161 Bump version to 4.0.2-SNAPSHOT for development 2019-05-15 19:20:50 -04:00
Jikoo df96d5106a Bump version to 4.0.1 for release 2019-05-15 19:20:25 -04:00
Jikoo fe77a1d2e7 Drop support for 1.14, add support for 1.14.1 2019-05-15 19:19:40 -04:00
Jikoo 3096e43540 Update to Java 8 and Minecraft 1.8.8 2019-05-05 22:20:43 -04:00
Jikoo 2939551d65 Delete modules for versions no longer being supported 2019-05-05 18:03:22 -04:00
Jikoo fb74fd3ced Bump version to 4.0.1-SNAPSHOT for development 2019-05-05 16:55:36 -04:00
Jikoo 393fe1d837 Bump version to 4.0.0 for release 2019-05-05 16:55:12 -04:00
Jikoo f80df9d83b Copy pasted javadocs are super great 2019-05-05 16:49:41 -04:00
Jikoo 5c006f8ebd QOL: Warn users when plugin is running on an unsupported version 2019-05-05 15:43:41 -04:00
Jikoo 57097e626e Reduce duplicate code in core plugin 2019-05-05 15:39:54 -04:00
Jikoo 0f266c8a64 Custom inventory titles for 1.14 2019-05-05 15:15:17 -04:00
Jikoo 185f037254 Revert API changes, fix SpecialPlayerInventory implementation 2019-05-05 12:40:47 -04:00
Jikoo e4d0020296 Update to 1.14 (#101) 2019-04-28 20:37:45 -04:00
Jikoo 9e37cbbca8 Prepare for 1.14
To continue providing renamed ender chests/player inventories we can no longer just provide an Inventory, a full InventoryView is required. To avoid confusion the old method has been removed entirely, leading to a major API revision bump.
2019-04-28 20:37:05 -04:00
Jikoo adc35e9ad5 Correct players not being properly released 2019-04-28 12:11:59 -04:00
Jikoo a469c732cc Store UUID instead of name for faster re-open lookups 2019-04-28 11:03:00 -04:00
Jikoo c5c1f47167 Hacky workaround for Java 9 reflection changes (#93) 2019-04-12 20:56:05 -04:00
Jikoo dc59356f76 Bump version to 3.3.8-SNAPSHOT for development 2019-01-18 18:36:28 -05:00
Jikoo d497772ad7 Bump version to 3.3.7 for release 2019-01-18 18:35:50 -05:00
Jikoo 4f4d46974a Support 1.13.2 (#94) 2019-01-15 20:01:41 -05:00
Jikoo 96c38895e2 Bump version to 3.3.7-SNAPSHOT for development 2018-08-26 14:47:13 -04:00
Jikoo 5753648d77 Bump version to 3.3.6 for release 2018-08-26 14:46:33 -04:00
Jikoo 3725711b94 Support Spigot 1.13.1 2018-08-26 14:43:21 -04:00
Jikoo c22e18c096 Correct unnecessary AnyContainer usage 2018-08-26 14:37:29 -04:00
Jikoo 6bff759d72 Bump version to 3.3.6-SNAPSHOT for development 2018-08-13 21:31:46 -04:00
Jikoo 582c7201dd Bump version to 3.3.5 for release 2018-08-13 21:31:17 -04:00
Jikoo 59a8ed70bb Correct double chest logic for Silent/AnyContainer in 1.13 2018-08-09 18:50:24 -04:00
Jikoo 27812c133d Bump version to 3.3.5-SNAPSHOT for development 2018-07-22 09:45:01 -04:00
Jikoo 165f3fb00e Bump version to 3.3.4 for release 2018-07-22 09:44:27 -04:00
Jikoo 60dcb64558 Bump version for alpha release 2018-07-15 12:05:52 -04:00
Jikoo 077b34d304 Support 1.13-pre7 2018-07-15 12:01:45 -04:00
Jikoo 8ce6e2f8d3 Reverse order of wildcard permission check, respect explicit values (#85) 2018-05-26 06:58:56 -04:00
Jikoo f5dce23f18 Bump version to 3.3.4-SNAPSHOT for development 2018-02-07 18:36:15 -05:00
Jikoo 669cfd72aa Bump version to 3.3.3 for release 2018-02-07 18:35:39 -05:00
Jikoo 9e66885690 First load should not "update" nonexistent config, just use a default 2018-02-07 18:17:33 -05:00
Jikoo a802769265 Sneaky tabs, trying to slip in there. 2018-02-04 10:35:35 -05:00
Jikoo 50c45b6616 Cleaned up code, updated copyright at long last. 2018-02-04 10:29:09 -05:00
Jikoo eaf01fa32c Don't cache simultaneously added players forever 2017-11-19 14:46:52 -05:00
Jikoo 4abaa6ea51 Backport spectate abuse to 1.8-1.10 to support PaperSpigot
This may break functionality on C(K)auldron and other server implementations with different remapping names.
2017-11-08 19:07:23 -05:00
Jikoo 7c621bf899 Bump version to 3.3.3-SNAPSHOT for development 2017-11-08 17:53:16 -05:00
Jikoo f5c682ff2b Bump version to 3.3.2 for release 2017-11-08 17:52:41 -05:00
Jikoo e652b43670 Classic mistake, changed my mind and only changed part of the code.
Also the actual mistake. Never forget. (#81)
2017-11-08 17:40:01 -05:00
Jikoo f07cef5621 Bump version to 3.3.2-SNAPSHOT for development 2017-11-07 18:18:33 -05:00
Jikoo ded6421e33 Bump version to 3.3.1 for release 2017-11-07 18:17:12 -05:00
Jikoo cbb2b4d232 Lowercase permissions can wait for a major version bump
I don't want to double our permissions checks for backwards compatibility.
2017-11-07 18:16:38 -05:00
Jikoo 48c61eeb82 Support lowercase permissions for consistency. 2017-11-06 19:23:26 -05:00
Jikoo e3d1af010b Add permissions to alter the default state of Any/SilentChest (#76) 2017-11-05 20:00:22 -05:00
Jikoo 2195677651 Actually fix CME (#71) 2017-08-06 16:35:18 -04:00
Jikoo c72af5dbac Bump version to 3.3.1-SNAPSHOT for development 2017-07-05 05:53:38 -04:00
Jikoo 931cdb6fb1 Bump version to 3.3.0 for release 2017-07-05 05:52:33 -04:00
Jikoo 9db18613a1 Abuse spectator mode for SilentContainer (#64, #68)
Potentially causes issues with Cauldron and similar mods that use different mapping names.
2017-07-04 13:22:03 -04:00
Jikoo 784935a975 Synchronize cache (for real), updated dependencies
Closes #69
2017-07-03 18:06:18 -04:00
Jikoo d9abe76531 Bump version to 3.2.2-SNAPSHOT for development 2017-06-09 20:21:30 -04:00
Jikoo ca85a392aa Correct field name for list of inventory contents (#66) 2017-06-09 20:15:51 -04:00
Jikoo 307f47e4d3 Bump version to 3.2.1-SNAPSHOT for development 2017-06-08 18:44:10 -04:00
Jikoo 96c59f163d Slightly improve API, bump version to 3.2.0 for release
Methods are now properly annotated @Nullable when they may return null. More descriptive exceptions are thrown when issues occur instead of just returning null.
2017-06-08 18:36:01 -04:00
Jikoo 01f147b13c Fix incorrect method call for checking if a block is occluding
Switched to using the API for statistic manipulation.
2017-06-08 18:26:26 -04:00
Jikoo 1c104b775f For improved compatibility, our own Levenshtein implementation 2017-05-28 09:53:59 -04:00
Jikoo 9a53e46dd3 Replaced modern profile with recent
Going forward, the primary file uploaded to Bukkit will probably be the smaller build made with the `recent` profile, supporting only the last 2 versions. The uberjar created by the `all` will be provided as an additional download. OpenInv v3.1.3-SNAPSHOT `all` uberjar currently is 276KB. The `recent` jar is only 81KB. It's getting silly, and will only continue to get worse.
2017-05-26 05:52:35 -04:00
Jikoo 6744e71127 Support 1.12-pre2 (#65) 2017-05-14 11:47:15 -04:00
Jikoo 12c3ebb798 Bump version to 3.1.3-SNAPSHOT for development 2017-02-13 20:02:12 -05:00
Jikoo 32ec8d8147 Bump version to 3.1.2 for release 2017-02-13 20:01:18 -05:00
Jikoo 443e0c489e Synchronize cache (#63) 2017-02-13 19:56:32 -05:00
Jikoo 7ab0003b62 Bump version to 3.1.2-SNAPSHOT for development 2017-01-30 13:38:36 -05:00
Jikoo 12c0cac311 Bump version to 3.1.1 for release 2017-01-30 13:38:10 -05:00
Jikoo f54481e872 Fix (NoSuchMethod)Exception being caught instead of NoSuchMethodError
Closes #62
2017-01-30 13:35:58 -05:00
Jikoo f27dd8a233 Bump version to 3.1.1-SNAPSHOT for development 2017-01-20 13:02:47 -05:00
Jikoo d6df1a0871 Bump version to 3.1.0 for release 2017-01-20 12:59:03 -05:00
Jikoo e34e51d127 Better support other Player implementations
Closes #60
Removed all volatile comments - they require me to occasionally manually maintain them and NMS/OBC imports are already kept separate
2017-01-20 12:56:31 -05:00
Jikoo 5ca2ae461a Properly use Maven versioning for better support of dependent plugins
Closes #59
Bumped version to 3.1.0-SNAPSHOT for development, really should have bumped the minor version a while back.
2017-01-17 18:06:35 -05:00
Jikoo 4095e8039d RIPo.bukkit.org
repo.bukkit.org is dead, Spigot doesn't host builds that old. Didn't realize that I'd installed it locally when compiling CB 1.4.5 to use with OpenInv. Whoops.

Corrected dependency order - no idea why this compiled at all before. My bad.
2017-01-15 08:08:51 -05:00
Jikoo 73f390ab20 Jitpack's Maven version is pretty outdated. Hopefully fixes build.
The `all` profile is no longer active by default, just in case.
2017-01-15 07:33:53 -05:00
Jikoo 2f7d3bc235 Call InventoryOpenEvent when using SilentChest
Backport fix for incorrect parameter as well, just in case.
Fixed 1.7 and lower forcing all chests' default names to be "Large chest" instead of the translatable string.
2017-01-10 14:12:58 -05:00
Jikoo ef486032f1 Fix incorrect parameter for SilentChest PacketPlayOutOpenWindow
Probably fixes issues with ProtocolSupport, and if it doesn't there's nothing else I can do as we'll be as close to identical to NMS as possible.
2017-01-10 12:50:24 -05:00
Jikoo 72ef873772 Fixes for shulker boxes and AnyChest in 1.11
Fixes IBlockData used being the default for a shulker box, closes #55
Corrected using wrong method to check if blocked in 1.11.2. Something something NMS version bumps.
2016-12-31 07:05:52 -05:00
Jikoo 9b6e32a775 Fix statistic changes breaking silent/anycontainer in 1.11.1+
C'mon Spigot team, this is why the revision bumps existed in the first place, to allow plugins that deal with NMS to easily and gracefully fail on unsupported versions. 1.11.1 should be R2, 1.11.2 should be R3. I get that NMS isn't officially supported, but honestly, either do away with the versioned packages entirely or keep up with them properly. It's a single string change, it's not like it's prohibitively difficult.
2016-12-29 09:05:01 -05:00
Jikoo f05110c9b8 Fix getOnlinePlayers call to support all versions
Moved IPlayerDataManager from api module to common module - it is not part of the API as there is no supported way to obtain an instance of it.
2016-12-22 09:55:51 -05:00
Jikoo a41f89b011 Release any players held by a disabling plugin 2016-12-16 15:13:04 -05:00
Jikoo d24827ffcb Allow plugins to indicate to OpenInv that a Player is in use
This allows API users to prevent issues caused by multiple different copies of the Player being loaded, such as #49. Multiple instances of the same player could be obtained by calling IOpenInv#loadPlayer, waiting for OpenInv to remove it from the cache, then calling the method again.
2016-12-14 19:49:18 -05:00
Jikoo 802ce28103 Fix issue caused by module cleanup while backporting awarding achievement 2016-12-05 19:02:43 -05:00
Jikoo f31356b227 Fix permissions mistakes in readme 2016-12-05 19:01:21 -05:00
Jikoo 7942466863 Maven cleanliness and API progress
The project was very messy and due to older Bukkit packaging conventions, 1_4_5 and 1_4_6 were sorted away from the rest of the versioned code. All of the versioned internals are now submodules of the internal module.
Rather than use the hackish existing method of abusing the shade plugin to combine "dependencies" for a dummy assembly project, we're actually using the assembly plugin.
Profiles are still split up between the parent pom and the internal module pom, but they're much more clean.

The API is now its own module and can be compiled and released as a separate file for developers. Soon, Bukkit ticket 20, you'll be closed.
2016-11-30 21:26:56 -05:00
Jikoo db2cade4e2 Don't convert names in config to UUIDs on the main thread
This is pretty messy, but I can't think of a better way to avoid saving about 5 times in a row. Then again, I did just wake up, so my brain may not be on point yet.
2016-11-27 17:30:39 -05:00
199 changed files with 5624 additions and 16791 deletions

13
.github/workflows/close-issue.yml vendored Normal file
View file

@ -0,0 +1,13 @@
name: Close Issue
on:
issues:
types: [opened]
jobs:
run:
runs-on: ubuntu-latest
steps:
- uses: peter-evans/close-issue@v1.0.3
with:
comment: "Per the notice in the readme, OpenInv is now being maintained at [Jikoo/OpenInv](https://github.com/Jikoo/OpenInv)."

13
.github/workflows/close-pr.yml vendored Normal file
View file

@ -0,0 +1,13 @@
name: Close Pull Request
on:
pull_request_target:
types: [opened]
jobs:
run:
runs-on: ubuntu-latest
steps:
- uses: superbrothers/close-pull-request@v3.1.0
with:
comment: "Per the notice in the readme, OpenInv is now being maintained at [Jikoo/OpenInv](https://github.com/Jikoo/OpenInv)."

14
.gitignore vendored
View file

@ -1,10 +1,10 @@
**/.settings
**/.gitignore
**/.project
**/.classpath
**/.idea
**/target
**/bin
**/lib
**/out
**dependency-reduced-pom.xml
**/.idea/
**.iml
**/target/
**/bin/
**/out/
**/dependency-reduced-pom.xml
**/pom.xml.versionsBackup

View file

@ -1,28 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinv</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>openinvadapter1_4_5</artifactId>
<name>OpenInvAdapter1_4_5</name>
<dependencies>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvplugin</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.4.5-R1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View file

@ -1,158 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_5;
import com.lishid.openinv.internal.IAnySilentContainer;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
// Volatile
import net.minecraft.server.v1_4_5.AxisAlignedBB;
import net.minecraft.server.v1_4_5.BlockEnderChest;
import net.minecraft.server.v1_4_5.EntityOcelot;
import net.minecraft.server.v1_4_5.EntityPlayer;
import net.minecraft.server.v1_4_5.IInventory;
import net.minecraft.server.v1_4_5.InventoryEnderChest;
import net.minecraft.server.v1_4_5.InventoryLargeChest;
import net.minecraft.server.v1_4_5.Packet100OpenWindow;
import net.minecraft.server.v1_4_5.TileEntityChest;
import net.minecraft.server.v1_4_5.TileEntityEnderChest;
import net.minecraft.server.v1_4_5.World;
import org.bukkit.craftbukkit.v1_4_5.entity.CraftPlayer;
public class AnySilentContainer implements IAnySilentContainer {
@Override
public boolean isAnySilentContainer(org.bukkit.block.Block block) {
return block.getType() == Material.ENDER_CHEST || block.getState() instanceof org.bukkit.block.Chest;
}
@Override
public boolean isAnyContainerNeeded(Player p, org.bukkit.block.Block block) {
// FOR REFERENCE, LOOK AT net.minecraft.server.BlockChest
EntityPlayer player = ((CraftPlayer) p).getHandle();
World world = player.world;
if (block instanceof BlockEnderChest) {
// Ender chests are not blocked by ocelots.
return world.t(block.getX(), block.getY() + 1, block.getZ());
}
// If block or ocelot on top
if (isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ())) {
return true;
}
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
// If block next to chest is chest and has a block or ocelot on top
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() + 1);
} else if(world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() - 1);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() + 1, block.getY() + 1, block.getZ());
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() - 1, block.getY() + 1, block.getZ());
}
return false;
}
private boolean isBlockedChest(World world, int x, int y, int z) {
return world.t(x, y + 1, z) || hasOcelotOnTop(world, x, y, z);
}
private boolean hasOcelotOnTop(World world, int x, int y, int z) {
for (Object localEntity : world.a(EntityOcelot.class,
AxisAlignedBB.a(x, y + 1, z, x + 1, y + 2, z + 1))) {
EntityOcelot localEntityOcelot = (EntityOcelot) localEntity;
if (localEntityOcelot.isSitting()) {
return true;
}
}
return false;
}
@Override
public boolean activateContainer(Player p, boolean silentchest, org.bukkit.block.Block block) {
EntityPlayer player = ((CraftPlayer) p).getHandle();
// Silent ender chest is API-only
if (silentchest && block.getType() == Material.ENDER_CHEST) {
p.openInventory(p.getEnderChest());
return true;
}
World world = player.world;
Object tile = world.getTileEntity(block.getX(), block.getY(), block.getZ());
if (tile == null) {
return false;
}
if (tile instanceof TileEntityEnderChest) {
// Anychest ender chest. See net.minecraft.server.BlockEnderChest
InventoryEnderChest enderChest = player.getEnderChest();
enderChest.a((TileEntityEnderChest) tile);
player.openContainer(enderChest);
return true;
}
if (!(tile instanceof IInventory)) {
return false;
}
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
tile = new InventoryLargeChest("Large chest", (IInventory) tile, (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() + 1));
} else if (world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
tile = new InventoryLargeChest("Large chest", (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() - 1), (IInventory) tile);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
tile = new InventoryLargeChest("Large chest", (IInventory) tile, (TileEntityChest) world.getTileEntity(block.getX() + 1, block.getY(), block.getZ()));
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
tile = new InventoryLargeChest("Large chest", (TileEntityChest) world.getTileEntity(block.getX() - 1, block.getY(), block.getZ()), (IInventory) tile);
}
boolean returnValue = false;
if (!silentchest) {
player.openContainer((IInventory) tile);
returnValue = true;
} else {
try {
int windowId = player.nextContainerCounter();
player.netServerHandler.sendPacket(new Packet100OpenWindow(windowId, 0, ((IInventory) tile).getName(), ((IInventory) tile).getSize()));
player.activeContainer = new SilentContainerChest(player.inventory, ((IInventory) tile));
player.activeContainer.windowId = windowId;
player.activeContainer.addSlotListener(player);
returnValue = true;
} catch (Exception e) {
e.printStackTrace();
p.sendMessage(ChatColor.RED + "Error while sending silent chest.");
}
}
return returnValue;
}
}

View file

@ -1,79 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_5;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.internal.InternalAccessor;
import org.bukkit.inventory.Inventory;
// Volatile
import net.minecraft.server.v1_4_5.IInventory;
import org.bukkit.craftbukkit.v1_4_5.inventory.CraftInventory;
public class InventoryAccess implements IInventoryAccess {
@Override
public boolean isSpecialPlayerInventory(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialPlayerInventory;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialPlayerInventory;
}
@Override
public ISpecialPlayerInventory getSpecialPlayerInventory(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialPlayerInventory) {
return (SpecialPlayerInventory) inv;
}
return null;
}
@Override
public boolean isSpecialEnderChest(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialEnderChest;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialEnderChest;
}
@Override
public ISpecialEnderChest getSpecialEnderChest(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialEnderChest) {
return (SpecialEnderChest) inv;
}
return null;
}
}

View file

@ -1,72 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_5;
import com.lishid.openinv.internal.IPlayerDataManager;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
// Volatile
import net.minecraft.server.v1_4_5.EntityPlayer;
import net.minecraft.server.v1_4_5.ItemInWorldManager;
import net.minecraft.server.v1_4_5.MinecraftServer;
import org.bukkit.craftbukkit.v1_4_5.CraftServer;
public class PlayerDataManager implements IPlayerDataManager {
@Override
public Player loadPlayer(OfflinePlayer offline) {
// Ensure the player has data
if (offline == null || !offline.hasPlayedBefore()) {
return null;
}
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
// Create an entity to load the player data
EntityPlayer entity = new EntityPlayer(server, server.getWorldServer(0), offline.getName(),
new ItemInWorldManager(server.getWorldServer(0)));
// Get the bukkit entity
Player target = (entity == null) ? null : entity.getBukkitEntity();
if (target != null) {
// Load data
target.loadData();
}
// Return the entity
return target;
}
@Override
public String getPlayerDataID(OfflinePlayer player) {
return player.getName();
}
@Override
public OfflinePlayer getPlayerByID(String identifier) {
OfflinePlayer player = Bukkit.getOfflinePlayer(identifier);
// Ensure player is a real player, otherwise return null
if (player == null || !player.hasPlayedBefore() && !player.isOnline()) {
return null;
}
return player;
}
}

View file

@ -1,46 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_5;
// Volatile
import net.minecraft.server.v1_4_5.ContainerChest;
import net.minecraft.server.v1_4_5.EntityHuman;
import net.minecraft.server.v1_4_5.IInventory;
import net.minecraft.server.v1_4_5.ItemStack;
import net.minecraft.server.v1_4_5.PlayerInventory;
public class SilentContainerChest extends ContainerChest {
public SilentContainerChest(IInventory i1, IInventory i2) {
super(i1, i2);
// Send close signal
i2.f();
}
@Override
public void b(EntityHuman entityHuman) {
// Don't send close signal twice, might screw up
PlayerInventory playerinventory = entityHuman.inventory;
if (playerinventory.getCarried() != null) {
ItemStack carried = playerinventory.getCarried();
playerinventory.setCarried(null);
entityHuman.drop(carried);
}
}
}

View file

@ -1,128 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_5;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.lishid.openinv.internal.ISpecialEnderChest;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
// Volatile
import net.minecraft.server.v1_4_5.IInventory;
import net.minecraft.server.v1_4_5.InventoryEnderChest;
import net.minecraft.server.v1_4_5.InventorySubcontainer;
import net.minecraft.server.v1_4_5.ItemStack;
import org.bukkit.craftbukkit.v1_4_5.entity.CraftHumanEntity;
import org.bukkit.craftbukkit.v1_4_5.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_4_5.inventory.CraftInventory;
public class SpecialEnderChest extends InventorySubcontainer implements IInventory, ISpecialEnderChest {
private final InventoryEnderChest enderChest;
private final CraftInventory inventory = new CraftInventory(this);
private final List<HumanEntity> transaction = new ArrayList<HumanEntity>();
private boolean playerOnline = false;
private CraftPlayer owner;
private int maxStack = MAX_STACK;
public SpecialEnderChest(Player p, Boolean online) {
super(((CraftPlayer) p).getHandle().getEnderChest().getName(),
((CraftPlayer) p).getHandle().getEnderChest().getSize());
CraftPlayer player = (CraftPlayer) p;
this.enderChest = player.getHandle().getEnderChest();
this.owner = player;
this.items = enderChest.getContents();
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
try {
owner = (CraftPlayer) player;
InventoryEnderChest playerEnderChest = owner.getHandle().getEnderChest();
Field field = playerEnderChest.getClass().getField("items");
field.setAccessible(true);
field.set(playerEnderChest, this.items);
} catch (Exception e) {}
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public ItemStack[] getContents() {
return this.items;
}
@Override
public void onOpen(CraftHumanEntity who) {
transaction.add(who);
}
@Override
public void onClose(CraftHumanEntity who) {
transaction.remove(who);
}
@Override
public List<HumanEntity> getViewers() {
return transaction;
}
@Override
public InventoryHolder getOwner() {
return this.owner;
}
@Override
public void setMaxStackSize(int size) {
maxStack = size;
}
@Override
public int getMaxStackSize() {
return maxStack;
}
@Override
public void update() {
super.update();
enderChest.update();
}
}

View file

@ -1,237 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_5;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
// Volatile
import net.minecraft.server.v1_4_5.ItemStack;
import net.minecraft.server.v1_4_5.PlayerInventory;
import org.bukkit.craftbukkit.v1_4_5.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_4_5.inventory.CraftInventory;
public class SpecialPlayerInventory extends PlayerInventory implements ISpecialPlayerInventory {
private final ItemStack[] extra = new ItemStack[5];
private final CraftInventory inventory = new CraftInventory(this);
private boolean playerOnline = false;
public SpecialPlayerInventory(Player bukkitPlayer, Boolean online) {
super(((CraftPlayer) bukkitPlayer).getHandle());
this.playerOnline = online;
this.items = player.inventory.items;
this.armor = player.inventory.armor;
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
this.player = ((CraftPlayer) player).getHandle();
this.player.inventory.items = this.items;
this.player.inventory.armor = this.armor;
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public ItemStack[] getContents() {
ItemStack[] contents = new ItemStack[getSize()];
System.arraycopy(items, 0, contents, 0, items.length);
System.arraycopy(armor, 0, contents, items.length, armor.length);
return contents;
}
@Override
public int getSize() {
return super.getSize() + 5;
}
@Override
public ItemStack getItem(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
}
else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
return is[i];
}
@Override
public ItemStack splitStack(int i, int j) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
}
else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (is[i] != null) {
ItemStack itemstack;
if (is[i].count <= j) {
itemstack = is[i];
is[i] = null;
return itemstack;
}
else {
itemstack = is[i].a(j);
if (is[i].count == 0) {
is[i] = null;
}
return itemstack;
}
}
else {
return null;
}
}
@Override
public ItemStack splitWithoutUpdate(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
}
else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (is[i] != null) {
ItemStack itemstack = is[i];
is[i] = null;
return itemstack;
}
else {
return null;
}
}
@Override
public void setItem(int i, ItemStack itemstack) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
}
else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
// Effects
if (is == this.extra) {
player.drop(itemstack);
itemstack = null;
}
is[i] = itemstack;
player.defaultContainer.b();
}
private int getReversedItemSlotNum(int i) {
if (i >= 27)
return i - 27;
else
return i + 9;
}
private int getReversedArmorSlotNum(int i) {
if (i == 0)
return 3;
if (i == 1)
return 2;
if (i == 2)
return 1;
if (i == 3)
return 0;
else
return i;
}
@Override
public String getName() {
if (player.getName().length() > 16) {
return player.getName().substring(0, 16);
}
return player.getName();
}
}

View file

@ -1,28 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinv</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>openinvadapter1_4_6</artifactId>
<name>OpenInvAdapter1_4_6</name>
<dependencies>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvplugin</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.4.6-R0.3</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View file

@ -1,158 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_6;
import com.lishid.openinv.internal.IAnySilentContainer;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
// Volatile
import net.minecraft.server.v1_4_6.AxisAlignedBB;
import net.minecraft.server.v1_4_6.BlockEnderChest;
import net.minecraft.server.v1_4_6.EntityOcelot;
import net.minecraft.server.v1_4_6.EntityPlayer;
import net.minecraft.server.v1_4_6.IInventory;
import net.minecraft.server.v1_4_6.InventoryEnderChest;
import net.minecraft.server.v1_4_6.InventoryLargeChest;
import net.minecraft.server.v1_4_6.Packet100OpenWindow;
import net.minecraft.server.v1_4_6.TileEntityChest;
import net.minecraft.server.v1_4_6.TileEntityEnderChest;
import net.minecraft.server.v1_4_6.World;
import org.bukkit.craftbukkit.v1_4_6.entity.CraftPlayer;
public class AnySilentContainer implements IAnySilentContainer {
@Override
public boolean isAnySilentContainer(org.bukkit.block.Block block) {
return block.getType() == Material.ENDER_CHEST || block.getState() instanceof org.bukkit.block.Chest;
}
@Override
public boolean isAnyContainerNeeded(Player p, org.bukkit.block.Block block) {
// FOR REFERENCE, LOOK AT net.minecraft.server.BlockChest
EntityPlayer player = ((CraftPlayer) p).getHandle();
World world = player.world;
if (block instanceof BlockEnderChest) {
// Ender chests are not blocked by ocelots.
return world.t(block.getX(), block.getY() + 1, block.getZ());
}
// If block or ocelot on top
if (isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ())) {
return true;
}
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
// If block next to chest is chest and has a block or ocelot on top
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() + 1);
} else if(world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() - 1);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() + 1, block.getY() + 1, block.getZ());
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() - 1, block.getY() + 1, block.getZ());
}
return false;
}
private boolean isBlockedChest(World world, int x, int y, int z) {
return world.t(x, y + 1, z) || hasOcelotOnTop(world, x, y, z);
}
private boolean hasOcelotOnTop(World world, int x, int y, int z) {
for (Object localEntity : world.a(EntityOcelot.class,
AxisAlignedBB.a(x, y + 1, z, x + 1, y + 2, z + 1))) {
EntityOcelot localEntityOcelot = (EntityOcelot) localEntity;
if (localEntityOcelot.isSitting()) {
return true;
}
}
return false;
}
@Override
public boolean activateContainer(Player p, boolean silentchest, org.bukkit.block.Block block) {
EntityPlayer player = ((CraftPlayer) p).getHandle();
// Silent ender chest is API-only
if (silentchest && block.getType() == Material.ENDER_CHEST) {
p.openInventory(p.getEnderChest());
return true;
}
World world = player.world;
Object tile = world.getTileEntity(block.getX(), block.getY(), block.getZ());
if (tile == null) {
return false;
}
if (tile instanceof TileEntityEnderChest) {
// Anychest ender chest. See net.minecraft.server.BlockEnderChest
InventoryEnderChest enderChest = player.getEnderChest();
enderChest.a((TileEntityEnderChest) tile);
player.openContainer(enderChest);
return true;
}
if (!(tile instanceof IInventory)) {
return false;
}
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
tile = new InventoryLargeChest("Large chest", (IInventory) tile, (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() + 1));
} else if (world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
tile = new InventoryLargeChest("Large chest", (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() - 1), (IInventory) tile);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
tile = new InventoryLargeChest("Large chest", (IInventory) tile, (TileEntityChest) world.getTileEntity(block.getX() + 1, block.getY(), block.getZ()));
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
tile = new InventoryLargeChest("Large chest", (TileEntityChest) world.getTileEntity(block.getX() - 1, block.getY(), block.getZ()), (IInventory) tile);
}
boolean returnValue = false;
if (!silentchest) {
player.openContainer((IInventory) tile);
returnValue = true;
} else {
try {
int windowId = player.nextContainerCounter();
player.playerConnection.sendPacket(new Packet100OpenWindow(windowId, 0, ((IInventory) tile).getName(), ((IInventory) tile).getSize()));
player.activeContainer = new SilentContainerChest(player.inventory, ((IInventory) tile));
player.activeContainer.windowId = windowId;
player.activeContainer.addSlotListener(player);
returnValue = true;
} catch (Exception e) {
e.printStackTrace();
p.sendMessage(ChatColor.RED + "Error while sending silent chest.");
}
}
return returnValue;
}
}

View file

@ -1,79 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_6;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.internal.InternalAccessor;
import org.bukkit.inventory.Inventory;
// Volatile
import net.minecraft.server.v1_4_6.IInventory;
import org.bukkit.craftbukkit.v1_4_6.inventory.CraftInventory;
public class InventoryAccess implements IInventoryAccess {
@Override
public boolean isSpecialPlayerInventory(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialPlayerInventory;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialPlayerInventory;
}
@Override
public ISpecialPlayerInventory getSpecialPlayerInventory(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialPlayerInventory) {
return (SpecialPlayerInventory) inv;
}
return null;
}
@Override
public boolean isSpecialEnderChest(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialEnderChest;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialEnderChest;
}
@Override
public ISpecialEnderChest getSpecialEnderChest(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialEnderChest) {
return (SpecialEnderChest) inv;
}
return null;
}
}

View file

@ -1,72 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_6;
import com.lishid.openinv.internal.IPlayerDataManager;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
// Volatile
import net.minecraft.server.v1_4_6.EntityPlayer;
import net.minecraft.server.v1_4_6.MinecraftServer;
import net.minecraft.server.v1_4_6.PlayerInteractManager;
import org.bukkit.craftbukkit.v1_4_6.CraftServer;
public class PlayerDataManager implements IPlayerDataManager {
@Override
public Player loadPlayer(OfflinePlayer offline) {
// Ensure the player has data
if (offline == null || !offline.hasPlayedBefore()) {
return null;
}
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
// Create an entity to load the player data
EntityPlayer entity = new EntityPlayer(server, server.getWorldServer(0), offline.getName(),
new PlayerInteractManager(server.getWorldServer(0)));
// Get the bukkit entity
Player target = (entity == null) ? null : entity.getBukkitEntity();
if (target != null) {
// Load data
target.loadData();
}
// Return the entity
return target;
}
@Override
public String getPlayerDataID(OfflinePlayer player) {
return player.getName();
}
@Override
public OfflinePlayer getPlayerByID(String identifier) {
OfflinePlayer player = Bukkit.getOfflinePlayer(identifier);
// Ensure player is a real player, otherwise return null
if (player == null || !player.hasPlayedBefore() && !player.isOnline()) {
return null;
}
return player;
}
}

View file

@ -1,46 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_6;
// Volatile
import net.minecraft.server.v1_4_6.ContainerChest;
import net.minecraft.server.v1_4_6.EntityHuman;
import net.minecraft.server.v1_4_6.IInventory;
import net.minecraft.server.v1_4_6.ItemStack;
import net.minecraft.server.v1_4_6.PlayerInventory;
public class SilentContainerChest extends ContainerChest {
public SilentContainerChest(IInventory i1, IInventory i2) {
super(i1, i2);
// Send close signal
i2.f();
}
@Override
public void b(EntityHuman entityHuman) {
// Don't send close signal twice, might screw up
PlayerInventory playerinventory = entityHuman.inventory;
if (playerinventory.getCarried() != null) {
ItemStack carried = playerinventory.getCarried();
playerinventory.setCarried(null);
entityHuman.drop(carried);
}
}
}

View file

@ -1,128 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_6;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.lishid.openinv.internal.ISpecialEnderChest;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
// Volatile
import net.minecraft.server.v1_4_6.IInventory;
import net.minecraft.server.v1_4_6.InventoryEnderChest;
import net.minecraft.server.v1_4_6.InventorySubcontainer;
import net.minecraft.server.v1_4_6.ItemStack;
import org.bukkit.craftbukkit.v1_4_6.entity.CraftHumanEntity;
import org.bukkit.craftbukkit.v1_4_6.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_4_6.inventory.CraftInventory;
public class SpecialEnderChest extends InventorySubcontainer implements IInventory, ISpecialEnderChest {
private final InventoryEnderChest enderChest;
private final CraftInventory inventory = new CraftInventory(this);
private final List<HumanEntity> transaction = new ArrayList<HumanEntity>();
private boolean playerOnline = false;
private CraftPlayer owner;
private int maxStack = MAX_STACK;
public SpecialEnderChest(Player p, Boolean online) {
super(((CraftPlayer) p).getHandle().getEnderChest().getName(),
((CraftPlayer) p).getHandle().getEnderChest().getSize());
CraftPlayer player = (CraftPlayer) p;
this.enderChest = player.getHandle().getEnderChest();
this.owner = player;
this.items = enderChest.getContents();
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
try {
owner = (CraftPlayer) player;
InventoryEnderChest playerEnderChest = owner.getHandle().getEnderChest();
Field field = playerEnderChest.getClass().getField("items");
field.setAccessible(true);
field.set(playerEnderChest, this.items);
} catch (Exception e) {}
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public ItemStack[] getContents() {
return this.items;
}
@Override
public void onOpen(CraftHumanEntity who) {
transaction.add(who);
}
@Override
public void onClose(CraftHumanEntity who) {
transaction.remove(who);
}
@Override
public List<HumanEntity> getViewers() {
return transaction;
}
@Override
public InventoryHolder getOwner() {
return this.owner;
}
@Override
public void setMaxStackSize(int size) {
maxStack = size;
}
@Override
public int getMaxStackSize() {
return maxStack;
}
@Override
public void update() {
super.update();
enderChest.update();
}
}

View file

@ -1,229 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_6;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
// Volatile
import net.minecraft.server.v1_4_6.ItemStack;
import net.minecraft.server.v1_4_6.PlayerInventory;
import org.bukkit.craftbukkit.v1_4_6.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_4_6.inventory.CraftInventory;
public class SpecialPlayerInventory extends PlayerInventory implements ISpecialPlayerInventory {
private final ItemStack[] extra = new ItemStack[5];
private final CraftInventory inventory = new CraftInventory(this);
private boolean playerOnline = false;
public SpecialPlayerInventory(Player bukkitPlayer, Boolean online) {
super(((CraftPlayer) bukkitPlayer).getHandle());
this.playerOnline = online;
this.items = player.inventory.items;
this.armor = player.inventory.armor;
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
this.player = ((CraftPlayer) player).getHandle();
this.player.inventory.items = this.items;
this.player.inventory.armor = this.armor;
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public ItemStack[] getContents() {
ItemStack[] contents = new ItemStack[getSize()];
System.arraycopy(items, 0, contents, 0, items.length);
System.arraycopy(armor, 0, contents, items.length, armor.length);
return contents;
}
@Override
public int getSize() {
return super.getSize() + 5;
}
@Override
public ItemStack getItem(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
return is[i];
}
@Override
public ItemStack splitStack(int i, int j) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (is[i] != null) {
ItemStack itemstack;
if (is[i].count <= j) {
itemstack = is[i];
is[i] = null;
return itemstack;
} else {
itemstack = is[i].a(j);
if (is[i].count == 0) {
is[i] = null;
}
return itemstack;
}
}
return null;
}
@Override
public ItemStack splitWithoutUpdate(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (is[i] != null) {
ItemStack itemstack = is[i];
is[i] = null;
return itemstack;
}
return null;
}
@Override
public void setItem(int i, ItemStack itemstack) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
// Effects
if (is == this.extra) {
player.drop(itemstack);
itemstack = null;
}
is[i] = itemstack;
player.defaultContainer.b();
}
private int getReversedItemSlotNum(int i) {
if (i >= 27) {
return i - 27;
}
return i + 9;
}
private int getReversedArmorSlotNum(int i) {
if (i == 0) {
return 3;
}
if (i == 1) {
return 2;
}
if (i == 2) {
return 1;
}
if (i == 3) {
return 0;
}
return i;
}
@Override
public String getName() {
if (player.getName().length() > 16) {
return player.getName().substring(0, 16);
}
return player.getName();
}
}

View file

@ -1,3 +1,6 @@
## Notice
I am now maintaining OpenInv over at [Jikoo/OpenInv](https://github.com/Jikoo/OpenInv) because I needed higher levels of access to add secrets to the repository for Github Actions. It feels ruder to send an email saying what amounts to "pls op" than to redirect people to my fork, though neither option is polite. Existing issues will remain open here until resolved (you can't transfer issues across organizations/users), but any new issues in this repo will be closed without resolution.
## About
OpenInv is a [Bukkit plugin](https://dev.bukkit.org/bukkit-plugins/openinv/) which allows users to open and edit anyone's inventory or ender chest - online or not!
@ -7,12 +10,12 @@ OpenInv is a [Bukkit plugin](https://dev.bukkit.org/bukkit-plugins/openinv/) whi
- Cross-world support! Don't grant `OpenInv.crossworld`
- No self-opening! Don't grant `OpenInv.openself`
- Drop items as the player! Place items in the unused slots to the right of the armor to drop them
- **OpenEnder**: Open anyone's inventory, even if they're offline.
- **OpenEnder**: Open anyone's ender chest, even if they're offline.
- Read-only mode! No edits allowed! Don't grant `OpenInv.editender`
- Cross-world support! Don't grant `OpenInv.crossworld`
- No self-opening! Don't grant `OpenInv.openself`
- **SilentChest**: Open containers without displaying an animation or making sound.
- **AnyChest**: Open containers, even if blocked by ocelots or blocks.
- No opening others! Don't grant `OpenInv.openenderall`
- **SilentContainer**: Open containers without displaying an animation or making sound.
- **AnyContainer**: Open containers, even if blocked by ocelots or blocks.
## Commands
<table width=100%>
@ -42,14 +45,19 @@ OpenInv is a [Bukkit plugin](https://dev.bukkit.org/bukkit-plugins/openinv/) whi
<td>Lists all online players that have a certain item in their ender chest.</td>
</tr>
<tr>
<td>/anychest [check]</td>
<td>ac</td>
<td>Check or toggle the AnyChest function, allowing opening blocked containers.</td>
<td>/searchenchant &lt[enchantment] [MinLevel]&gt</td>
<td>searchenchants</td>
<td>Lists all online players with a specific enchantment.</td>
</tr>
<tr>
<td>/silentchest [check]</td>
<td>sc</td>
<td>Check or toggle the SilentChest function, allowing opening containers silently.</td>
<td>/anycontainer [check]</td>
<td>ac, anychest</td>
<td>Check or toggle the AnyContainer function, allowing opening blocked containers.</td>
</tr>
<tr>
<td>/silentcontainer [check]</td>
<td>sc, silentchest</td>
<td>Check or toggle the SilentContainer function, allowing opening containers silently.</td>
</tr>
</table>
@ -75,12 +83,20 @@ OpenInv is a [Bukkit plugin](https://dev.bukkit.org/bukkit-plugins/openinv/) whi
<td>OpenInv.editinv</td>
<td>Required to make changes to open inventories.</td>
</tr>
<tr>
<td>OpenInv.openonline</td>
<td>Allows users to open online players' inventories. For compatibility reasons this is granted by the nodes OpenInv.openinv and OpenInv.openender.</td>
</tr>
<tr>
<td>OpenInv.openoffline</td>
<td>Allows users to open offline players' inventories. For compatibility reasons this is granted by the nodes OpenInv.openinv and OpenInv.openender.</td>
</tr>
<tr>
<td>OpenInv.openender</td>
<td>Required to use /openender.</td>
</tr>
<tr>
<td>OpenInv.editinv</td>
<td>OpenInv.editender</td>
<td>Required to make changes to open ender chests.</td>
</tr>
<tr>
@ -103,37 +119,57 @@ OpenInv is a [Bukkit plugin](https://dev.bukkit.org/bukkit-plugins/openinv/) whi
<td>OpenInv.search</td>
<td>Required to use /searchinv and /searchender.</td>
</tr>
<tr>
<td>OpenInv.searchenchant</td>
<td>Required to use /searchenchant.</td>
</tr>
<tr>
<td>OpenInv.anychest</td>
<td>Required to use /anychest.</td>
</tr>
<tr>
<td>OpenInv.any.default</td>
<td>Cause AnyContainer to be enabled by default.</td>
</tr>
<tr>
<td>OpenInv.silent</td>
<td>Required to use /silentchest.</td>
<td>Required to use /silentcontainer.</td>
</tr>
<tr>
<td>OpenInv.silent.default</td>
<td>Cause SilentContainer to be enabled by default.</td>
</tr>
<tr>
<td>OpenInv.spectate</td>
<td>Allows users in spectate gamemode to edit inventories.</td>
</tr>
</table>
## For Developers
To compile, the relevant Craftbukkit/Spigot jars must be installed in your local repository using the install plugin.
Ex: `mvn install:install-file -Dpackaging=jar -Dfile=spigot-1.11-R0.1-SNAPSHOT.jar -DgroupId=org.spigotmc -DartifactId=spigot -Dversion=1.11-R0.1-SNAPSHOT`
To compile, the relevant Craftbukkit/Spigot jars must be installed in your local repository using the install plugin.
Ex: `mvn install:install-file -Dpackaging=jar -Dfile=spigot-1.8-R0.1-SNAPSHOT.jar -DgroupId=org.spigotmc -DartifactId=spigot -Dversion=1.8-R0.1-SNAPSHOT`
Compiling OpenInv for a specific version is very easy - just compile the correct module.
To compile for a single version, specify the NMS revision you are targeting: `mvn -pl <NMS module> -am clean install`
Compiling for a set of versions is slightly more complex. You'll need to use a profile for the versions you want to compile. Provided profiles are latest, modern (versions 1.8+), and all. For more information, check out the [official guide](http://maven.apache.org/guides/introduction/introduction-to-profiles.html).
To compile for a set of versions, you'll need to use a profile. The only provided profile is `all`. Select a profile using the `-P` argument: `mvn clean package -am -P all`
For more information, check out the [official Maven guide](http://maven.apache.org/guides/introduction/introduction-to-profiles.html).
The final file is `target/OpenInv.jar`
## License
```
Copyright (C) 2011-2014 lishid. All rights reserved.
Copyright (C) 2011-2020 lishid. All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3.
the Free Software Foundation, version 3.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
```
```

57
api/pom.xml Normal file
View file

@ -0,0 +1,57 @@
<!--
~ Copyright (C) 2011-2020 lishid. All rights reserved.
~
~ This program is free software: you can redistribute it and/or modify
~ it under the terms of the GNU General Public License as published by
~ the Free Software Foundation, version 3.
~
~ This program is distributed in the hope that it will be useful,
~ but WITHOUT ANY WARRANTY; without even the implied warranty of
~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
~ GNU General Public License for more details.
~
~ You should have received a copy of the GNU General Public License
~ along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinvparent</artifactId>
<version>4.1.5-TF</version>
</parent>
<artifactId>openinvapi</artifactId>
<name>OpenInvAPI</name>
<dependencies>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>17.0.0</version>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.16.5-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View file

@ -0,0 +1,309 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv;
import com.lishid.openinv.internal.IAnySilentContainer;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.util.InventoryAccess;
import com.lishid.openinv.util.StringMetric;
import java.util.UUID;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryView;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Interface defining behavior for the OpenInv plugin.
*
* @author Jikoo
*/
public interface IOpenInv {
/**
* Check the configuration value for whether or not OpenInv saves player data when unloading
* players. This is exclusively for users who do not allow editing of inventories, only viewing,
* and wish to prevent any possibility of bugs such as lishid#40. If true, OpenInv will not ever
* save any edits made to players.
*
* @return false unless configured otherwise
*/
boolean disableSaving();
/**
* Gets the active ISilentContainer implementation.
*
* @return the ISilentContainer
* @throws IllegalStateException if the server version is unsupported
*/
@NotNull IAnySilentContainer getAnySilentContainer();
/**
* Gets the active IInventoryAccess implementation.
*
* @return the IInventoryAccess
* @throws IllegalStateException if the server version is unsupported
*/
@Deprecated
default @NotNull IInventoryAccess getInventoryAccess() {
return new InventoryAccess();
}
/**
* Gets the provided player's AnyChest setting.
*
* @param player the OfflinePlayer
* @return true if AnyChest is enabled
* @throws IllegalStateException if the server version is unsupported
*/
boolean getPlayerAnyChestStatus(@NotNull OfflinePlayer player);
/**
* Gets a unique identifier by which the OfflinePlayer can be referenced. Using the value
* returned to look up a Player will generally be much faster for later implementations.
*
* @param offline the OfflinePlayer
* @return the identifier
* @throws IllegalStateException if the server version is unsupported
*/
default @NotNull String getPlayerID(@NotNull OfflinePlayer offline) {
return offline.getUniqueId().toString();
}
/**
* Gets a player's SilentChest setting.
*
* @param offline the OfflinePlayer
* @return true if SilentChest is enabled
* @throws IllegalStateException if the server version is unsupported
*/
boolean getPlayerSilentChestStatus(@NotNull OfflinePlayer offline);
/**
* Gets an ISpecialEnderChest for the given Player.
*
* @param player the Player
* @param online true if the Player is currently online
* @return the ISpecialEnderChest
* @throws IllegalStateException if the server version is unsupported
* @throws InstantiationException if the ISpecialEnderChest could not be instantiated
*/
@NotNull ISpecialEnderChest getSpecialEnderChest(@NotNull Player player, boolean online) throws InstantiationException;
/**
* Gets an ISpecialPlayerInventory for the given Player.
*
* @param player the Player
* @param online true if the Player is currently online
* @return the ISpecialPlayerInventory
* @throws IllegalStateException if the server version is unsupported
* @throws InstantiationException if the ISpecialPlayerInventory could not be instantiated
*/
@NotNull ISpecialPlayerInventory getSpecialInventory(@NotNull Player player, boolean online) throws InstantiationException;
/**
* Checks if the server version is supported by OpenInv.
*
* @return true if the server version is supported
*/
boolean isSupportedVersion();
/**
* Load a Player from an OfflinePlayer. May return null under some circumstances.
*
* @param offline the OfflinePlayer to load a Player for
* @return the Player, or null
* @throws IllegalStateException if the server version is unsupported
*/
@Nullable Player loadPlayer(@NotNull final OfflinePlayer offline);
/**
* Get an OfflinePlayer by name.
* <p>
* Note: This method is potentially very heavily blocking. It should not ever be called on the
* main thread, and if it is, a stack trace will be displayed alerting server owners to the
* call.
*
* @param name the name of the Player
* @return the OfflinePlayer with the closest matching name or null if no players have ever logged in
*/
default @Nullable OfflinePlayer matchPlayer(@NotNull String name) {
// Warn if called on the main thread - if we resort to searching offline players, this may take several seconds.
if (Bukkit.getServer().isPrimaryThread()) {
this.getLogger().warning("Call to OpenInv#matchPlayer made on the main thread!");
this.getLogger().warning("This can cause the server to hang, potentially severely.");
this.getLogger().warning("Trace:");
for (StackTraceElement element : new Throwable().fillInStackTrace().getStackTrace()) {
this.getLogger().warning(element.toString());
}
}
OfflinePlayer player;
try {
UUID uuid = UUID.fromString(name);
player = Bukkit.getOfflinePlayer(uuid);
// Ensure player is a real player, otherwise return null
if (player.hasPlayedBefore() || player.isOnline()) {
return player;
}
} catch (IllegalArgumentException ignored) {
// Not a UUID
}
// Ensure name is valid if server is in online mode to avoid unnecessary searching
if (Bukkit.getServer().getOnlineMode() && !name.matches("[a-zA-Z0-9_]{3,16}")) {
return null;
}
player = Bukkit.getServer().getPlayerExact(name);
if (player != null) {
return player;
}
player = Bukkit.getServer().getOfflinePlayer(name);
if (player.hasPlayedBefore()) {
return player;
}
player = Bukkit.getServer().getPlayer(name);
if (player != null) {
return player;
}
float bestMatch = 0;
for (OfflinePlayer offline : Bukkit.getServer().getOfflinePlayers()) {
if (offline.getName() == null) {
// Loaded by UUID only, name has never been looked up.
continue;
}
float currentMatch = StringMetric.compareJaroWinkler(name, offline.getName());
if (currentMatch == 1.0F) {
return offline;
}
if (currentMatch > bestMatch) {
bestMatch = currentMatch;
player = offline;
}
}
// Only null if no players have played ever, otherwise even the worst match will do.
return player;
}
/**
* Open an ISpecialInventory for a Player.
*
* @param player the Player
* @param inventory the ISpecialInventory
* @return the InventoryView for the opened ISpecialInventory
*/
@Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory);
/**
* Check the configuration value for whether or not OpenInv displays a notification to the user
* when a container is activated with AnyChest.
*
* @return true unless configured otherwise
*/
boolean notifyAnyChest();
/**
* Check the configuration value for whether or not OpenInv displays a notification to the user
* when a container is activated with SilentChest.
*
* @return true unless configured otherwise
*/
boolean notifySilentChest();
/**
* Mark a Player as no longer in use by a Plugin to allow OpenInv to remove it from the cache
* when eligible.
*
* @param player the Player
* @param plugin the Plugin no longer holding a reference to the Player
* @throws IllegalStateException if the server version is unsupported
*/
void releasePlayer(@NotNull Player player, @NotNull Plugin plugin);
/**
* Mark a Player as in use by a Plugin to prevent it from being removed from the cache. Used to
* prevent issues with multiple copies of the same Player being loaded such as lishid#49.
* Changes made to loaded copies overwrite changes to the others when saved, leading to
* duplication bugs and more.
* <p>
* When finished with the Player object, be sure to call {@link #releasePlayer(Player, Plugin)}
* to prevent the cache from keeping it stored until the plugin is disabled.
* <p>
* When using a Player object from OpenInv, you must handle the Player coming online, replacing
* your Player reference with the Player from the PlayerJoinEvent. In addition, you must change
* any values in the Player to reflect any unsaved alterations to the existing Player which do
* not affect the inventory or ender chest contents.
* <p>
* OpenInv only saves player data when unloading a Player from the cache, and then only if
* {@link #disableSaving()} returns false. If you are making changes that OpenInv does not cause
* to persist when a Player logs in as noted above, it is suggested that you manually call
* {@link Player#saveData()} when releasing your reference to ensure your changes persist.
*
* @param player the Player
* @param plugin the Plugin holding the reference to the Player
* @throws IllegalStateException if the server version is unsupported
*/
void retainPlayer(@NotNull Player player, @NotNull Plugin plugin);
/**
* Sets a player's AnyChest setting.
*
* @param offline the OfflinePlayer
* @param status the status
* @throws IllegalStateException if the server version is unsupported
*/
void setPlayerAnyChestStatus(@NotNull OfflinePlayer offline, boolean status);
/**
* Sets a player's SilentChest setting.
*
* @param offline the OfflinePlayer
* @param status the status
* @throws IllegalStateException if the server version is unsupported
*/
void setPlayerSilentChestStatus(@NotNull OfflinePlayer offline, boolean status);
/**
* Forcibly unload a cached Player's data.
*
* @param offline the OfflinePlayer to unload
* @throws IllegalStateException if the server version is unsupported
*/
void unload(@NotNull OfflinePlayer offline);
Logger getLogger();
}

View file

@ -0,0 +1,61 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public interface IAnySilentContainer {
/**
* Opens the container at the given coordinates for the Player. If you do not want blocked
* containers to open, be sure to check {@link #isAnyContainerNeeded(Player, Block)}
* first.
*
* @param player the Player opening the container
* @param silent whether the container's noise is to be silenced
* @param block the Block
* @return true if the container can be opened
*/
boolean activateContainer(@NotNull Player player, boolean silent, @NotNull Block block);
/**
* Closes the Player's currently open container silently, if necessary.
*
* @param player the Player closing a container
*/
void deactivateContainer(@NotNull Player player);
/**
* Checks if the container at the given coordinates is blocked.
*
* @param player the Player opening the container
* @param block the Block
* @return true if the container is blocked
*/
boolean isAnyContainerNeeded(@NotNull Player player, @NotNull Block block);
/**
* Checks if the given block is a container which can be unblocked or silenced.
*
* @param block the BlockState
* @return true if the Block is a supported container
*/
boolean isAnySilentContainer(@NotNull Block block);
}

View file

@ -1,15 +1,15 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
@ -17,41 +17,48 @@
package com.lishid.openinv.internal;
import org.bukkit.inventory.Inventory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@Deprecated
public interface IInventoryAccess {
/**
* Check if an Inventory is an ISpecialPlayerInventory implementation.
*
* @param inventory the Inventory
* @return true if the Inventory is backed by an ISpecialPlayerInventory
*/
public boolean isSpecialPlayerInventory(Inventory inventory);
/**
* Gets an ISpecialPlayerInventory from an Inventory or null if the Inventory is not backed by
* an ISpecialPlayerInventory.
*
* @param inventory the Inventory
* @return the ISpecialPlayerInventory or null
*/
public ISpecialPlayerInventory getSpecialPlayerInventory(Inventory inventory);
/**
* Check if an Inventory is an ISpecialEnderChest implementation.
*
* @param inventory the Inventory
* @return true if the Inventory is backed by an ISpecialEnderChest
*/
public boolean isSpecialEnderChest(Inventory inventory);
/**
* Gets an ISpecialEnderChest from an Inventory or null if the Inventory is not backed by an
* ISpecialEnderChest.
*
*
* @param inventory the Inventory
* @return the ISpecialEnderChest or null
*/
public ISpecialEnderChest getSpecialEnderChest(Inventory inventory);
@Deprecated
@Nullable ISpecialEnderChest getSpecialEnderChest(@NotNull Inventory inventory);
/**
* Gets an ISpecialPlayerInventory from an Inventory or null if the Inventory is not backed by
* an ISpecialPlayerInventory.
*
* @param inventory the Inventory
* @return the ISpecialPlayerInventory or null
*/
@Deprecated
@Nullable ISpecialPlayerInventory getSpecialPlayerInventory(@NotNull Inventory inventory);
/**
* Check if an Inventory is an ISpecialEnderChest implementation.
*
* @param inventory the Inventory
* @return true if the Inventory is backed by an ISpecialEnderChest
*/
@Deprecated
boolean isSpecialEnderChest(@NotNull Inventory inventory);
/**
* Check if an Inventory is an ISpecialPlayerInventory implementation.
*
* @param inventory the Inventory
* @return true if the Inventory is backed by an ISpecialPlayerInventory
*/
@Deprecated
boolean isSpecialPlayerInventory(@NotNull Inventory inventory);
}

View file

@ -0,0 +1,21 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal;
public interface ISpecialEnderChest extends ISpecialInventory {
}

View file

@ -0,0 +1,51 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.jetbrains.annotations.NotNull;
public interface ISpecialInventory {
/**
* Gets the Inventory associated with this ISpecialInventory.
*
* @return the Inventory
*/
@NotNull Inventory getBukkitInventory();
/**
* Sets the Player associated with this ISpecialInventory online.
*
* @param player the Player coming online
*/
void setPlayerOnline(@NotNull Player player);
/**
* Sets the Player associated with this ISpecialInventory offline.
*/
void setPlayerOffline();
/**
* Gets whether or not this ISpecialInventory is in use.
*
* @return true if the ISpecialInventory is in use
*/
boolean isInUse();
}

View file

@ -0,0 +1,21 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal;
public interface ISpecialPlayerInventory extends ISpecialInventory {
}

View file

@ -0,0 +1,134 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.bukkit.Bukkit;
import org.bukkit.inventory.Inventory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class InventoryAccess implements IInventoryAccess {
private static Class<?> craftInventory = null;
private static Method getInventory = null;
static {
String packageName = Bukkit.getServer().getClass().getPackage().getName();
try {
craftInventory = Class.forName(packageName + ".inventory.CraftInventory");
} catch (ClassNotFoundException ignored) {}
try {
getInventory = craftInventory.getDeclaredMethod("getInventory");
} catch (NoSuchMethodException ignored) {}
}
/**
* @deprecated use {@link #isUsable()}
*/
@Deprecated
public static boolean isUseable() {
return isUsable();
}
public static boolean isUsable() {
return craftInventory != null && getInventory != null;
}
public static boolean isPlayerInventory(@NotNull Inventory inventory) {
return getPlayerInventory(inventory) != null;
}
public static @Nullable ISpecialPlayerInventory getPlayerInventory(@NotNull Inventory inventory) {
return getSpecialInventory(ISpecialPlayerInventory.class, inventory);
}
public static boolean isEnderChest(@NotNull Inventory inventory) {
return getEnderChest(inventory) != null;
}
public static @Nullable ISpecialEnderChest getEnderChest(@NotNull Inventory inventory) {
return getSpecialInventory(ISpecialEnderChest.class, inventory);
}
private static <T extends ISpecialInventory> @Nullable T getSpecialInventory(@NotNull Class<T> expected, @NotNull Inventory inventory) {
Object inv;
if (craftInventory != null && getInventory != null && craftInventory.isAssignableFrom(inventory.getClass())) {
try {
inv = getInventory.invoke(inventory);
if (expected.isInstance(inv)) {
return expected.cast(inv);
}
} catch (ReflectiveOperationException ignored) {}
}
inv = grabFieldOfTypeFromObject(expected, inventory);
if (expected.isInstance(inv)) {
return expected.cast(inv);
}
return null;
}
private static <T> @Nullable T grabFieldOfTypeFromObject(final Class<T> type, final Object object) {
// Use reflection to find the IInventory
Class<?> clazz = object.getClass();
T result = null;
for (Field f : clazz.getDeclaredFields()) {
f.setAccessible(true);
if (type.isAssignableFrom(f.getDeclaringClass())) {
try {
result = type.cast(f.get(object));
} catch (Exception e) {
e.printStackTrace();
}
}
}
return result;
}
@Deprecated
@Override
public @Nullable ISpecialEnderChest getSpecialEnderChest(@NotNull Inventory inventory) {
return getEnderChest(inventory);
}
@Deprecated
@Override
public @Nullable ISpecialPlayerInventory getSpecialPlayerInventory(@NotNull Inventory inventory) {
return getPlayerInventory(inventory);
}
@Deprecated
@Override
public boolean isSpecialEnderChest(@NotNull Inventory inventory) {
return isEnderChest(inventory);
}
@Deprecated
@Override
public boolean isSpecialPlayerInventory(@NotNull Inventory inventory) {
return isPlayerInventory(inventory);
}
}

View file

@ -0,0 +1,150 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
public class StringMetric {
public static float compareJaroWinkler(String a, String b) {
final float jaroScore = compareJaro(a, b);
if (jaroScore < (float) 0.7) {
return jaroScore;
}
String prefix = commonPrefix(a, b);
int prefixLength = Math.min(prefix.codePointCount(0, prefix.length()), 4);
return jaroScore + (prefixLength * (float) 0.1 * (1.0f - jaroScore));
}
private static float compareJaro(String a, String b) {
if (a.isEmpty() && b.isEmpty()) {
return 1.0f;
}
if (a.isEmpty() || b.isEmpty()) {
return 0.0f;
}
final int[] charsA = a.codePoints().toArray();
final int[] charsB = b.codePoints().toArray();
// Intentional integer division to round down.
final int halfLength = Math.max(0, Math.max(charsA.length, charsB.length) / 2 - 1);
final int[] commonA = getCommonCodePoints(charsA, charsB, halfLength);
final int[] commonB = getCommonCodePoints(charsB, charsA, halfLength);
// commonA and commonB will always contain the same multi-set of
// characters. Because getCommonCharacters has been optimized, commonA
// and commonB are -1-padded. So in this loop we count transposition
// and use commonCharacters to determine the length of the multi-set.
float transpositions = 0;
int commonCharacters = 0;
for (int length = commonA.length; commonCharacters < length
&& commonA[commonCharacters] > -1; commonCharacters++) {
if (commonA[commonCharacters] != commonB[commonCharacters]) {
transpositions++;
}
}
if (commonCharacters == 0) {
return 0.0f;
}
float aCommonRatio = commonCharacters / (float) charsA.length;
float bCommonRatio = commonCharacters / (float) charsB.length;
float transpositionRatio = (commonCharacters - transpositions / 2.0f) / commonCharacters;
return (aCommonRatio + bCommonRatio + transpositionRatio) / 3.0f;
}
/*
* Returns an array of code points from a within b. A character in b is
* counted as common when it is within separation distance from the position
* in a.
*/
private static int[] getCommonCodePoints(final int[] charsA, final int[] charsB, final int separation) {
final int[] common = new int[Math.min(charsA.length, charsB.length)];
final boolean[] matched = new boolean[charsB.length];
// Iterate of string a and find all characters that occur in b within
// the separation distance. Mark any matches found to avoid
// duplicate matchings.
int commonIndex = 0;
for (int i = 0, length = charsA.length; i < length; i++) {
final int character = charsA[i];
final int index = indexOf(character, charsB, i - separation, i
+ separation + 1, matched);
if (index > -1) {
common[commonIndex++] = character;
matched[index] = true;
}
}
if (commonIndex < common.length) {
common[commonIndex] = -1;
}
// Both invocations will yield the same multi-set terminated by -1, so
// they can be compared for transposition without making a copy.
return common;
}
/*
* Search for code point in buffer starting at fromIndex to toIndex - 1.
*
* Returns -1 when not found.
*/
private static int indexOf(int character, int[] buffer, int fromIndex, int toIndex, boolean[] matched) {
// compare char with range of characters to either side
for (int j = Math.max(0, fromIndex), length = Math.min(toIndex, buffer.length); j < length; j++) {
// check if found
if (buffer[j] == character && !matched[j]) {
return j;
}
}
return -1;
}
private static String commonPrefix(CharSequence a, CharSequence b) {
int maxPrefixLength = Math.min(a.length(), b.length());
int p;
p = 0;
while (p < maxPrefixLength && a.charAt(p) == b.charAt(p)) {
++p;
}
if (validSurrogatePairAt(a, p - 1) || validSurrogatePairAt(b, p - 1)) {
--p;
}
return a.subSequence(0, p).toString();
}
private static boolean validSurrogatePairAt(CharSequence string, int index) {
return index >= 0 && index <= string.length() - 2 && Character.isHighSurrogate(string.charAt(index)) && Character.isLowSurrogate(string.charAt(index + 1));
}
private StringMetric(){}
}

View file

@ -1,208 +1,58 @@
<!--
~ Copyright (C) 2011-2020 lishid. All rights reserved.
~
~ This program is free software: you can redistribute it and/or modify
~ it under the terms of the GNU General Public License as published by
~ the Free Software Foundation, version 3.
~
~ This program is distributed in the hope that it will be useful,
~ but WITHOUT ANY WARRANTY; without even the implied warranty of
~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
~ GNU General Public License for more details.
~
~ You should have received a copy of the GNU General Public License
~ along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinv</artifactId>
<version>1.0-SNAPSHOT</version>
<artifactId>openinvparent</artifactId>
<version>4.1.5-TF</version>
</parent>
<artifactId>openinvassembly</artifactId>
<name>OpenInvAssembly</name>
<profiles>
<profile>
<id>latest</id>
<dependencies>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_11_R1</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</profile>
<profile>
<id>modern</id>
<dependencies>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_8_R1</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_8_R2</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_8_R3</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_9_R1</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_9_R2</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_10_R1</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_11_R1</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</profile>
<profile>
<id>all</id>
<dependencies>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_4_5</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_4_6</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_4_R1</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_5_R2</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_5_R3</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_6_R1</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_6_R2</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_6_R3</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_7_R1</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_7_R2</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_7_R3</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_7_R4</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_8_R1</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_8_R2</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_8_R3</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_9_R1</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_9_R2</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_10_R1</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvadapter1_11_R1</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</profile>
</profiles>
<build>
<directory>../target</directory>
<finalName>OpenInv</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
<configuration>
<!--
~ This keeps the final file clean, but may cause issues for people not familiar with the setup.
~ If you're having trouble with the final product missing files, remove or tweak this configuration.
-->
<minimizeJar>true</minimizeJar>
<filters>
<filter>
<artifact>com.lishid:*</artifact>
<includes>
<include>com/lishid/openinv/**/*</include>
<include>plugin.yml</include>
</includes>
</filter>
</filters>
</configuration>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>reactor-uberjar</id>
<phase>package</phase>
<goals>
<goal>shade</goal>
<goal>single</goal>
</goals>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/reactor-uberjar.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
</project>

View file

@ -0,0 +1,44 @@
<!--
~ Copyright (C) 2011-2020 lishid. All rights reserved.
~
~ This program is free software: you can redistribute it and/or modify
~ it under the terms of the GNU General Public License as published by
~ the Free Software Foundation, version 3.
~
~ This program is distributed in the hope that it will be useful,
~ but WITHOUT ANY WARRANTY; without even the implied warranty of
~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
~ GNU General Public License for more details.
~
~ You should have received a copy of the GNU General Public License
~ along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd">
<id>reactor-uberjar</id>
<formats>
<format>jar</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<moduleSets>
<moduleSet>
<useAllReactorProjects>true</useAllReactorProjects>
<binaries>
<outputDirectory>/</outputDirectory>
<unpack>true</unpack>
<!-- unpackOptions must be present or build breaks. -->
<unpackOptions/>
</binaries>
</moduleSet>
</moduleSets>
</assembly>

View file

@ -1,23 +1,42 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!--
~ Copyright (C) 2011-2020 lishid. All rights reserved.
~
~ This program is free software: you can redistribute it and/or modify
~ it under the terms of the GNU General Public License as published by
~ the Free Software Foundation, version 3.
~
~ This program is distributed in the hope that it will be useful,
~ but WITHOUT ANY WARRANTY; without even the implied warranty of
~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
~ GNU General Public License for more details.
~
~ You should have received a copy of the GNU General Public License
~ along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinv</artifactId>
<version>1.0-SNAPSHOT</version>
<artifactId>openinvparent</artifactId>
<version>4.1.5-TF</version>
</parent>
<artifactId>openinvinternal</artifactId>
<name>OpenInvInternal</name>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.4.5-R1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<packaging>pom</packaging>
<profiles>
<profile>
<id>all</id>
<modules>
<module>v1_16_R3</module>
</modules>
</profile>
</profiles>
</project>

View file

@ -1,37 +0,0 @@
package com.lishid.openinv.internal;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
public interface IAnySilentContainer {
/**
* Checks if the given block is a container which can be unblocked or silenced.
*
* @param block the BlockState
* @return true if the Block is a supported container
*/
public boolean isAnySilentContainer(Block block);
/**
* Checks if the container at the given coordinates is blocked.
*
* @param player the Player opening the container
* @param block the Block
* @return true if the container is blocked
*/
public boolean isAnyContainerNeeded(Player player, Block block);
/**
* Opens the container at the given coordinates for the Player. If you do not want blocked
* containers to open, be sure to check {@link #isAnyContainerNeeded(Player, Block)}
* first.
*
* @param player
* @param silentchest whether the container's noise is to be silenced
* @param block the Block
* @return true if the container can be opened
*/
public boolean activateContainer(Player player, boolean silentchest, Block block);
}

View file

@ -1,50 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
public interface IPlayerDataManager {
/**
* Loads a Player for an OfflinePlayer.
* </p>
* This method is potentially blocking, and should not be called on the main thread.
*
* @param offline
* @return
*/
public Player loadPlayer(OfflinePlayer offline);
/**
* Gets a unique identifying string for an OfflinePlayer.
*
* @param player
* @return
*/
public String getPlayerDataID(OfflinePlayer player);
/**
* Gets an OfflinePlayer by the given unique identifier.
*
* @param identifier the unique identifier
* @return the OfflinePlayer, or null if no exact match was found
*/
public OfflinePlayer getPlayerByID(String identifier);
}

View file

@ -1,50 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
public interface ISpecialEnderChest {
/**
* Gets the Inventory associated with this ISpecialEnderChest.
*
* @return the Inventory
*/
public Inventory getBukkitInventory();
/**
* Sets the Player associated with this ISpecialEnderChest online.
*
* @param player the Player coming online
*/
public void setPlayerOnline(Player player);
/**
* Sets the Player associated with this ISpecialEnderChest offline.
*/
public void setPlayerOffline();
/**
* Gets whether or not this ISpecialEnderChest is in use.
*
* @return true if the ISpecialEnderChest is in use
*/
public boolean isInUse();
}

View file

@ -1,50 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
public interface ISpecialPlayerInventory {
/**
* Gets the Inventory associated with this ISpecialPlayerInventory.
*
* @return the Inventory
*/
public Inventory getBukkitInventory();
/**
* Sets the Player associated with this ISpecialPlayerInventory online.
*
* @param player the Player coming online
*/
public void setPlayerOnline(Player player);
/**
* Sets the Player associated with this ISpecialPlayerInventory offline.
*/
public void setPlayerOffline();
/**
* Gets whether or not this ISpecialPlayerInventory is in use.
*
* @return true if the ISpecialPlayerInventory is in use
*/
public boolean isInUse();
}

View file

@ -1,180 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class InternalAccessor {
private final Plugin plugin;
private final String version;
private boolean supported = false;
public InternalAccessor(Plugin plugin) {
this.plugin = plugin;
String packageName = plugin.getServer().getClass().getPackage().getName();
version = packageName.substring(packageName.lastIndexOf('.') + 1);
try {
Class.forName("com.lishid.openinv.internal." + version + ".PlayerDataManager");
supported = true;
} catch (Exception e) {}
}
/**
* Gets the server implementation version. If not initialized, returns the string "null"
* instead.
*
* @return the version, or "null"
*/
public String getVersion() {
return this.version != null ? this.version : "null";
}
/**
* Checks if the server implementation is supported.
*
* @return true if initialized for a supported server version
*/
public boolean isSupported() {
return this.supported;
}
/**
* Creates an instance of the IPlayerDataManager implementation for the current server version,
* or null if unsupported.
*
* @return the IPlayerDataManager
*/
public IPlayerDataManager newPlayerDataManager() {
return createObject(IPlayerDataManager.class, "PlayerDataManager");
}
/**
* Creates an instance of the IInventoryAccess implementation for the current server version, or
* null if unsupported.
*
* @return the IInventoryAccess
*/
public IInventoryAccess newInventoryAccess() {
return createObject(IInventoryAccess.class, "InventoryAccess");
}
/**
* Creates an instance of the IAnySilentContainer implementation for the current server version,
* or null if unsupported.
*
* @return the IAnySilentContainer
*/
public IAnySilentContainer newAnySilentContainer() {
return createObject(IAnySilentContainer.class, "AnySilentContainer");
}
/**
* Creates an instance of the ISpecialPlayerInventory implementation for the given Player, or
* null if the current version is unsupported.
*
* @param player the Player
* @param online true if the Player is online
* @return the ISpecialPlayerInventory created
*/
public ISpecialPlayerInventory newSpecialPlayerInventory(Player player, boolean online) {
return createObject(ISpecialPlayerInventory.class, "SpecialPlayerInventory", player, online);
}
/**
* Creates an instance of the ISpecialEnderChest implementation for the given Player, or
* null if the current version is unsupported.
*
* @param player the Player
* @param online true if the Player is online
* @return the ISpecialEnderChest created
*/
public ISpecialEnderChest newSpecialEnderChest(Player player, boolean online) {
return createObject(ISpecialEnderChest.class, "SpecialEnderChest", player, online);
}
private <T> T createObject(Class<? extends T> assignableClass, String className, Object... params) {
try {
// Check if internal versioned class exists
Class<?> internalClass = Class.forName("com.lishid.openinv.internal." + version + "." + className);
if (!assignableClass.isAssignableFrom(internalClass)) {
plugin.getLogger().warning("Found class " + internalClass.getName() + " but cannot cast to " + assignableClass.getName());
return null;
}
// Quick return: no parameters, no need to fiddle about finding the correct constructor.
if (params.length == 0) {
return assignableClass.cast(internalClass.getConstructor().newInstance());
}
// Search constructors for one matching the given parameters
nextConstructor: for (Constructor<?> constructor : internalClass.getConstructors()) {
Class<?>[] requiredClasses = constructor.getParameterTypes();
if (requiredClasses.length != params.length) {
continue;
}
for (int i = 0; i < params.length; ++i) {
if (!requiredClasses[i].isAssignableFrom(params[i].getClass())) {
continue nextConstructor;
}
}
return assignableClass.cast(constructor.newInstance(params));
}
StringBuilder message = new StringBuilder("Found class ").append(internalClass.getName())
.append(" but cannot find any matching constructors for [");
for (Object object : params) {
message.append(object.getClass().getName()).append(", ");
}
if (params.length > 0) {
message.delete(message.length() - 2, message.length());
}
plugin.getLogger().warning(message.append(']').toString());
} catch (Exception e) {
plugin.getLogger().warning("OpenInv encountered an error with the CraftBukkit version \"" + version + "\". Please look for an updated version of OpenInv.");
e.printStackTrace();
}
return null;
}
public static <T> T grabFieldOfTypeFromObject(Class<T> type, Object object) {
// Use reflection to find the iinventory
Class<?> clazz = object.getClass();
T result = null;
for (Field f : clazz.getDeclaredFields()) {
f.setAccessible(true);
if (type.isAssignableFrom(f.getDeclaringClass())) {
try {
result = type.cast(f.get(object));
} catch (Exception e) {
e.printStackTrace();
}
}
}
return result;
}
}

75
internal/v1_16_R3/pom.xml Normal file
View file

@ -0,0 +1,75 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (C) 2011-2020 lishid. All rights reserved.
~
~ This program is free software: you can redistribute it and/or modify
~ it under the terms of the GNU General Public License as published by
~ the Free Software Foundation, version 3.
~
~ This program is distributed in the hope that it will be useful,
~ but WITHOUT ANY WARRANTY; without even the implied warranty of
~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
~ GNU General Public License for more details.
~
~ You should have received a copy of the GNU General Public License
~ along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinvinternal</artifactId>
<version>4.1.5-TF</version>
</parent>
<artifactId>openinvadapter1_16_R3</artifactId>
<name>OpenInvAdapter1_16_R3</name>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.16.5-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvplugincore</artifactId>
<version>4.1.5-TF</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<minimizeJar>true</minimizeJar>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View file

@ -0,0 +1,343 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_16_R3;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.internal.IAnySilentContainer;
import java.lang.reflect.Field;
import net.minecraft.server.v1_16_R3.Block;
import net.minecraft.server.v1_16_R3.BlockBarrel;
import net.minecraft.server.v1_16_R3.BlockChest;
import net.minecraft.server.v1_16_R3.BlockChestTrapped;
import net.minecraft.server.v1_16_R3.BlockPosition;
import net.minecraft.server.v1_16_R3.BlockPropertyChestType;
import net.minecraft.server.v1_16_R3.BlockShulkerBox;
import net.minecraft.server.v1_16_R3.ChatMessage;
import net.minecraft.server.v1_16_R3.Container;
import net.minecraft.server.v1_16_R3.ContainerChest;
import net.minecraft.server.v1_16_R3.Containers;
import net.minecraft.server.v1_16_R3.EntityHuman;
import net.minecraft.server.v1_16_R3.EntityPlayer;
import net.minecraft.server.v1_16_R3.EnumGamemode;
import net.minecraft.server.v1_16_R3.IBlockData;
import net.minecraft.server.v1_16_R3.IChatBaseComponent;
import net.minecraft.server.v1_16_R3.ITileInventory;
import net.minecraft.server.v1_16_R3.InventoryEnderChest;
import net.minecraft.server.v1_16_R3.InventoryLargeChest;
import net.minecraft.server.v1_16_R3.PlayerInteractManager;
import net.minecraft.server.v1_16_R3.PlayerInventory;
import net.minecraft.server.v1_16_R3.TileEntity;
import net.minecraft.server.v1_16_R3.TileEntityChest;
import net.minecraft.server.v1_16_R3.TileEntityEnderChest;
import net.minecraft.server.v1_16_R3.TileEntityLootable;
import net.minecraft.server.v1_16_R3.TileInventory;
import net.minecraft.server.v1_16_R3.World;
import org.bukkit.Material;
import org.bukkit.Statistic;
import org.bukkit.block.Barrel;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.EnderChest;
import org.bukkit.block.ShulkerBox;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Directional;
import org.bukkit.block.data.type.Chest;
import org.bukkit.entity.Cat;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryView;
import org.bukkit.util.BoundingBox;
import org.jetbrains.annotations.NotNull;
public class AnySilentContainer implements IAnySilentContainer {
private Field playerInteractManagerGamemode;
public AnySilentContainer() {
try {
this.playerInteractManagerGamemode = PlayerInteractManager.class.getDeclaredField("gamemode");
this.playerInteractManagerGamemode.setAccessible(true);
} catch (NoSuchFieldException | SecurityException e) {
System.err.println("[OpenInv] Unable to directly write player gamemode! SilentChest will fail.");
e.printStackTrace();
}
}
@Override
public boolean isAnySilentContainer(@NotNull final org.bukkit.block.Block bukkitBlock) {
if (bukkitBlock.getType() == Material.ENDER_CHEST) {
return true;
}
BlockState state = bukkitBlock.getState();
return state instanceof org.bukkit.block.Chest
|| state instanceof org.bukkit.block.ShulkerBox
|| state instanceof org.bukkit.block.Barrel;
}
@Override
public boolean isAnyContainerNeeded(@NotNull final Player p, @NotNull final org.bukkit.block.Block block) {
BlockState blockState = block.getState();
// Barrels do not require AnyContainer.
if (blockState instanceof Barrel) {
return false;
}
// Enderchests require a non-occluding block on top to open.
if (blockState instanceof EnderChest) {
return block.getRelative(0, 1, 0).getType().isOccluding();
}
// Shulker boxes require 1/2 a block clear in the direction they open.
if (blockState instanceof ShulkerBox) {
BoundingBox boundingBox = block.getBoundingBox();
if (boundingBox.getVolume() > 1) {
// Shulker box is already open.
return false;
}
BlockData blockData = block.getBlockData();
if (!(blockData instanceof Directional)) {
// Shouldn't be possible. Just in case, demand AnyChest.
return true;
}
Directional directional = (Directional) blockData;
BlockFace face = directional.getFacing();
boundingBox.shift(face.getDirection());
// Return whether or not bounding boxes overlap.
return block.getRelative(face, 1).getBoundingBox().overlaps(boundingBox);
}
if (!(blockState instanceof org.bukkit.block.Chest)) {
return false;
}
if (isBlockedChest(block)) {
return true;
}
BlockData blockData = block.getBlockData();
if (!(blockData instanceof Chest) || ((Chest) blockData).getType() == Chest.Type.SINGLE) {
return false;
}
Chest chest = (Chest) blockData;
int ordinal = (chest.getFacing().ordinal() + 4 + (chest.getType() == Chest.Type.RIGHT ? -1 : 1)) % 4;
BlockFace relativeFace = BlockFace.values()[ordinal];
org.bukkit.block.Block relative = block.getRelative(relativeFace);
if (relative.getType() != block.getType()) {
return false;
}
BlockData relativeData = relative.getBlockData();
if (!(relativeData instanceof Chest)) {
return false;
}
Chest relativeChest = (Chest) relativeData;
if (relativeChest.getFacing() != chest.getFacing()
|| relativeChest.getType() != (chest.getType() == Chest.Type.RIGHT ? Chest.Type.LEFT : Chest.Type.RIGHT)) {
return false;
}
return isBlockedChest(relative);
}
private boolean isBlockedChest(org.bukkit.block.Block block) {
org.bukkit.block.Block relative = block.getRelative(0, 1, 0);
return relative.getType().isOccluding()
|| block.getWorld().getNearbyEntities(BoundingBox.of(relative), entity -> entity instanceof Cat).size() > 0;
}
@Override
public boolean activateContainer(@NotNull final Player bukkitPlayer, final boolean silentchest,
@NotNull final org.bukkit.block.Block bukkitBlock) {
// Silent ender chest is API-only
if (silentchest && bukkitBlock.getType() == Material.ENDER_CHEST) {
bukkitPlayer.openInventory(bukkitPlayer.getEnderChest());
bukkitPlayer.incrementStatistic(Statistic.ENDERCHEST_OPENED);
return true;
}
EntityPlayer player = PlayerDataManager.getHandle(bukkitPlayer);
final World world = player.world;
final BlockPosition blockPosition = new BlockPosition(bukkitBlock.getX(), bukkitBlock.getY(), bukkitBlock.getZ());
final TileEntity tile = world.getTileEntity(blockPosition);
if (tile == null) {
return false;
}
if (tile instanceof TileEntityEnderChest) {
// Anychest ender chest. See net.minecraft.server.BlockEnderChest
InventoryEnderChest enderChest = player.getEnderChest();
enderChest.a((TileEntityEnderChest) tile);
player.openContainer(new TileInventory((containerCounter, playerInventory, ignored) -> {
Containers<?> containers = PlayerDataManager.getContainers(enderChest.getSize());
int rows = enderChest.getSize() / 9;
return new ContainerChest(containers, containerCounter, playerInventory, enderChest, rows);
}, new ChatMessage("container.enderchest")));
bukkitPlayer.incrementStatistic(Statistic.ENDERCHEST_OPENED);
return true;
}
if (!(tile instanceof ITileInventory)) {
return false;
}
ITileInventory tileInventory = (ITileInventory) tile;
IBlockData blockData = world.getType(blockPosition);
Block block = blockData.getBlock();
if (block instanceof BlockChest) {
BlockPropertyChestType chestType = blockData.get(BlockChest.c);
if (chestType != BlockPropertyChestType.SINGLE) {
BlockPosition adjacentBlockPosition = blockPosition.shift(BlockChest.h(blockData));
IBlockData adjacentBlockData = world.getType(adjacentBlockPosition);
if (adjacentBlockData.getBlock() == block) {
BlockPropertyChestType adjacentChestType = adjacentBlockData.get(BlockChest.c);
if (adjacentChestType != BlockPropertyChestType.SINGLE && chestType != adjacentChestType
&& adjacentBlockData.get(BlockChest.FACING) == blockData.get(BlockChest.FACING)) {
TileEntity adjacentTile = world.getTileEntity(adjacentBlockPosition);
if (adjacentTile instanceof TileEntityChest && tileInventory instanceof TileEntityChest) {
TileEntityChest rightChest = chestType == BlockPropertyChestType.RIGHT ? ((TileEntityChest) tileInventory) : (TileEntityChest) adjacentTile;
TileEntityChest leftChest = chestType == BlockPropertyChestType.RIGHT ? (TileEntityChest) adjacentTile : ((TileEntityChest) tileInventory);
if (silentchest && (rightChest.lootTable != null || leftChest.lootTable != null)) {
OpenInv.getPlugin(OpenInv.class).sendSystemMessage(bukkitPlayer, "messages.error.lootNotGenerated");
return false;
}
tileInventory = new ITileInventory() {
public Container createMenu(int containerCounter, PlayerInventory playerInventory, EntityHuman entityHuman) {
leftChest.d(playerInventory.player);
rightChest.d(playerInventory.player);
return ContainerChest.b(containerCounter, playerInventory, new InventoryLargeChest(rightChest, leftChest));
}
public IChatBaseComponent getScoreboardDisplayName() {
if (leftChest.hasCustomName()) {
return leftChest.getScoreboardDisplayName();
}
if (rightChest.hasCustomName()) {
return rightChest.getScoreboardDisplayName();
}
return new ChatMessage("container.chestDouble");
}
};
}
}
}
}
if (block instanceof BlockChestTrapped) {
bukkitPlayer.incrementStatistic(Statistic.TRAPPED_CHEST_TRIGGERED);
} else {
bukkitPlayer.incrementStatistic(Statistic.CHEST_OPENED);
}
}
if (block instanceof BlockShulkerBox) {
bukkitPlayer.incrementStatistic(Statistic.SHULKER_BOX_OPENED);
}
if (block instanceof BlockBarrel) {
bukkitPlayer.incrementStatistic(Statistic.OPEN_BARREL);
}
// AnyChest only - SilentChest not active, container unsupported, or unnecessary.
if (!silentchest || player.playerInteractManager.getGameMode() == EnumGamemode.SPECTATOR) {
player.openContainer(tileInventory);
return true;
}
// SilentChest requires access to setting players' gamemode directly.
if (this.playerInteractManagerGamemode == null) {
return false;
}
if (tile instanceof TileEntityLootable) {
TileEntityLootable lootable = (TileEntityLootable) tile;
if (lootable.lootTable != null) {
OpenInv.getPlugin(OpenInv.class).sendSystemMessage(bukkitPlayer, "messages.error.lootNotGenerated");
return false;
}
}
EnumGamemode gamemode = player.playerInteractManager.getGameMode();
this.forceGameMode(player, EnumGamemode.SPECTATOR);
player.openContainer(tileInventory);
this.forceGameMode(player, gamemode);
return true;
}
@Override
public void deactivateContainer(@NotNull final Player bukkitPlayer) {
if (this.playerInteractManagerGamemode == null) {
return;
}
InventoryView view = bukkitPlayer.getOpenInventory();
switch (view.getType()) {
case CHEST:
case ENDER_CHEST:
case SHULKER_BOX:
case BARREL:
break;
default:
return;
}
EntityPlayer player = PlayerDataManager.getHandle(bukkitPlayer);
EnumGamemode gamemode = player.playerInteractManager.getGameMode();
this.forceGameMode(player, EnumGamemode.SPECTATOR);
player.activeContainer.b(player);
player.activeContainer.a(player, false);
player.activeContainer.transferTo(player.defaultContainer, player.getBukkitEntity());
player.activeContainer = player.defaultContainer;
this.forceGameMode(player, gamemode);
}
private void forceGameMode(final EntityPlayer player, final EnumGamemode gameMode) {
if (this.playerInteractManagerGamemode == null) {
// No need to warn repeatedly, error on startup and lack of function should be enough.
return;
}
try {
if (!this.playerInteractManagerGamemode.isAccessible()) {
// Just in case, ensure accessible.
this.playerInteractManagerGamemode.setAccessible(true);
}
this.playerInteractManagerGamemode.set(player.playerInteractManager, gameMode);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,69 @@
/*
* Copyright (C) 2011-2021 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_16_R3;
import java.io.File;
import java.io.FileOutputStream;
import net.minecraft.server.v1_16_R3.EntityPlayer;
import net.minecraft.server.v1_16_R3.NBTCompressedStreamTools;
import net.minecraft.server.v1_16_R3.NBTTagCompound;
import net.minecraft.server.v1_16_R3.WorldNBTStorage;
import org.apache.logging.log4j.LogManager;
import org.bukkit.craftbukkit.v1_16_R3.CraftServer;
import org.bukkit.craftbukkit.v1_16_R3.entity.CraftPlayer;
public class OpenPlayer extends CraftPlayer {
public OpenPlayer(CraftServer server, EntityPlayer entity) {
super(server, entity);
}
@Override
public void saveData() {
super.saveData();
EntityPlayer player = this.getHandle();
// See net.minecraft.server.WorldNBTStorage#save(EntityPlayer)
try {
WorldNBTStorage worldNBTStorage = player.server.getPlayerList().playerFileData;
NBTTagCompound playerData = player.save(new NBTTagCompound());
if (!isOnline()) {
// Special case: save old vehicle data
NBTTagCompound oldData = worldNBTStorage.load(player);
if (oldData != null && oldData.hasKeyOfType("RootVehicle", 10)) {
// See net.minecraft.server.PlayerList#a(NetworkManager, EntityPlayer) and net.minecraft.server.EntityPlayer#b(NBTTagCompound)
playerData.set("RootVehicle", oldData.getCompound("RootVehicle"));
}
}
File file = new File(worldNBTStorage.getPlayerDir(), player.getUniqueIDString() + ".dat.tmp");
File file1 = new File(worldNBTStorage.getPlayerDir(), player.getUniqueIDString() + ".dat");
NBTCompressedStreamTools.a(playerData, new FileOutputStream(file));
if (file1.exists() && !file1.delete() || !file.renameTo(file1)) {
LogManager.getLogger().warn("Failed to save player data for {}", player.getDisplayName().getString());
}
} catch (Exception e) {
LogManager.getLogger().warn("Failed to save player data for {}", player.getDisplayName().getString());
}
}
}

View file

@ -0,0 +1,237 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_16_R3;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.OpenInventoryView;
import com.mojang.authlib.GameProfile;
import java.lang.reflect.Field;
import net.minecraft.server.v1_16_R3.ChatComponentText;
import net.minecraft.server.v1_16_R3.Container;
import net.minecraft.server.v1_16_R3.Containers;
import net.minecraft.server.v1_16_R3.Entity;
import net.minecraft.server.v1_16_R3.EntityPlayer;
import net.minecraft.server.v1_16_R3.MinecraftServer;
import net.minecraft.server.v1_16_R3.PacketPlayOutOpenWindow;
import net.minecraft.server.v1_16_R3.PlayerInteractManager;
import net.minecraft.server.v1_16_R3.World;
import net.minecraft.server.v1_16_R3.WorldServer;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.craftbukkit.v1_16_R3.CraftServer;
import org.bukkit.craftbukkit.v1_16_R3.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_16_R3.event.CraftEventFactory;
import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftContainer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryView;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class PlayerDataManager implements IPlayerDataManager {
private @Nullable Field bukkitEntity;
public PlayerDataManager() {
try {
bukkitEntity = Entity.class.getDeclaredField("bukkitEntity");
} catch (NoSuchFieldException e) {
System.out.println("Unable to obtain field to inject custom save process - players' mounts may be deleted when loaded.");
e.printStackTrace();
bukkitEntity = null;
}
}
@NotNull
public static EntityPlayer getHandle(final Player player) {
if (player instanceof CraftPlayer) {
return ((CraftPlayer) player).getHandle();
}
Server server = player.getServer();
EntityPlayer nmsPlayer = null;
if (server instanceof CraftServer) {
nmsPlayer = ((CraftServer) server).getHandle().getPlayer(player.getName());
}
if (nmsPlayer == null) {
// Could use reflection to examine fields, but it's honestly not worth the bother.
throw new RuntimeException("Unable to fetch EntityPlayer from provided Player implementation");
}
return nmsPlayer;
}
@Nullable
@Override
public Player loadPlayer(@NotNull final OfflinePlayer offline) {
// Ensure player has data
if (!offline.hasPlayedBefore()) {
return null;
}
// Create a profile and entity to load the player data
// See net.minecraft.server.PlayerList#attemptLogin
GameProfile profile = new GameProfile(offline.getUniqueId(),
offline.getName() != null ? offline.getName() : offline.getUniqueId().toString());
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
WorldServer worldServer = server.getWorldServer(World.OVERWORLD);
if (worldServer == null) {
return null;
}
EntityPlayer entity = new EntityPlayer(server, worldServer, profile, new PlayerInteractManager(worldServer));
try {
injectPlayer(entity);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
// Get the bukkit entity
Player target = entity.getBukkitEntity();
if (target != null) {
// Load data
target.loadData();
}
// Return the entity
return target;
}
void injectPlayer(EntityPlayer player) throws IllegalAccessException {
if (bukkitEntity == null) {
return;
}
bukkitEntity.setAccessible(true);
bukkitEntity.set(player, new OpenPlayer(player.server.server, player));
}
@NotNull
@Override
public Player inject(@NotNull Player player) {
try {
EntityPlayer nmsPlayer = getHandle(player);
injectPlayer(nmsPlayer);
return nmsPlayer.getBukkitEntity();
} catch (IllegalAccessException e) {
e.printStackTrace();
return player;
}
}
@Nullable
@Override
public InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory) {
EntityPlayer nmsPlayer = getHandle(player);
if (nmsPlayer.playerConnection == null) {
return null;
}
InventoryView view = getView(player, inventory);
if (view == null) {
return player.openInventory(inventory.getBukkitInventory());
}
Container container = new CraftContainer(view, nmsPlayer, nmsPlayer.nextContainerCounter()) {
@Override
public Containers<?> getType() {
return getContainers(inventory.getBukkitInventory().getSize());
}
};
container.setTitle(new ChatComponentText(view.getTitle()));
container = CraftEventFactory.callInventoryOpenEvent(nmsPlayer, container);
if (container == null) {
return null;
}
nmsPlayer.playerConnection.sendPacket(new PacketPlayOutOpenWindow(container.windowId, container.getType(),
new ChatComponentText(container.getBukkitView().getTitle())));
nmsPlayer.activeContainer = container;
container.addSlotListener(nmsPlayer);
return container.getBukkitView();
}
private @Nullable InventoryView getView(Player player, ISpecialInventory inventory) {
if (inventory instanceof SpecialEnderChest) {
return new OpenInventoryView(player, inventory, "container.enderchest", "'s Ender Chest");
} else if (inventory instanceof SpecialPlayerInventory) {
return new OpenInventoryView(player, inventory, "container.player", "'s Inventory");
} else {
return null;
}
}
static @NotNull Containers<?> getContainers(int inventorySize) {
switch (inventorySize) {
case 9:
return Containers.GENERIC_9X1;
case 18:
return Containers.GENERIC_9X2;
case 36:
return Containers.GENERIC_9X4;
case 41: // PLAYER
case 45:
return Containers.GENERIC_9X5;
case 54:
return Containers.GENERIC_9X6;
case 27:
default:
return Containers.GENERIC_9X3;
}
}
@Override
public int convertToPlayerSlot(InventoryView view, int rawSlot) {
int topSize = view.getTopInventory().getSize();
if (topSize <= rawSlot) {
// Slot is not inside special inventory, use Bukkit logic.
return view.convertSlot(rawSlot);
}
// Main inventory, slots 0-26 -> 9-35
if (rawSlot < 27) {
return rawSlot + 9;
}
// Hotbar, slots 27-35 -> 0-8
if (rawSlot < 36) {
return rawSlot - 27;
}
// Armor, slots 36-39 -> 39-36
if (rawSlot < 40) {
return 36 + (39 - rawSlot);
}
// Off hand
if (rawSlot == 40) {
return 40;
}
// Drop slots, "out of inventory"
return -1;
}
}

View file

@ -0,0 +1,256 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_16_R3;
import com.lishid.openinv.internal.ISpecialEnderChest;
import java.util.List;
import net.minecraft.server.v1_16_R3.AutoRecipeStackManager;
import net.minecraft.server.v1_16_R3.ContainerUtil;
import net.minecraft.server.v1_16_R3.EntityHuman;
import net.minecraft.server.v1_16_R3.EntityPlayer;
import net.minecraft.server.v1_16_R3.IInventoryListener;
import net.minecraft.server.v1_16_R3.InventoryEnderChest;
import net.minecraft.server.v1_16_R3.ItemStack;
import net.minecraft.server.v1_16_R3.NonNullList;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_16_R3.entity.CraftHumanEntity;
import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftInventory;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryHolder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class SpecialEnderChest extends InventoryEnderChest implements ISpecialEnderChest {
private final CraftInventory inventory;
private EntityPlayer owner;
private NonNullList<ItemStack> items;
private boolean playerOnline;
public SpecialEnderChest(final Player player, final Boolean online) {
super(PlayerDataManager.getHandle(player));
this.inventory = new CraftInventory(this);
this.owner = PlayerDataManager.getHandle(player);
this.playerOnline = online;
this.items = this.owner.getEnderChest().items;
}
@Override
public @NotNull CraftInventory getBukkitInventory() {
return inventory;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public void setPlayerOffline() {
this.playerOnline = false;
}
@Override
public void setPlayerOnline(@NotNull final Player player) {
if (!this.playerOnline) {
try {
this.owner = PlayerDataManager.getHandle(player);
InventoryEnderChest enderChest = owner.getEnderChest();
for (int i = 0; i < enderChest.getSize(); ++i) {
enderChest.setItem(i, this.items.get(i));
}
this.items = enderChest.items;
} catch (Exception ignored) {}
this.playerOnline = true;
}
}
@Override
public void update() {
this.owner.getEnderChest().update();
}
@Override
public List<ItemStack> getContents() {
return this.items;
}
@Override
public void onOpen(CraftHumanEntity who) {
this.owner.getEnderChest().onOpen(who);
}
@Override
public void onClose(CraftHumanEntity who) {
this.owner.getEnderChest().onClose(who);
}
@Override
public List<HumanEntity> getViewers() {
return this.owner.getEnderChest().getViewers();
}
@Override
public void setMaxStackSize(int i) {
this.owner.getEnderChest().setMaxStackSize(i);
}
@Override
public InventoryHolder getOwner() {
return this.owner.getEnderChest().getOwner();
}
@Override
public @Nullable Location getLocation() {
return null;
}
@Override
public void a(IInventoryListener iinventorylistener) {
this.owner.getEnderChest().a(iinventorylistener);
}
@Override
public void b(IInventoryListener iinventorylistener) {
this.owner.getEnderChest().b(iinventorylistener);
}
@Override
public ItemStack getItem(int i) {
return i >= 0 && i < this.items.size() ? this.items.get(i) : ItemStack.b;
}
@Override
public ItemStack splitStack(int i, int j) {
ItemStack itemstack = ContainerUtil.a(this.items, i, j);
if (!itemstack.isEmpty()) {
this.update();
}
return itemstack;
}
@Override
public ItemStack a(ItemStack itemstack) {
ItemStack itemstack1 = itemstack.cloneItemStack();
for (int i = 0; i < this.getSize(); ++i) {
ItemStack itemstack2 = this.getItem(i);
if (itemstack2.isEmpty()) {
this.setItem(i, itemstack1);
this.update();
return ItemStack.b;
}
if (ItemStack.c(itemstack2, itemstack1)) {
int j = Math.min(this.getMaxStackSize(), itemstack2.getMaxStackSize());
int k = Math.min(itemstack1.getCount(), j - itemstack2.getCount());
if (k > 0) {
itemstack2.add(k);
itemstack1.subtract(k);
if (itemstack1.isEmpty()) {
this.update();
return ItemStack.b;
}
}
}
}
if (itemstack1.getCount() != itemstack.getCount()) {
this.update();
}
return itemstack1;
}
@Override
public ItemStack splitWithoutUpdate(int i) {
ItemStack itemstack = this.items.get(i);
if (itemstack.isEmpty()) {
return ItemStack.b;
} else {
this.items.set(i, ItemStack.b);
return itemstack;
}
}
@Override
public void setItem(int i, ItemStack itemstack) {
this.items.set(i, itemstack);
if (!itemstack.isEmpty() && itemstack.getCount() > this.getMaxStackSize()) {
itemstack.setCount(this.getMaxStackSize());
}
this.update();
}
@Override
public int getSize() {
return this.owner.getEnderChest().getSize();
}
@Override
public boolean isEmpty() {
for (ItemStack itemstack : this.items) {
if (!itemstack.isEmpty()) {
return false;
}
}
return true;
}
@Override
public int getMaxStackSize() {
return 64;
}
@Override
public boolean a(EntityHuman entityhuman) {
return true;
}
@Override
public void startOpen(EntityHuman entityhuman) {
}
@Override
public void closeContainer(EntityHuman entityhuman) {
}
@Override
public boolean b(int i, ItemStack itemstack) {
return true;
}
@Override
public void clear() {
this.items.clear();
}
@Override
public void a(AutoRecipeStackManager autorecipestackmanager) {
for (ItemStack itemstack : this.items) {
autorecipestackmanager.b(itemstack);
}
}
}

View file

@ -0,0 +1,733 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_16_R3;
import com.google.common.collect.ImmutableList;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.util.Iterator;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import net.minecraft.server.v1_16_R3.AutoRecipeStackManager;
import net.minecraft.server.v1_16_R3.ChatMessage;
import net.minecraft.server.v1_16_R3.ContainerUtil;
import net.minecraft.server.v1_16_R3.CrashReport;
import net.minecraft.server.v1_16_R3.CrashReportSystemDetails;
import net.minecraft.server.v1_16_R3.DamageSource;
import net.minecraft.server.v1_16_R3.EntityHuman;
import net.minecraft.server.v1_16_R3.EntityPlayer;
import net.minecraft.server.v1_16_R3.EnumItemSlot;
import net.minecraft.server.v1_16_R3.IBlockData;
import net.minecraft.server.v1_16_R3.IChatBaseComponent;
import net.minecraft.server.v1_16_R3.IInventory;
import net.minecraft.server.v1_16_R3.Item;
import net.minecraft.server.v1_16_R3.ItemArmor;
import net.minecraft.server.v1_16_R3.ItemStack;
import net.minecraft.server.v1_16_R3.NBTTagCompound;
import net.minecraft.server.v1_16_R3.NBTTagList;
import net.minecraft.server.v1_16_R3.NonNullList;
import net.minecraft.server.v1_16_R3.PacketPlayOutSetSlot;
import net.minecraft.server.v1_16_R3.PlayerInventory;
import net.minecraft.server.v1_16_R3.ReportedException;
import net.minecraft.server.v1_16_R3.World;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_16_R3.entity.CraftHumanEntity;
import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftInventory;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryHolder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class SpecialPlayerInventory extends PlayerInventory implements ISpecialPlayerInventory {
private final CraftInventory inventory;
private boolean playerOnline;
private EntityHuman player;
private NonNullList<ItemStack> items, armor, extraSlots;
private List<NonNullList<ItemStack>> f;
public SpecialPlayerInventory(final Player bukkitPlayer, final Boolean online) {
super(PlayerDataManager.getHandle(bukkitPlayer));
this.inventory = new CraftInventory(this);
this.playerOnline = online;
this.player = super.player;
this.items = this.player.inventory.items;
this.armor = this.player.inventory.armor;
this.extraSlots = this.player.inventory.extraSlots;
this.f = ImmutableList.of(this.items, this.armor, this.extraSlots);
}
@Override
public void setPlayerOnline(@NotNull final Player player) {
if (!this.playerOnline) {
EntityPlayer entityPlayer = PlayerDataManager.getHandle(player);
entityPlayer.inventory.transaction.addAll(this.transaction);
this.player = entityPlayer;
for (int i = 0; i < getSize(); ++i) {
this.player.inventory.setItem(i, getRawItem(i));
}
this.player.inventory.itemInHandIndex = this.itemInHandIndex;
this.items = this.player.inventory.items;
this.armor = this.player.inventory.armor;
this.extraSlots = this.player.inventory.extraSlots;
this.f = ImmutableList.of(this.items, this.armor, this.extraSlots);
this.playerOnline = true;
}
}
@Override
public boolean a(final EntityHuman entityhuman) {
return true;
}
@Override
public @NotNull CraftInventory getBukkitInventory() {
return this.inventory;
}
@Override
public ItemStack getItem(int i) {
List<ItemStack> list = this.items;
if (i >= list.size()) {
i -= list.size();
list = this.armor;
} else {
i = this.getReversedItemSlotNum(i);
}
if (i >= list.size()) {
i -= list.size();
list = this.extraSlots;
} else if (list == this.armor) {
i = this.getReversedArmorSlotNum(i);
}
if (i >= list.size()) {
return ItemStack.b;
}
return list.get(i);
}
private ItemStack getRawItem(int i) {
NonNullList<ItemStack> list = null;
for (NonNullList<ItemStack> next : this.f) {
if (i < next.size()) {
list = next;
break;
}
i -= next.size();
}
return list == null ? ItemStack.b : list.get(i);
}
@Override
public IChatBaseComponent getDisplayName() {
return new ChatMessage(this.player.getName());
}
@Override
public boolean hasCustomName() {
return false;
}
private int getReversedArmorSlotNum(final int i) {
if (i == 0) {
return 3;
}
if (i == 1) {
return 2;
}
if (i == 2) {
return 1;
}
if (i == 3) {
return 0;
}
return i;
}
private int getReversedItemSlotNum(final int i) {
if (i >= 27) {
return i - 27;
}
return i + 9;
}
@Override
public int getSize() {
return 45;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public void setItem(int i, final ItemStack itemstack) {
List<ItemStack> list = this.items;
if (i >= list.size()) {
i -= list.size();
list = this.armor;
} else {
i = this.getReversedItemSlotNum(i);
}
if (i >= list.size()) {
i -= list.size();
list = this.extraSlots;
} else if (list == this.armor) {
i = this.getReversedArmorSlotNum(i);
}
if (i >= list.size()) {
this.player.drop(itemstack, true);
return;
}
list.set(i, itemstack);
}
@Override
public void setPlayerOffline() {
this.playerOnline = false;
}
@Override
public ItemStack splitStack(int i, final int j) {
List<ItemStack> list = this.items;
if (i >= list.size()) {
i -= list.size();
list = this.armor;
} else {
i = this.getReversedItemSlotNum(i);
}
if (i >= list.size()) {
i -= list.size();
list = this.extraSlots;
} else if (list == this.armor) {
i = this.getReversedArmorSlotNum(i);
}
if (i >= list.size()) {
return ItemStack.b;
}
return list.get(i).isEmpty() ? ItemStack.b : ContainerUtil.a(list, i, j);
}
@Override
public ItemStack splitWithoutUpdate(int i) {
List<ItemStack> list = this.items;
if (i >= list.size()) {
i -= list.size();
list = this.armor;
} else {
i = this.getReversedItemSlotNum(i);
}
if (i >= list.size()) {
i -= list.size();
list = this.extraSlots;
} else if (list == this.armor) {
i = this.getReversedArmorSlotNum(i);
}
if (i >= list.size()) {
return ItemStack.b;
}
if (!list.get(i).isEmpty()) {
ItemStack itemstack = list.get(i);
list.set(i, ItemStack.b);
return itemstack;
}
return ItemStack.b;
}
@Override
public List<ItemStack> getContents() {
return this.f.stream().flatMap(List::stream).collect(Collectors.toList());
}
@Override
public List<ItemStack> getArmorContents() {
return this.armor;
}
@Override
public void onOpen(CraftHumanEntity who) {
this.transaction.add(who);
}
@Override
public void onClose(CraftHumanEntity who) {
this.transaction.remove(who);
}
@Override
public List<HumanEntity> getViewers() {
return this.transaction;
}
@Override
public InventoryHolder getOwner() {
return this.player.getBukkitEntity();
}
@Override
public Location getLocation() {
return this.player.getBukkitEntity().getLocation();
}
@Override
public ItemStack getItemInHand() {
return d(this.itemInHandIndex) ? this.items.get(this.itemInHandIndex) : ItemStack.b;
}
private boolean isSimilarAndNotFull(ItemStack itemstack, ItemStack itemstack1) {
return !itemstack.isEmpty() && this.b(itemstack, itemstack1) && itemstack.isStackable() && itemstack.getCount() < itemstack.getMaxStackSize() && itemstack.getCount() < this.getMaxStackSize();
}
private boolean b(ItemStack itemstack, ItemStack itemstack1) {
return itemstack.getItem() == itemstack1.getItem() && ItemStack.equals(itemstack, itemstack1);
}
@Override
public int canHold(ItemStack itemstack) {
int remains = itemstack.getCount();
for (int i = 0; i < this.items.size(); ++i) {
ItemStack itemstack1 = this.getItem(i);
if (itemstack1.isEmpty()) {
return itemstack.getCount();
}
if (!this.isSimilarAndNotFull(itemstack, itemstack1)) {
remains -= Math.min(itemstack1.getMaxStackSize(), this.getMaxStackSize()) - itemstack1.getCount();
}
if (remains <= 0) {
return itemstack.getCount();
}
}
ItemStack offhandItemStack = this.getItem(this.items.size() + this.armor.size());
if (this.isSimilarAndNotFull(offhandItemStack, itemstack)) {
remains -= Math.min(offhandItemStack.getMaxStackSize(), this.getMaxStackSize()) - offhandItemStack.getCount();
}
return itemstack.getCount() - remains;
}
@Override
public int getFirstEmptySlotIndex() {
for (int i = 0; i < this.items.size(); ++i) {
if (this.items.get(i).isEmpty()) {
return i;
}
}
return -1;
}
@Override
public void c(int i) {
this.itemInHandIndex = this.i();
ItemStack itemstack = this.items.get(this.itemInHandIndex);
this.items.set(this.itemInHandIndex, this.items.get(i));
this.items.set(i, itemstack);
}
@Override
public int c(ItemStack itemstack) {
for (int i = 0; i < this.items.size(); ++i) {
ItemStack itemstack1 = this.items.get(i);
if (!this.items.get(i).isEmpty() && this.b(itemstack, this.items.get(i)) && !this.items.get(i).f() && !itemstack1.hasEnchantments() && !itemstack1.hasName()) {
return i;
}
}
return -1;
}
@Override
public int i() {
int i;
int j;
for (j = 0; j < 9; ++j) {
i = (this.itemInHandIndex + j) % 9;
if (this.items.get(i).isEmpty()) {
return i;
}
}
for (j = 0; j < 9; ++j) {
i = (this.itemInHandIndex + j) % 9;
if (!this.items.get(i).hasEnchantments()) {
return i;
}
}
return this.itemInHandIndex;
}
@Override
public int a(Predicate<ItemStack> predicate, int i, IInventory iinventory) {
byte b0 = 0;
boolean flag = i == 0;
int j = b0 + ContainerUtil.a(this, predicate, i - b0, flag);
j += ContainerUtil.a(iinventory, predicate, i - j, flag);
j += ContainerUtil.a(this.getCarried(), predicate, i - j, flag);
if (this.getCarried().isEmpty()) {
this.setCarried(ItemStack.b);
}
return j;
}
private int i(ItemStack itemstack) {
int i = this.firstPartial(itemstack);
if (i == -1) {
i = this.getFirstEmptySlotIndex();
}
return i == -1 ? itemstack.getCount() : this.d(i, itemstack);
}
private int d(int i, ItemStack itemstack) {
Item item = itemstack.getItem();
int j = itemstack.getCount();
ItemStack itemstack1 = this.getItem(i);
if (itemstack1.isEmpty()) {
itemstack1 = new ItemStack(item, 0);
NBTTagCompound tag = itemstack.getTag();
if (tag != null) {
itemstack1.setTag(tag.clone());
}
this.setItem(i, itemstack1);
}
int k = j;
if (j > itemstack1.getMaxStackSize() - itemstack1.getCount()) {
k = itemstack1.getMaxStackSize() - itemstack1.getCount();
}
if (k > this.getMaxStackSize() - itemstack1.getCount()) {
k = this.getMaxStackSize() - itemstack1.getCount();
}
if (k != 0) {
j -= k;
itemstack1.add(k);
itemstack1.d(5);
}
return j;
}
@Override
public int firstPartial(ItemStack itemstack) {
if (this.isSimilarAndNotFull(this.getItem(this.itemInHandIndex), itemstack)) {
return this.itemInHandIndex;
} else if (this.isSimilarAndNotFull(this.getItem(40), itemstack)) {
return 40;
} else {
for (int i = 0; i < this.items.size(); ++i) {
if (this.isSimilarAndNotFull(this.items.get(i), itemstack)) {
return i;
}
}
return -1;
}
}
@Override
public void j() {
for (List<ItemStack> itemStacks : this.f) {
for (int i = 0; i < itemStacks.size(); ++i) {
if (!itemStacks.get(i).isEmpty()) {
itemStacks.get(i).a(this.player.world, this.player, i, this.itemInHandIndex == i);
}
}
}
}
@Override
public boolean pickup(ItemStack itemstack) {
return this.c(-1, itemstack);
}
@Override
public boolean c(int i, ItemStack itemstack) {
if (itemstack.isEmpty()) {
return false;
} else {
try {
if (itemstack.f()) {
if (i == -1) {
i = this.getFirstEmptySlotIndex();
}
if (i >= 0) {
this.items.set(i, itemstack.cloneItemStack());
this.items.get(i).d(5);
itemstack.setCount(0);
return true;
} else if (this.player.abilities.canInstantlyBuild) {
itemstack.setCount(0);
return true;
} else {
return false;
}
} else {
int j;
do {
j = itemstack.getCount();
if (i == -1) {
itemstack.setCount(this.i(itemstack));
} else {
itemstack.setCount(this.d(i, itemstack));
}
} while(!itemstack.isEmpty() && itemstack.getCount() < j);
if (itemstack.getCount() == j && this.player.abilities.canInstantlyBuild) {
itemstack.setCount(0);
return true;
} else {
return itemstack.getCount() < j;
}
}
} catch (Throwable var6) {
CrashReport crashreport = CrashReport.a(var6, "Adding item to inventory");
CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Item being added");
crashreportsystemdetails.a("Item ID", Item.getId(itemstack.getItem()));
crashreportsystemdetails.a("Item data", itemstack.getDamage());
crashreportsystemdetails.a("Item name", () -> itemstack.getName().getString());
throw new ReportedException(crashreport);
}
}
}
@Override
public void a(World world, ItemStack itemstack) {
if (!world.isClientSide) {
while(!itemstack.isEmpty()) {
int i = this.firstPartial(itemstack);
if (i == -1) {
i = this.getFirstEmptySlotIndex();
}
if (i == -1) {
this.player.drop(itemstack, false);
break;
}
int j = itemstack.getMaxStackSize() - this.getItem(i).getCount();
if (this.c(i, itemstack.cloneAndSubtract(j))) {
((EntityPlayer)this.player).playerConnection.sendPacket(new PacketPlayOutSetSlot(-2, i, this.getItem(i)));
}
}
}
}
@Override
public void f(ItemStack itemstack) {
for (List<ItemStack> list : this.f) {
for (int i = 0; i < list.size(); ++i) {
if (list.get(i) == itemstack) {
list.set(i, ItemStack.b);
break;
}
}
}
}
@Override
public float a(IBlockData iblockdata) {
return this.items.get(this.itemInHandIndex).a(iblockdata);
}
@Override
public NBTTagList a(NBTTagList nbttaglist) {
NBTTagCompound nbttagcompound;
int i;
for (i = 0; i < this.items.size(); ++i) {
if (!this.items.get(i).isEmpty()) {
nbttagcompound = new NBTTagCompound();
nbttagcompound.setByte("Slot", (byte) i);
this.items.get(i).save(nbttagcompound);
nbttaglist.add(nbttagcompound);
}
}
for (i = 0; i < this.armor.size(); ++i) {
if (!this.armor.get(i).isEmpty()) {
nbttagcompound = new NBTTagCompound();
nbttagcompound.setByte("Slot", (byte) (i + 100));
this.armor.get(i).save(nbttagcompound);
nbttaglist.add(nbttagcompound);
}
}
for (i = 0; i < this.extraSlots.size(); ++i) {
if (!this.extraSlots.get(i).isEmpty()) {
nbttagcompound = new NBTTagCompound();
nbttagcompound.setByte("Slot", (byte) (i + 150));
this.extraSlots.get(i).save(nbttagcompound);
nbttaglist.add(nbttagcompound);
}
}
return nbttaglist;
}
@Override
public void b(NBTTagList nbttaglist) {
this.items.clear();
this.armor.clear();
this.extraSlots.clear();
for(int i = 0; i < nbttaglist.size(); ++i) {
NBTTagCompound nbttagcompound = nbttaglist.getCompound(i);
int j = nbttagcompound.getByte("Slot") & 255;
ItemStack itemstack = ItemStack.a(nbttagcompound);
if (!itemstack.isEmpty()) {
if (j < this.items.size()) {
this.items.set(j, itemstack);
} else if (j >= 100 && j < this.armor.size() + 100) {
this.armor.set(j - 100, itemstack);
} else if (j >= 150 && j < this.extraSlots.size() + 150) {
this.extraSlots.set(j - 150, itemstack);
}
}
}
}
@Override
public boolean isEmpty() {
Iterator<ItemStack> iterator = this.items.iterator();
ItemStack itemstack;
while (iterator.hasNext()) {
itemstack = iterator.next();
if (!itemstack.isEmpty()) {
return false;
}
}
iterator = this.armor.iterator();
while (iterator.hasNext()) {
itemstack = iterator.next();
if (!itemstack.isEmpty()) {
return false;
}
}
iterator = this.extraSlots.iterator();
while (iterator.hasNext()) {
itemstack = iterator.next();
if (!itemstack.isEmpty()) {
return false;
}
}
return true;
}
@Nullable
@Override
public IChatBaseComponent getCustomName() {
return null;
}
@Override
public void a(DamageSource damagesource, float f) {
if (f > 0.0F) {
f /= 4.0F;
if (f < 1.0F) {
f = 1.0F;
}
for (int i = 0; i < this.armor.size(); ++i) {
ItemStack itemstack = this.armor.get(0);
int index = i;
if ((!damagesource.isFire() || !itemstack.getItem().u()) && itemstack.getItem() instanceof ItemArmor) {
itemstack.damage((int) f, this.player, (entityHuman) -> entityHuman.broadcastItemBreak(EnumItemSlot.a(EnumItemSlot.Function.ARMOR, index)));
}
}
}
}
@Override
public void dropContents() {
for (List<ItemStack> itemStacks : this.f) {
for (int i = 0; i < itemStacks.size(); ++i) {
ItemStack itemstack = itemStacks.get(i);
if (!itemstack.isEmpty()) {
itemStacks.set(i, ItemStack.b);
this.player.a(itemstack, true, false);
}
}
}
}
@Override
public boolean h(ItemStack itemstack) {
return this.f.stream().flatMap(List::stream).anyMatch(itemStack1 -> !itemStack1.isEmpty() && itemStack1.doMaterialsMatch(itemstack));
}
@Override
public void a(PlayerInventory playerinventory) {
for (int i = 0; i < playerinventory.getSize(); ++i) {
this.setItem(i, playerinventory.getItem(i));
}
this.itemInHandIndex = playerinventory.itemInHandIndex;
}
@Override
public void clear() {
this.f.forEach(List::clear);
}
@Override
public void a(AutoRecipeStackManager autorecipestackmanager) {
for (ItemStack itemstack : this.items) {
autorecipestackmanager.a(itemstack);
}
}
}

View file

@ -1,28 +1,43 @@
<!--
~ Copyright (C) 2011-2020 lishid. All rights reserved.
~
~ This program is free software: you can redistribute it and/or modify
~ it under the terms of the GNU General Public License as published by
~ the Free Software Foundation, version 3.
~
~ This program is distributed in the hope that it will be useful,
~ but WITHOUT ANY WARRANTY; without even the implied warranty of
~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
~ GNU General Public License for more details.
~
~ You should have received a copy of the GNU General Public License
~ along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinv</artifactId>
<version>1.0-SNAPSHOT</version>
<artifactId>openinvparent</artifactId>
<version>4.1.5-TF</version>
</parent>
<artifactId>openinvplugin</artifactId>
<artifactId>openinvplugincore</artifactId>
<name>OpenInvPlugin</name>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<!-- Really should use 1.4.5-R1.0, but the InventoryDragEvent doesn't exist. TODO separate module? -->
<version>1.11-R0.1-SNAPSHOT</version>
<scope>provided</scope>
<groupId>com.lishid</groupId>
<artifactId>openinvapi</artifactId>
<version>4.1.5-TF</version>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvinternal</artifactId>
<version>1.0-SNAPSHOT</version>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.15.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
@ -33,6 +48,33 @@
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<minimizeJar>true</minimizeJar>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
</project>

View file

@ -1,137 +0,0 @@
package com.lishid.openinv;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.ConfigurationSection;
public class ConfigUpdater {
private static final int CONFIG_VERSION = 3;
private final OpenInv plugin;
public ConfigUpdater(OpenInv plugin) {
this.plugin = plugin;
}
private int getConfigVersion() {
return plugin.getConfig().getInt("config-version", 1);
}
private boolean isConfigOutdated() {
return getConfigVersion() < CONFIG_VERSION;
}
public void checkForUpdates() {
if (isConfigOutdated()) {
plugin.getLogger().info("Configuration update found! Performing update...");
performUpdate();
plugin.getLogger().info("Configuration update complete!");
}
}
private void performUpdate() {
// Update according to the right version
switch (getConfigVersion()) {
case 1:
updateConfig1To2();
case 2:
updateConfig2To3();
break;
}
}
private void updateConfig2To3() {
plugin.getConfig().set("config-version", 3);
plugin.getConfig().set("items.open-inv", null);
plugin.getConfig().set("toggles.items.open-inv", null);
plugin.getConfig().set("settings.disable-saving", plugin.getConfig().getBoolean("DisableSaving", false));
plugin.getConfig().set("DisableSaving", null);
// Save the new config
plugin.saveConfig();
}
private void updateConfig1To2() {
// Backup the old config file
try {
plugin.getConfig().save(new File(plugin.getDataFolder(), "config_old.yml"));
plugin.getLogger().info("Backed up config.yml to config_old.yml before updating.");
} catch (IOException e) {
plugin.getLogger().warning("Could not back up config.yml before updating!");
}
// Get the old config settings
int itemOpenInvItemId = plugin.getConfig().getInt("ItemOpenInvItemID", 280);
plugin.getConfig().set("ItemOpenInvItemID", null);
boolean notifySilentChest = plugin.getConfig().getBoolean("NotifySilentChest", true);
plugin.getConfig().set("NotifySilentChest", null);
boolean notifyAnyChest = plugin.getConfig().getBoolean("NotifyAnyChest", true);
plugin.getConfig().set("NotifyAnyChest", null);
updateToggles("AnyChest", ".toggle", "toggles.any-chest");
updateToggles("ItemOpenInv", ".toggle", "toggles.items.open-inv");
updateToggles("SilentChest", ".toggle", "toggles.silent-chest");
plugin.getConfig().set("config-version", 2);
plugin.getConfig().set("items.open-inv", getMaterialById(itemOpenInvItemId).toString());
plugin.getConfig().set("notify.any-chest", notifyAnyChest);
plugin.getConfig().set("notify.silent-chest", notifySilentChest);
// Save the new config
plugin.saveConfig();
}
private void updateToggles(String sectionName, String suffix, String newSectionName) {
// Ensure section exists
if (!plugin.getConfig().isConfigurationSection(sectionName)) {
return;
}
ConfigurationSection section = plugin.getConfig().getConfigurationSection(sectionName);
Set<String> keys = section.getKeys(false);
// Ensure section has content
if (keys == null || keys.isEmpty()) {
return;
}
Map<String, Boolean> toggles = new HashMap<String, Boolean>();
for (String playerName : keys) {
OfflinePlayer player = plugin.matchPlayer(playerName);
String dataID = plugin.getPlayerID(player);
toggles.put(dataID, section.getBoolean(playerName + suffix, false));
}
// Wipe old ConfigurationSection
plugin.getConfig().set(sectionName, null);
// Prepare new ConfigurationSection
if (plugin.getConfig().isConfigurationSection(newSectionName)) {
section = plugin.getConfig().getConfigurationSection(newSectionName);
} else {
section = plugin.getConfig().createSection(newSectionName);
}
// Set new values
for (Map.Entry<String, Boolean> entry : toggles.entrySet()) {
section.set(entry.getKey(), entry.getValue());
}
}
@SuppressWarnings("deprecation")
private Material getMaterialById(int id) {
Material material = Material.getMaterial(id);
if (material == null) {
material = Material.STICK;
}
return material;
}
}

View file

@ -1,137 +1,347 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.lishid.openinv.commands.ContainerSettingCommand;
import com.lishid.openinv.commands.OpenInvCommand;
import com.lishid.openinv.commands.SearchContainerCommand;
import com.lishid.openinv.commands.SearchEnchantCommand;
import com.lishid.openinv.commands.SearchInvCommand;
import com.lishid.openinv.internal.IAnySilentContainer;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.listeners.InventoryListener;
import com.lishid.openinv.listeners.PlayerListener;
import com.lishid.openinv.listeners.PluginListener;
import com.lishid.openinv.util.Cache;
import com.lishid.openinv.util.ConfigUpdater;
import com.lishid.openinv.util.InternalAccessor;
import com.lishid.openinv.util.LanguageManager;
import com.lishid.openinv.util.Permissions;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import com.lishid.openinv.commands.AnyChestPluginCommand;
import com.lishid.openinv.commands.OpenEnderPluginCommand;
import com.lishid.openinv.commands.OpenInvPluginCommand;
import com.lishid.openinv.commands.SearchEnchantPluginCommand;
import com.lishid.openinv.commands.SearchInvPluginCommand;
import com.lishid.openinv.commands.SilentChestPluginCommand;
import com.lishid.openinv.internal.IAnySilentContainer;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.internal.InternalAccessor;
import com.lishid.openinv.util.Cache;
import com.lishid.openinv.util.Function;
import java.util.function.Consumer;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Open other player's inventory
*
*
* @author lishid
*/
public class OpenInv extends JavaPlugin {
public class OpenInv extends JavaPlugin implements IOpenInv {
private final Map<String, ISpecialPlayerInventory> inventories = new HashMap<String, ISpecialPlayerInventory>();
private final Map<String, ISpecialEnderChest> enderChests = new HashMap<String, ISpecialEnderChest>();
private final Cache<String, Player> playerCache = new Cache<String, Player>(300000L,
new Function<Player>() {
@Override
public boolean run(Player value) {
String key = playerLoader.getPlayerDataID(value);
return inventories.containsKey(key) && inventories.get(key).isInUse()
|| enderChests.containsKey(key) && enderChests.get(key).isInUse();
}
private final Map<String, ISpecialPlayerInventory> inventories = new HashMap<>();
private final Map<String, ISpecialEnderChest> enderChests = new HashMap<>();
private final Multimap<String, Class<? extends Plugin>> pluginUsage = HashMultimap.create();
private final Cache<String, Player> playerCache = new Cache<>(300000L,
value -> {
String key = OpenInv.this.getPlayerID(value);
return OpenInv.this.inventories.containsKey(key)
&& OpenInv.this.inventories.get(key).isInUse()
|| OpenInv.this.enderChests.containsKey(key)
&& OpenInv.this.enderChests.get(key).isInUse()
|| OpenInv.this.pluginUsage.containsKey(key);
},
new Function<Player>() {
@Override
public boolean run(Player value) {
String key = playerLoader.getPlayerDataID(value);
value -> {
String key = OpenInv.this.getPlayerID(value);
// Check if inventory is stored, and if it is, remove it and eject all viewers
if (inventories.containsKey(key)) {
Inventory inv = inventories.remove(key).getBukkitInventory();
for (HumanEntity entity : inv.getViewers()) {
entity.closeInventory();
}
// Check if inventory is stored, and if it is, remove it and eject all viewers
if (OpenInv.this.inventories.containsKey(key)) {
Inventory inv = OpenInv.this.inventories.remove(key).getBukkitInventory();
List<HumanEntity> viewers = inv.getViewers();
for (HumanEntity entity : viewers.toArray(new HumanEntity[0])) {
entity.closeInventory();
}
}
// Check if ender chest is stored, and if it is, remove it and eject all viewers
if (enderChests.containsKey(key)) {
Inventory inv = enderChests.remove(key).getBukkitInventory();
for (HumanEntity entity : inv.getViewers()) {
entity.closeInventory();
}
// Check if ender chest is stored, and if it is, remove it and eject all viewers
if (OpenInv.this.enderChests.containsKey(key)) {
Inventory inv = OpenInv.this.enderChests.remove(key).getBukkitInventory();
List<HumanEntity> viewers = inv.getViewers();
for (HumanEntity entity : viewers.toArray(new HumanEntity[0])) {
entity.closeInventory();
}
}
if (!OpenInv.this.disableSaving() && !value.isOnline()) {
value.saveData();
}
return true;
if (!OpenInv.this.disableSaving() && !value.isOnline()) {
value.saveData();
}
});
private InternalAccessor accessor;
private IPlayerDataManager playerLoader;
private IInventoryAccess inventoryAccess;
private IAnySilentContainer anySilentContainer;
private LanguageManager languageManager;
@Override
public void onEnable() {
// Get plugin manager
PluginManager pm = getServer().getPluginManager();
/**
* Evicts all viewers lacking cross-world permissions from a Player's inventory.
*
* @param player the Player
*/
public void changeWorld(final Player player) {
accessor = new InternalAccessor(this);
// Version check
if (!accessor.isSupported()) {
getLogger().info("Your version of CraftBukkit (" + accessor.getVersion() + ") is not supported.");
getLogger().info("Please look for an updated version of OpenInv.");
pm.disablePlugin(this);
String key = this.getPlayerID(player);
// Check if the player is cached. If not, neither of their inventories is open.
if (!this.playerCache.containsKey(key)) {
return;
}
playerLoader = accessor.newPlayerDataManager();
inventoryAccess = accessor.newInventoryAccess();
anySilentContainer = accessor.newAnySilentContainer();
if (this.inventories.containsKey(key)) {
Iterator<HumanEntity> iterator = this.inventories.get(key).getBukkitInventory().getViewers().iterator();
//noinspection WhileLoopReplaceableByForEach
while (iterator.hasNext()) {
HumanEntity human = iterator.next();
// If player has permission or is in the same world, allow continued access
// Just in case, also allow null worlds.
if (Permissions.CROSSWORLD.hasPermission(human) || human.getWorld().equals(player.getWorld())) {
continue;
}
human.closeInventory();
}
}
new ConfigUpdater(this).checkForUpdates();
if (this.enderChests.containsKey(key)) {
Iterator<HumanEntity> iterator = this.enderChests.get(key).getBukkitInventory().getViewers().iterator();
//noinspection WhileLoopReplaceableByForEach
while (iterator.hasNext()) {
HumanEntity human = iterator.next();
if (Permissions.CROSSWORLD.hasPermission(human) || human.getWorld().equals(player.getWorld())) {
continue;
}
human.closeInventory();
}
}
}
pm.registerEvents(new OpenInvPlayerListener(this), this);
pm.registerEvents(new OpenInvInventoryListener(this), this);
/**
* Convert a raw slot number into a player inventory slot number.
*
* <p>Note that this method is specifically for converting an ISpecialPlayerInventory slot number into a regular
* player inventory slot number.
*
* @param view the open inventory view
* @param rawSlot the raw slot in the view
* @return the converted slot number
*/
public int convertToPlayerSlot(InventoryView view, int rawSlot) {
return this.accessor.getPlayerDataManager().convertToPlayerSlot(view, rawSlot);
}
getCommand("openinv").setExecutor(new OpenInvPluginCommand(this));
getCommand("openender").setExecutor(new OpenEnderPluginCommand(this));
SearchInvPluginCommand searchInv = new SearchInvPluginCommand();
getCommand("searchinv").setExecutor(searchInv);
getCommand("searchender").setExecutor(searchInv);
getCommand("searchenchant").setExecutor(new SearchEnchantPluginCommand());
getCommand("silentchest").setExecutor(new SilentChestPluginCommand(this));
getCommand("anychest").setExecutor(new AnyChestPluginCommand(this));
@Override
public boolean disableSaving() {
return this.getConfig().getBoolean("settings.disable-saving", false);
}
@NotNull
@Override
public IAnySilentContainer getAnySilentContainer() {
return this.accessor.getAnySilentContainer();
}
@Override
public boolean getPlayerAnyChestStatus(@NotNull final OfflinePlayer player) {
boolean defaultState = false;
if (player.isOnline()) {
Player onlinePlayer = player.getPlayer();
if (onlinePlayer != null) {
defaultState = Permissions.ANY_DEFAULT.hasPermission(onlinePlayer);
}
}
return this.getConfig().getBoolean("toggles.any-chest." + this.getPlayerID(player), defaultState);
}
@Override
public boolean getPlayerSilentChestStatus(@NotNull final OfflinePlayer offline) {
boolean defaultState = false;
if (offline.isOnline()) {
Player onlinePlayer = offline.getPlayer();
if (onlinePlayer != null) {
defaultState = Permissions.SILENT_DEFAULT.hasPermission(onlinePlayer);
}
}
return this.getConfig().getBoolean("toggles.silent-chest." + this.getPlayerID(offline), defaultState);
}
@NotNull
@Override
public ISpecialEnderChest getSpecialEnderChest(@NotNull final Player player, final boolean online)
throws InstantiationException {
String id = this.getPlayerID(player);
if (this.enderChests.containsKey(id)) {
return this.enderChests.get(id);
}
ISpecialEnderChest inv = this.accessor.newSpecialEnderChest(player, online);
this.enderChests.put(id, inv);
this.playerCache.put(id, player);
return inv;
}
@NotNull
@Override
public ISpecialPlayerInventory getSpecialInventory(@NotNull final Player player, final boolean online)
throws InstantiationException {
String id = this.getPlayerID(player);
if (this.inventories.containsKey(id)) {
return this.inventories.get(id);
}
ISpecialPlayerInventory inv = this.accessor.newSpecialPlayerInventory(player, online);
this.inventories.put(id, inv);
this.playerCache.put(id, player);
return inv;
}
@Override
public boolean isSupportedVersion() {
return this.accessor != null && this.accessor.isSupported();
}
@Override
public @Nullable Player loadPlayer(@NotNull final OfflinePlayer offline) {
String key = this.getPlayerID(offline);
if (this.playerCache.containsKey(key)) {
return this.playerCache.get(key);
}
Player player = offline.getPlayer();
if (player != null) {
this.playerCache.put(key, player);
return player;
}
if (!this.isSupportedVersion()) {
return null;
}
if (Bukkit.isPrimaryThread()) {
return this.accessor.getPlayerDataManager().loadPlayer(offline);
}
Future<Player> future = Bukkit.getScheduler().callSyncMethod(this,
() -> OpenInv.this.accessor.getPlayerDataManager().loadPlayer(offline));
try {
player = future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
return null;
}
if (player != null) {
this.playerCache.put(key, player);
}
return player;
}
@Override
public @Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory) {
return this.accessor.getPlayerDataManager().openInventory(player, inventory);
}
public void sendMessage(@NotNull CommandSender sender, @NotNull String key) {
String message = this.languageManager.getValue(key, getLocale(sender));
if (message != null && !message.isEmpty()) {
sender.sendMessage(message);
}
}
public void sendMessage(@NotNull CommandSender sender, @NotNull String key, String... replacements) {
String message = this.languageManager.getValue(key, getLocale(sender), replacements);
if (message != null && !message.isEmpty()) {
sender.sendMessage(message);
}
}
public void sendSystemMessage(@NotNull Player player, @NotNull String key) {
String message = this.languageManager.getValue(key, getLocale(player));
if (message == null) {
return;
}
int newline = message.indexOf('\n');
if (newline != -1) {
// No newlines in action bar chat.
message = message.substring(0, newline);
}
if (message.isEmpty()) {
return;
}
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(message));
}
public @Nullable String getLocalizedMessage(@NotNull CommandSender sender, @NotNull String key) {
return this.languageManager.getValue(key, getLocale(sender));
}
public @Nullable String getLocalizedMessage(@NotNull CommandSender sender, @NotNull String key, String... replacements) {
return this.languageManager.getValue(key, getLocale(sender), replacements);
}
private @Nullable String getLocale(@NotNull CommandSender sender) {
if (sender instanceof Player) {
return ((Player) sender).getLocale();
} else {
return this.getConfig().getString("settings.locale", "en_us");
}
}
@Override
public boolean notifyAnyChest() {
return this.getConfig().getBoolean("notify.any-chest", true);
}
@Override
public boolean notifySilentChest() {
return this.getConfig().getBoolean("notify.silent-chest", true);
}
@Override
@ -141,327 +351,148 @@ public class OpenInv extends JavaPlugin {
return;
}
this.playerCache.invalidateAll();
if (this.isSupportedVersion()) {
this.playerCache.invalidateAll();
}
}
@Override
public void onEnable() {
// Save default configuration if not present.
this.saveDefaultConfig();
// Get plugin manager
PluginManager pm = this.getServer().getPluginManager();
this.accessor = new InternalAccessor(this);
this.languageManager = new LanguageManager(this, "en_us");
// Version check
if (this.accessor.isSupported()) {
// Update existing configuration. May require internal access.
new ConfigUpdater(this).checkForUpdates();
// Register listeners
pm.registerEvents(new PlayerListener(this), this);
pm.registerEvents(new PluginListener(this), this);
pm.registerEvents(new InventoryListener(this), this);
// Register commands to their executors
this.setCommandExecutor(new OpenInvCommand(this), "openinv", "openender");
this.setCommandExecutor(new SearchContainerCommand(this), "searchcontainer");
this.setCommandExecutor(new SearchInvCommand(this), "searchinv", "searchender");
this.setCommandExecutor(new SearchEnchantCommand(this), "searchenchant");
this.setCommandExecutor(new ContainerSettingCommand(this), "silentcontainer", "anycontainer");
} else {
this.sendVersionError(this.getLogger()::warning);
}
}
private void sendVersionError(Consumer<String> messageMethod) {
messageMethod.accept("Your server version (" + this.accessor.getVersion() + ") is not supported.");
messageMethod.accept("Please obtain an appropriate version here: " + accessor.getReleasesLink());
}
private void setCommandExecutor(CommandExecutor executor, String... commands) {
for (String commandName : commands) {
PluginCommand command = this.getCommand(commandName);
if (command != null) {
command.setExecutor(executor);
}
}
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (!this.accessor.isSupported()) {
this.sendVersionError(sender::sendMessage);
return true;
}
return false;
}
public void releaseAllPlayers(final Plugin plugin) {
Iterator<Map.Entry<String, Class<? extends Plugin>>> iterator = this.pluginUsage.entries().iterator();
if (!iterator.hasNext()) {
return;
}
for (Map.Entry<String, Class<? extends Plugin>> entry = iterator.next(); iterator.hasNext(); entry = iterator.next()) {
if (entry.getValue().equals(plugin.getClass())) {
iterator.remove();
}
}
}
@Override
public void releasePlayer(@NotNull final Player player, @NotNull final Plugin plugin) {
String key = this.getPlayerID(player);
if (!this.pluginUsage.containsEntry(key, plugin.getClass())) {
return;
}
this.pluginUsage.remove(key, plugin.getClass());
}
@Override
public void retainPlayer(@NotNull final Player player, @NotNull final Plugin plugin) {
String key = this.getPlayerID(player);
if (this.pluginUsage.containsEntry(key, plugin.getClass())) {
return;
}
this.pluginUsage.put(key, plugin.getClass());
}
@Override
public void setPlayerAnyChestStatus(@NotNull final OfflinePlayer offline, final boolean status) {
this.getConfig().set("toggles.any-chest." + this.getPlayerID(offline), status);
this.saveConfig();
}
/**
* Checks if the server version is supported by OpenInv.
*
* @return true if the server version is supported
*/
public boolean isSupportedVersion() {
return this.accessor.isSupported();
}
/**
* Gets the active IInventoryAccess implementation. May return null if the server version is
* unsupported.
*
* @return the IInventoryAccess
*/
public IInventoryAccess getInventoryAccess() {
return this.inventoryAccess;
}
/**
* Gets the active ISilentContainer implementation. May return null if the server version is
* unsupported.
*
* @return the ISilentContainer
*/
public IAnySilentContainer getAnySilentContainer() {
return this.anySilentContainer;
}
/**
* Gets an ISpecialPlayerInventory for the given Player.
*
* Method for handling a Player going offline.
*
* @param player the Player
* @param online true if the Player is currently online
* @return the ISpecialPlayerInventory
* @throws IllegalStateException if the server version is unsupported
*/
public ISpecialPlayerInventory getInventory(Player player, boolean online) {
String id = playerLoader.getPlayerDataID(player);
if (inventories.containsKey(id)) {
return inventories.get(id);
}
ISpecialPlayerInventory inv = accessor.newSpecialPlayerInventory(player, online);
inventories.put(id, inv);
playerCache.put(id, player);
return inv;
}
public void setPlayerOffline(final Player player) {
/**
* Gets an ISpecialEnderChest for the given Player.
*
* @param player the Player
* @param online true if the Player is currently online
* @return the ISpecialEnderChest
*/
public ISpecialEnderChest getEnderChest(Player player, boolean online) {
String id = playerLoader.getPlayerDataID(player);
if (enderChests.containsKey(id)) {
return enderChests.get(id);
}
ISpecialEnderChest inv = accessor.newSpecialEnderChest(player, online);
enderChests.put(id, inv);
playerCache.put(id, player);
return inv;
}
String key = this.getPlayerID(player);
/**
* Forcibly unload a cached Player's data.
*
* @param player the OfflinePlayer to unload
*/
public void unload(OfflinePlayer player) {
this.playerCache.invalidate(this.playerLoader.getPlayerDataID(player));
}
/**
* Check the configuration value for whether or not OpenInv saves player data when unloading
* players. This is exclusively for users who do not allow editing of inventories, only viewing,
* and wish to prevent any possibility of bugs such as lishid#40. If true, OpenInv will not ever
* save any edits made to players.
*
* @return false unless configured otherwise
*/
public boolean disableSaving() {
return getConfig().getBoolean("settings.disable-saving", false);
}
/**
* Check the configuration value for whether or not OpenInv displays a notification to the user
* when a container is activated with SilentChest.
*
* @return true unless configured otherwise
*/
public boolean notifySilentChest() {
return getConfig().getBoolean("notify.silent-chest", true);
}
/**
* Check the configuration value for whether or not OpenInv displays a notification to the user
* when a container is activated with AnyChest.
*
* @return true unless configured otherwise
*/
public boolean notifyAnyChest() {
return getConfig().getBoolean("notify.any-chest", true);
}
/**
* Gets a player's SilentChest setting.
*
* @param player the OfflinePlayer
* @return true if SilentChest is enabled
*/
public boolean getPlayerSilentChestStatus(OfflinePlayer player) {
return getConfig().getBoolean("toggles.silent-chest." + playerLoader.getPlayerDataID(player), false);
}
/**
* Sets a player's SilentChest setting.
*
* @param player the OfflinePlayer
* @param status the status
*/
public void setPlayerSilentChestStatus(OfflinePlayer player, boolean status) {
getConfig().set("toggles.silent-chest." + playerLoader.getPlayerDataID(player), status);
saveConfig();
}
/**
* Gets the provided player's AnyChest setting.
*
* @param player the OfflinePlayer
* @return true if AnyChest is enabled
*/
public boolean getPlayerAnyChestStatus(OfflinePlayer player) {
return getConfig().getBoolean("toggles.any-chest." + playerLoader.getPlayerDataID(player), false);
}
/**
* Sets a player's AnyChest setting.
*
* @param player the OfflinePlayer
* @param status the status
*/
public void setPlayerAnyChestStatus(OfflinePlayer player, boolean status) {
getConfig().set("toggles.any-chest." + playerLoader.getPlayerDataID(player), status);
saveConfig();
}
/**
* Gets a unique identifier by which the OfflinePlayer can be referenced. Using the value
* returned to look up a Player will generally be much faster for later implementations.
*
* @param offline the OfflinePlayer
* @return the identifier
*/
public String getPlayerID(OfflinePlayer offline) {
return this.playerLoader.getPlayerDataID(offline);
}
/**
* Get an OfflinePlayer by name.
* <p>
* Note: This method is potentially very heavily blocking. It should not ever be called on the
* main thread, and if it is, a stack trace will be displayed alerting server owners to the
* call.
*
* @param name the name of the Player
* @return the OfflinePlayer with the closest matching name or null if no players have ever logged in
*/
public OfflinePlayer matchPlayer(String name) {
// Warn if called on the main thread - if we resort to searching offline players, this may take several seconds.
if (getServer().isPrimaryThread()) {
getLogger().warning("Call to OpenInv#matchPlayer made on the main thread!");
getLogger().warning("This can cause the server to hang, potentially severely.");
getLogger().warning("Trace:");
for (StackTraceElement element : new Throwable().fillInStackTrace().getStackTrace()) {
getLogger().warning(element.toString());
}
// Check if the player is cached. If not, neither of their inventories is open.
if (!this.playerCache.containsKey(key)) {
return;
}
// Attempt exact offline match first - adds UUID support for later versions
OfflinePlayer player = this.playerLoader.getPlayerByID(name);
// Replace stored player with our own version
this.playerCache.put(key, this.accessor.getPlayerDataManager().inject(player));
if (player != null) {
return player;
if (this.inventories.containsKey(key)) {
this.inventories.get(key).setPlayerOffline();
}
// Ensure name is valid if server is in online mode to avoid unnecessary searching
if (getServer().getOnlineMode() && !name.matches("[a-zA-Z0-9_]{3,16}")) {
return null;
if (this.enderChests.containsKey(key)) {
this.enderChests.get(key).setPlayerOffline();
}
player = getServer().getPlayerExact(name);
if (player != null) {
return player;
}
player = getServer().getOfflinePlayer(name);
/*
* Compatibility: Pre-UUID, getOfflinePlayer always returns an OfflinePlayer. Post-UUID,
* getOfflinePlayer will return null if no matching player is found. To preserve
* compatibility, only return the player if they have played before. Ignoring current online
* status is fine, they'd have been found by getPlayerExact otherwise.
*/
if (player != null && player.hasPlayedBefore()) {
return player;
}
player = getServer().getPlayer(name);
if (player != null) {
return player;
}
int bestMatch = Integer.MAX_VALUE;
for (OfflinePlayer offline : getServer().getOfflinePlayers()) {
if (offline.getName() == null) {
// Loaded by UUID only, name has never been looked up.
continue;
}
// Compatibility: Lang3 is only bundled with 1.8+
int currentMatch = org.apache.commons.lang.StringUtils.getLevenshteinDistance(name, offline.getName());
if (currentMatch == 0) {
return offline;
}
if (currentMatch < bestMatch) {
bestMatch = currentMatch;
player = offline;
}
}
// Only null if no players have played ever, otherwise even the worst match will do.
return player;
}
/**
* Load a Player from an OfflinePlayer. May return null under some circumstances.
*
* @param offline the OfflinePlayer to load a Player for
* @return the Player
*/
public Player loadPlayer(final OfflinePlayer offline) {
if (offline == null) {
return null;
}
String key = this.playerLoader.getPlayerDataID(offline);
if (this.playerCache.containsKey(key)) {
return this.playerCache.get(key);
}
Player loaded;
if (offline.isOnline()) {
loaded = offline.getPlayer();
this.playerCache.put(key, loaded);
return loaded;
}
if (Bukkit.isPrimaryThread()) {
return this.playerLoader.loadPlayer(offline);
}
Future<Player> future = Bukkit.getScheduler().callSyncMethod(this,
new Callable<Player>() {
@Override
public Player call() throws Exception {
return playerLoader.loadPlayer(offline);
}
});
int ticks = 0;
while (!future.isDone() && !future.isCancelled() && ticks < 10) {
++ticks;
try {
Thread.sleep(50L);
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
}
if (!future.isDone() || future.isCancelled()) {
return null;
}
try {
loaded = future.get();
} catch (InterruptedException e) {
e.printStackTrace();
return null;
} catch (ExecutionException e) {
e.printStackTrace();
return null;
}
if (loaded != null) {
this.playerCache.put(key, loaded);
}
return loaded;
}
/**
* Method for handling a Player coming online.
*
*
* @param player the Player
* @throws IllegalStateException if the server version is unsupported
*/
public void setPlayerOnline(final Player player) {
String key = this.playerLoader.getPlayerDataID(player);
String key = this.getPlayerID(player);
// Check if the player is cached. If not, neither of their inventories is open.
if (!this.playerCache.containsKey(key)) {
@ -487,76 +518,18 @@ public class OpenInv extends JavaPlugin {
}
}
/**
* Method for handling a Player going offline.
*
* @param player the Player
*/
public void setPlayerOffline(final Player player) {
String key = this.playerLoader.getPlayerDataID(player);
// Check if the player is cached. If not, neither of their inventories is open.
if (!this.playerCache.containsKey(key)) {
return;
}
if (this.inventories.containsKey(key)) {
this.inventories.get(key).setPlayerOffline();
}
if (this.enderChests.containsKey(key)) {
this.enderChests.get(key).setPlayerOffline();
}
}
/**
* Evicts all viewers lacking cross-world permissions from a Player's inventory.
*
* @param player the Player
*/
public void changeWorld(final Player player) {
String key = this.playerLoader.getPlayerDataID(player);
// Check if the player is cached. If not, neither of their inventories is open.
if (!this.playerCache.containsKey(key)) {
return;
}
if (this.inventories.containsKey(key)) {
Iterator<HumanEntity> iterator = this.inventories.get(key).getBukkitInventory().getViewers().iterator();
while (iterator.hasNext()) {
HumanEntity human = iterator.next();
// If player has permission or is in the same world, allow continued access
// Just in case, also allow null worlds.
if (Permissions.CROSSWORLD.hasPermission(human) || human.getWorld() == null
|| human.getWorld().equals(player.getWorld())) {
continue;
}
human.closeInventory();
}
}
if (this.enderChests.containsKey(key)) {
Iterator<HumanEntity> iterator = this.enderChests.get(key).getBukkitInventory().getViewers().iterator();
while (iterator.hasNext()) {
HumanEntity human = iterator.next();
if (Permissions.CROSSWORLD.hasPermission(human) || human.getWorld() == null
|| human.getWorld().equals(player.getWorld())) {
continue;
}
human.closeInventory();
}
}
@Override
public void setPlayerSilentChestStatus(@NotNull final OfflinePlayer offline, final boolean status) {
this.getConfig().set("toggles.silent-chest." + this.getPlayerID(offline), status);
this.saveConfig();
}
/**
* Displays all applicable help for OpenInv commands.
*
*
* @param player the Player to help
*/
public void showHelp(Player player) {
public void showHelp(final Player player) {
// Get registered commands
for (String commandName : this.getDescription().getCommands().keySet()) {
PluginCommand command = this.getCommand(commandName);
@ -586,4 +559,9 @@ public class OpenInv extends JavaPlugin {
}
}
@Override
public void unload(@NotNull final OfflinePlayer offline) {
this.playerCache.invalidate(this.getPlayerID(offline));
}
}

View file

@ -1,62 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv;
import org.bukkit.entity.HumanEntity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.inventory.Inventory;
public class OpenInvInventoryListener implements Listener {
private final OpenInv plugin;
public OpenInvInventoryListener(OpenInv plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event) {
if (cancelInteract(event.getWhoClicked(), event.getInventory())) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onInventoryDrag(InventoryDragEvent event) {
if (cancelInteract(event.getWhoClicked(), event.getInventory())) {
event.setCancelled(true);
}
}
private boolean cancelInteract(HumanEntity entity, Inventory inventory) {
return plugin.getInventoryAccess().isSpecialPlayerInventory(inventory)
&& !Permissions.EDITINV.hasPermission(entity)
|| plugin.getInventoryAccess().isSpecialEnderChest(inventory)
&& !Permissions.EDITENDER.hasPermission(entity);
}
@EventHandler
public void onWorldChange(PlayerChangedWorldEvent event) {
plugin.changeWorld(event.getPlayer());
}
}

View file

@ -1,78 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
public class OpenInvPlayerListener implements Listener {
private final OpenInv plugin;
public OpenInvPlayerListener(OpenInv plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerJoin(final PlayerJoinEvent event) {
plugin.setPlayerOnline(event.getPlayer());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerQuit(PlayerQuitEvent event) {
plugin.setPlayerOffline(event.getPlayer());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getPlayer().isSneaking()
|| event.useInteractedBlock() == Result.DENY
|| !plugin.getAnySilentContainer().isAnySilentContainer(event.getClickedBlock())) {
return;
}
Player player = event.getPlayer();
boolean anychest = Permissions.ANYCHEST.hasPermission(player) && plugin.getPlayerAnyChestStatus(player);
boolean needsAnyChest = plugin.getAnySilentContainer().isAnyContainerNeeded(player, event.getClickedBlock());
if (!anychest && needsAnyChest) {
return;
}
boolean silentchest = Permissions.SILENT.hasPermission(player) && plugin.getPlayerSilentChestStatus(player);
// If anychest or silentchest is active
if ((anychest || silentchest) && plugin.getAnySilentContainer().activateContainer(player, silentchest, event.getClickedBlock())) {
if (silentchest && plugin.notifySilentChest() && needsAnyChest && plugin.notifyAnyChest()) {
player.sendMessage("You are opening a blocked container silently.");
} else if (silentchest && plugin.notifySilentChest()) {
player.sendMessage("You are opening a container silently.");
} else if (needsAnyChest && plugin.notifyAnyChest()) {
player.sendMessage("You are opening a blocked container.");
}
event.setCancelled(true);
}
}
}

View file

@ -1,38 +0,0 @@
package com.lishid.openinv;
import org.bukkit.permissions.Permissible;
public enum Permissions {
OPENINV("OpenInv.openinv"),
OVERRIDE("OpenInv.override"),
EXEMPT("OpenInv.exempt"),
CROSSWORLD("OpenInv.crossworld"),
SILENT("OpenInv.silent"),
ANYCHEST("OpenInv.anychest"),
ENDERCHEST("OpenInv.openender"),
ENDERCHEST_ALL("OpenInv.openenderall"),
SEARCH("OpenInv.search"),
EDITINV("OpenInv.editinv"),
EDITENDER("OpenInv.editender"),
OPENSELF("OpenInv.openself");
private final String permission;
private Permissions(String permission) {
this.permission = permission;
}
public boolean hasPermission(Permissible permissible) {
String[] parts = permission.split("\\.");
String perm = "";
for (int i = 0; i < parts.length; i++) {
if (permissible.hasPermission(perm + "*")) {
return true;
}
perm += parts[i] + ".";
}
return permissible.hasPermission(permission);
}
}

View file

@ -1,54 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.commands;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.lishid.openinv.OpenInv;
public class AnyChestPluginCommand implements CommandExecutor {
private final OpenInv plugin;
public AnyChestPluginCommand(OpenInv plugin) {
this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You can't use this from the console.");
return true;
}
Player player = (Player) sender;
if (args.length > 0 && args[0].equalsIgnoreCase("check")) {
sender.sendMessage("AnyChest is " + (plugin.getPlayerAnyChestStatus(player) ? "ON" : "OFF") + ".");
return true;
}
plugin.setPlayerAnyChestStatus(player, !plugin.getPlayerAnyChestStatus(player));
sender.sendMessage("AnyChest is now " + (plugin.getPlayerAnyChestStatus(player) ? "ON" : "OFF") + ".");
return true;
}
}

View file

@ -0,0 +1,87 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.commands;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.util.TabCompleter;
import java.util.Collections;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class ContainerSettingCommand implements TabExecutor {
private final OpenInv plugin;
public ContainerSettingCommand(final OpenInv plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (!(sender instanceof Player)) {
plugin.sendMessage(sender, "messages.error.consoleUnsupported");
return true;
}
Player player = (Player) sender;
boolean any = command.getName().startsWith("any");
Predicate<Player> getSetting = any ? plugin::getPlayerAnyChestStatus : plugin::getPlayerSilentChestStatus;
BiConsumer<OfflinePlayer, Boolean> setSetting = any ? plugin::setPlayerAnyChestStatus : plugin::setPlayerSilentChestStatus;
if (args.length > 0) {
args[0] = args[0].toLowerCase();
if (args[0].equals("on")) {
setSetting.accept(player, true);
} else if (args[0].equals("off")) {
setSetting.accept(player, false);
} else if (!args[0].equals("check")) {
// Invalid argument, show usage.
return false;
}
} else {
setSetting.accept(player, !getSetting.test(player));
}
String onOff = plugin.getLocalizedMessage(player, getSetting.test(player) ? "messages.info.on" : "messages.info.off");
if (onOff == null) {
onOff = String.valueOf(getSetting.test(player));
}
plugin.sendMessage(sender, "messages.info.settingState","%setting%", any ? "AnyContainer" : "SilentContainer", "%state%", onOff);
return true;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (!command.testPermissionSilent(sender) || args.length != 1) {
return Collections.emptyList();
}
return TabCompleter.completeString(args[0], new String[] {"check", "on", "off"});
}
}

View file

@ -1,141 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.commands;
import java.util.HashMap;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.Permissions;
import com.lishid.openinv.internal.ISpecialEnderChest;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
public class OpenEnderPluginCommand implements CommandExecutor {
private final OpenInv plugin;
private final HashMap<Player, String> openEnderHistory = new HashMap<Player, String>();
public OpenEnderPluginCommand(OpenInv plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You can't use this from the console.");
return true;
}
if (args.length > 0 && args[0].equalsIgnoreCase("?")) {
plugin.showHelp((Player) sender);
return true;
}
final Player player = (Player) sender;
// History management
String history = openEnderHistory.get(player);
if (history == null || history == "") {
history = player.getName();
openEnderHistory.put(player, history);
}
final String name;
// Read from history if target is not named
if (args.length < 1) {
name = history;
} else {
name = args[0];
}
new BukkitRunnable() {
@Override
public void run() {
final OfflinePlayer offlinePlayer = plugin.matchPlayer(name);
if (offlinePlayer == null || !offlinePlayer.hasPlayedBefore() && !offlinePlayer.isOnline()) {
player.sendMessage(ChatColor.RED + "Player not found!");
return;
}
new BukkitRunnable() {
@Override
public void run() {
if (!player.isOnline()) {
return;
}
openInventory(player, offlinePlayer);
}
}.runTask(plugin);
}
}.runTaskAsynchronously(plugin);
return true;
}
private void openInventory(Player player, OfflinePlayer target) {
Player onlineTarget;
boolean online = target.isOnline();
if (!online) {
// Try loading the player's data
onlineTarget = plugin.loadPlayer(target);
if (onlineTarget == null) {
player.sendMessage(ChatColor.RED + "Player not found!");
return;
}
} else {
onlineTarget = target.getPlayer();
}
if (!onlineTarget.equals(player)) {
if (!Permissions.ENDERCHEST_ALL.hasPermission(player)) {
player.sendMessage(ChatColor.RED + "You do not have permission to access other players' enderchests.");
return;
}
if (!Permissions.CROSSWORLD.hasPermission(player) && !player.getWorld().equals(onlineTarget.getWorld())) {
player.sendMessage(ChatColor.RED + onlineTarget.getDisplayName() + " is not in your world!");
return;
}
if (!Permissions.OVERRIDE.hasPermission(player) && Permissions.EXEMPT.hasPermission(onlineTarget)) {
player.sendMessage(ChatColor.RED + onlineTarget.getDisplayName() + "'s inventory is protected!");
return;
}
}
// Record the target
openEnderHistory.put(player, onlineTarget.getName());
// Create the inventory
ISpecialEnderChest chest = plugin.getEnderChest(onlineTarget, online);
// Open the inventory
player.openInventory(chest.getBukkitInventory());
}
}

View file

@ -0,0 +1,185 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.commands;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.util.Permissions;
import com.lishid.openinv.util.TabCompleter;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.jetbrains.annotations.NotNull;
public class OpenInvCommand implements TabExecutor {
private final OpenInv plugin;
private final HashMap<Player, String> openInvHistory = new HashMap<>();
private final HashMap<Player, String> openEnderHistory = new HashMap<>();
public OpenInvCommand(final OpenInv plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(@NotNull final CommandSender sender, @NotNull final Command command, @NotNull final String label, @NotNull final String[] args) {
if (!(sender instanceof Player)) {
plugin.sendMessage(sender, "messages.error.consoleUnsupported");
return true;
}
if (args.length > 0 && (args[0].equalsIgnoreCase("help") || args[0].equals("?"))) {
this.plugin.showHelp((Player) sender);
return true;
}
final Player player = (Player) sender;
final boolean openinv = command.getName().equals("openinv");
// History management
String history = (openinv ? this.openInvHistory : this.openEnderHistory).get(player);
if (history == null || history.isEmpty()) {
history = player.getName();
(openinv ? this.openInvHistory : this.openEnderHistory).put(player, history);
}
final String name;
// Read from history if target is not named
if (args.length < 1) {
name = history;
} else {
name = args[0];
}
new BukkitRunnable() {
@Override
public void run() {
final OfflinePlayer offlinePlayer = OpenInvCommand.this.plugin.matchPlayer(name);
if (offlinePlayer == null || !offlinePlayer.hasPlayedBefore() && !offlinePlayer.isOnline()) {
plugin.sendMessage(player, "messages.error.invalidPlayer");
return;
}
new BukkitRunnable() {
@Override
public void run() {
if (!player.isOnline()) {
return;
}
OpenInvCommand.this.openInventory(player, offlinePlayer, openinv);
}
}.runTask(OpenInvCommand.this.plugin);
}
}.runTaskAsynchronously(this.plugin);
return true;
}
private void openInventory(final Player player, final OfflinePlayer target, boolean openinv) {
Player onlineTarget;
boolean online = target.isOnline();
if (!online) {
if (Permissions.OPENOFFLINE.hasPermission(player)) {
// Try loading the player's data
onlineTarget = this.plugin.loadPlayer(target);
} else {
plugin.sendMessage(player, "messages.error.permissionPlayerOffline");
return;
}
} else {
if (Permissions.OPENONLINE.hasPermission(player)) {
onlineTarget = target.getPlayer();
} else {
plugin.sendMessage(player, "messages.error.permissionPlayerOnline");
return;
}
}
if (onlineTarget == null) {
plugin.sendMessage(player, "messages.error.invalidPlayer");
return;
}
// Permissions checks
if (onlineTarget.equals(player)) {
// Inventory: Additional permission required to open own inventory
if (openinv && !Permissions.OPENSELF.hasPermission(player)) {
plugin.sendMessage(player, "messages.error.permissionOpenSelf");
return;
}
} else {
// Enderchest: Additional permission required to open others' ender chests
if (!openinv && !Permissions.ENDERCHEST_ALL.hasPermission(player)) {
plugin.sendMessage(player, "messages.error.permissionEnderAll");
return;
}
// Protected check
if (!Permissions.OVERRIDE.hasPermission(player)
&& Permissions.EXEMPT.hasPermission(onlineTarget)) {
plugin.sendMessage(player, "messages.error.permissionExempt",
"%target%", onlineTarget.getDisplayName());
return;
}
// Crossworld check
if (!Permissions.CROSSWORLD.hasPermission(player)
&& !onlineTarget.getWorld().equals(player.getWorld())) {
plugin.sendMessage(player, "messages.error.permissionCrossWorld",
"%target%", onlineTarget.getDisplayName());
return;
}
}
// Record the target
(openinv ? this.openInvHistory : this.openEnderHistory).put(player, this.plugin.getPlayerID(target));
// Create the inventory
final ISpecialInventory inv;
try {
inv = openinv ? this.plugin.getSpecialInventory(onlineTarget, online) : this.plugin.getSpecialEnderChest(onlineTarget, online);
} catch (Exception e) {
plugin.sendMessage(player, "messages.error.commandException");
e.printStackTrace();
return;
}
// Open the inventory
plugin.openInventory(player, inv);
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (!command.testPermissionSilent(sender) || args.length != 1) {
return Collections.emptyList();
}
return TabCompleter.completeOnlinePlayer(sender, args[0]);
}
}

View file

@ -1,148 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.commands;
import java.util.HashMap;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.Permissions;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
public class OpenInvPluginCommand implements CommandExecutor {
private final OpenInv plugin;
private final HashMap<Player, String> openInvHistory = new HashMap<Player, String>();
public OpenInvPluginCommand(OpenInv plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You can't use this from the console.");
return true;
}
if (args.length > 0 && args[0].equalsIgnoreCase("?")) {
plugin.showHelp((Player) sender);
return true;
}
final Player player = (Player) sender;
// History management
String history = openInvHistory.get(player);
if (history == null || history == "") {
history = player.getName();
openInvHistory.put(player, history);
}
final String name;
// Read from history if target is not named
if (args.length < 1) {
name = history;
} else {
name = args[0];
}
new BukkitRunnable() {
@Override
public void run() {
final OfflinePlayer offlinePlayer = plugin.matchPlayer(name);
if (offlinePlayer == null || !offlinePlayer.hasPlayedBefore() && !offlinePlayer.isOnline()) {
player.sendMessage(ChatColor.RED + "Player not found!");
return;
}
new BukkitRunnable() {
@Override
public void run() {
if (!player.isOnline()) {
return;
}
openInventory(player, offlinePlayer);
}
}.runTask(plugin);
}
}.runTaskAsynchronously(plugin);
return true;
}
private void openInventory(Player player, OfflinePlayer target) {
Player onlineTarget;
boolean online = target.isOnline();
if (!online) {
// Try loading the player's data
onlineTarget = plugin.loadPlayer(target);
if (onlineTarget == null) {
player.sendMessage(ChatColor.RED + "Player not found!");
return;
}
} else {
onlineTarget = target.getPlayer();
}
// Permissions checks
if (onlineTarget.equals(player)) {
// Self-open check
if (!Permissions.OPENSELF.hasPermission(player)) {
player.sendMessage(ChatColor.RED + "You're not allowed to openinv yourself.");
return;
}
} else {
// Protected check
if (!Permissions.OVERRIDE.hasPermission(player) && Permissions.EXEMPT.hasPermission(onlineTarget)) {
player.sendMessage(ChatColor.RED + onlineTarget.getDisplayName() + "'s inventory is protected!");
return;
}
// Crossworld check
if ((!Permissions.CROSSWORLD.hasPermission(player) && !Permissions.OVERRIDE.hasPermission(player)) && onlineTarget.getWorld() != player.getWorld()) {
player.sendMessage(ChatColor.RED + onlineTarget.getDisplayName() + " is not in your world!");
return;
}
}
// Record the target
openInvHistory.put(player, onlineTarget.getName());
// Create the inventory
ISpecialPlayerInventory inv = plugin.getInventory(onlineTarget, online);
// Open the inventory
player.openInventory(inv.getBukkitInventory());
}
}

View file

@ -0,0 +1,134 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.commands;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.util.TabCompleter;
import java.util.Collections;
import java.util.List;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.BlockState;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryHolder;
import org.jetbrains.annotations.NotNull;
/**
* Command for searching containers in a radius of chunks.
*/
public class SearchContainerCommand implements TabExecutor {
private final OpenInv plugin;
public SearchContainerCommand(OpenInv plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (!(sender instanceof Player)) {
plugin.sendMessage(sender, "messages.error.consoleUnsupported");
return true;
}
if (args.length < 1) {
// Must supply material
return false;
}
Material material = Material.getMaterial(args[0].toUpperCase());
if (material == null) {
plugin.sendMessage(sender, "messages.error.invalidMaterial", "%target%", args[0]);
return false;
}
int radius = 5;
if (args.length > 1) {
try {
radius = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
// Invalid radius supplied
return false;
}
}
if (radius > 20)
{
radius = 20;
}
Player senderPlayer = (Player) sender;
World world = senderPlayer.getWorld();
Chunk centerChunk = senderPlayer.getLocation().getChunk();
StringBuilder locations = new StringBuilder();
for (int dX = -radius; dX <= radius; ++dX) {
for (int dZ = -radius; dZ <= radius; ++dZ) {
if (!world.loadChunk(centerChunk.getX() + dX, centerChunk.getZ() + dZ, false)) {
continue;
}
Chunk chunk = world.getChunkAt(centerChunk.getX() + dX, centerChunk.getZ() + dZ);
for (BlockState tileEntity : chunk.getTileEntities()) {
if (!(tileEntity instanceof InventoryHolder)) {
continue;
}
InventoryHolder holder = (InventoryHolder) tileEntity;
if (!holder.getInventory().contains(material)) {
continue;
}
locations.append(holder.getInventory().getType().name().toLowerCase()).append(" (")
.append(tileEntity.getX()).append(',').append(tileEntity.getY()).append(',')
.append(tileEntity.getZ()).append("), ");
}
}
}
// Matches found, delete trailing comma and space
if (locations.length() > 0) {
locations.delete(locations.length() - 2, locations.length());
} else {
plugin.sendMessage(sender, "messages.info.container.noMatches",
"%target%", material.name());
return true;
}
plugin.sendMessage(sender, "messages.info.container.matches",
"%target%", material.name(), "%detail%", locations.toString());
return true;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
if (args.length < 1 || args.length > 2 || !command.testPermissionSilent(sender)) {
return Collections.emptyList();
}
String argument = args[args.length - 1];
if (args.length == 1) {
return TabCompleter.completeEnum(argument, Material.class);
} else {
return TabCompleter.completeInteger(argument);
}
}
}

View file

@ -0,0 +1,169 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.commands;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.util.TabCompleter;
import java.util.Collections;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Command adding the ability to search online players' inventories for enchantments of a specific
* type at or above the level specified.
*
* @author Jikoo
*/
public class SearchEnchantCommand implements TabExecutor {
private final OpenInv plugin;
public SearchEnchantCommand(OpenInv plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (args.length == 0) {
return false;
}
Enchantment enchant = null;
int level = 0;
for (String argument : args) {
try {
level = Integer.parseInt(argument);
continue;
} catch (NumberFormatException ignored) {}
argument = argument.toLowerCase();
int colon = argument.indexOf(':');
NamespacedKey key;
try {
if (colon > -1 && colon < argument.length() - 1) {
key = new NamespacedKey(argument.substring(0, colon), argument.substring(colon + 1));
} else {
key = NamespacedKey.minecraft(argument);
}
} catch (IllegalArgumentException ignored) {
continue;
}
Enchantment localEnchant = Enchantment.getByKey(key);
if (localEnchant != null) {
enchant = localEnchant;
}
}
// Arguments not set correctly
if (level == 0 && enchant == null) {
return false;
}
StringBuilder players = new StringBuilder();
for (Player player : plugin.getServer().getOnlinePlayers()) {
boolean flagInventory = containsEnchantment(player.getInventory(), enchant, level);
boolean flagEnder = containsEnchantment(player.getEnderChest(), enchant, level);
// No matches, continue
if (!flagInventory && !flagEnder) {
continue;
}
// Matches, append details
players.append(player.getName()).append(" (");
if (flagInventory) {
players.append("inv");
}
if (flagEnder) {
if (flagInventory) {
players.append(',');
}
players.append("ender");
}
players.append("), ");
}
if (players.length() > 0) {
// Matches found, delete trailing comma and space
players.delete(players.length() - 2, players.length());
} else {
plugin.sendMessage(sender, "messages.info.player.noMatches",
"%target%", (enchant != null ? enchant.getKey().toString() : "") + " >= " + level);
return true;
}
plugin.sendMessage(sender, "messages.info.player.matches",
"%target%", (enchant != null ? enchant.getKey().toString() : "") + " >= " + level,
"%detail%", players.toString());
return true;
}
private boolean containsEnchantment(Inventory inventory, @Nullable Enchantment enchant, int minLevel) {
for (ItemStack item : inventory.getContents()) {
//noinspection ConstantConditions // Spigot improperly annotated, should be ItemStack @NotNull []
if (item == null || item.getType() == Material.AIR) {
continue;
}
if (enchant != null) {
if (item.containsEnchantment(enchant) && item.getEnchantmentLevel(enchant) >= minLevel) {
return true;
}
} else {
if (!item.hasItemMeta()) {
continue;
}
ItemMeta meta = item.getItemMeta();
if (meta == null || !meta.hasEnchants()) {
continue;
}
for (int enchLevel : meta.getEnchants().values()) {
if (enchLevel >= minLevel) {
return true;
}
}
}
}
return false;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (!command.testPermissionSilent(sender) || args.length < 1 || args.length > 2) {
return Collections.emptyList();
}
if (args.length == 1) {
return TabCompleter.completeObject(args[0], enchantment -> enchantment.getKey().toString(), Enchantment.values());
} else {
return TabCompleter.completeInteger(args[1]);
}
}
}

View file

@ -1,111 +0,0 @@
package com.lishid.openinv.commands;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
/**
* Command adding the ability to search online players' inventories for enchantments of a specific
* type at or above the level specified.
*
* @author Jikoo
*/
public class SearchEnchantPluginCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 0) {
return false;
}
Enchantment enchant = null;
int level = 0;
for (String argument : args) {
Enchantment localEnchant = Enchantment.getByName(argument.toUpperCase());
if (localEnchant != null) {
enchant = localEnchant;
continue;
}
try {
level = Integer.parseInt(argument);
} catch (NumberFormatException ignored) {}
}
// Arguments not set correctly
if (level == 0 && enchant == null) {
return false;
}
StringBuilder players = new StringBuilder();
for (Player player : Bukkit.getServer().getOnlinePlayers()) {
boolean flagInventory = containsEnchantment(player.getInventory(), enchant, level);
boolean flagEnder = containsEnchantment(player.getEnderChest(), enchant, level);
// No matches, continue
if (!flagInventory && !flagEnder) {
continue;
}
// Matches, append details
players.append(player.getName()).append(" (");
if (flagInventory) {
players.append("inv");
}
if (flagEnder) {
if (flagInventory) {
players.append(',');
}
players.append("ender");
}
players.append("), ");
}
if (players.length() > 0) {
// Matches found, delete trailing comma and space
players.delete(players.length() - 2, players.length());
} else {
sender.sendMessage("No players found with " + (enchant == null ? "any enchant" : enchant.getName())
+ " of level " + level + " or higher.");
return true;
}
sender.sendMessage("Players: " + players.toString());
return true;
}
private boolean containsEnchantment(Inventory inventory, Enchantment enchant, int minLevel) {
for (ItemStack item : inventory.getContents()) {
if (item == null || item.getType() == Material.AIR) {
continue;
}
if (enchant != null) {
if (item.containsEnchantment(enchant) && item.getEnchantmentLevel(enchant) >= minLevel) {
return true;
}
} else {
if (!item.hasItemMeta()) {
continue;
}
ItemMeta meta = item.getItemMeta();
if (!meta.hasEnchants()) {
continue;
}
for (int enchLevel : meta.getEnchants().values()) {
if (enchLevel >= minLevel) {
return true;
}
}
}
}
return false;
}
}

View file

@ -0,0 +1,101 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.commands;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.util.TabCompleter;
import java.util.Collections;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.jetbrains.annotations.NotNull;
public class SearchInvCommand implements TabExecutor {
private final OpenInv plugin;
public SearchInvCommand(OpenInv plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
Material material = null;
if (args.length >= 1) {
material = Material.getMaterial(args[0].toUpperCase());
}
if (material == null) {
plugin.sendMessage(sender, "messages.error.invalidMaterial", "%target%", args.length > 0 ? args[0] : "null");
return false;
}
int count = 1;
if (args.length >= 2) {
try {
count = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
plugin.sendMessage(sender, "messages.error.invalidNumber", "%target%", args[1]);
return false;
}
}
StringBuilder players = new StringBuilder();
boolean searchInv = command.getName().equals("searchinv");
for (Player player : plugin.getServer().getOnlinePlayers()) {
Inventory inventory = searchInv ? player.getInventory() : player.getEnderChest();
if (inventory.contains(material, count)) {
players.append(player.getName()).append(", ");
}
}
// Matches found, delete trailing comma and space
if (players.length() > 0) {
players.delete(players.length() - 2, players.length());
} else {
plugin.sendMessage(sender, "messages.info.player.noMatches",
"%target%", material.name());
return true;
}
plugin.sendMessage(sender, "messages.info.player.matches",
"%target%", material.name(), "%detail%", players.toString());
return true;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (args.length < 1 || args.length > 2 || !command.testPermissionSilent(sender)) {
return Collections.emptyList();
}
String argument = args[args.length - 1];
if (args.length == 1) {
return TabCompleter.completeEnum(argument, Material.class);
} else {
return TabCompleter.completeInteger(argument);
}
}
}

View file

@ -1,75 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.commands;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
public class SearchInvPluginCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
Material material = null;
int count = 1;
if (args.length >= 1) {
String[] gData = null;
gData = args[0].split(":");
material = Material.matchMaterial(gData[0]);
}
if (args.length >= 2) {
try {
count = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "'" + args[1] + "' is not a number!");
return false;
}
}
if (material == null) {
sender.sendMessage(ChatColor.RED + "Unknown item");
return false;
}
StringBuilder players = new StringBuilder();
for (Player player : Bukkit.getServer().getOnlinePlayers()) {
Inventory inventory = command.getName().equals("searchinv") ? player.getInventory() : player.getEnderChest();
if (inventory.contains(material, count)) {
players.append(player.getName()).append(", ");
}
}
// Matches found, delete trailing comma and space
if (players.length() > 0) {
players.delete(players.length() - 2, players.length());
} else {
sender.sendMessage("No players found with " + material.toString());
}
sender.sendMessage("Players with the item " + material.toString() + ": " + players.toString());
return true;
}
}

View file

@ -1,53 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.commands;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.lishid.openinv.OpenInv;
public class SilentChestPluginCommand implements CommandExecutor {
private final OpenInv plugin;
public SilentChestPluginCommand(OpenInv plugin) {
this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You can't use this from the console.");
return true;
}
Player player = (Player) sender;
if (args.length > 0 && args[0].equalsIgnoreCase("check")) {
sender.sendMessage("SilentChest is " + (plugin.getPlayerAnyChestStatus(player) ? "ON" : "OFF") + ".");
return true;
}
plugin.setPlayerSilentChestStatus(player, !plugin.getPlayerSilentChestStatus(player));
sender.sendMessage("SilentChest is now " + (plugin.getPlayerSilentChestStatus(player) ? "ON" : "OFF") + ".");
return true;
}
}

View file

@ -0,0 +1,66 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryView;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public interface IPlayerDataManager {
/**
* Loads a Player for an OfflinePlayer.
* </p>
* This method is potentially blocking, and should not be called on the main thread.
*
* @param offline the OfflinePlayer
* @return the Player loaded
*/
@Nullable Player loadPlayer(@NotNull OfflinePlayer offline);
/**
* Creates a new Player from an existing one that will function slightly better offline.
*
* @return the Player
*/
@NotNull Player inject(@NotNull Player player);
/**
* Opens an ISpecialInventory for a Player.
*
* @param player the Player opening the ISpecialInventory
* @param inventory the Inventory
*`
* @return the InventoryView opened
*/
@Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory);
/**
* Convert a raw slot number into a player inventory slot number.
*
* <p>Note that this method is specifically for converting an ISpecialPlayerInventory slot number into a regular
* player inventory slot number.
*
* @param view the open inventory view
* @param rawSlot the raw slot in the view
* @return the converted slot number
*/
int convertToPlayerSlot(InventoryView view, int rawSlot);
}

View file

@ -0,0 +1,83 @@
/*
* Copyright (C) 2011-2021 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal;
import com.lishid.openinv.OpenInv;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.jetbrains.annotations.NotNull;
public class OpenInventoryView extends InventoryView {
private final Player player;
private final ISpecialInventory inventory;
private final String titleKey;
private final String titleDefaultSuffix;
private String title;
public OpenInventoryView(Player player, ISpecialInventory inventory, String titleKey, String titleDefaultSuffix) {
this.player = player;
this.inventory = inventory;
this.titleKey = titleKey;
this.titleDefaultSuffix = titleDefaultSuffix;
}
@Override
public @NotNull Inventory getTopInventory() {
return inventory.getBukkitInventory();
}
@Override
public @NotNull Inventory getBottomInventory() {
return getPlayer().getInventory();
}
@Override
public @NotNull HumanEntity getPlayer() {
return player;
}
@Override
public @NotNull InventoryType getType() {
return inventory.getBukkitInventory().getType();
}
@Override
public @NotNull String getTitle() {
if (title == null) {
HumanEntity owner = getPlayer();
String localTitle = OpenInv.getPlugin(OpenInv.class)
.getLocalizedMessage(
owner,
titleKey,
"%player%",
owner.getName());
if (localTitle != null) {
title = localTitle;
} else {
title = owner.getName() + titleDefaultSuffix;
}
}
return title;
}
}

View file

@ -0,0 +1,205 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.listeners;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.util.InventoryAccess;
import com.lishid.openinv.util.Permissions;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.bukkit.GameMode;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryInteractEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Listener for inventory-related events to prevent modification of inventories where not allowed.
*
* @author Jikoo
*/
public class InventoryListener implements Listener {
private final OpenInv plugin;
public InventoryListener(final OpenInv plugin) {
this.plugin = plugin;
}
@EventHandler
public void onInventoryClose(@NotNull final InventoryCloseEvent event) {
if (!(event.getPlayer() instanceof Player)) {
return;
}
Player player = (Player) event.getPlayer();
if (this.plugin.getPlayerSilentChestStatus(player)) {
this.plugin.getAnySilentContainer().deactivateContainer(player);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onInventoryClick(@NotNull final InventoryClickEvent event) {
if (handleInventoryInteract(event)) {
return;
}
// Safe cast - has to be a player to be the holder of a special player inventory.
Player player = (Player) event.getWhoClicked();
if (event.getAction() != InventoryAction.MOVE_TO_OTHER_INVENTORY) {
// All own-inventory interactions require updates to display properly.
// Update in same tick after event completion.
this.plugin.getServer().getScheduler().runTask(this.plugin, player::updateInventory);
return;
}
// Extra handling for MOVE_TO_OTHER_INVENTORY - apparently Mojang no longer removes the item from the target
// inventory prior to adding it to existing stacks.
ItemStack currentItem = event.getCurrentItem();
if (currentItem == null) {
// Other plugin doing some sort of handling (would be NOTHING for null item otherwise), ignore.
return;
}
ItemStack clone = currentItem.clone();
event.setCurrentItem(null);
// Complete add action in same tick after event completion.
this.plugin.getServer().getScheduler().runTask(this.plugin, () -> {
player.getInventory().addItem(clone);
player.updateInventory();
});
}
@EventHandler(priority = EventPriority.LOWEST)
public void onInventoryDrag(@NotNull final InventoryDragEvent event) {
if (handleInventoryInteract(event)) {
return;
}
InventoryView view = event.getView();
int topSize = view.getTopInventory().getSize();
// Get bottom inventory active slots as player inventory slots.
Set<Integer> slots = event.getRawSlots().stream()
.filter(slot -> slot >= topSize)
.map(slot -> plugin.convertToPlayerSlot(view, slot)).collect(Collectors.toSet());
int overlapLosses = 0;
// Count overlapping slots.
for (Map.Entry<Integer, ItemStack> newItem : event.getNewItems().entrySet()) {
int rawSlot = newItem.getKey();
// Skip bottom inventory slots.
if (rawSlot >= topSize) {
continue;
}
int convertedSlot = plugin.convertToPlayerSlot(view, rawSlot);
if (slots.contains(convertedSlot)) {
overlapLosses += getCountDiff(view.getItem(rawSlot), newItem.getValue());
}
}
// Allow no overlap to proceed as usual.
if (overlapLosses < 1) {
return;
}
ItemStack cursor = event.getCursor();
if (cursor != null) {
cursor.setAmount(cursor.getAmount() + overlapLosses);
} else {
cursor = event.getOldCursor().clone();
cursor.setAmount(overlapLosses);
}
event.setCursor(cursor);
}
private int getCountDiff(@Nullable ItemStack original, @NotNull ItemStack result) {
if (original == null || original.getType() != result.getType()) {
return result.getAmount();
}
return result.getAmount() - original.getAmount();
}
/**
* Handle common InventoryInteractEvent functions.
*
* @param event the InventoryInteractEvent
* @return true unless the top inventory is the holder's own inventory
*/
private boolean handleInventoryInteract(@NotNull final InventoryInteractEvent event) {
HumanEntity entity = event.getWhoClicked();
// Un-cancel spectator interactions.
if (Permissions.SPECTATE.hasPermission(entity) && entity.getGameMode() == GameMode.SPECTATOR) {
event.setCancelled(false);
}
if (event.isCancelled()) {
return true;
}
Inventory inventory = event.getView().getTopInventory();
// Is the inventory a special ender chest?
if (InventoryAccess.isEnderChest(inventory)) {
// Disallow ender chest interaction for users without edit permission.
if (!Permissions.EDITENDER.hasPermission(entity)) {
event.setCancelled(true);
}
return true;
}
ISpecialPlayerInventory playerInventory = InventoryAccess.getPlayerInventory(inventory);
// Ignore inventories other than special player inventories.
if (playerInventory == null) {
return true;
}
// Disallow player inventory interaction for users without edit permission.
if (!Permissions.EDITINV.hasPermission(entity)) {
event.setCancelled(true);
return true;
}
// Only specially handle actions in the player's own inventory.
return !event.getWhoClicked().equals(event.getView().getTopInventory().getHolder());
}
}

View file

@ -0,0 +1,94 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.listeners;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.util.Permissions;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
public class PlayerListener implements Listener {
private final OpenInv plugin;
public PlayerListener(OpenInv plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerJoin(final PlayerJoinEvent event) {
plugin.setPlayerOnline(event.getPlayer());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerQuit(PlayerQuitEvent event) {
plugin.setPlayerOffline(event.getPlayer());
}
@EventHandler
public void onWorldChange(PlayerChangedWorldEvent event) {
plugin.changeWorld(event.getPlayer());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
// Do not cancel 3rd party plugins' custom events
if (!PlayerInteractEvent.class.equals(event.getClass())) {
return;
}
if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getPlayer().isSneaking()
|| event.useInteractedBlock() == Result.DENY || event.getClickedBlock() == null
|| !plugin.getAnySilentContainer().isAnySilentContainer(event.getClickedBlock())) {
return;
}
Player player = event.getPlayer();
boolean any = Permissions.ANYCHEST.hasPermission(player) && plugin.getPlayerAnyChestStatus(player);
boolean needsAny = plugin.getAnySilentContainer().isAnyContainerNeeded(player, event.getClickedBlock());
if (!any && needsAny) {
return;
}
boolean silent = Permissions.SILENT.hasPermission(player) && plugin.getPlayerSilentChestStatus(player);
// If anycontainer or silentcontainer is active
if (any || silent) {
if (plugin.getAnySilentContainer().activateContainer(player, silent, event.getClickedBlock())) {
if (silent && plugin.notifySilentChest() && needsAny && plugin.notifyAnyChest()) {
plugin.sendSystemMessage(player, "messages.info.containerBlockedSilent");
} else if (needsAny && plugin.notifyAnyChest()) {
plugin.sendSystemMessage(player, "messages.info.containerBlocked");
} else if (silent && plugin.notifySilentChest()) {
plugin.sendSystemMessage(player, "messages.info.containerSilent");
}
}
event.setCancelled(true);
}
}
}

View file

@ -0,0 +1,42 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.listeners;
import com.lishid.openinv.OpenInv;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
/**
* Listener for plugin-related events.
*
* @author Jikoo
*/
public class PluginListener implements Listener {
private final OpenInv plugin;
public PluginListener(OpenInv plugin) {
this.plugin = plugin;
}
@EventHandler
public void onPluginDisable(PluginDisableEvent event) {
plugin.releaseAllPlayers(event.getPlugin());
}
}

View file

@ -1,16 +1,35 @@
package com.lishid.openinv.util;
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
package com.lishid.openinv.util;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* A minimal time-based cache implementation backed by a HashMap and TreeMultimap.
*
* A minimal thread-safe time-based cache implementation backed by a HashMap and TreeMultimap.
*
* @author Jikoo
*/
public class Cache<K, V> {
@ -18,30 +37,20 @@ public class Cache<K, V> {
private final Map<K, V> internal;
private final Multimap<Long, K> expiry;
private final long retention;
private final Function<V> inUseCheck, postRemoval;
private final Predicate<V> inUseCheck;
private final Consumer<V> postRemoval;
/**
* Constructs a Cache with the specified retention duration, in use function, and post-removal function.
*
*
* @param retention duration after which keys are automatically invalidated if not in use
* @param inUseCheck Function used to check if a key is considered in use
* @param postRemoval Function used to perform any operations required when a key is invalidated
* @param inUseCheck Predicate used to check if a key is considered in use
* @param postRemoval Consumer used to perform any operations required when a key is invalidated
*/
public Cache(long retention, Function<V> inUseCheck, Function<V> postRemoval) {
this.internal = new HashMap<K, V>();
public Cache(final long retention, final Predicate<V> inUseCheck, final Consumer<V> postRemoval) {
this.internal = new HashMap<>();
this.expiry = TreeMultimap.create(new Comparator<Long>() {
@Override
public int compare(Long long1, Long long2) {
return long1.compareTo(long2);
}
},
new Comparator<K>() {
@Override
public int compare(K k1, K k2) {
return 0;
}
});
this.expiry = TreeMultimap.create(Long::compareTo, (k1, k2) -> Objects.equals(k1, k2) ? 0 : 1);
this.retention = retention;
this.inUseCheck = inUseCheck;
@ -51,66 +60,74 @@ public class Cache<K, V> {
/**
* Set a key and value pair. Keys are unique. Using an existing key will cause the old value to
* be overwritten and the expiration timer to be reset.
*
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
*/
public void put(K key, V value) {
public void put(final K key, final V value) {
// Invalidate key - runs lazy check and ensures value won't be cleaned up early
invalidate(key);
this.invalidate(key);
internal.put(key, value);
expiry.put(System.currentTimeMillis() + retention, key);
synchronized (this.internal) {
this.internal.put(key, value);
this.expiry.put(System.currentTimeMillis() + this.retention, key);
}
}
/**
* Returns the value to which the specified key is mapped, or null if no value is mapped for the key.
*
*
* @param key the key whose associated value is to be returned
* @return the value to which the specified key is mapped, or null if no value is mapped for the key
*/
public V get(K key) {
public V get(final K key) {
// Run lazy check to clean cache
lazyCheck();
this.lazyCheck();
return internal.get(key);
synchronized (this.internal) {
return this.internal.get(key);
}
}
/**
* Returns true if the specified key is mapped to a value.
*
*
* @param key key to check if a mapping exists for
* @return true if a mapping exists for the specified key
*/
public boolean containsKey(K key) {
public boolean containsKey(final K key) {
// Run lazy check to clean cache
lazyCheck();
this.lazyCheck();
return internal.containsKey(key);
synchronized (this.internal) {
return this.internal.containsKey(key);
}
}
/**
* Forcibly invalidates a key, even if it is considered to be in use.
*
*
* @param key key to invalidate
*/
public void invalidate(K key) {
public void invalidate(final K key) {
// Run lazy check to clean cache
lazyCheck();
this.lazyCheck();
if (!internal.containsKey(key)) {
// Value either not present or cleaned by lazy check. Either way, we're good
return;
}
synchronized (this.internal) {
if (!this.internal.containsKey(key)) {
// Value either not present or cleaned by lazy check. Either way, we're good
return;
}
// Remove stored object
internal.remove(key);
// Remove stored object
this.internal.remove(key);
// Remove expiration entry - prevents more work later, plus prevents issues with values invalidating early
for (Iterator<Map.Entry<Long, K>> iterator = expiry.entries().iterator(); iterator.hasNext();) {
if (key.equals(iterator.next().getValue())) {
iterator.remove();
break;
// Remove expiration entry - prevents more work later, plus prevents issues with values invalidating early
for (Iterator<Map.Entry<Long, K>> iterator = this.expiry.entries().iterator(); iterator.hasNext();) {
if (key.equals(iterator.next().getValue())) {
iterator.remove();
break;
}
}
}
}
@ -119,11 +136,13 @@ public class Cache<K, V> {
* Forcibly invalidates all keys, even if they are considered to be in use.
*/
public void invalidateAll() {
for (V value : internal.values()) {
postRemoval.run(value);
synchronized (this.internal) {
for (V value : this.internal.values()) {
this.postRemoval.accept(value);
}
this.expiry.clear();
this.internal.clear();
}
expiry.clear();
internal.clear();
}
/**
@ -132,28 +151,36 @@ public class Cache<K, V> {
*/
private void lazyCheck() {
long now = System.currentTimeMillis();
long nextExpiry = now + retention;
for (Iterator<Map.Entry<Long, K>> iterator = expiry.entries().iterator(); iterator.hasNext();) {
Map.Entry<Long, K> entry = iterator.next();
synchronized (this.internal) {
List<K> inUse = new ArrayList<>();
for (Iterator<Map.Entry<Long, K>> iterator = this.expiry.entries().iterator(); iterator
.hasNext();) {
Map.Entry<Long, K> entry = iterator.next();
if (entry.getKey() > now) {
break;
if (entry.getKey() > now) {
break;
}
iterator.remove();
if (this.inUseCheck.test(this.internal.get(entry.getValue()))) {
inUse.add(entry.getValue());
continue;
}
V value = this.internal.remove(entry.getValue());
if (value == null) {
continue;
}
this.postRemoval.accept(value);
}
iterator.remove();
if (inUseCheck.run(internal.get(entry.getValue()))) {
expiry.put(nextExpiry, entry.getValue());
continue;
long nextExpiry = now + this.retention;
for (K value : inUse) {
this.expiry.put(nextExpiry, value);
}
V value = internal.remove(entry.getValue());
if (value == null) {
continue;
}
postRemoval.run(value);
}
}

View file

@ -0,0 +1,147 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
import com.lishid.openinv.OpenInv;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.ConfigurationSection;
public class ConfigUpdater {
private final OpenInv plugin;
public ConfigUpdater(OpenInv plugin) {
this.plugin = plugin;
}
public void checkForUpdates() {
final int version = plugin.getConfig().getInt("config-version", 1);
ConfigurationSection defaults = plugin.getConfig().getDefaults();
if (defaults == null || version >= defaults.getInt("config-version")) {
return;
}
plugin.getLogger().info("Configuration update found! Performing update...");
// Backup the old config file
try {
plugin.getConfig().save(new File(plugin.getDataFolder(), "config_old.yml"));
plugin.getLogger().info("Backed up config.yml to config_old.yml before updating.");
} catch (IOException e) {
plugin.getLogger().warning("Could not back up config.yml before updating!");
}
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> {
if (version < 2) {
updateConfig1To2();
}
if (version < 3) {
updateConfig2To3();
}
if (version < 4) {
updateConfig3To4();
}
plugin.getServer().getScheduler().runTask(plugin, () -> {
plugin.saveConfig();
plugin.getLogger().info("Configuration update complete!");
});
});
}
private void updateConfig3To4() {
plugin.getServer().getScheduler().runTask(plugin, () -> {
plugin.getConfig().set("notify", null);
plugin.getConfig().set("settings.locale", "en_US");
plugin.getConfig().set("config-version", 4);
});
}
private void updateConfig2To3() {
plugin.getServer().getScheduler().runTask(plugin, () -> {
plugin.getConfig().set("config-version", 3);
plugin.getConfig().set("items.open-inv", null);
plugin.getConfig().set("ItemOpenInv", null);
plugin.getConfig().set("toggles.items.open-inv", null);
plugin.getConfig().set("settings.disable-saving",
plugin.getConfig().getBoolean("DisableSaving", false));
plugin.getConfig().set("DisableSaving", null);
});
}
private void updateConfig1To2() {
plugin.getServer().getScheduler().runTask(plugin, () -> {
// Get the old config settings
boolean notifySilentChest = plugin.getConfig().getBoolean("NotifySilentChest", true);
boolean notifyAnyChest = plugin.getConfig().getBoolean("NotifyAnyChest", true);
plugin.getConfig().set("ItemOpenInvItemID", null);
plugin.getConfig().set("NotifySilentChest", null);
plugin.getConfig().set("NotifyAnyChest", null);
plugin.getConfig().set("config-version", 2);
plugin.getConfig().set("notify.any-chest", notifyAnyChest);
plugin.getConfig().set("notify.silent-chest", notifySilentChest);
});
updateToggles("AnyChest", "toggles.any-chest");
updateToggles("SilentChest", "toggles.silent-chest");
}
private void updateToggles(final String sectionName, final String newSectionName) {
ConfigurationSection section = plugin.getConfig().getConfigurationSection(sectionName);
// Ensure section exists
if (section == null) {
return;
}
Set<String> keys = section.getKeys(false);
// Ensure section has content
if (keys.isEmpty()) {
return;
}
final Map<String, Boolean> toggles = new HashMap<>();
for (String playerName : keys) {
OfflinePlayer player = plugin.matchPlayer(playerName);
if (player != null) {
toggles.put(plugin.getPlayerID(player), section.getBoolean(playerName + ".toggle", false));
}
}
plugin.getServer().getScheduler().runTask(plugin, () -> {
// Wipe old ConfigurationSection
plugin.getConfig().set(sectionName, null);
// Prepare new ConfigurationSection
ConfigurationSection newSection = plugin.getConfig().getConfigurationSection(newSectionName);
if (newSection == null) {
newSection = plugin.getConfig().createSection(newSectionName);
}
// Set new values
for (Map.Entry<String, Boolean> entry : toggles.entrySet()) {
newSection.set(entry.getKey(), entry.getValue());
}
});
}
}

View file

@ -1,12 +0,0 @@
package com.lishid.openinv.util;
/**
* Abstraction for some simple cache calls.
*
* @author Jikoo
*/
public abstract class Function<V> {
public abstract boolean run(V value);
}

View file

@ -0,0 +1,219 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
import com.lishid.openinv.internal.IAnySilentContainer;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class InternalAccessor {
private final Plugin plugin;
private final String version;
private boolean supported = false;
private IPlayerDataManager playerDataManager;
private IAnySilentContainer anySilentContainer;
public InternalAccessor(final Plugin plugin) {
this.plugin = plugin;
String packageName = plugin.getServer().getClass().getPackage().getName();
this.version = packageName.substring(packageName.lastIndexOf('.') + 1);
try {
Class.forName("com.lishid.openinv.internal." + this.version + ".SpecialPlayerInventory");
Class.forName("com.lishid.openinv.internal." + this.version + ".SpecialEnderChest");
this.playerDataManager = this.createObject(IPlayerDataManager.class, "PlayerDataManager");
this.anySilentContainer = this.createObject(IAnySilentContainer.class, "AnySilentContainer");
this.supported = InventoryAccess.isUsable();
} catch (Exception ignored) {}
}
public String getReleasesLink() {
switch (version) {
case "1_4_5":
case "1_4_6":
case "v1_4_R1":
case "v1_5_R2":
case "v1_5_R3":
case "v1_6_R1":
case "v1_6_R2":
case "v1_6_R3":
case "v1_7_R1":
case "v1_7_R2":
case "v1_7_R3":
case "v1_7_R4":
case "v1_8_R1":
case "v1_8_R2":
case "v1_9_R1":
case "v1_9_R2":
case "v1_10_R1":
case "v1_11_R1":
case "v1_12_R1":
return "https://github.com/lishid/OpenInv/releases/tag/4.0.0 (OpenInv-legacy)";
case "v1_13_R1":
return "https://github.com/lishid/OpenInv/releases/tag/4.0.0";
case "v1_13_R2":
return "https://github.com/lishid/OpenInv/releases/tag/4.0.7";
case "v1_14_R1":
return "https://github.com/lishid/OpenInv/releases/tag/4.1.1";
case "v1_16_R1":
return "https://github.com/lishid/OpenInv/releases/tag/4.1.4";
case "v1_8_R3":
case "v1_15_R1":
case "v1_16_R2":
return "https://github.com/lishid/OpenInv/releases/tag/4.1.5";
case "v1_16_R3":
default:
return "https://github.com/lishid/OpenInv/releases";
}
}
private <T> T createObject(final Class<? extends T> assignableClass, final String className,
final Object... params) throws ClassCastException, ClassNotFoundException,
InstantiationException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException, NoSuchMethodException, SecurityException {
// Fetch internal class if it exists.
Class<?> internalClass = Class.forName("com.lishid.openinv.internal." + this.version + "." + className);
if (!assignableClass.isAssignableFrom(internalClass)) {
String message = String.format("Found class %s but cannot cast to %s!", internalClass.getName(), assignableClass.getName());
this.plugin.getLogger().warning(message);
throw new IllegalStateException(message);
}
// Quick return: no parameters, no need to fiddle about finding the correct constructor.
if (params.length == 0) {
return assignableClass.cast(internalClass.getConstructor().newInstance());
}
// Search constructors for one matching the given parameters
nextConstructor: for (Constructor<?> constructor : internalClass.getConstructors()) {
Class<?>[] requiredClasses = constructor.getParameterTypes();
if (requiredClasses.length != params.length) {
continue;
}
for (int i = 0; i < params.length; ++i) {
if (!requiredClasses[i].isAssignableFrom(params[i].getClass())) {
continue nextConstructor;
}
}
return assignableClass.cast(constructor.newInstance(params));
}
StringBuilder builder = new StringBuilder("Found class ").append(internalClass.getName())
.append(" but cannot find any matching constructors for [");
for (Object object : params) {
builder.append(object.getClass().getName()).append(", ");
}
builder.delete(builder.length() - 2, builder.length());
String message = builder.append(']').toString();
this.plugin.getLogger().warning(message);
throw new IllegalArgumentException(message);
}
/**
* Creates an instance of the IAnySilentContainer implementation for the current server version.
*
* @return the IAnySilentContainer
* @throws IllegalStateException if server version is unsupported
*/
public IAnySilentContainer getAnySilentContainer() {
if (!this.supported) {
throw new IllegalStateException(String.format("Unsupported server version %s!", this.version));
}
return this.anySilentContainer;
}
/**
* Creates an instance of the IPlayerDataManager implementation for the current server version.
*
* @return the IPlayerDataManager
* @throws IllegalStateException if server version is unsupported
*/
public IPlayerDataManager getPlayerDataManager() {
if (!this.supported) {
throw new IllegalStateException(String.format("Unsupported server version %s!", this.version));
}
return this.playerDataManager;
}
/**
* Gets the server implementation version. If not initialized, returns the string "null"
* instead.
*
* @return the version, or "null"
*/
public String getVersion() {
return this.version != null ? this.version : "null";
}
/**
* Checks if the server implementation is supported.
*
* @return true if initialized for a supported server version
*/
public boolean isSupported() {
return this.supported;
}
/**
* Creates an instance of the ISpecialEnderChest implementation for the given Player, or
* null if the current version is unsupported.
*
* @param player the Player
* @param online true if the Player is online
* @return the ISpecialEnderChest created
* @throws InstantiationException if the ISpecialEnderChest could not be instantiated
*/
public ISpecialEnderChest newSpecialEnderChest(final Player player, final boolean online) throws InstantiationException {
if (!this.supported) {
throw new IllegalStateException(String.format("Unsupported server version %s!", this.version));
}
try {
return this.createObject(ISpecialEnderChest.class, "SpecialEnderChest", player, online);
} catch (Exception e) {
throw new InstantiationException(String.format("Unable to create a new ISpecialEnderChest: %s", e.getMessage()));
}
}
/**
* Creates an instance of the ISpecialPlayerInventory implementation for the given Player..
*
* @param player the Player
* @param online true if the Player is online
* @return the ISpecialPlayerInventory created
* @throws InstantiationException if the ISpecialPlayerInventory could not be instantiated
*/
public ISpecialPlayerInventory newSpecialPlayerInventory(final Player player, final boolean online) throws InstantiationException {
if (!this.supported) {
throw new IllegalStateException(String.format("Unsupported server version %s!", this.version));
}
try {
return this.createObject(ISpecialPlayerInventory.class, "SpecialPlayerInventory", player, online);
} catch (Exception e) {
throw new InstantiationException(String.format("Unable to create a new ISpecialPlayerInventory: %s", e.getMessage()));
}
}
}

View file

@ -0,0 +1,170 @@
/*
* Copyright (C) 2011-2020 Jikoo. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
import com.lishid.openinv.OpenInv;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* A simple language manager supporting both custom and bundled languages.
*
* @author Jikoo
*/
public class LanguageManager {
private final OpenInv plugin;
private final String defaultLocale;
private final Map<String, YamlConfiguration> locales;
public LanguageManager(@NotNull OpenInv plugin, @NotNull String defaultLocale) {
this.plugin = plugin;
this.defaultLocale = defaultLocale;
this.locales = new HashMap<>();
getOrLoadLocale(defaultLocale);
}
private YamlConfiguration getOrLoadLocale(@NotNull String locale) {
YamlConfiguration loaded = locales.get(locale);
if (loaded != null) {
return loaded;
}
InputStream resourceStream = plugin.getResource(locale + ".yml");
YamlConfiguration localeConfigDefaults;
if (resourceStream == null) {
localeConfigDefaults = new YamlConfiguration();
} else {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceStream))) {
localeConfigDefaults = YamlConfiguration.loadConfiguration(reader);
} catch (IOException e) {
plugin.getLogger().log(Level.WARNING, "[LanguageManager] Unable to load resource " + locale + ".yml", e);
localeConfigDefaults = new YamlConfiguration();
}
}
File file = new File(plugin.getDataFolder(), locale + ".yml");
YamlConfiguration localeConfig;
if (!file.exists()) {
localeConfig = localeConfigDefaults;
try {
localeConfigDefaults.save(file);
} catch (IOException e) {
plugin.getLogger().log(Level.WARNING, "[LanguageManager] Unable to save resource " + locale + ".yml", e);
}
} else {
localeConfig = YamlConfiguration.loadConfiguration(file);
// Add new language keys
List<String> newKeys = new ArrayList<>();
for (String key : localeConfigDefaults.getKeys(true)) {
if (localeConfigDefaults.isConfigurationSection(key)) {
continue;
}
if (localeConfig.isSet(key)) {
continue;
}
localeConfig.set(key, localeConfigDefaults.get(key));
newKeys.add(key);
}
if (!newKeys.isEmpty()) {
plugin.getLogger().info("[LanguageManager] Added new language keys: " + String.join(", ", newKeys));
try {
localeConfig.save(file);
} catch (IOException e) {
plugin.getLogger().log(Level.WARNING, "[LanguageManager] Unable to save resource " + locale + ".yml", e);
}
}
}
if (!locale.equals(defaultLocale)) {
localeConfigDefaults = locales.get(defaultLocale);
// Check for missing keys
List<String> newKeys = new ArrayList<>();
for (String key : localeConfigDefaults.getKeys(true)) {
if (localeConfigDefaults.isConfigurationSection(key)) {
continue;
}
if (localeConfig.isSet(key)) {
continue;
}
newKeys.add(key);
}
if (!newKeys.isEmpty()) {
plugin.getLogger().info("[LanguageManager] Missing translations from " + locale + ".yml: " + String.join(", ", newKeys));
}
// Fall through to default locale
localeConfig.setDefaults(localeConfigDefaults);
}
locales.put(locale, localeConfig);
return localeConfig;
}
@Nullable
public String getValue(@NotNull String key, @Nullable String locale) {
String value = getOrLoadLocale(locale == null ? defaultLocale : locale.toLowerCase()).getString(key);
if (value == null || value.isEmpty()) {
return null;
}
value = ChatColor.translateAlternateColorCodes('&', value);
return value;
}
@Nullable
public String getValue(@NotNull String key, @Nullable String locale, @NotNull String... replacements) {
if (replacements.length % 2 != 0) {
plugin.getLogger().log(Level.WARNING, "[LanguageManager] Replacement data is uneven", new Exception());
}
String value = getValue(key, locale);
if (value == null) {
return null;
}
for (int i = 0; i < replacements.length; i += 2) {
value = value.replace(replacements[i], replacements[i + 1]);
}
return value;
}
}

View file

@ -0,0 +1,78 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
import org.bukkit.permissions.Permissible;
public enum Permissions {
OPENINV("openinv"),
OVERRIDE("override"),
EXEMPT("exempt"),
CROSSWORLD("crossworld"),
SILENT("silent"),
SILENT_DEFAULT("silent.default", true),
ANYCHEST("anychest"),
ANY_DEFAULT("any.default", true),
ENDERCHEST("openender"),
ENDERCHEST_ALL("openenderall"),
SEARCH("search"),
EDITINV("editinv"),
EDITENDER("editender"),
OPENSELF("openself"),
OPENONLINE("openonline"),
OPENOFFLINE("openoffline"),
SPECTATE("spectate");
private final String permission;
private final boolean uninheritable;
Permissions(String permission) {
this(permission, false);
}
Permissions(String permission, boolean uninheritable) {
this.permission = "OpenInv." + permission;
this.uninheritable = uninheritable;
}
public boolean hasPermission(Permissible permissible) {
boolean hasPermission = permissible.hasPermission(permission);
if (uninheritable || hasPermission || permissible.isPermissionSet(permission)) {
return hasPermission;
}
StringBuilder permissionDestroyer = new StringBuilder(permission);
for (int lastPeriod = permissionDestroyer.lastIndexOf("."); lastPeriod > 0;
lastPeriod = permissionDestroyer.lastIndexOf(".")) {
permissionDestroyer.delete(lastPeriod + 1, permissionDestroyer.length()).append('*');
hasPermission = permissible.hasPermission(permissionDestroyer.toString());
if (hasPermission || permissible.isPermissionSet(permissionDestroyer.toString())) {
return hasPermission;
}
permissionDestroyer.delete(lastPeriod, permissionDestroyer.length());
}
return permissible.hasPermission("*");
}
}

View file

@ -0,0 +1,147 @@
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.function.Function;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
/**
* Utility class for common tab completions.
*/
public class TabCompleter {
/**
* Offer tab completions for whole numbers.
*
* @param argument the argument to complete
* @return integer options
*/
public static List<String> completeInteger(String argument) {
// Ensure existing argument is actually a number
if (!argument.isEmpty()) {
try {
Integer.parseInt(argument);
} catch (NumberFormatException e) {
return Collections.emptyList();
}
}
List<String> completions = new ArrayList<>(10);
for (int i = 0; i < 10; ++i) {
completions.add(argument + i);
}
return completions;
}
/**
* Offer tab completions for a given Enum.
*
* @param argument the argument to complete
* @param enumClazz the Enum to complete for
* @return the matching Enum values
*/
public static List<String> completeEnum(String argument, Class<? extends Enum<?>> enumClazz) {
argument = argument.toLowerCase(Locale.ENGLISH);
List<String> completions = new ArrayList<>();
for (Enum<?> enumConstant : enumClazz.getEnumConstants()) {
String name = enumConstant.name().toLowerCase();
if (name.startsWith(argument)) {
completions.add(name);
}
}
return completions;
}
/**
* Offer tab completions for a given array of Strings.
*
* @param argument the argument to complete
* @param options the Strings which may be completed
* @return the matching Strings
*/
public static List<String> completeString(String argument, String[] options) {
argument = argument.toLowerCase(Locale.ENGLISH);
List<String> completions = new ArrayList<>();
for (String option : options) {
if (option.startsWith(argument)) {
completions.add(option);
}
}
return completions;
}
/**
* Offer tab completions for visible online Players' names.
*
* @param sender the command's sender
* @param argument the argument to complete
* @return the matching Players' names
*/
public static List<String> completeOnlinePlayer(CommandSender sender, String argument) {
List<String> completions = new ArrayList<>();
Player senderPlayer = sender instanceof Player ? (Player) sender : null;
for (Player player : Bukkit.getOnlinePlayers()) {
if (senderPlayer != null && !senderPlayer.canSee(player)) {
continue;
}
if (StringUtil.startsWithIgnoreCase(player.getName(), argument)) {
completions.add(player.getName());
}
}
return completions;
}
/**
* Offer tab completions for a given array of Objects.
*
* @param argument the argument to complete
* @param converter the Function for converting the Object into a comparable String
* @param options the Objects which may be completed
* @return the matching Strings
*/
public static <T> List<String> completeObject(String argument, Function<T, String> converter, T[] options) {
argument = argument.toLowerCase(Locale.ENGLISH);
List<String> completions = new ArrayList<>();
for (T option : options) {
String optionString = converter.apply(option).toLowerCase();
if (optionString.startsWith(argument)) {
completions.add(optionString);
}
}
return completions;
}
private TabCompleter() {}
}

View file

@ -0,0 +1,4 @@
config-version: 4
settings:
disable-saving: false
locale: 'en_us'

View file

@ -0,0 +1,30 @@
messages:
error:
consoleUnsupported: 'Du kannst diesen Befehl nicht von der Konsole ausführen.'
lootNotGenerated: '&cBeute noch nicht erstellt! Bitte schalte &b/silentcontainer&c aus.'
invalidMaterial: '&cUngültiges Material: "%target%"'
invalidNumber: '&cUngültige Nummer: "%target%"'
invalidPlayer: '&cSpieler nicht gefunden.'
permissionOpenSelf: '&cDu darfst dein eigenes Inventar nicht öffnen.'
permissionEnderAll: '&cDu darfst die Endertruhen von anderen Spielern nicht öffnen.'
permissionExempt: '&c%target%''s Inventar ist geschützt.'
permissionCrossWorld: '&c%target% ist nicht in der selben Welt wie du.'
permissionPlayerOnline: '&cDu darfst keine Inventare von Spielern öffnen, die online sind.'
permissionPlayerOffline: '&cDu darfst keine Inventare von Spielern öffnen, die offline sind.'
commandException: '&cAn error occurred. Please check console for details.'
info:
containerBlocked: 'Du öffnest einen gesperrten Container.'
containerBlockedSilent: 'Du öffnest einen gesperrten Container lautlos.'
containerSilent: 'Du öffnest einen Container lautlos.'
settingState: '%setting%: %state%'
player:
noMatches: 'Keine Spieler mit %target% gefunden.'
matches: 'Spieler hält %target%: %detail%'
container:
noMatches: 'Keine Container mit %target% gefunden.'
matches: 'Container hat %target%: %detail%'
on: 'an'
off: 'aus'
container:
player: '%player%''s Inventar'
enderchest: '%player%''s Endertruhe'

View file

@ -0,0 +1,30 @@
messages:
error:
consoleUnsupported: 'You cannot use this command from console.'
lootNotGenerated: '&cLoot not generated! Please disable &b/silentcontainer&c.'
invalidMaterial: '&cInvalid material: "%target%"'
invalidNumber: '&cInvalid number: "%target%"'
invalidPlayer: '&cPlayer not found!'
permissionOpenSelf: '&cYou''re not allowed to open your own inventory.'
permissionEnderAll: '&cYou''re not allowed to access other players'' ender chests.'
permissionExempt: '&c%target%''s inventory is protected.'
permissionCrossWorld: '&c%target% is not in your world.'
permissionPlayerOnline: '&cYou''re not allowed to open the inventory of online players.'
permissionPlayerOffline: '&cYou''re not allowed to open the inventory of offline players.'
commandException: '&cAn error occurred. Please check console for details.'
info:
containerBlocked: 'You are opening a blocked container.'
containerBlockedSilent: 'You are opening a blocked container silently.'
containerSilent: 'You are opening a container silently.'
settingState: '%setting%: %state%'
player:
noMatches: 'No players found with %target%.'
matches: 'Players holding %target%: %detail%'
container:
noMatches: 'No containers found with %target%.'
matches: 'Containers holding %target%: %detail%'
on: 'on'
off: 'off'
container:
player: '%player%''s Inventory'
enderchest: '%player%''s Ender Chest'

View file

@ -0,0 +1,31 @@
messages:
error:
consoleUnsupported: 'No puedes usar este comando desde la consola.'
lootNotGenerated: '&c¡Botín no generado! Desactiva &b/silentcontainer&c.'
invalidMaterial: '&cMaterial no válido: "%target%"'
invalidNumber: '&cNúmero no válido: "%target%"'
invalidPlayer: '&cJugador no encontrado'
permissionOpenSelf: '&cNo tienes permisos para abrir tu inventario de esa forma.'
permissionEnderAll: '&cNo tienes permiso para abrir cofres de ender de otros jugadores.'
permissionExempt: '&c El inventario de %target% está protegido.'
permissionCrossWorld: '&c%target% no está en tu dimensión.'
permissionPlayerOnline: '&cNo estás autorizado para abrir inventarios de jugadores conectados.'
permissionPlayerOffline: '&cNo estás autorizado para abrir inventarios de jugadores desconectados.'
commandException: '&cSe ha producido un error, lee la consola para mas información.'
info:
containerBlocked: 'Estás abriendo un contenedor protegido.'
containerBlockedSilent: 'Estás abriendo sigilosamente un contenedor protegido.'
containerSilent: 'Estás abriendo un contenedor sigilosamente.'
settingState: '%setting%: %state%'
player:
noMatches: 'No se encontraron jugadores con %target%.'
matches: 'Jugadores con %target%: %detail%'
container:
noMatches: 'No se encontraron contenedores con %target%.'
matches: 'Contenedores con %target%: %detail%'
on: 'activado'
off: 'desactivado'
container:
player: 'Inventario de %player%'
enderchest: 'Cofre de Ender de %player%'

View file

@ -1,50 +1,89 @@
name: OpenInv
main: com.lishid.openinv.OpenInv
version: ${openinv.version}
version: ${project.version}
author: lishid
authors: [Jikoo, ShadowRanger]
description: >
This plugin allows you to open a player's inventory as a chest and interact with it in real time.
api-version: "1.16"
permissions:
OpenInv.any.default:
description: Permission for AnyContainer to default on prior to toggling.
default: false
OpenInv.silent.default:
description: Permission for SilentContainer to default on prior to toggling.
default: false
OpenInv.*:
description: Permission for all OpenInv features.
default: op
children:
OpenInv.openinv: true
OpenInv.openender: true
OpenInv.search: true
OpenInv.silent: true
OpenInv.anychest: true
OpenInv.searchenchant: true
OpenInv.searchcontainer: true
OpenInv.openonline: true
OpenInv.openoffline: true
OpenInv.spectate: true
OpenInv.openinv:
default: op
children:
OpenInv.openonline: true
OpenInv.openoffline: true
OpenInv.openender:
default: op
children:
OpenInv.openonline: true
OpenInv.openoffline: true
commands:
openinv:
aliases: [oi, inv, open]
description: Open a player's inventory
permission: OpenInv.*;OpenInv.openinv
permission: OpenInv.openinv
usage: |-
/<command> [Player] - Open a player's inventory
openender:
aliases: [oe]
description: Opens the enderchest of a player
permission: OpenInv.*;OpenInv.openender
permission: OpenInv.openender
usage: |-
/<command> [Player] - Open a player's enderchest
searchinv:
aliases: [si]
description: Search and list players having a specific item
permission: OpenInv.*;OpenInv.search
permission: OpenInv.search
usage: |-
/<command> <Item> [MinAmount] - Item is the ID or the Bukkit Material, MinAmount is the minimum amount required
/<command> <Material> [MinAmount] - MinAmount is optional, the minimum amount required
searchender:
aliases: [se]
permission: OpenInv.*;OpenInv.search
permission: OpenInv.search
description: Searches and lists players having a specific item in their ender chest
usage: |-
/<command> <item> [MinAmount] - Item is the ID or the Bukkit Material, MinAmount is the minimum amount required
silentchest:
aliases: [sc, silent]
description: Toggle silent chest function, which stops sounds and animations when using containers.
permission: OpenInv.*;OpenInv.silent
/<command> <Material> [MinAmount] - MinAmount is optional, the minimum amount required
silentcontainer:
aliases: [sc, silent, silentchest]
description: SilentContainer stops sounds and animations when using containers.
permission: OpenInv.silent
usage: |-
/<command> [Check] - Check or toggle silent chest
anychest:
aliases: [ac]
description: Toggle anychest function, which allows opening of blocked chests.
permission: OpenInv.*;OpenInv.anychest
/<command> [check|on|off] - Check, toggle, or set SilentContainer
anycontainer:
aliases: [ac, anychest]
description: AnyContainer allows using blocked containers.
permission: OpenInv.anychest
usage: |-
/<command> [Check] - Checks or toggle anychest
/<command> [check|on|off] - Check, toggle, or set AnyContainer
searchenchant:
aliases: [searchenchants]
description: Search and list players with a specific enchantment.
permission: OpenInv.*;OpenInv.searchenchant
permission: OpenInv.searchenchant
usage: |-
/<command> <[enchantment] [MinLevel]> - Enchantment is the enchantment type, MinLevel is the minimum level. One is optional
/<command> <[Enchantment] [MinLevel]> - Enchantment is the enchantment type, MinLevel is the minimum level. One is optional
searchcontainer:
aliases: [searchchest]
description: Search and list containers with a specific material.
permission: OpenInv.searchcontainer
usage: /<command> <Material> [ChunkRadius] - ChunkRadius is optional, the length that will be searched for matching items. Default 5

View file

@ -0,0 +1,30 @@
messages:
error:
consoleUnsupported: 'Voce nao consegue usar esse comando pelo console.'
lootNotGenerated: '&cPilhagem nao gerada! Por favor desabilite &b/silentcontainer&c.'
invalidMaterial: '&cMaterial invalido: "%target%"'
invalidNumber: '&cNumero invalido: "%target%"'
invalidPlayer: '&cJogador nao encontrado!'
permissionOpenSelf: '&cVoce nao pode abrir seu proprio inventario.'
permissionEnderAll: '&cVoce nao tem permissao para abrir baus de ender de outros jogadores.'
permissionExempt: '&cO inventario de %target% e protegido.'
permissionCrossWorld: '&c%target% nao esta no seu mundo.'
permissionPlayerOnline: '&cVoce nao tem permissao para abrir o inventario de jogadores online.'
permissionPlayerOffline: '&cVoce nao tem permissao para abrir o inventario de jogadores offline.'
commandException: '&cUm erro ocorreu. Por favor cheque o console para detalhes.'
info:
containerBlocked: 'Voce esta abrindo um recipiente bloqueado.'
containerBlockedSilent: 'Voce esta abrindo um recipiente bloqueado silenciosamente.'
containerSilent: 'Voce esta abrindo um recipiente silenciosamente.'
settingState: '%setting%: %state%'
player:
noMatches: 'Nenhum jogador encontrado com %target%.'
matches: 'Jogadores segurando %target%: %detail%'
container:
noMatches: 'Nenhum recipiente encontrado com %target%.'
matches: 'Recipientes contendo %target%: %detail%'
on: 'ligado'
off: 'desligado'
container:
player: 'Inventario de %player%'
enderchest: 'Bau de Ender de %player%'

148
pom.xml
View file

@ -1,123 +1,57 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (C) 2011-2020 lishid. All rights reserved.
~
~ This program is free software: you can redistribute it and/or modify
~ it under the terms of the GNU General Public License as published by
~ the Free Software Foundation, version 3.
~
~ This program is distributed in the hope that it will be useful,
~ but WITHOUT ANY WARRANTY; without even the implied warranty of
~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
~ GNU General Public License for more details.
~
~ You should have received a copy of the GNU General Public License
~ along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lishid</groupId>
<artifactId>openinv</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>OpenInv</name>
<artifactId>openinvparent</artifactId>
<name>OpenInvParent</name>
<url>http://dev.bukkit.org/bukkit-plugins/openinv/</url>
<version>4.1.5-TF</version>
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<openinv.version>3.0.2</openinv.version>
</properties>
<modules>
<module>api</module>
<module>plugin</module>
<module>internal</module>
<module>assembly</module>
</modules>
<profiles>
<!--
~ N.B.: All dependencies for profiles are set in ./assembly/pom.xml
~
~ This is to prevent recursive dependencies. It's not ideal, but it works.
~ The parent project always builds first. Then, due to profile ordering here,
~ whatever modules are enabled are built. Finally, the assembly module is built,
~ which contains no actual code, but shades all its "dependencies" into one jar.
~ N.B.: All version-specific code is handled in submodules of the internal module.
~
~ Internal submodules built by each profile are handled in internal/pom.xml
-->
<!--
~ This profile exists to simplify profile usage.
~ The interface and plugin modules should be built first to ensure that they are up to date.
-->
<profile>
<id>reactorbuildfirst</id>
<activation>
<property>
<name>!breakBuildProcess</name>
</property>
</activation>
<modules>
<module>internal</module>
<module>plugin</module>
</modules>
</profile>
<profile>
<id>latest</id>
<activation>
<property>
<name>latest</name>
<value>true</value>
</property>
</activation>
<modules>
<module>v1_11_R1</module>
</modules>
</profile>
<profile>
<id>modern</id>
<activation>
<property>
<name>modern</name>
<value>true</value>
</property>
</activation>
<modules>
<module>v1_8_R1</module>
<module>v1_8_R2</module>
<module>v1_8_R3</module>
<module>v1_9_R1</module>
<module>v1_9_R2</module>
<module>v1_10_R1</module>
<module>v1_11_R1</module>
</modules>
</profile>
<profile>
<id>all</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<modules>
<module>1_4_5</module>
<module>1_4_6</module>
<module>v1_4_R1</module>
<!-- 1_5_R1 was never released -->
<module>v1_5_R2</module>
<module>v1_5_R3</module>
<!-- 1_6_R1 also had no tagged releases, remove? -->
<module>v1_6_R1</module>
<module>v1_6_R2</module>
<module>v1_6_R3</module>
<!-- TODO: Recompile CB for 1_7_R1 through 1_7_R4, currently using whatever jars worked -->
<module>v1_7_R1</module>
<module>v1_7_R2</module>
<module>v1_7_R3</module>
<module>v1_7_R4</module>
<module>v1_8_R1</module>
<module>v1_8_R2</module>
<module>v1_8_R3</module>
<module>v1_9_R1</module>
<module>v1_9_R2</module>
<module>v1_10_R1</module>
<module>v1_11_R1</module>
</modules>
</profile>
<!--
~ This profile exists to fix reactor build order.
~ The assembly module must be built last to aggregate all active modules into the final jar.
-->
<profile>
<id>reactorbuildlast</id>
<activation>
<property>
<name>!breakBuildProcess</name>
<name>all</name>
<value>true</value>
</property>
</activation>
<modules>
<module>assembly</module>
</modules>
</profile>
</profiles>
@ -134,13 +68,15 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
<version>3.2.2</version>
<configuration>
<filters>
<filter>
<artifact>*:*</artifact>
<!-- Keep the file clean, don't include every single pom from all modules -->
<excludes>META-INF/maven/**</excludes>
<excludes>
<exclude>META-INF/maven/**</exclude>
</excludes>
</filter>
</filters>
</configuration>
@ -156,13 +92,13 @@
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<version>3.8.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
</project>

View file

@ -0,0 +1,67 @@
#!/bin/bash
#
# Copyright (C) 2011-2021 lishid. All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# A script for generating a changelog from Git.
#
# Note that this script is designed for use in GitHub Actions, and is not
# particularly robust nor configurable. Run from project parent directory.
# Query GitHub for the username of the given email address.
# Falls through to the given author name.
lookup_email_username() {
lookup=$(curl -G --data-urlencode "q=$1 in:email" https://api.github.com/search/users -H 'Accept: application/vnd.github.v3+json' | grep '"login":' | sed -e 's/^.*": "//g' -e 's/",.*$//g')
if [[ $lookup ]]; then
echo -n "@$lookup"
else
echo "$2"
fi
}
# Use formatted log to pull authors list
authors_raw=$(git log --pretty=format:"%ae|%an" "$(git describe --tags --abbrev=0 @^)"..@)
readarray -t authors <<<"$authors_raw"
declare -A author_data
for author in "${authors[@]}"; do
# Match author email
author_email=${author%|*}
# Convert to lower case
author_email=${author_email,,}
# Match author name
author_name=${author##*|}
if [[ -n ${author_data[$author_email]} ]]; then
# Skip emails we already have data for
continue
fi
# Fetch and store author GitHub username by email
author_data[$author_email]=$(lookup_email_username "$author_email" "$author_name")
done
# Fetch actual formatted changelog
changelog=$(git log --pretty=format:"%s (%h) - %ae" "$(git describe --tags --abbrev=0 @^)"..@)
for author_email in "${!author_data[@]}"; do
# Ignore case when matching
shopt -s nocasematch
# Match and replace email
changelog=${changelog//$author_email/${author_data[$author_email]}}
done
echo "GENERATED_CHANGELOG<<EOF${changelog}EOF" >> "$GITHUB_ENV"

View file

@ -0,0 +1,75 @@
#!/bin/bash
#
# Copyright (C) 2011-2021 lishid. All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# A script for installing required Spigot versions.
#
# Note that this script is designed for use in GitHub Actions, and is
# not particularly robust nor configurable.
# In its current state, the script must be run from OpenInv's parent
# project directory and will always install BuildTools to ~/buildtools.
buildtools_dir=~/buildtools
buildtools=$buildtools_dir/BuildTools.jar
get_spigot_versions () {
# Get all submodules of internal module
modules=$(mvn help:evaluate -Dexpression=project.modules -q -DforceStdout -P all -pl internal | grep -oP '(?<=<string>)(.*)(?=<\/string>)')
for module in "${modules[@]}"; do
# Get number of dependencies declared in pom of specified internal module
max_index=$(mvn help:evaluate -Dexpression=project.dependencies -q -DforceStdout -P all -pl internal/"$module" | grep -c "<dependency>")
for ((i=0; i < max_index; i++)); do
# Get artifactId of dependency
artifact_id=$(mvn help:evaluate -Dexpression=project.dependencies["$i"].artifactId -q -DforceStdout -P all -pl internal/"$module")
# Ensure dependency is spigot
if [[ "$artifact_id" == spigot ]]; then
# Get spigot version
spigot_version=$(mvn help:evaluate -Dexpression=project.dependencies["$i"].version -q -DforceStdout -P all -pl internal/"$module")
echo "$spigot_version"
break
fi
done
done
}
get_buildtools () {
if [[ -d $buildtools_dir && -f $buildtools ]]; then
return
fi
mkdir $buildtools_dir
wget https://hub.spigotmc.org/jenkins/job/BuildTools/lastSuccessfulBuild/artifact/target/BuildTools.jar -O $buildtools
}
versions=$(get_spigot_versions)
echo Found Spigot dependencies: "$versions"
for version in "${versions[@]}"; do
set -e
exit_code=0
mvn dependency:get -Dartifact=org.spigotmc:spigot:"$version" -q -o || exit_code=$?
if [ $exit_code -ne 0 ]; then
echo Installing missing Spigot version "$version"
revision=$(echo "$version" | grep -oP '(\d+\.\d+(\.\d+)?)(?=-R[0-9\.]+-SNAPSHOT)')
get_buildtools
java -jar $buildtools -rev "$revision"
else
echo Spigot "$version" is already installed
fi
done

View file

@ -1,28 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinv</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>openinvadapter1_10_R1</artifactId>
<name>OpenInvAdapter1_10_R1</name>
<dependencies>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvplugin</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.10-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View file

@ -1,206 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_10_R1;
import com.lishid.openinv.internal.IAnySilentContainer;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
// Volatile
import net.minecraft.server.v1_10_R1.AxisAlignedBB;
import net.minecraft.server.v1_10_R1.Block;
import net.minecraft.server.v1_10_R1.BlockChest;
import net.minecraft.server.v1_10_R1.BlockChest.Type;
import net.minecraft.server.v1_10_R1.BlockEnderChest;
import net.minecraft.server.v1_10_R1.BlockPosition;
import net.minecraft.server.v1_10_R1.Entity;
import net.minecraft.server.v1_10_R1.EntityOcelot;
import net.minecraft.server.v1_10_R1.EntityPlayer;
import net.minecraft.server.v1_10_R1.EnumDirection;
import net.minecraft.server.v1_10_R1.IInventory;
import net.minecraft.server.v1_10_R1.ITileInventory;
import net.minecraft.server.v1_10_R1.InventoryEnderChest;
import net.minecraft.server.v1_10_R1.InventoryLargeChest;
import net.minecraft.server.v1_10_R1.PacketPlayOutOpenWindow;
import net.minecraft.server.v1_10_R1.StatisticList;
import net.minecraft.server.v1_10_R1.TileEntity;
import net.minecraft.server.v1_10_R1.TileEntityChest;
import net.minecraft.server.v1_10_R1.TileEntityEnderChest;
import net.minecraft.server.v1_10_R1.World;
import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer;
public class AnySilentContainer implements IAnySilentContainer {
@Override
public boolean isAnySilentContainer(org.bukkit.block.Block block) {
return block.getType() == Material.ENDER_CHEST || block.getState() instanceof org.bukkit.block.Chest;
}
@Override
public boolean isAnyContainerNeeded(Player p, org.bukkit.block.Block b) {
EntityPlayer player = ((CraftPlayer) p).getHandle();
World world = player.world;
BlockPosition blockPosition = new BlockPosition(b.getX(), b.getY(), b.getZ());
Block block = world.getType(blockPosition).getBlock();
if (block instanceof BlockEnderChest) {
// Ender chests are not blocked by ocelots.
return world.getType(blockPosition.up()).m();
}
// Check if chest is blocked or has an ocelot on top
if (isBlockedChest(world, blockPosition)) {
return true;
}
// Check for matching adjacent chests that are blocked or have an ocelot on top
for (EnumDirection localEnumDirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) {
BlockPosition localBlockPosition = blockPosition.shift(localEnumDirection);
Block localBlock = world.getType(localBlockPosition).getBlock();
if (localBlock != block) {
continue;
}
TileEntity localTileEntity = world.getTileEntity(localBlockPosition);
if (!(localTileEntity instanceof TileEntityChest)) {
continue;
}
if (isBlockedChest(world, localBlockPosition)) {
return true;
}
}
return false;
}
private boolean isBlockedChest(World world, BlockPosition blockPosition) {
// For reference, loot at net.minecraft.server.BlockChest
return world.getType(blockPosition.up()).l() || hasOcelotOnTop(world, blockPosition);
}
private boolean hasOcelotOnTop(World world, BlockPosition blockPosition) {
for (Entity localEntity : world.a(EntityOcelot.class,
new AxisAlignedBB(blockPosition.getX(), blockPosition.getY() + 1,
blockPosition.getZ(), blockPosition.getX() + 1, blockPosition.getY() + 2,
blockPosition.getZ() + 1))) {
EntityOcelot localEntityOcelot = (EntityOcelot) localEntity;
if (localEntityOcelot.isSitting()) {
return true;
}
}
return false;
}
@Override
public boolean activateContainer(Player p, boolean silentchest, org.bukkit.block.Block b) {
EntityPlayer player = ((CraftPlayer) p).getHandle();
// Silent ender chest is pretty much API-only
if (silentchest && b.getType() == Material.ENDER_CHEST) {
p.openInventory(p.getEnderChest());
player.b(StatisticList.X);
return true;
}
World world = player.world;
BlockPosition blockPosition = new BlockPosition(b.getX(), b.getY(), b.getZ());
Object tile = world.getTileEntity(blockPosition);
if (tile == null) {
return false;
}
if (tile instanceof TileEntityEnderChest) {
// Anychest ender chest. See net.minecraft.server.BlockEnderChest
InventoryEnderChest enderChest = player.getEnderChest();
enderChest.a((TileEntityEnderChest) tile);
player.openContainer(enderChest);
player.b(StatisticList.X);
return true;
}
if (!(tile instanceof IInventory)) {
return false;
}
Block block = world.getType(blockPosition).getBlock();
if (block instanceof BlockChest) {
for (EnumDirection localEnumDirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) {
BlockPosition localBlockPosition = blockPosition.shift(localEnumDirection);
Block localBlock = world.getType(localBlockPosition).getBlock();
if (localBlock != block) {
continue;
}
TileEntity localTileEntity = world.getTileEntity(localBlockPosition);
if (!(localTileEntity instanceof TileEntityChest)) {
continue;
}
if ((localEnumDirection == EnumDirection.WEST) || (localEnumDirection == EnumDirection.NORTH)) {
tile = new InventoryLargeChest("container.chestDouble",
(TileEntityChest) localTileEntity, (ITileInventory) tile);
} else {
tile = new InventoryLargeChest("container.chestDouble",
(ITileInventory) tile, (TileEntityChest) localTileEntity);
}
break;
}
if (silentchest) {
tile = new SilentContainerChest(player.inventory, ((IInventory) tile), player);
}
if (((BlockChest) block).g == Type.BASIC)
player.b(StatisticList.ac);
else if (((BlockChest) block).g == Type.TRAP) {
player.b(StatisticList.W);
}
}
boolean returnValue = false;
if (!silentchest) {
player.openContainer((IInventory) tile);
returnValue = true;
} else {
try {
SilentContainerChest silentContainerChest = new SilentContainerChest(player.inventory, ((IInventory) tile), player);
int windowId = player.nextContainerCounter();
player.playerConnection.sendPacket(new PacketPlayOutOpenWindow(windowId, "minecraft:chest", ((IInventory) tile).getScoreboardDisplayName(), ((IInventory) tile).getSize()));
player.activeContainer = silentContainerChest;
player.activeContainer.windowId = windowId;
player.activeContainer.addSlotListener(player);
returnValue = true;
} catch (Exception e) {
e.printStackTrace();
p.sendMessage(ChatColor.RED + "Error while sending silent chest.");
}
}
return returnValue;
}
}

View file

@ -1,79 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_10_R1;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.internal.InternalAccessor;
import org.bukkit.inventory.Inventory;
// Volatile
import net.minecraft.server.v1_10_R1.IInventory;
import org.bukkit.craftbukkit.v1_10_R1.inventory.CraftInventory;
public class InventoryAccess implements IInventoryAccess {
@Override
public boolean isSpecialPlayerInventory(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialPlayerInventory;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialPlayerInventory;
}
@Override
public ISpecialPlayerInventory getSpecialPlayerInventory(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialPlayerInventory) {
return (SpecialPlayerInventory) inv;
}
return null;
}
@Override
public boolean isSpecialEnderChest(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialEnderChest;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialEnderChest;
}
@Override
public ISpecialEnderChest getSpecialEnderChest(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialEnderChest) {
return (SpecialEnderChest) inv;
}
return null;
}
}

View file

@ -1,82 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_10_R1;
import java.util.UUID;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.mojang.authlib.GameProfile;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
// Volatile
import net.minecraft.server.v1_10_R1.EntityPlayer;
import net.minecraft.server.v1_10_R1.MinecraftServer;
import net.minecraft.server.v1_10_R1.PlayerInteractManager;
import org.bukkit.craftbukkit.v1_10_R1.CraftServer;
public class PlayerDataManager implements IPlayerDataManager {
@Override
public Player loadPlayer(OfflinePlayer offline) {
// Ensure player has data
if (offline == null || !offline.hasPlayedBefore()) {
return null;
}
// Create a profile and entity to load the player data
GameProfile profile = new GameProfile(offline.getUniqueId(), offline.getName());
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
EntityPlayer entity = new EntityPlayer(server, server.getWorldServer(0), profile,
new PlayerInteractManager(server.getWorldServer(0)));
// Get the bukkit entity
Player target = (entity == null) ? null : entity.getBukkitEntity();
if (target != null) {
// Load data
target.loadData();
}
// Return the entity
return target;
}
@Override
public String getPlayerDataID(OfflinePlayer player) {
return player.getUniqueId().toString();
}
@Override
public OfflinePlayer getPlayerByID(String identifier) {
try {
UUID uuid = UUID.fromString(identifier);
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
// Ensure player is a real player, otherwise return null
if (player == null || !player.hasPlayedBefore() && !player.isOnline()) {
return null;
}
return player;
} catch (IllegalArgumentException e) {
// Not a UUID
return null;
}
}
}

View file

@ -1,46 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_10_R1;
// Volatile
import net.minecraft.server.v1_10_R1.ContainerChest;
import net.minecraft.server.v1_10_R1.EntityHuman;
import net.minecraft.server.v1_10_R1.IInventory;
import net.minecraft.server.v1_10_R1.ItemStack;
import net.minecraft.server.v1_10_R1.PlayerInventory;
public class SilentContainerChest extends ContainerChest {
public SilentContainerChest(IInventory i1, IInventory i2, EntityHuman e1) {
super(i1, i2, e1);
// Send close signal
i2.closeContainer(e1);
}
@Override
public void b(EntityHuman entityHuman) {
// Don't send close signal twice, might screw up
PlayerInventory playerinventory = entityHuman.inventory;
if (playerinventory.getCarried() != null) {
ItemStack carried = playerinventory.getCarried();
playerinventory.setCarried(null);
entityHuman.drop(carried, false);
}
}
}

View file

@ -1,105 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_10_R1;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import com.lishid.openinv.internal.ISpecialEnderChest;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
// Volatile
import net.minecraft.server.v1_10_R1.IInventory;
import net.minecraft.server.v1_10_R1.InventoryEnderChest;
import net.minecraft.server.v1_10_R1.InventorySubcontainer;
import net.minecraft.server.v1_10_R1.ItemStack;
import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_10_R1.inventory.CraftInventory;
public class SpecialEnderChest extends InventorySubcontainer implements IInventory, ISpecialEnderChest {
private final InventoryEnderChest enderChest;
private final CraftInventory inventory = new CraftInventory(this);
private boolean playerOnline = false;
public SpecialEnderChest(Player player, Boolean online) {
super(((CraftPlayer) player).getHandle().getEnderChest().getName(),
((CraftPlayer) player).getHandle().getEnderChest().hasCustomName(),
((CraftPlayer) player).getHandle().getEnderChest().getSize());
CraftPlayer craftPlayer = (CraftPlayer) player;
this.enderChest = craftPlayer.getHandle().getEnderChest();
this.bukkitOwner = craftPlayer;
setItemArrays(this, enderChest.getContents());
}
private void setItemArrays(InventorySubcontainer subcontainer, ItemStack[] items) {
try {
// Prepare to remove final modifier
Field modifiers = Field.class.getDeclaredField("modifiers");
modifiers.setAccessible(true);
// Access and replace main inventory array
Field field = InventorySubcontainer.class.getField("items");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(subcontainer, items);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
try {
this.bukkitOwner = player;
CraftPlayer craftPlayer = (CraftPlayer) player;
setItemArrays(craftPlayer.getHandle().getEnderChest(), this.items);
} catch (Exception e) {}
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public void update() {
super.update();
enderChest.update();
}
}

View file

@ -1,296 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_10_R1;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
// Volatile
import net.minecraft.server.v1_10_R1.EntityHuman;
import net.minecraft.server.v1_10_R1.ItemStack;
import net.minecraft.server.v1_10_R1.PlayerInventory;
import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_10_R1.inventory.CraftInventory;
public class SpecialPlayerInventory extends PlayerInventory implements ISpecialPlayerInventory {
private final ItemStack[] extra = new ItemStack[4];
private final CraftInventory inventory = new CraftInventory(this);
private boolean playerOnline = false;
public SpecialPlayerInventory(Player bukkitPlayer, Boolean online) {
super(((CraftPlayer) bukkitPlayer).getHandle());
this.playerOnline = online;
setItemArrays(this, player.inventory.items, player.inventory.armor, player.inventory.extraSlots);
}
private void setItemArrays(PlayerInventory inventory, ItemStack[] items, ItemStack[] armor,
ItemStack[] extraSlots) {
try {
// Prepare to remove final modifier
Field modifiers = Field.class.getDeclaredField("modifiers");
modifiers.setAccessible(true);
// Access and replace main inventory array
Field field = PlayerInventory.class.getField("items");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, items);
// Access and replace armor inventory array
field = PlayerInventory.class.getField("armor");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, armor);
// Access and replace offhand inventory array
field = PlayerInventory.class.getField("extraSlots");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, extraSlots);
// Access and replace array containing all inventory arrays
field = PlayerInventory.class.getDeclaredField("g");
field.setAccessible(true);
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, new ItemStack[][] { items, armor, extraSlots });
} catch (NoSuchFieldException e) {
// Unable to set final fields to item arrays, we're screwed. Noisily fail.
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
this.player = ((CraftPlayer) player).getHandle();
setItemArrays(this.player.inventory, items, armor, extraSlots);
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public ItemStack[] getContents() {
ItemStack[] contents = new ItemStack[getSize()];
System.arraycopy(items, 0, contents, 0, items.length);
System.arraycopy(armor, 0, contents, items.length, armor.length);
System.arraycopy(extraSlots, 0, contents, items.length + armor.length, extraSlots.length);
return contents;
}
@Override
public int getSize() {
return super.getSize() + 4;
}
@Override
public ItemStack getItem(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extraSlots;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
// extraSlots is, for now, just an array with length 1. No need for special handling.
return is[i];
}
@Override
public ItemStack splitStack(int i, int j) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extraSlots;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
if (is[i] != null) {
ItemStack itemstack;
if (is[i].count <= j) {
itemstack = is[i];
is[i] = null;
return itemstack;
} else {
itemstack = is[i].cloneAndSubtract(j);
if (is[i].count == 0) {
is[i] = null;
}
return itemstack;
}
}
return null;
}
@Override
public ItemStack splitWithoutUpdate(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extraSlots;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
if (is[i] != null) {
ItemStack itemstack = is[i];
is[i] = null;
return itemstack;
}
return null;
}
@Override
public void setItem(int i, ItemStack itemstack) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extraSlots;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
// Effects
if (is == this.extra) {
player.drop(itemstack, true);
itemstack = null;
}
is[i] = itemstack;
player.defaultContainer.b();
}
private int getReversedItemSlotNum(int i) {
if (i >= 27) {
return i - 27;
}
return i + 9;
}
private int getReversedArmorSlotNum(int i) {
if (i == 0) {
return 3;
}
if (i == 1) {
return 2;
}
if (i == 2) {
return 1;
}
if (i == 3) {
return 0;
}
return i;
}
@Override
public String getName() {
if (player.getName().length() > 16) {
return player.getName().substring(0, 16);
}
return player.getName();
}
@Override
public boolean a(EntityHuman entityhuman) {
return true;
}
}

View file

@ -1,28 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinv</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>openinvadapter1_11_R1</artifactId>
<name>OpenInvAdapter1_11_R1</name>
<dependencies>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvplugin</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.11-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View file

@ -1,276 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_11_R1;
import com.lishid.openinv.internal.IAnySilentContainer;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
// Volatile
import net.minecraft.server.v1_11_R1.AxisAlignedBB;
import net.minecraft.server.v1_11_R1.Block;
import net.minecraft.server.v1_11_R1.BlockChest;
import net.minecraft.server.v1_11_R1.BlockChest.Type;
import net.minecraft.server.v1_11_R1.BlockEnderChest;
import net.minecraft.server.v1_11_R1.BlockPosition;
import net.minecraft.server.v1_11_R1.BlockShulkerBox;
import net.minecraft.server.v1_11_R1.Container;
import net.minecraft.server.v1_11_R1.Entity;
import net.minecraft.server.v1_11_R1.EntityOcelot;
import net.minecraft.server.v1_11_R1.EntityPlayer;
import net.minecraft.server.v1_11_R1.EnumDirection;
import net.minecraft.server.v1_11_R1.IBlockData;
import net.minecraft.server.v1_11_R1.IInventory;
import net.minecraft.server.v1_11_R1.ITileInventory;
import net.minecraft.server.v1_11_R1.InventoryEnderChest;
import net.minecraft.server.v1_11_R1.InventoryLargeChest;
import net.minecraft.server.v1_11_R1.PacketPlayOutOpenWindow;
import net.minecraft.server.v1_11_R1.StatisticList;
import net.minecraft.server.v1_11_R1.TileEntity;
import net.minecraft.server.v1_11_R1.TileEntityChest;
import net.minecraft.server.v1_11_R1.TileEntityEnderChest;
import net.minecraft.server.v1_11_R1.TileEntityShulkerBox;
import net.minecraft.server.v1_11_R1.World;
import org.bukkit.craftbukkit.v1_11_R1.entity.CraftPlayer;
public class AnySilentContainer implements IAnySilentContainer {
@Override
public boolean isAnySilentContainer(org.bukkit.block.Block block) {
if (block.getType() == Material.ENDER_CHEST) {
return true;
}
BlockState state = block.getState();
return state instanceof org.bukkit.block.Chest || state instanceof org.bukkit.block.ShulkerBox;
}
@Override
public boolean isAnyContainerNeeded(Player p, org.bukkit.block.Block b) {
EntityPlayer player = ((CraftPlayer) p).getHandle();
World world = player.world;
BlockPosition blockPosition = new BlockPosition(b.getX(), b.getY(), b.getZ());
Block block = world.getType(blockPosition).getBlock();
if (block instanceof BlockShulkerBox) {
return isBlockedShulkerBox(world, blockPosition, block);
}
if (block instanceof BlockEnderChest) {
// Ender chests are not blocked by ocelots.
return world.getType(blockPosition.up()).m();
}
// Check if chest is blocked or has an ocelot on top
if (isBlockedChest(world, blockPosition)) {
return true;
}
// Check for matching adjacent chests that are blocked or have an ocelot on top
for (EnumDirection localEnumDirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) {
BlockPosition localBlockPosition = blockPosition.shift(localEnumDirection);
Block localBlock = world.getType(localBlockPosition).getBlock();
if (localBlock != block) {
continue;
}
TileEntity localTileEntity = world.getTileEntity(localBlockPosition);
if (!(localTileEntity instanceof TileEntityChest)) {
continue;
}
if (isBlockedChest(world, localBlockPosition)) {
return true;
}
}
return false;
}
private boolean isBlockedShulkerBox(World world, BlockPosition blockPosition, Block block) {
// For reference, look at net.minecraft.server.BlockShulkerBox
TileEntity tile = world.getTileEntity(blockPosition);
if (!(tile instanceof TileEntityShulkerBox)) {
return false;
}
IBlockData iBlockData = block.getBlockData();
EnumDirection enumDirection = iBlockData.get(BlockShulkerBox.a);
if (((TileEntityShulkerBox) tile).p() == TileEntityShulkerBox.AnimationPhase.CLOSED) {
AxisAlignedBB axisAlignedBB = BlockShulkerBox.j.b(0.5F * enumDirection.getAdjacentX(),
0.5F * enumDirection.getAdjacentY(), 0.5F * enumDirection.getAdjacentZ())
.a(enumDirection.getAdjacentX(), enumDirection.getAdjacentY(),
enumDirection.getAdjacentZ());
return world.b(axisAlignedBB.a(blockPosition.shift(enumDirection)));
}
return false;
}
private boolean isBlockedChest(World world, BlockPosition blockPosition) {
// For reference, loot at net.minecraft.server.BlockChest
return world.getType(blockPosition.up()).m() || hasOcelotOnTop(world, blockPosition);
}
private boolean hasOcelotOnTop(World world, BlockPosition blockPosition) {
for (Entity localEntity : world.a(EntityOcelot.class,
new AxisAlignedBB(blockPosition.getX(), blockPosition.getY() + 1,
blockPosition.getZ(), blockPosition.getX() + 1, blockPosition.getY() + 2,
blockPosition.getZ() + 1))) {
EntityOcelot localEntityOcelot = (EntityOcelot) localEntity;
if (localEntityOcelot.isSitting()) {
return true;
}
}
return false;
}
@Override
public boolean activateContainer(Player p, boolean silentchest, org.bukkit.block.Block b) {
EntityPlayer player = ((CraftPlayer) p).getHandle();
// Silent ender chest is pretty much API-only
if (silentchest && b.getType() == Material.ENDER_CHEST) {
p.openInventory(p.getEnderChest());
player.b(StatisticList.X);
return true;
}
final World world = player.world;
final BlockPosition blockPosition = new BlockPosition(b.getX(), b.getY(), b.getZ());
Object tile = world.getTileEntity(blockPosition);
if (tile == null) {
return false;
}
if (tile instanceof TileEntityEnderChest) {
// Anychest ender chest. See net.minecraft.server.BlockEnderChest
InventoryEnderChest enderChest = player.getEnderChest();
enderChest.a((TileEntityEnderChest) tile);
player.openContainer(enderChest);
player.b(StatisticList.X);
return true;
}
if (!(tile instanceof IInventory)) {
return false;
}
Block block = world.getType(blockPosition).getBlock();
Container container = null;
if (block instanceof BlockChest) {
BlockChest blockChest = (BlockChest) block;
for (EnumDirection localEnumDirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) {
BlockPosition localBlockPosition = blockPosition.shift(localEnumDirection);
Block localBlock = world.getType(localBlockPosition).getBlock();
if (localBlock != block) {
continue;
}
TileEntity localTileEntity = world.getTileEntity(localBlockPosition);
if (!(localTileEntity instanceof TileEntityChest)) {
continue;
}
if ((localEnumDirection == EnumDirection.WEST) || (localEnumDirection == EnumDirection.NORTH)) {
tile = new InventoryLargeChest("container.chestDouble",
(TileEntityChest) localTileEntity, (ITileInventory) tile);
} else {
tile = new InventoryLargeChest("container.chestDouble",
(ITileInventory) tile, (TileEntityChest) localTileEntity);
}
break;
}
if (blockChest.g == Type.BASIC)
player.b(StatisticList.ac);
else if (blockChest.g == Type.TRAP) {
player.b(StatisticList.W);
}
if (silentchest) {
container = new SilentContainerChest(player.inventory, ((IInventory) tile), player);
}
}
if (block instanceof BlockShulkerBox) {
player.b(StatisticList.ae);
if (silentchest && tile instanceof TileEntityShulkerBox) {
// Set value to current + 1. Ensures consistency later when resetting.
SilentContainerShulkerBox.setOpenValue((TileEntityShulkerBox) tile,
SilentContainerShulkerBox.getOpenValue((TileEntityShulkerBox) tile) + 1);
container = new SilentContainerShulkerBox(player.inventory, (IInventory) tile, player);
}
}
boolean returnValue = false;
final IInventory iInventory = (IInventory) tile;
if (!silentchest || container == null) {
player.openContainer(iInventory);
returnValue = true;
} else {
try {
int windowId = player.nextContainerCounter();
player.playerConnection.sendPacket(new PacketPlayOutOpenWindow(windowId, iInventory.getName(), iInventory.getScoreboardDisplayName(), iInventory.getSize()));
player.activeContainer = container;
player.activeContainer.windowId = windowId;
player.activeContainer.addSlotListener(player);
returnValue = true;
if (tile instanceof TileEntityShulkerBox) {
new BukkitRunnable() {
@Override
public void run() {
// TODO hacky
Object tile = world.getTileEntity(blockPosition);
if (!(tile instanceof TileEntityShulkerBox)) {
return;
}
TileEntityShulkerBox box = (TileEntityShulkerBox) tile;
// Reset back - we added 1, and calling TileEntityShulkerBox#startOpen adds 1 more.
SilentContainerShulkerBox.setOpenValue(box,
SilentContainerShulkerBox.getOpenValue((TileEntityShulkerBox) tile) - 2);
}
}.runTaskLater(Bukkit.getPluginManager().getPlugin("OpenInv"), 2);
}
} catch (Exception e) {
e.printStackTrace();
p.sendMessage(ChatColor.RED + "Error while sending silent chest.");
}
}
return returnValue;
}
}

View file

@ -1,79 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_11_R1;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.internal.InternalAccessor;
import org.bukkit.inventory.Inventory;
// Volatile
import net.minecraft.server.v1_11_R1.IInventory;
import org.bukkit.craftbukkit.v1_11_R1.inventory.CraftInventory;
public class InventoryAccess implements IInventoryAccess {
@Override
public boolean isSpecialPlayerInventory(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialPlayerInventory;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialPlayerInventory;
}
@Override
public ISpecialPlayerInventory getSpecialPlayerInventory(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialPlayerInventory) {
return (SpecialPlayerInventory) inv;
}
return null;
}
@Override
public boolean isSpecialEnderChest(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialEnderChest;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialEnderChest;
}
@Override
public ISpecialEnderChest getSpecialEnderChest(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialEnderChest) {
return (SpecialEnderChest) inv;
}
return null;
}
}

View file

@ -1,82 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_11_R1;
import java.util.UUID;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.mojang.authlib.GameProfile;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
// Volatile
import net.minecraft.server.v1_11_R1.EntityPlayer;
import net.minecraft.server.v1_11_R1.MinecraftServer;
import net.minecraft.server.v1_11_R1.PlayerInteractManager;
import org.bukkit.craftbukkit.v1_11_R1.CraftServer;
public class PlayerDataManager implements IPlayerDataManager {
@Override
public Player loadPlayer(OfflinePlayer offline) {
// Ensure player has data
if (offline == null || !offline.hasPlayedBefore()) {
return null;
}
// Create a profile and entity to load the player data
GameProfile profile = new GameProfile(offline.getUniqueId(), offline.getName());
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
EntityPlayer entity = new EntityPlayer(server, server.getWorldServer(0), profile,
new PlayerInteractManager(server.getWorldServer(0)));
// Get the bukkit entity
Player target = (entity == null) ? null : entity.getBukkitEntity();
if (target != null) {
// Load data
target.loadData();
}
// Return the entity
return target;
}
@Override
public String getPlayerDataID(OfflinePlayer player) {
return player.getUniqueId().toString();
}
@Override
public OfflinePlayer getPlayerByID(String identifier) {
try {
UUID uuid = UUID.fromString(identifier);
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
// Ensure player is a real player, otherwise return null
if (player == null || !player.hasPlayedBefore() && !player.isOnline()) {
return null;
}
return player;
} catch (IllegalArgumentException e) {
// Not a UUID
return null;
}
}
}

View file

@ -1,47 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_11_R1;
// Volatile
import net.minecraft.server.v1_11_R1.ContainerChest;
import net.minecraft.server.v1_11_R1.EntityHuman;
import net.minecraft.server.v1_11_R1.IInventory;
import net.minecraft.server.v1_11_R1.ItemStack;
import net.minecraft.server.v1_11_R1.PlayerInventory;
public class SilentContainerChest extends ContainerChest {
public SilentContainerChest(PlayerInventory playerInventory, IInventory iInventory,
EntityHuman entityHuman) {
super(playerInventory, iInventory, entityHuman);
// Send close signal
iInventory.closeContainer(entityHuman);
}
@Override
public void b(EntityHuman entityHuman) {
// Don't send close signal twice, might screw up
PlayerInventory playerinventory = entityHuman.inventory;
if (playerinventory.getCarried() != ItemStack.a) {
ItemStack carried = playerinventory.getCarried();
playerinventory.setCarried(ItemStack.a);
entityHuman.drop(carried, false);
}
}
}

View file

@ -1,56 +0,0 @@
package com.lishid.openinv.internal.v1_11_R1;
import java.lang.reflect.Field;
import net.minecraft.server.v1_11_R1.ContainerShulkerBox;
import net.minecraft.server.v1_11_R1.EntityHuman;
import net.minecraft.server.v1_11_R1.IInventory;
import net.minecraft.server.v1_11_R1.ItemStack;
import net.minecraft.server.v1_11_R1.PlayerInventory;
import net.minecraft.server.v1_11_R1.TileEntityShulkerBox;
public class SilentContainerShulkerBox extends ContainerShulkerBox {
private static Field fieldShulkerActionData;
public SilentContainerShulkerBox(PlayerInventory playerInventory, IInventory iInventory,
EntityHuman entityHuman) {
super(playerInventory, iInventory, entityHuman);
}
@Override
public void b(EntityHuman entityHuman) {
PlayerInventory playerinventory = entityHuman.inventory;
if (!playerinventory.getCarried().isEmpty()) {
entityHuman.drop(playerinventory.getCarried(), false);
playerinventory.setCarried(ItemStack.a);
}
}
private static Field exposeOpenStatus() throws NoSuchFieldException, SecurityException {
if (fieldShulkerActionData == null) {
fieldShulkerActionData = TileEntityShulkerBox.class.getDeclaredField("h");
fieldShulkerActionData.setAccessible(true);
}
return fieldShulkerActionData;
}
public static void setOpenValue(TileEntityShulkerBox tileShulkerBox, Object value) {
try {
exposeOpenStatus().set(tileShulkerBox, value);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Integer getOpenValue(TileEntityShulkerBox tileShulkerBox) {
try {
return (Integer) exposeOpenStatus().get(tileShulkerBox);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}

View file

@ -1,106 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_11_R1;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
import com.lishid.openinv.internal.ISpecialEnderChest;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
// Volatile
import net.minecraft.server.v1_11_R1.IInventory;
import net.minecraft.server.v1_11_R1.InventoryEnderChest;
import net.minecraft.server.v1_11_R1.InventorySubcontainer;
import net.minecraft.server.v1_11_R1.ItemStack;
import org.bukkit.craftbukkit.v1_11_R1.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_11_R1.inventory.CraftInventory;
public class SpecialEnderChest extends InventorySubcontainer implements IInventory, ISpecialEnderChest {
private final InventoryEnderChest enderChest;
private final CraftInventory inventory = new CraftInventory(this);
private boolean playerOnline = false;
public SpecialEnderChest(Player player, Boolean online) {
super(((CraftPlayer) player).getHandle().getEnderChest().getName(),
((CraftPlayer) player).getHandle().getEnderChest().hasCustomName(),
((CraftPlayer) player).getHandle().getEnderChest().getSize());
CraftPlayer craftPlayer = (CraftPlayer) player;
this.enderChest = craftPlayer.getHandle().getEnderChest();
this.bukkitOwner = craftPlayer;
setItemLists(this, enderChest.getContents());
}
private void setItemLists(InventorySubcontainer subcontainer, List<ItemStack> list) {
try {
// Prepare to remove final modifier
Field modifiers = Field.class.getDeclaredField("modifiers");
modifiers.setAccessible(true);
// Access and replace main inventory array
Field field = InventorySubcontainer.class.getField("items");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(subcontainer, list);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
try {
this.bukkitOwner = player;
CraftPlayer craftPlayer = (CraftPlayer) player;
setItemLists(craftPlayer.getHandle().getEnderChest(), this.items);
} catch (Exception e) {}
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public void update() {
super.update();
enderChest.update();
}
}

View file

@ -1,261 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_11_R1;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_11_R1.ContainerUtil;
// Volatile
import net.minecraft.server.v1_11_R1.EntityHuman;
import net.minecraft.server.v1_11_R1.ItemStack;
import net.minecraft.server.v1_11_R1.NonNullList;
import net.minecraft.server.v1_11_R1.PlayerInventory;
import org.bukkit.craftbukkit.v1_11_R1.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_11_R1.inventory.CraftInventory;
public class SpecialPlayerInventory extends PlayerInventory implements ISpecialPlayerInventory {
private final CraftInventory inventory = new CraftInventory(this);
private boolean playerOnline = false;
public SpecialPlayerInventory(Player bukkitPlayer, Boolean online) {
super(((CraftPlayer) bukkitPlayer).getHandle());
this.playerOnline = online;
setItemArrays(this, player.inventory.items, player.inventory.armor, player.inventory.extraSlots);
}
private void setItemArrays(PlayerInventory inventory, NonNullList<ItemStack> items,
NonNullList<ItemStack> armor, NonNullList<ItemStack> extraSlots) {
try {
// Prepare to remove final modifier
Field modifiers = Field.class.getDeclaredField("modifiers");
modifiers.setAccessible(true);
// Access and replace main inventory array
Field field = PlayerInventory.class.getField("items");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, items);
// Access and replace armor inventory array
field = PlayerInventory.class.getField("armor");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, armor);
// Access and replace offhand inventory array
field = PlayerInventory.class.getField("extraSlots");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, extraSlots);
// Access and replace array containing all inventory arrays
field = PlayerInventory.class.getDeclaredField("g");
field.setAccessible(true);
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, Arrays.asList(new NonNullList[] { items, armor, extraSlots }));
} catch (NoSuchFieldException e) {
// Unable to set final fields to item arrays, we're screwed. Noisily fail.
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
this.player = ((CraftPlayer) player).getHandle();
setItemArrays(this.player.inventory, items, armor, extraSlots);
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public int getSize() {
return super.getSize() + 4;
}
@Override
public ItemStack getItem(int i) {
NonNullList<ItemStack> list = this.items;
if (i >= list.size()) {
i -= list.size();
list = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= list.size()) {
i -= list.size();
list = this.extraSlots;
} else if (list == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (i >= list.size()) {
return ItemStack.a;
}
return list.get(i);
}
@Override
public ItemStack splitStack(int i, int j) {
NonNullList<ItemStack> list = this.items;
if (i >= list.size()) {
i -= list.size();
list = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= list.size()) {
i -= list.size();
list = this.extraSlots;
} else if (list == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (i >= list.size()) {
return ItemStack.a;
}
return list == null || list.get(i).isEmpty() ? ItemStack.a : ContainerUtil.a(list, i, j);
}
@Override
public ItemStack splitWithoutUpdate(int i) {
NonNullList<ItemStack> list = this.items;
if (i >= list.size()) {
i -= list.size();
list = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= list.size()) {
i -= list.size();
list = this.extraSlots;
} else if (list == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (i >= list.size()) {
return ItemStack.a;
}
if (list != null && !list.get(i).isEmpty()) {
ItemStack itemstack = list.get(i);
list.set(i, ItemStack.a);
return itemstack;
}
return ItemStack.a;
}
@Override
public void setItem(int i, ItemStack itemstack) {
NonNullList<ItemStack> list = this.items;
if (i >= list.size()) {
i -= list.size();
list = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= list.size()) {
i -= list.size();
list = this.extraSlots;
} else if (list == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (i >= list.size()) {
player.drop(itemstack, true);
return;
}
if (list != null) {
list.set(i, itemstack);
}
}
private int getReversedItemSlotNum(int i) {
if (i >= 27) {
return i - 27;
}
return i + 9;
}
private int getReversedArmorSlotNum(int i) {
if (i == 0) {
return 3;
}
if (i == 1) {
return 2;
}
if (i == 2) {
return 1;
}
if (i == 3) {
return 0;
}
return i;
}
@Override
public String getName() {
if (player.getName().length() > 16) {
return player.getName().substring(0, 16);
}
return player.getName();
}
@Override
public boolean a(EntityHuman entityhuman) {
return true;
}
}

View file

@ -1,28 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinv</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>openinvadapter1_4_R1</artifactId>
<name>OpenInvAdapter1_4_R1</name>
<dependencies>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvplugin</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.4.7-R1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View file

@ -1,158 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_R1;
import com.lishid.openinv.internal.IAnySilentContainer;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
// Volatile
import net.minecraft.server.v1_4_R1.AxisAlignedBB;
import net.minecraft.server.v1_4_R1.BlockEnderChest;
import net.minecraft.server.v1_4_R1.EntityOcelot;
import net.minecraft.server.v1_4_R1.EntityPlayer;
import net.minecraft.server.v1_4_R1.IInventory;
import net.minecraft.server.v1_4_R1.InventoryEnderChest;
import net.minecraft.server.v1_4_R1.InventoryLargeChest;
import net.minecraft.server.v1_4_R1.Packet100OpenWindow;
import net.minecraft.server.v1_4_R1.TileEntityChest;
import net.minecraft.server.v1_4_R1.TileEntityEnderChest;
import net.minecraft.server.v1_4_R1.World;
import org.bukkit.craftbukkit.v1_4_R1.entity.CraftPlayer;
public class AnySilentContainer implements IAnySilentContainer {
@Override
public boolean isAnySilentContainer(org.bukkit.block.Block block) {
return block.getType() == Material.ENDER_CHEST || block.getState() instanceof org.bukkit.block.Chest;
}
@Override
public boolean isAnyContainerNeeded(Player p, org.bukkit.block.Block block) {
// FOR REFERENCE, LOOK AT net.minecraft.server.BlockChest
EntityPlayer player = ((CraftPlayer) p).getHandle();
World world = player.world;
if (block instanceof BlockEnderChest) {
// Ender chests are not blocked by ocelots.
return world.t(block.getX(), block.getY() + 1, block.getZ());
}
// If block or ocelot on top
if (isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ())) {
return true;
}
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
// If block next to chest is chest and has a block or ocelot on top
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() + 1);
} else if(world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() - 1);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() + 1, block.getY() + 1, block.getZ());
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() - 1, block.getY() + 1, block.getZ());
}
return false;
}
private boolean isBlockedChest(World world, int x, int y, int z) {
return world.t(x, y + 1, z) || hasOcelotOnTop(world, x, y, z);
}
private boolean hasOcelotOnTop(World world, int x, int y, int z) {
for (Object localEntity : world.a(EntityOcelot.class,
AxisAlignedBB.a(x, y + 1, z, x + 1, y + 2, z + 1))) {
EntityOcelot localEntityOcelot = (EntityOcelot) localEntity;
if (localEntityOcelot.isSitting()) {
return true;
}
}
return false;
}
@Override
public boolean activateContainer(Player p, boolean silentchest, org.bukkit.block.Block block) {
EntityPlayer player = ((CraftPlayer) p).getHandle();
// Silent ender chest is API-only
if (silentchest && block.getType() == Material.ENDER_CHEST) {
p.openInventory(p.getEnderChest());
return true;
}
World world = player.world;
Object tile = world.getTileEntity(block.getX(), block.getY(), block.getZ());
if (tile == null) {
return false;
}
if (tile instanceof TileEntityEnderChest) {
// Anychest ender chest. See net.minecraft.server.BlockEnderChest
InventoryEnderChest enderChest = player.getEnderChest();
enderChest.a((TileEntityEnderChest) tile);
player.openContainer(enderChest);
return true;
}
if (!(tile instanceof IInventory)) {
return false;
}
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
tile = new InventoryLargeChest("Large chest", (IInventory) tile, (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() + 1));
} else if (world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
tile = new InventoryLargeChest("Large chest", (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() - 1), (IInventory) tile);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
tile = new InventoryLargeChest("Large chest", (IInventory) tile, (TileEntityChest) world.getTileEntity(block.getX() + 1, block.getY(), block.getZ()));
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
tile = new InventoryLargeChest("Large chest", (TileEntityChest) world.getTileEntity(block.getX() - 1, block.getY(), block.getZ()), (IInventory) tile);
}
boolean returnValue = false;
if (!silentchest) {
player.openContainer((IInventory) tile);
returnValue = true;
} else {
try {
int windowId = player.nextContainerCounter();
player.playerConnection.sendPacket(new Packet100OpenWindow(windowId, 0, ((IInventory) tile).getName(), ((IInventory) tile).getSize()));
player.activeContainer = new SilentContainerChest(player.inventory, ((IInventory) tile));
player.activeContainer.windowId = windowId;
player.activeContainer.addSlotListener(player);
returnValue = true;
} catch (Exception e) {
e.printStackTrace();
p.sendMessage(ChatColor.RED + "Error while sending silent chest.");
}
}
return returnValue;
}
}

View file

@ -1,79 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_R1;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.internal.InternalAccessor;
import org.bukkit.inventory.Inventory;
// Volatile
import net.minecraft.server.v1_4_R1.IInventory;
import org.bukkit.craftbukkit.v1_4_R1.inventory.CraftInventory;
public class InventoryAccess implements IInventoryAccess {
@Override
public boolean isSpecialPlayerInventory(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialPlayerInventory;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialPlayerInventory;
}
@Override
public ISpecialPlayerInventory getSpecialPlayerInventory(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialPlayerInventory) {
return (SpecialPlayerInventory) inv;
}
return null;
}
@Override
public boolean isSpecialEnderChest(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialEnderChest;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialEnderChest;
}
@Override
public ISpecialEnderChest getSpecialEnderChest(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialEnderChest) {
return (SpecialEnderChest) inv;
}
return null;
}
}

View file

@ -1,73 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_R1;
import com.lishid.openinv.internal.IPlayerDataManager;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_4_R1.EntityPlayer;
import net.minecraft.server.v1_4_R1.MinecraftServer;
import net.minecraft.server.v1_4_R1.PlayerInteractManager;
// Volatile
import org.bukkit.craftbukkit.v1_4_R1.CraftServer;
public class PlayerDataManager implements IPlayerDataManager {
@Override
public Player loadPlayer(OfflinePlayer offline) {
// Ensure the player has data
if (offline == null || !offline.hasPlayedBefore()) {
return null;
}
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
// Create an entity to load the player data
EntityPlayer entity = new EntityPlayer(server, server.getWorldServer(0), offline.getName(),
new PlayerInteractManager(server.getWorldServer(0)));
// Get the bukkit entity
Player target = (entity == null) ? null : entity.getBukkitEntity();
if (target != null) {
// Load data
target.loadData();
}
// Return the entity
return target;
}
@Override
public String getPlayerDataID(OfflinePlayer player) {
return player.getName();
}
@Override
public OfflinePlayer getPlayerByID(String identifier) {
OfflinePlayer player = Bukkit.getOfflinePlayer(identifier);
// Ensure player is a real player, otherwise return null
if (player == null || !player.hasPlayedBefore() && !player.isOnline()) {
return null;
}
return player;
}
}

View file

@ -1,46 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_R1;
// Volatile
import net.minecraft.server.v1_4_R1.ContainerChest;
import net.minecraft.server.v1_4_R1.EntityHuman;
import net.minecraft.server.v1_4_R1.IInventory;
import net.minecraft.server.v1_4_R1.ItemStack;
import net.minecraft.server.v1_4_R1.PlayerInventory;
public class SilentContainerChest extends ContainerChest {
public SilentContainerChest(IInventory i1, IInventory i2) {
super(i1, i2);
// Send close signal
i2.f();
}
@Override
public void b(EntityHuman entityHuman) {
// Don't send close signal twice, might screw up
PlayerInventory playerinventory = entityHuman.inventory;
if (playerinventory.getCarried() != null) {
ItemStack carried = playerinventory.getCarried();
playerinventory.setCarried(null);
entityHuman.drop(carried);
}
}
}

View file

@ -1,128 +0,0 @@
/*
* Copyright (C) 2011-2014 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_R1;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.lishid.openinv.internal.ISpecialEnderChest;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
// Volatile
import net.minecraft.server.v1_4_R1.IInventory;
import net.minecraft.server.v1_4_R1.InventoryEnderChest;
import net.minecraft.server.v1_4_R1.InventorySubcontainer;
import net.minecraft.server.v1_4_R1.ItemStack;
import org.bukkit.craftbukkit.v1_4_R1.entity.CraftHumanEntity;
import org.bukkit.craftbukkit.v1_4_R1.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_4_R1.inventory.CraftInventory;
public class SpecialEnderChest extends InventorySubcontainer implements IInventory, ISpecialEnderChest {
private final InventoryEnderChest enderChest;
private final CraftInventory inventory = new CraftInventory(this);
private final List<HumanEntity> transaction = new ArrayList<HumanEntity>();
private boolean playerOnline = false;
private CraftPlayer owner;
private int maxStack = MAX_STACK;
public SpecialEnderChest(Player p, Boolean online) {
super(((CraftPlayer) p).getHandle().getEnderChest().getName(),
((CraftPlayer) p).getHandle().getEnderChest().getSize());
CraftPlayer player = (CraftPlayer) p;
this.enderChest = player.getHandle().getEnderChest();
this.owner = player;
this.items = enderChest.getContents();
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
try {
owner = (CraftPlayer) player;
InventoryEnderChest playerEnderChest = owner.getHandle().getEnderChest();
Field field = playerEnderChest.getClass().getField("items");
field.setAccessible(true);
field.set(playerEnderChest, this.items);
} catch (Exception e) {}
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public ItemStack[] getContents() {
return this.items;
}
@Override
public void onOpen(CraftHumanEntity who) {
transaction.add(who);
}
@Override
public void onClose(CraftHumanEntity who) {
transaction.remove(who);
}
@Override
public List<HumanEntity> getViewers() {
return transaction;
}
@Override
public InventoryHolder getOwner() {
return this.owner;
}
@Override
public void setMaxStackSize(int size) {
maxStack = size;
}
@Override
public int getMaxStackSize() {
return maxStack;
}
@Override
public void update() {
super.update();
enderChest.update();
}
}

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