Compare commits

..
543 Commits
Author SHA1 Message Date
md5sha256 03ed2803bd Bump version to 2.7.3 2022-01-15 07:38:40 +08:00
md5sha256 b3f1225934 Deprecate the FAWE WG handler and fix fawe version parsing 2022-01-15 07:36:43 +08:00
md5sha256 68651899b7 Update the fawe module 2022-01-10 22:59:03 +08:00
md5sha256 4a7a4ca4ee Fix reobf 2022-01-10 22:34:35 +08:00
md5sha256 0d272c8fe9 Publish nms provider poms 2021-12-05 23:07:05 +08:00
md5sha256 6b2c905939 Parallel builds 2021-12-05 22:57:17 +08:00
md5sha256 7ab782799b Fix maven publish tasks 2021-12-05 22:57:03 +08:00
md5sha256 bea82eae88 Fix maven publish tasks 2021-12-05 22:56:37 +08:00
md5sha256 4ac0e045bd Add maven publish task 2021-12-05 18:22:41 +08:00
md5sha256 e5061b218e Java 17 and 1.18 2021-12-01 17:59:17 +08:00
md5sha256 40fdfba47d Fix silly typo in the buildscript 2021-11-18 22:16:36 +08:00
md5sha256 e9260cede6 Bump gradle wrapper version to 7.3 2021-11-18 22:14:56 +08:00
md5sha256 bb297c9ff1 Bump version 2021-11-16 15:28:14 +08:00
Andrew Wong 666742ad56 Merge pull request #2 from md5sha256/feature/purge 2021-11-16 15:25:54 +08:00
md5sha256 36eb8c3a5e Fix imports 2021-11-16 15:25:01 +08:00
Olzie-12 06a9f7b28e file management 2021-11-14 14:41:41 +00:00
md5sha256 e101780420 Fix compat for file manager 2021-11-11 13:31:09 +08:00
md5sha256 6abe99e807 Log sign warnings to the sign error logger 2021-11-09 19:06:02 +08:00
md5sha256 a1d18521ee Introduce interface for FileManager 2021-10-11 00:00:57 +08:00
md5sha256 363b416c59 Retain compat for FileManager 2021-10-10 03:48:12 +08:00
md5sha256 7bf516108b Rename AreaShop again and fix teleport feature 2021-10-09 22:22:53 +08:00
md5sha256 7567cb5fe4 Cleanup global features 2021-10-09 21:33:19 +08:00
md5sha256 d2ca54e8ea Fix signs not updating 2021-10-09 21:03:25 +08:00
md5sha256 e47cda4254 Fix plugin.yml 2021-10-09 17:44:01 +08:00
md5sha256 98d4c6a778 Fix relocations and cleanup DI for Economy and Permission 2021-10-09 17:40:10 +08:00
md5sha256 2a44dd29cc Fix relocations 2021-10-09 17:29:36 +08:00
md5sha256 c1665c33ff Finish cleaning up DI 2021-10-09 17:24:28 +08:00
md5sha256 2cdab9b6db Initial work on guice 2021-10-09 13:27:46 +08:00
md5sha256 72faf76619 Fix ClassCastException in RegionSign 2021-10-09 13:27:28 +08:00
md5sha256 ad66ce00b1 Actually register the sign listener 2021-10-09 02:00:38 +08:00
md5sha256 edc7126b87 Performance improvements to FileManager and various commands 2021-10-09 01:02:00 +08:00
md5sha256 a7f0ac248c Initial work on sign refactoring 2021-10-08 17:44:43 +08:00
md5sha256 675dee2cd3 Add sign error logger 2021-10-07 03:12:45 +08:00
md5sha256 c7226750ab Don't check for WG v5 2021-10-07 01:36:36 +08:00
md5sha256 2ecbb61053 Performance improvements for the teleport feature 2021-10-07 01:34:18 +08:00
md5sha256 fc132558a3 Add a BlockBehaviourHelper 2021-10-07 01:24:20 +08:00
md5sha256 b172413b62 Minor performance improvements 2021-10-07 00:11:09 +08:00
md5sha256 dcbb1f5896 Fix buildscripts and Java 16 support 2021-10-06 23:59:23 +08:00
md5sha256 6e3855c0c3 Remove legacy modules, remove use of ScriptEngine 2021-10-06 23:46:58 +08:00
md5sha256 27991d17a2 Gradle 2021-10-06 23:39:57 +08:00
md5sha256 159221d53d Initial work on updating to 1.17 2021-10-05 23:45:25 +08:00
dependabot[bot] 557d11dfb4 Bump checkstyle from 8.21 to 8.29
Bumps [checkstyle](https://github.com/checkstyle/checkstyle) from 8.21 to 8.29.
- [Release notes](https://github.com/checkstyle/checkstyle/releases)
- [Commits](https://github.com/checkstyle/checkstyle/compare/checkstyle-8.21...checkstyle-8.29)

Signed-off-by: dependabot[bot] <support@github.com>
2020-02-26 11:02:43 +01:00
Thijs Wiefferink b9547e2c67 Remove github action experiment 2019-08-16 18:22:19 +02:00
Thijs Wiefferink 221785ae55 Add test workflow maven build 2019-08-16 17:42:22 +02:00
Thijs Wiefferink 0d04676bce Fix including bukkit into the AreaShop jar 2019-06-23 22:27:35 +02:00
Thijs Wiefferink c8cd68c17b Fixup javadoc build 2019-06-23 22:07:34 +02:00
Thijs Wiefferink 539887449c pom.xml: build with craftbukkit 1.13 2019-06-23 21:59:04 +02:00
Thijs Wiefferink 4cda8a9292 Fix sign handling for 1.14
- Setup modules to load different classes for different Bukkit/Spigot versions
- Create BukkitHandler to get/set the sign facing and get the block it is attached to
- Fix `/as addsign` to use new sign methods
- Fix sign updates to use new sign methods
- Implement full forwards and backwards compatibility of the saved sign material type
    - On Bukkit 1.12 and lower all special wood types are translated to the standard sign
    - On Bukkit 1.13 the internal sign name is translated (and special wood types to the standard one)
    - On Bukkit 1.14 the signs of 1.13- are translated to the OAK variants
- Cleanup the .gitignore files inside of the module folders
2019-06-23 21:53:48 +02:00
Thijs Wiefferink fe131dc157 BuyRegion/RentRegion: fix %player% placeholders for selling/unrenting confirmation messages 2019-06-16 21:40:58 +02:00
Thijs Wiefferink 41ced9ee6c Update checkstyle from 7.6 to 8.21 2019-06-01 17:08:30 +02:00
Thijs Wiefferink 03de0ff252 default.yml: fix spelling mistake 2019-06-01 16:24:15 +02:00
Thijs Wiefferink b057271394 Fix permission check of /as rent, fix 'already bought' check of /as buy 2019-02-20 19:33:37 +01:00
Thijs Wiefferink d7cdff0b22 /as setteleport: fix check that hides it from /as help 2019-02-08 22:29:57 +01:00
Thijs Wiefferink 1035b6b41b Move event commands to a feature class, add two events
- Move eventCommandProfile code to a separate class
- Add AddingRegionEvent
- Add DeletingRegionEvent
- Cleanup a couple of duplicate code paths (merge RentRegion/BuyRegion branches)
2019-01-28 23:37:43 +01:00
Thijs Wiefferink e0bad7397c Refactoring based on SonarLint and Intellij IDEA inspections 2019-01-26 21:23:49 +01:00
Thijs Wiefferink b7124e8cdd Remove mcstats.org metrics class, I don't believe they will be online again 2019-01-26 20:11:26 +01:00
Thijs Wiefferink f0952c32c9 Update issue templates
Add 'NEW' label to issues created using the template
2019-01-13 22:26:54 +01:00
Thijs Wiefferink d3dfa86a65 Set version to 2.6.0 2019-01-13 17:34:50 +01:00
Thijs Wiefferink 8f73b8af3c documentation/release.md: add instructions for releasing a new version 2019-01-13 17:34:37 +01:00
Thijs Wiefferink 51b24c74b4 langHeader.yml: add the template used to generate the language file headers to the repository 2019-01-13 17:33:54 +01:00
Thijs Wiefferink 9beb1eb61b Move the changelog from the wiki to the repository 2019-01-13 17:33:09 +01:00
Thijs Wiefferink de5fdafca0 Pull translations from Transifex 2019-01-08 21:18:19 +01:00
Thijs Wiefferink 0aea914d20 Add FastAsyncWorldEdit support on Spigot 1.13
- FastAsyncWorldEdit now supported on Spigot 1.13
- Improved support for the beta-01 versions of WorldGuard and WorldEdit
- Resolves #436
2019-01-08 00:19:48 +01:00
Thijs Wiefferink b4efe7d5bf Add default labels to issue templates 2019-01-05 16:27:05 +01:00
Thijs Wiefferink ec7983e126 Fix handling of sign updates at places where they will pop off immediately
1. When placing back a missing sign it could be placed in the middle of the air
2. BlockPhysicsEvent would fire immediately (synchronously) breaking the sign
3. Sign update would break because the sign has not actually been placed
2019-01-01 19:32:34 +01:00
Thijs Wiefferink e45c353030 Fix detecting region by location when using WorldEdit 7 beta-2 or later
- The WorldEdit 7 beta-2 handler was inheriting a function from the handler of older version that uses the old Vector class
- Fixes #466
- Fixes #467
2019-01-01 19:30:16 +01:00
Thijs Wiefferink 44b1cb0fc8 /as add: fix setting player as landlord when he is an owner of the region
- Fixes #427
- Adds a debug message to check the behavior easily in the future
2018-12-28 17:11:48 +01:00
Thijs Wiefferink c7299fa56c Update Discord image to a widget image 2018-12-27 23:14:56 +01:00
pmme 12bf467714 Simplify WorldEdit 7 flushQueue vs. flushSession 2018-12-27 22:47:14 +01:00
Thijs Wiefferink 5b327db316 signs: instead of cancelling indirect break, remove the sign to prevent lagg 2018-12-27 19:44:30 +01:00
Thijs Wiefferink b4f33589a1 Cleanup old directory 2018-12-27 17:45:19 +01:00
Thijs Wiefferink 530c74ccd2 Add support for the WorldEdit vector refactor update
- Add WorldEdit and WorldGuard module that supports the new vector system
- WorldGuard/WordEdit dependencies are in the repository itself to make builds more reliable
- Change code that uses WorldEdit vectors to use Spigot vectors
- Rename all modules to areashop-[worldguard|worldedit]-<version>
- Change maven versions of internal modules to 'latest' to be less confusing
2018-12-27 17:42:24 +01:00
Thijs Wiefferink fa4857cbce Simplify code in the handler for WorldEdit 7 2018-12-27 15:00:53 +01:00
Thijs Wiefferink 93fd4e96cb Fix restoring schematics for the latest WorldEdit dev builds
- Fixes #447
- Thanks pmme and x1p for reporting the issue!
2018-10-28 17:58:09 +01:00
Thijs Wiefferink a6863ae782 Also put the Vault dependency into /dependencies
- Now it should be easy again to built AreaShop yourself, only need to run BuildTools for 1.13.0 and it should work
2018-10-28 01:15:12 +02:00
Thijs Wiefferink e5e2c4ca08 Fixup dependencies, use Bukkit/CraftBukkit 1.7.9 instead of 1.8
- 1.7.9 is the lowest supported version, so it is good to use that as base
2018-10-28 00:53:30 +02:00
Thijs Wiefferink b0341e2a3e Fix compatibility with 1.13 Material class
- Fixes sign handling to properly detect and store signs, fixes #440
- Fixes safe teleporting (also improves block detection, making it even safer)
2018-10-28 00:12:24 +02:00
Thijs Wiefferink c8e1ebb068 Change WorldGuard/WorldEdit/Bukkit dependencies to file links
- Fixes the issue that olders WorldEdit and Bukkit versions are not available on Maven anymore
- This speeds up the build a lot
2018-10-28 00:00:41 +02:00
Thijs Wiefferink 39c8eb5f73 Fix tab complete types for /as setduration 2018-10-22 23:44:31 +02:00
Thijs Wiefferink 2483cf1614 Try to add compatibility with the FAWE schematic format 2018-10-21 21:59:45 +02:00
Thijs Wiefferink 769f8ee4ca Set version to 2.5.0, ready for release! 2018-10-20 21:58:14 +02:00
Thijs Wiefferink 2c04b87a9f Add the latest Transifex translations for DE, ES and FR 2018-10-20 21:57:05 +02:00
Thijs Wiefferink 8ce1ed0264 Fix showing /as del and /as add in /help for landlords 2018-10-20 18:36:51 +02:00
Thijs Wiefferink 035f8e1932 Possibly fix default value for areashop.limits.default (documentation is inconsistent for not op) 2018-10-20 18:36:51 +02:00
Thijs Wiefferink 4d3482994f Smaller discord image 2018-10-20 15:53:14 +02:00
Thijs Wiefferink 45f1c510e5 Add link to the AreaShop Discord 2018-10-20 15:49:36 +02:00
Thijs Wiefferink 5c13223b9e Fix for 1.13.1, depend on WorldGuard and WorldEdit 7 beta-01 2018-10-20 14:54:52 +02:00
Thijs Wiefferink 8c47ae9b3c Add README.md files in a couple of packages, closes #128 2018-08-12 16:41:03 +02:00
Thijs Wiefferink 28d03a6a3a Small fixes suggested by Intellij IDEA 2018-08-12 16:23:43 +02:00
Thijs Wiefferink aa585e9b11 Deal with empty date/time settings (handle as 'unlimited'/'disabled')
- Fixes #412
2018-08-12 16:17:02 +02:00
Thijs Wiefferink 36d2ce60b9 Disable copying entities (WorldEdit 7), and enable removing entities (WorldEdit 6)
- Fixes security problem of #273:
    - Throw item into a region
    - Rent/buy the region -> it gets saved as schematic
    - Pick up items
    - Unrent/sell the region -> items appear again
    - Pick up second set of items, they got duplicated
2018-08-11 22:31:15 +02:00
Thijs Wiefferink bdea9448a4 Update WorldEdit 7 to build 3817, update WorldGuard 7 to build 1735 2018-08-11 22:19:25 +02:00
Thijs Wiefferink bd2f40f5c8 Use new schematic format when using WorldEdit 7 2018-08-11 22:18:48 +02:00
Thijs Wiefferink 9e908cee73 Fix getting region by location for WorldGuard 7 2018-08-11 22:17:13 +02:00
Thijs Wiefferink 0d326d973d Fix saving/restoring schematics with WorldEdit 7 2018-08-05 12:23:32 +02:00
Thijs Wiefferink 27eaa27765 Add WorldGuard 7 and WorldEdit 7 support, now 1.13 works
- Closes #411
2018-08-05 00:34:50 +02:00
Thijs Wiefferink fb35153eb2 Pull translations from Transifex 2018-07-22 17:52:25 +02:00
Thijs Wiefferink aec6295516 Remove dependency on javafx 2018-06-17 17:14:23 +02:00
Thijs Wiefferink 38cd77e487 Fix compilation error in the import command 2018-06-01 19:54:02 +02:00
Thijs Wiefferink 6b9866a4c4 Ignore hidden files in the /regions directory (like .DS_Store) 2018-05-29 22:58:15 +02:00
Thijs Wiefferink 5aceb81cfd Import: setup permanent region settings when not rentable and buyable 2018-05-29 22:21:43 +02:00
Thijs Wiefferink 50f6bce64e Fix region limits, thanks @ZachryWilsn for reporting! 2018-05-29 21:59:55 +02:00
Thijs Wiefferink f713edc5b5 Disable moneyback message in /as info if sellDisabled is true 2018-05-26 01:33:23 +02:00
Thijs Wiefferink 012920a51c Cleanups because of Intellij IDEA inspections 2018-05-23 23:46:57 +02:00
Thijs Wiefferink 6154454f96 Indicate if a region has already been added with another world
- Closes #287
2018-05-23 22:53:07 +02:00
Thijs Wiefferink e34daeb5ff Update readme to use issue template selection link 2018-05-23 22:38:12 +02:00
Thijs Wiefferink 0a2dc22c59 Setup issue templates 2018-05-23 22:29:29 +02:00
Thijs Wiefferink 2482bd88c2 Add option to ignore regions for limit calculation
Set `countForLimit` to `false` in default.yml, a group or the region file to ignore it for limits
2018-05-23 22:13:42 +02:00
Thijs Wiefferink e86281ab28 Safer sign update, don't assume location/world still exists 2018-05-12 14:41:45 +02:00
Thijs Wiefferink 5a9ca74b75 Add option to disable selling and reselling your own regions 2018-05-10 20:07:10 +02:00
Thijs Wiefferink d301be2304 Add licence, issues and CI to the root pom file 2018-04-03 22:44:16 +02:00
Thijs Wiefferink a23c6fa66f Hide progress messages of region update, speed up region updates 2018-04-02 20:05:38 +02:00
Thijs Wiefferink cd63517041 Fix list of region names for error indicating missing worlds 2018-04-02 20:00:22 +02:00
Thijs Wiefferink e3043c476b Fix available languages link 2018-04-02 12:10:34 +02:00
Thijs Wiefferink 3be7573863 Parse currency prefix and suffix with InteractiveMessenger
- Allows proper colors and escaping
2018-03-09 11:50:08 +01:00
Thijs Wiefferink 51161fffee Remove unused chunkunload event 2018-03-09 11:08:15 +01:00
Thijs Wiefferink c82067ad0b Add back Paypal donate button 2018-02-17 19:04:18 +01:00
Thijs Wiefferink 46dbb8d22c More customizable metric suffixes, better currency formatting
- 'metricSymbols' section in 'config.yml' to customize the used suffixes for large numbers
- Remove trailing zeros from numbers with metric suffix
- Properly handle rounding of 1.235 to 1.24 (different double to BigDecimal conversion)
- Closes #373
2018-02-12 14:44:48 +01:00
Thijs Wiefferink cace086466 Add UTF8 awareness flag in plugin.yml
- I think it only does something if you use JavaPlugin#getConfig(), but it does not harm either
2018-02-12 12:49:04 +01:00
Thijs Wiefferink 06a716b1fd Make %uuid% available to schematics when selling a region
- Schematic save/restore would happen after removing the owner, which means %uuid% would be null
- Unrenting already does the save/restore before removing the renter, so now it is more consistent
- Thanks to Behoston on Github for reporting the issue
- Closes #383
2018-02-01 13:59:48 +01:00
Thijs Wiefferink 4530717045 Command confirmation for /as import
- Can also be used for all WordEdit based add/delete actions in the future
2018-01-26 16:16:11 +01:00
Thijs Wiefferink 741bbd879f Fix hashCode() of RegionSign 2018-01-26 14:33:27 +01:00
Thijs Wiefferink 8474edd29d Save region name as given to /as add and /as stack
- Previously the WorldGuard region id was used, converting the name to lowercase
2018-01-26 13:55:41 +01:00
Thijs Wiefferink d4df691166 FIx usage of > in javadocs 2018-01-26 12:15:10 +01:00
Thijs Wiefferink 3e247e6cb1 Move sign listeners into SignsFeature
- Fix removing signs not removing it from the signsByChunk map
2018-01-26 12:08:22 +01:00
Thijs Wiefferink f3527134e8 Prevent chunk loading by sign updates
- When sign needs update, only do it if the chunk is already loaded
- If a chunk gets loaded (by a player or something else), update any signs in that chunk
- Improve some javadocs, let checkstyle require @param, @throws and @returns
2018-01-22 18:12:15 +01:00
Thijs Wiefferink 0e14b121b8 InfoCommand: fix showing list of signs (was only showing the first one) 2018-01-22 18:08:16 +01:00
Thijs Wiefferink 8cc632fc05 Pull latest translations from Transifex (automated script) 2018-01-22 16:31:03 +01:00
Thijs Wiefferink 77c1b3f288 Fix error in help message of the import command 2018-01-22 16:10:02 +01:00
Thijs Wiefferink 21339cbf7c Fix incorrect message reference for /as message 2018-01-22 16:07:52 +01:00
Thijs Wiefferink 0351188671 Update live support link 2018-01-21 22:10:02 +01:00
Thijs Wiefferink 47e1d80821 Add live support chat link to 99messages 2018-01-18 16:16:40 +01:00
Thijs Wiefferink 1d0472b052 Improve feedback when placing [as] sign for region that is not added 2017-12-22 12:25:30 +01:00
Thijs Wiefferink 22dcfc76af Fix confirmation messages of /as del (failed refactor)
Thanks Noudux for reporting it!
2017-12-21 18:09:55 +01:00
Thijs Wiefferink 6b59176048 Fix startup error: call init method of the scheduling library 2017-11-27 10:02:51 +01:00
Thijs Wiefferink 5dc4d11408 Fix missing spaces in /as message messages 2017-11-26 23:49:42 +01:00
Thijs Wiefferink 00bd305381 Use Map#putIfAbsent where applicable 2017-11-26 16:01:05 +01:00
Thijs Wiefferink 9daa50b23b Use BukkitDo scheduling library
- Much cleaner code for scheduling tasks,
- Makes proper use of Java 8 functionality
2017-11-26 15:47:51 +01:00
Thijs Wiefferink 33b73a0369 Remove Paypal donate button 2017-11-25 17:07:54 +01:00
Thijs Wiefferink 591540af30 Partially fix problem with importing regions from RegionForSale
- When checking the type of a region AreaShop would only look at the settings of the region, not the settings of the world, parent regions and config.yml
- Checking parent regions for these settings should still be added (requires bigger changes)
2017-11-23 22:54:55 +01:00
Thijs Wiefferink 4e1e50e993 Fix /as linksigns <profile> for configs without signProfiles
The `signProfiles` section is not in the default config.yml file anymore, so getting that section can return null
2017-11-20 09:19:35 +01:00
Thijs Wiefferink 9a52ca3d9b Add missing @return Javadoc for RegionGroup#getAutoRegions() 2017-11-10 00:04:39 +01:00
Thijs Wiefferink 858b019806 Add option to teleport X blocks away from the sign
- Implements #364
- Option `general.teleportSignDistance` to `default.yml` to set the number of blocks to teleport away from the sign
- Changes the pitch/yaw of the player so that he faces the sign
- Handles wall and floor signs in any direction
- Improve SignsFeature code structure
2017-11-09 23:56:18 +01:00
Thijs Wiefferink b1dfe93088 Add RegionForSale import, rental auto-extend and other things
- `/as import RegionForSale`, as requested in #98:
    - Imports all regions from RegionForSale
    - Converts almost all settings to their AreaShop equivalent
    - Handles parent regions
- Add `rent.autoExtend` for use with rental regions to automatically extend the rent when the time is out, start of #29, still need the command
    - Vault compatible permissions plugin is required to let this work while the player is offline
    - All permissions, limits and the player balance are checked as during a normal rent
- Add option to region groups to automatically add all regions of a certain world
- BREAKING: Region events now use OfflinePlayer instead of Player
- Automatically import existing region owners/members when adding a region to AreaShop

There are still a couple of things missing in the import and it needs to be tested a lot.
2017-10-20 13:41:30 +02:00
Thijs Wiefferink 0bf2314f2a Add licence (as already listed on BukkitDev) 2017-10-16 11:56:04 +02:00
Thijs Wiefferink 33ddb8ae88 Fix %volume% for polygon regions
- WorldGuard does not implement volume() for Polygon regions, always returns 0
- Volume result is cached, calculating it for polygon regions could be slow
2017-10-05 16:53:42 +02:00
Thijs Wiefferink 234e4b6261 Prevent indirectly breaking signs with non-solid blocks
- Fixes #358
2017-10-05 13:43:27 +02:00
Thijs Wiefferink ed2ffaeaa3 Move base command to EN.yml for /as info paging 2017-10-05 13:15:51 +02:00
Thijs Wiefferink e073438862 Add %volume% variable to get the number of blocks in a region
- Works properly for polygon regions
2017-10-05 12:20:03 +02:00
Thijs Wiefferink 07194f07da Add region masking to schematic restore
- When restoring a schematic the paste is masked to the region blocks, so that only blocks that are actually inside the region are pasted (necessary for polygon regions)
- Closes #20
2017-10-01 19:49:05 +02:00
Thijs Wiefferink dfa3e0be66 Checkstyle fix 2017-09-04 17:09:31 +02:00
Thijs Wiefferink 8eef029400 Fix %month% variable using 0-11 instead of 1-12
- Fixes #354, thanks skippyaut
2017-09-04 16:58:39 +02:00
Thijs Wiefferink c8d869ce15 Fix usage of teleport location set by '/as settp'
- It was accidentally trying to get the teleport location from the plugin config file instead of the region config file.
- Also added the possibility to set the teleport location in groups and default.yml
2017-08-05 20:25:06 +02:00
Thijs Wiefferink 053d75181d Update to InteractiveMessenger 1.1-SNAPSHOT
- Ensures AreaShop is rebuild when InteractiveMessenger updates
- Fixes crash bug that was in InteractiveMessenger
- Fixes #334
2017-07-30 17:25:49 +02:00
Thijs Wiefferink f0128c221b Update README.md 2017-06-23 14:59:16 +02:00
Thijs Wiefferink ce6c01c5d0 Add Transifex translation stats image 2017-06-23 14:54:19 +02:00
Thijs Wiefferink b835c4dded Only reset WorldGuard flag/groupFlag if not already empty 2017-06-12 22:05:09 +02:00
Thijs Wiefferink 07e6782714 Fix /as setowner for regions that are not rented yet
Add a rental period to the time when setting owner of a rental region that is not rented yet, otherwise it would get expired immediately
2017-06-12 21:58:42 +02:00
Thijs Wiefferink 4002956aeb Fix javadoc comments 2017-06-12 20:42:36 +02:00
Thijs Wiefferink 0b96b9cb42 Github update checker, Java 8
- Add Github update checker, closes #201, it is implemented to allow reuse by other plugins, it will probably move to a separate repository later
- Switch to Java 8, if people did not update already they probably never will
- Add used Bukkit version as property, use that in all pom files
- Add Task class with methods to easily use BukkitRunnable (not all code is migrated to this pattern yet)
2017-06-12 20:39:28 +02:00
Thijs Wiefferink 0c192c2444 Cleanup setOwners/setMembers, only edit WorldGuard region if different
- Improve code layout for changing owners and members of WorldGuard regions
- Only edit flags and other WorldGuard region settings if they are different than the current option, this prevents useless saves in WorldGuard (which shows a message in console)
2017-06-12 20:39:28 +02:00
Thijs Wiefferink 2381aaeacc Remove link to Shop plugin because it is not fixed yet 2017-04-30 14:15:35 +02:00
Thijs Wiefferink 906b331758 Fix line endings in config.yml 2017-04-20 23:35:49 +02:00
Thijs Wiefferink f0f2e09be0 Always add English time indicators
- Internal timers specified using settings in hiddenConfig.yml use the English words, so if you remove the English words from config.yml timers do not run (regions not expiring, no notifications, no file saving)
- Warn in console when an unknown time specifier is found, might get spammy but at least gets the point across
2017-04-20 23:23:57 +02:00
Thijs Wiefferink 395cc6de07 Fix usage of 'resale' in 'default.yml' for 'flagProfile' section
- 'resale' was used instead of 'resell' (as defined in GeneralRegion#RegionState) in the 'flagProfile' section, causing the flags not getting applied when the region is in reselling state.
- Added fallback to 'resale' section if 'resell' section is not present (to properly read old config.yml/default.yml files)
- Fixed usage of '%resaleprice%' in the resale greeting, should be '%resellprice%'
- Fixes #303, thanks electro2560 for the great bug report!
2017-04-20 15:26:26 +02:00
Thijs Wiefferink 3b9d6187ca Fix checkstyle fail 2017-04-17 21:34:32 +02:00
Thijs Wiefferink 9d1585f513 Fix groups file getting cleared on server start
- Fixes #299
- Because of an earlier change the groups file is loaded before regions are loaded on server start, and region groups remove themselves if there are no valid regions in them anymore.
- Keep groups even though they are empty (so that configuration done in the group is not lost)
2017-04-17 21:32:15 +02:00
Thijs Wiefferink 9d6955039a Fix '/as groupdel' with non-existing group creating an empty one 2017-04-17 21:26:24 +02:00
Thijs Wiefferink 747b47057b Allow # in region name for /as stack to determine counter position 2017-04-11 21:22:35 +02:00
Thijs Wiefferink a973e254e6 Fix '/as addfriend' not allowing you to add players that are playing for the first time
- Fixes #297
2017-04-02 22:34:02 +02:00
Thijs Wiefferink a5105af3ad Add 'use' flag to default.yml again since people mess it up 2017-03-29 20:18:14 +02:00
Thijs Wiefferink 0bb0a05b76 Cleanup checkstyle from pom.xml in AreaShop module 2017-03-29 20:17:42 +02:00
Thijs Wiefferink dad502ec0c Add checkstyle to enforce formatting, change all formatting to comply 2017-03-29 20:15:44 +02:00
Thijs Wiefferink f471b9bbf0 Don't show 'in advance renting:' in '/as info' if maxExtends is zero
- Thanks to R0bstar for noticing this weird weird message combination
2017-03-09 16:14:30 +01:00
Thijs Wiefferink f69d1c41e6 Code cleanup and stricter visibility of methods/variables 2017-03-09 16:01:36 +01:00
Thijs Wiefferink 4ea6f59c49 Remove GeneralRegion#is{Rent|Buy}Region()
- It served no purpose and prevents IDEs from detecting type safety
2017-03-09 15:29:01 +01:00
Thijs Wiefferink 0b7158290f Add some more bStats statistics 2017-03-09 15:09:05 +01:00
Thijs Wiefferink e6757d23de Add bStats analytics
- Add bStats analytics because MCStats is down constantly
- Add custom graphs:
  - Language pie chart
  - Number of registered regions
  - Number of rental regions
  - Number of buy regions
- Closes #287
- In the future MCStats can be removed, for now I would like to keep complete data there for the times it does work
- Could add more graphs in the future for number of friends and things like that
2017-03-02 18:14:07 +01:00
Thijs Wiefferink 7cda35f4da Remove duplicate link in the readme 2017-02-12 20:04:35 +01:00
Thijs Wiefferink ee293d14b9 Fix link to CI in the readme 2017-02-12 20:03:46 +01:00
Thijs Wiefferink 2e0fce4955 Update repository url 2017-02-09 14:59:53 +01:00
Thijs Wiefferink 7afdefc9ed Add missing javadoc to loadFiles methods 2017-02-02 23:03:55 +01:00
Thijs Wiefferink 11f80e7ed1 Start using InteractiveMessenger
- Messaging functionality has been split into the InteractiveMessenger project: https://github.com/NLthijs48/InteractiveMessenger
- Jenkins build server has been changed to publish a Maven repository: http://jenkins.wiefferink.me/plugin/repository/everything
2017-02-02 22:59:00 +01:00
Thijs Wiefferink 40d45c7786 Fix using landlordName setting without using landlord (uuid) setting 2017-02-02 17:20:26 +01:00
Thijs Wiefferink 6b8e161e43 Ensure buy/rent/resell price is never below zero
This prevents problems with negative payment or withdrawal in Vault if input validation of a command is not good enough or if a price has manually been set below zero.
2017-02-02 17:18:26 +01:00
Thijs Wiefferink e1b2f7391c Improve message when you cannot rent/buy a region
The message did not specify which region cannot be rented/bought, which has now been added.
2017-02-02 16:45:15 +01:00
leNic 89ae8b9b4a Fixed reselling with negative prices (#280)
Prevents setting a negative resell price,. Some economy plugins accept a withdraw with a negative number, which has bad consequences (for example EssentialsEco does not accept it).
2017-01-28 20:25:24 +01:00
Thijs Wiefferink fab415bf19 Speed up expiration and expireWarning tasks
The expire task was triggering more often than the expireWarning task, causing lost warnings when warnings with a low time are specified
2017-01-23 14:26:25 +01:00
Thijs Wiefferink c7aa92be81 Indicate in default.yml that expressions can be used for region prices 2017-01-13 19:25:31 +01:00
Thijs Wiefferink 705c8d6891 Update README.md 2017-01-13 18:42:04 +01:00
Thijs Wiefferink 429d87c9ff Improve feature list 2017-01-13 18:41:16 +01:00
Thijs Wiefferink 1fdd8b32cc Add prices depending on a formula
- Price can be specified with an expression (JavaScript syntax)
- You can also use a block of JavaScript code, the value of the last line is used as result (for more complex logic)
- Supported settings: rent.price, buy.price, rent.moneyBack, buy.moneyBack (need more? ask me)
- Before evaluating the expression all region variables as defined in the config.yml file will be replaced (allows you to use %width% etc)
- Added %timesExtended% variable for use in expressions (to know how long the user is renting for)
- '/as setprice' and signs still only allow number input to prevent security problems (this means actual config access is required to do anything of harm with JavaScript)
- Closes #23
2017-01-13 16:56:02 +01:00
Thijs Wiefferink 7900f78a8c Change default WorldGuard flags to include block-place and block-break
Way too many people set the block-break and block-place flags on bigger or even the global region to deny (which is unnecessary and wrong relatively, for global use 'passthrough: deny' instead) so this patches up those mistakes by setting them at the AreaShop region
2017-01-13 16:06:18 +01:00
Thijs Wiefferink 3a65a88849 Fix replacing variables into language variables
- Previously it would insert it as a message, causing the language variable to be split up into multiple parts (which prevents recognizing it later)
- If a Message is marked as inline with Message#inline() it will be inserted without breaking up the message
2016-12-27 16:17:04 +01:00
Thijs Wiefferink 7b491d0389 Lazily instantiate feature classes to improve performance 2016-12-27 16:15:17 +01:00
Thijs Wiefferink fd02c51492 Add setting to prevent cross-world teleportation with '/as find'
- If a region is in another world and 'findCrossWorld' is off, it will be filtered from the results
- 'teleportCrossWorld' will not be checked anymore if the teleport is called from '/as find'
- Resolves  #234
2016-12-26 23:29:40 +01:00
Thijs Wiefferink bb1f592807 Add setting to prevent cross-world teleportation with '/as tp'
Related to #234
2016-12-26 23:20:12 +01:00
Thijs Wiefferink 16c7a044ea Add and make use of escaping in messages
- Add escaping support to FancyMessageFormat: put a backslash before a tag and it will not be interpreted, also works for color codes (&2 and §2) and variables
- Make use of escaping in the Message class to properly handle user input as plaintext (previously user input that got printed back also got interpreted, like colors apply to it)
- All replacements given to Message are escaped, unless you wrap them in a Message before it.
- Replacement limits and infinite replacing detection have changed slightly
2016-12-26 22:56:35 +01:00
Thijs Wiefferink 152f183670 Fix region update after /as reload, cleanup unused code 2016-12-25 23:02:23 +01:00
Thijs Wiefferink 09b6e4c584 Fix string setting as profile in default.yml
- This has been broken in b525c5902c
- Fixes #267
2016-12-25 22:40:11 +01:00
Thijs Wiefferink aeb70196a3 Fix shutdown exception in SignsFeature 2016-12-24 19:59:04 +01:00
Thijs Wiefferink 62148ea577 Move teleportation code to a feature class 2016-12-23 23:25:41 +01:00
Thijs Wiefferink fcc9fb0945 Refactor to introduce Manager and RegionFeature
- Manager to serve as abstract class for managers (like FileManager), implements a lifecycle to allow for shutdown operations (like save all files)
- RegionFeature to server as abstract class for region features
- Improve instantiation and lifecycle of features (global features and region specific ones)
- This is preparation for moving more region functionality into feature specific classes (which makes GeneralRegion smaller and easier to maintain)
2016-12-23 16:03:22 +01:00
Thijs Wiefferink b525c5902c Fix default settings leaking when getting configuration sections
- Default settings and custom settings are in separate YamlConfiguration instances now to prevent leaking
- When getting a configuration section you now know that either it is from the current default.yml file or the default.yml file in the jar (querying settings from the section will always have the same source)
- Fixed a startup null pointer
- Fixed #266
2016-12-23 14:07:26 +01:00
Thijs Wiefferink b18a7cc6d5 Fix [break] in hover lines
Hover lines are still a bit broken when trying to insert complex messages into them, this is hard to do in a proper way though.
2016-12-10 15:19:34 +01:00
Thijs Wiefferink 54b6e84558 File loading improvements to be more robust 2016-12-04 21:14:31 +01:00
Thijs Wiefferink bae3c0a199 Ask for config files in the issue template 2016-12-04 17:56:37 +01:00
Very Evil Olaf 508270a280 Update ISSUE_TEMPLATE.md (#258)
Note that 'latest' is not a correct version
2016-12-04 17:48:36 +01:00
Thijs Wiefferink 87b2cb9ecd Prevent exceptions if a schematicProfile does not exist 2016-12-04 17:31:22 +01:00
Thijs Wiefferink 271b17b6be Set version to 2.4.0 and update language files 2016-12-02 14:37:27 +01:00
Desjardins Jérôme 1dfedea50c Create a permission for teleporting to available regions (#241)
* Update GeneralRegion.java
Add Available abstract function
Check Permission modification

Update BuyRegion.java
Add Available function for selled

Update RentRegion.java
Add Available function for rented

Update TeleportCommand.java
Check new permission

Finish feature teleport available region

* Fix translation
2016-11-19 17:15:23 +01:00
Thijs Wiefferink d9abe2e347 FIx problem with null regionFlags sections 2016-11-14 18:02:59 +01:00
Thijs Wiefferink 1ba2e21ae9 Make profile based settings easier to understand
- Remove 'signProfiles', 'flagProfiles', 'eventCommandProfiles', 'schematicProfiles' and 'expirationWarningProfiles' from the config.yml file
- Add the removed profile contents directly to the setting without the trailing 's' in the default.yml file (this prevents the need to understand the creation of profiles, and then assigning them, taking out a step in the thought process of users)
- Added method in GeneralRegion to get a ConfigurationSection from the region file, group files or default file while also taking into account the translation from a string to a profile that is defined in the config.yml file. This ensures backwards compatibility with current config files (the old style will not be promoted anymore though).
- The 'expirationWarningProfiles' does not have the subkeys 'warnPlayer' and 'commands' anymore, it is just a list of commands now, using the '/areashop message' command to warn a player.
- Add a workaround for the empty sign problem after unrent/sell of a region while having restore enabled, an AsyncWorldEdit plugin installed and signs inside the region (sign will be updated again half a second after unrent/sell).
2016-11-13 00:44:35 +01:00
Thijs Wiefferink fcdfdc6094 Update language files
- Swedish is added
- German, French and Russian are improved
2016-11-07 14:13:03 +01:00
Thijs Wiefferink 8a7e2ba5c2 Indicate limits when a MaxChangedBlocksException is thrown by WorldEdit 2016-11-07 13:52:54 +01:00
Thijs Wiefferink 0950452692 Fix a couple of problems caused by vertical /as stack addition 2016-10-31 21:07:08 +01:00
Thijs Wiefferink 293978f068 Decouple Message class from replacement providers
- Instead of applying replacements by testing for a replacement that has the GeneralRegion type, it now checks for a ReplacementProvider instances (one step closer to making Message independent of AreaShop).
- Replacements are handled one by one with a switch-case instead of getting them from a map, helps performance a lot.
2016-10-25 20:57:58 +02:00
Thijs Wiefferink 5efe14b8e9 Add up and down direction for '/as stack'
Prevents creating regions above and below the world limits, still needs
testing.
Progress for #105
2016-10-24 15:02:49 +02:00
Thijs Wiefferink 839d510151 Switch from Bukkit to Spigot Maven repo since it is down
Also switched from Bukkit 1.7.9 to Bukkit 1.8.0 because that is the lowest version available on the Spigot repo
2016-10-17 23:45:08 +02:00
Thijs Wiefferink 9180d9b8ee Fix small language file issue
When you only have a formatting code before a language variable, the hover/click effects will accidentally be applied to one text part earlier
2016-10-16 18:29:26 +02:00
Thijs Wiefferink 7aa786f4ce Fix default config trying to execute /as message as player
Fixes #221
2016-09-04 22:43:03 +02:00
Thijs Wiefferink 10ea8540e7 Add tab completion for '/as me [player]'
Closes #220
2016-09-04 00:59:04 +02:00
Thijs Wiefferink dba00769f6 Fix problem with line breaks 2016-09-03 20:58:45 +02:00
Thijs Wiefferink 44c70c6a33 Cleanup messages about region that does not exist in WorldGuard 2016-09-03 19:46:05 +02:00
Thijs Wiefferink 570f7b4055 Don't extend rent when using '/as setowner' to set a different owner
Also remove new owner from the friends list.
Fixes #219
2016-09-03 19:19:40 +02:00
Thijs Wiefferink feafa012dd Fix issue with \n on 1.7.x servers
- Each line of a message will now be sent separately instead of using '\n' in the text
- Drastically reduced the number of StringBuilders that are instantiated during message construction
- Fixes #222
2016-09-03 17:22:40 +02:00
Thijs Wiefferink 82b340ce1a Messages: also parse section signs into color tags properly
Fixes line-wrapping removing color in some cases
2016-09-02 21:43:58 +02:00
Thijs Wiefferink 93809f27fc Rename events to be consistent with commands
- AddFriendEvent -> AddedFriendEvent
- DeleteFriendEvent -> DeletedFriendEvent
- RemovedRegionEvent -> DeletedRegionEvent
2016-08-28 22:45:20 +02:00
Thijs Wiefferink f8ed3654fd Fix compilation error 2016-08-28 22:31:06 +02:00
Thijs Wiefferink 58a1afccf3 Invert inheritance of RegionEvent and CancellabelRegionEvent/NotifyRegionEvent 2016-08-28 22:29:45 +02:00
Thijs Wiefferink d9c3573225 Change RegionUpdateEvent to UpdateRegionEvent
This breaks plugins using the event
2016-08-28 22:21:33 +02:00
Thijs Wiefferink 1577443203 Generalize events better
Adds generic classes for events with a region (BuyRegion, RentRegion or GeneralRegion)
2016-08-28 22:11:17 +02:00
Thijs Wiefferink ab7a92c57d Update README.md 2016-08-26 19:49:21 +02:00
Thijs Wiefferink 2e09b0f60f Update README.md 2016-08-26 19:48:59 +02:00
Thijs Wiefferink 6e5c35f95b Add extension plugins section 2016-08-26 19:45:37 +02:00
Thijs Wiefferink 066ceedafd Add 'build' flag by default to prevent inheriting from parent regions. 2016-08-21 22:20:25 +02:00
Thijs Wiefferink c8ebe24bd3 Put break in '/as info' help message in the right spot 2016-08-19 20:52:07 +02:00
Thijs Wiefferink ad7db5ee23 Attempt to fix unable to add new players with '/as addfriend' 2016-08-16 22:43:09 +02:00
Thijs Wiefferink f80a8178ff Fix formatting not clearing on new lines 2016-08-13 22:28:15 +02:00
Thijs Wiefferink 05c8e1a7e4 Make loggin methods more generic 2016-08-10 16:07:39 +02:00
Thijs Wiefferink 9904805310 Improve version detection of WorldGuard
- First detect version 5
- Then detect lower than 6.1.3
- Else check build number:
  - Build number exists and lower than 1672: 6
  - Build number exists and Is 1672: broken
  - Else: 6_1_3
2016-08-09 22:56:21 +02:00
Thijs Wiefferink 0df2f429c0 Only print build number warning if we found it 2016-08-09 22:38:33 +02:00
Thijs Wiefferink b3408a2648 Fix compilation error and WorldGuard version detection 2016-08-09 21:52:53 +02:00
Thijs Wiefferink e1f89e7904 Cleanup some leftover logging in an old style 2016-08-08 22:06:31 +02:00
Thijs Wiefferink 064b129205 Change version to 2.3.2 and update languages
- Russian has been added
- Spelling errors in French have been corrected
2016-08-07 22:21:57 +02:00
Thijs Wiefferink 8111387f32 Improve friend line of /as me, add click hint
Change blue color of hover popup to gold, which will be used as action color
2016-08-07 22:06:09 +02:00
Thijs Wiefferink a4b23bebba Improve line of rented regions in info command 2016-08-07 21:49:44 +02:00
Thijs Wiefferink 7421e685fa Improve robustness of variable replacing in messages
- Once the limit is reached the argument replacer would still continue sometimes (if a the replacement itself triggers the limit and the inserted message increases the size of the message we are building and adds a parameter tag again, like %0%)
- The language tag replacer also stops earlier now, it did not have the above problem though
- Fixed FancyMessageFormat.insertMessage() not checking its parameters
- Message.get() with a limit will now return an empty message if the limit is reached to prevent problems like above.
- Closes #205
2016-08-07 00:09:30 +02:00
Christoph Krüger @Androkai 374b68d8fa Update VaultAPI-repo (#206)
The url of the Vault Maven repository has changed.
2016-08-06 22:36:26 +02:00
Thijs Wiefferink ca7a9664f3 Fix error in info command of rental region 2016-08-02 22:27:55 +02:00
Thijs Wiefferink e957b4fc73 Remove all reflection for sending fancy messages
- Reflection removed
- JSON is now fully escaped instead of lenient escaping
- Sending is now done with /tellraw
2016-08-01 21:31:14 +02:00
Thijs Wiefferink 6493bc4f78 Add empty lines if a page does not fill the screen
Relevant for commands like `/as info all` that can have pages
2016-08-01 21:28:11 +02:00
Thijs Wiefferink 2db1b6a243 Prevent updater throwing errors sometimes when BukkitDev is offline 2016-08-01 20:46:40 +02:00
Thijs Wiefferink 864662a3c4 Add javadocs to limitgroup inner class and setting methods 2016-08-01 20:23:49 +02:00
Thijs Wiefferink 59b960b87c Update languages, set version number to 2.3.1
- Added German translation
- Added French translation
- Added Norwegian translation
2016-08-01 19:36:50 +02:00
Thijs Wiefferink 2de653d73f Add automatic conversion of language files downloaded from Transifex 2016-08-01 18:03:09 +02:00
Thijs Wiefferink 4feee59834 Cleanup info and warning messages. 2016-08-01 16:18:05 +02:00
Thijs Wiefferink 816d136a62 Change version number to 2.3.0, update languages
- Only English and Dutch are available yet
2016-07-24 21:48:39 +02:00
Thijs Wiefferink 121de7dc7e Add build number option to Maven
- Build number option can be used by Jenkins to add the build number
- Build number of soruce on Github will be #CUSTOM to mark custom builds
- Release versions will not contain a build number
- Closes #185
2016-07-24 20:59:25 +02:00
Thijs Wiefferink f7c86881cc Fix the default flagProfiles settings, fix migration issues. 2016-07-24 20:25:58 +02:00
Thijs Wiefferink 351d51b664 Correct message for reselling region entries. 2016-07-23 19:31:45 +02:00
Thijs Wiefferink 5a28476cf0 Add better limits for messages
- Recursive replacements are handled by catching stackoverflow exceptions
- Messages are limited 30000 in length for the produced JSON string since the client cannot handle more
- Error message print out the message key and start of the message
2016-07-23 17:21:08 +02:00
Thijs Wiefferink 8143bdae27 Add pages to the /as info command to prevent crashes
- Output displayed in pages of 18 (+ header and footer it fills the max of 20 you can see without scrolling)
- Footer shows current and max page, and has buttons to go to next/previous
- Commands accept [group] [page] both as optional arguments, works because page is a number (number as group would be weird)
- Entries show basic info about regions (owner/price/duration), and of course can be clicked to show all info
- Made debug command more generic
- Closes #172
2016-07-23 02:57:31 +02:00
Thijs Wiefferink b62744fe10 Add warnings for missing settings in limit groups.
Closes #164
2016-07-21 23:00:19 +02:00
Thijs Wiefferink fe0b63c760 Remove incorrect check 2016-07-17 23:51:24 +02:00
Thijs Wiefferink def774c7a1 Link javadoc of external classes properly
Classes of Bukkit, WorldGuard and WorldEdit that appear in the javadoc now link to the javadoc of them.
2016-06-27 23:38:44 +02:00
Thijs Wiefferink 7c5cb5f5aa Add javadoc to getApplicableRegions methods 2016-06-27 23:16:21 +02:00
Thijs Wiefferink 8af6e1d6f1 Fix small Maven warning 2016-06-25 22:20:21 +02:00
Thijs Wiefferink e0e6c39dae Fix WorldGuard version detection for later stable releases 2016-06-21 22:42:56 +02:00
Thijs Wiefferink dabe46bd47 Move all sign related methods into SignsFeature
- Each GeneralRegion now has a SignsFeature
- Each SignsFeature contains RegionSign instances representing the actual signs
 - The RegionSign class contains methods to update them etc
 - There is one SignsFeature that is not linked to a region, but registered as listener to update the signs at events
2016-06-20 20:16:13 +02:00
Thijs Wiefferink ec478a05d1 Move region friends code to separate Feature class 2016-06-20 18:22:35 +02:00
Thijs Wiefferink e21c0aafde Add events for adding/removing friends
- Cancellable event for adding friends: AddFriendEvent (region, friend and who is trying to add it available)
- Cancellable event for removing friends: DeleteFriendEvent (region, friend and who is trying to delete it available)
- Closes #54
2016-06-20 17:03:12 +02:00
Thijs Wiefferink 52bf88f4a5 Prevent RemovedRegionEvent triggering twice
Add debug logging for RemovedRegionEvent and AddedRegionEvent
2016-06-20 16:32:10 +02:00
Thijs Wiefferink e4de560a65 Prevent Maven warning
It was trying to include the WorldGuard6 handler class twice in the jar file
2016-06-20 16:28:23 +02:00
Thijs Wiefferink 6481da29e4 Add compatibility for WorldGuard build 1674 and up.
- Added a module for WorldGuard 6.1.3 to adapt to changes in flag related methods.
- No compatibility with build 1672, since there is no dependency in the Maven repo of WorldGuard to target this (this is a dev build though so I don't expect people using it long-term)
- Move properties for setting Java version to the parent pom file (other modules inherit them)
- Move repositories to the parent pom file (other modules inherit them)
- Fix AreaShop module not declaring its parent
- Fixes #170
2016-06-18 23:23:22 +02:00
Thijs Wiefferink f287cc91a6 Remove leftover logging 2016-06-13 21:11:00 +02:00
Thijs Wiefferink 95b7b50346 Add development builds and javadocs links 2016-06-13 20:59:08 +02:00
Thijs Wiefferink 21db2ff440 Improve Maven setup for javadoc and source
- Generate a .jar file with the sources if -Dsources is provided
- Generate javadocs if -Djavadoc=/path/to/destination is provided
- Copy final .jar file to directory if -DcopyResult=/path/to/server is provided
- Adding missing javadoc comments
2016-06-13 20:36:17 +02:00
Thijs Wiefferink 36dd978a92 Cleanup the config file and settings
- Moved scheduled task settings to hiddenConfig.yml (settings that are not visible, but still usable)
- Remove 'postCommandErrors' setting
- Also execute commands defined in 'expirationWarningProfiles' when player is not online
- Move around settings in config.yml and improve explanations
- Closes #168
2016-06-13 17:03:20 +02:00
Thijs Wiefferink 6cc3f2a52f Combine all messages about region not registered
And replace mentions of 'this region' with the actual region name.
2016-06-13 14:47:10 +02:00
Thijs Wiefferink 852731b1ad Add action confirmations when using signs
- Confirmations by default for selling/unrenting by signs, not for renting/buying
- Fixed a bug with message composing which would duplicate hover/click parts.
- Added `/as message <player> <message...>` for internal/console use (not shown in help).
- Closes #50
2016-06-12 21:39:12 +02:00
Thijs Wiefferink 30faa77da9 Fix small error in multiple regions found message 2016-06-12 19:38:05 +02:00
Thijs Wiefferink ec57b922b8 Messages: Version fixes, fallback to plain.
- Properly parse NMS version number to support 1.10
- Fallback to plain messages if sending a fancy message breaks (we try again after restart/reload)
2016-06-12 16:48:47 +02:00
Thijs Wiefferink c2bcc6008b Add hover/click to some forgotten mentions of regions 2016-06-12 13:25:55 +02:00
Thijs Wiefferink 72a05bedce Merge personal/all help messages. 2016-06-11 22:40:09 +02:00
Thijs Wiefferink bc73a8b20d Cleanup links to issues 2016-06-11 17:35:00 +02:00
Thijs Wiefferink 832e8218b6 Add issue template for bugs/feature requests 2016-06-11 17:29:47 +02:00
Thijs Wiefferink 6fcb629133 Move to the me.wiefferink package
The nl.evolutioncoding domain is soon not mine anymore, and this new one I do intend on keeping.
2016-06-07 22:39:45 +02:00
Thijs Wiefferink 7d6a1f35c1 Messages: Add hover/click items to region info
- The hover/click parts only appear if you have permission to use the command linked to it
- Red crosses added next to the friends in the friend list to remove them
2016-06-05 17:04:38 +02:00
Thijs Wiefferink 60257d45c2 Messages: Add a bunch of click/hover actions to '/as info region <region>'
- rent/unrent/buy/sell/extend
- teleport, set teleport location
2016-06-04 22:46:10 +02:00
Thijs Wiefferink 2300227d87 Messages: Fix problem with message insertion sometimes missing leftover part 2016-06-04 20:57:14 +02:00
Thijs Wiefferink b1852b10bb Improve /as me, remove /as info player
And change underline to bold for clickable things (underline leaks through in the next line, giving annoying layout issues)
2016-06-02 22:39:30 +02:00
Thijs Wiefferink 88fdb0c3fc Add 'ALL' flagProfiles state that is always applied
And add block-break and block-place by default.
2016-05-31 22:36:18 +02:00
Christoph Krüger 491e55fc77 Change Vault dependency to Maven repo instead of .jar
Use the Maven repository of Vault instead of including a jar file in the repository.
2016-05-28 23:19:23 +02:00
Thijs Wiefferink c7b0a2c663 Let /as help respect the areashop.help permission
Closes #155
2016-05-28 17:04:06 +02:00
Thijs Wiefferink 868f4d6b58 Events: Add refunded money to UnrentedRegionEvent and SoldRegionEvent
Closes #147
2016-05-28 17:00:52 +02:00
Thijs Wiefferink 0d4b034181 Messages: Detect and stop replacement loops. 2016-05-28 16:51:32 +02:00
Thijs Wiefferink 5f20689ba3 Improve language variable argument detection 2016-05-27 21:01:14 +02:00
Thijs Wiefferink 38b658fccf Message changes: click on regions/players
- Click on region name for region details
- Click on player name for regions of the player
- Click on landlord name for regions of the landlord
- Change color codes to things like [blue] instead of &9 (both are supported though)
2016-05-24 23:18:25 +02:00
Thijs Wiefferink 28ed20c0b5 Message system fixes and improved robustness
Hover/click message for '/as info'
2016-05-23 12:16:19 +02:00
Thijs Wiefferink aaff36b2eb Add hover/click support for messages #18
- Language files support a way to add hover tooltips, click commands and click insert commands (using FancyMessageFormat created together with PhoenixIV)
- Language variables support arguments
- Help listing (/as help) uses the new hover/click things, more to come
- See #18 for the TODO list
2016-05-22 21:36:58 +02:00
Spidev46 49b536cab0 There is a mistake with the messages (#153)
Confirmation message of reselling a region does not go to the old owner.
2016-05-22 21:19:10 +02:00
Thijs Wiefferink 9a9969dea3 Fix problems with detecting most important region when placing a sign.
WorldGuard filters child regions from the ApplicableRegionSet for some reason, so setting parent/child relations on regions messes up the detection because the children can never be found.
2016-03-07 12:21:33 +01:00
Thijs Wiefferink 84e4b49bfd Update language files
English, Dutch and German are complete, others are only partially complete.
2016-03-06 00:07:31 +01:00
Thijs Wiefferink 6daaf6997d 1.9 compatibility fixes (getOnlinePlayers() method) 2016-03-05 22:15:21 +01:00
Thijs Wiefferink c445a62334 Add variable support to all messages where a region is known (mostly messages of commands were not using it yet). 2016-02-08 19:39:33 +01:00
Thijs Wiefferink 0d205b0d9e Change general.teleportLocationY to also accept a number. 2016-02-08 14:43:24 +01:00
Thijs Wiefferink 8c33826c2c Add build flag to default flagprofiles, users are often having trouble with this 2016-01-26 22:35:01 +01:00
Thijs Wiefferink 51e1dbafb7 Fix running sign commands going wrong.
Player commands are run first, which normally rents/buys a region, so when the console commands are ran after that, then it will run the commands of the wrong state (since the state just changed). Also fixed a minor WorldGuard version dependency issue.
2016-01-26 22:20:45 +01:00
Thijs Wiefferink 6edad3faff Add priority and interact flag to config.yml by default
50% of the issues are having more regions at the same place, and therefore requiring a higher priority for the AreaShop region and having chests accessible by anyone instead of only the region owner/member. This should fix these problems.
2016-01-12 21:43:04 +01:00
Thijs Wiefferink f89e0f861b Add a link to a preview server 2016-01-08 20:18:47 +01:00
Thijs Wiefferink 770b1d98df Refactoring:
- Move a bunch of utility methods from the AreaShop class to Utils
- Comments styling cleanup
- Display warning in console when region file does not load correctly (is empty)
2016-01-05 22:31:55 +01:00
Thijs Wiefferink 8e5baa47af Fix variables of sell messages 2015-12-26 20:08:01 +01:00
Thijs Wiefferink 367466735e Fix the 'n:<name>' option for member/owner region flags
Before it would keep the 'n:' part when adding the name to the region, therefore adding an incorrect name.
2015-12-26 00:45:05 +01:00
Thijs Wiefferink ade6bc3971 Add AddedRegionEvent+RemovedRegionEvent, moved sign/flags updating
- Sign updating now uses the event system
- WorldGuard region flag updating now uses the event system
- After changes made by commands/other user input it will now use update() on the region instead of the sign and region flag commands.
2015-12-13 19:55:47 +01:00
Thijs Wiefferink 05fd8c0156 Implement event system
- 'ask' type events that can be cancelled, broadcasted before the action happens
- 'notify' type events that cannot be cancelled, but only let you know that it has happened
- Events for renting (with extending flag), unrenting, buying, selling, reselling
- General 'RegionUpdateEvent' to listen to as display service (update signs, update regions flags, etc)

All messages in the GeneralRegion, RentRegion and BuyRegion classes can now use all region variables (in the future all other messages will also be worked through)

Closes #84
Closes #86
2015-12-11 20:54:12 +01:00
Thijs Wiefferink 5403472476 Cleanup/update config.yml and default.yml comments
- Add links to the wiki.
- Make things more consistent.
2015-12-10 23:16:19 +01:00
Thijs Wiefferink c4ee7bc7aa Add 'areashop.linksigns' to the 'areashop.*' permission group 2015-11-24 20:59:58 +01:00
Thijs Wiefferink 940f1969b6 Add link to dev builds on Jenkins 2015-11-24 20:43:44 +01:00
Thijs Wiefferink 07eb5477b8 Update Metrics 2015-11-17 21:21:27 +01:00
Thijs Wiefferink a4112092b5 Fix inclusion of the version specific classes of WorldGuard/WorldEdit in the final jar 2015-11-15 23:47:23 +01:00
Thijs Wiefferink 872d81b0a9 Cleanup code, fix some small bugs
Most of these things have been found with help of Intellij IDEA, preferring it over Eclipse already
2015-11-15 23:35:48 +01:00
Thijs Wiefferink b04871c553 Add rental to max when rental would go above maxRentTime otherwise
- Setting `extendToFullWhenAboveMaxRentTime` to set if AreaShop should
automatically extend to max when the player cannot rent a full duration
because of `maxRentTime`.

Fixes #94
2015-11-11 11:56:16 +01:00
Thijs Wiefferink fd1b8fba4c Fix inactiveSetting debug messages
The messages still assumed the inactiveSettings was in minutes instead
of in milliseconds.
2015-11-02 22:39:40 +01:00
Thijs Wiefferink 991e7b1961 Fix lastActive sometimes not updating correctly
- Update the lastActive time at rent/buy to ensure it is non-zero
- Ignore lastActive time of zero, give back current time
- Update lastActive time at server shutdown for players that are still
online, quit events are not fired at shutdown
2015-11-02 22:32:51 +01:00
Thijs Wiefferink aac963325a CI run :) 2015-11-01 23:03:41 +01:00
Thijs Wiefferink 3e7c7ce76b Fix message variables for '/as info player <player>' feedback 2015-10-31 23:15:11 +01:00
Thijs Wiefferink c858d30481 Add .gitignore to the repository 2015-10-19 19:07:31 +02:00
Thijs Wiefferink b090fd5577 Remove MCStats image, site is more offline than online 2015-10-17 22:10:38 +02:00
Thijs Wiefferink 8d132c66c4 Prepare for the v2.2.1 release
- Update version number
- Update language files from Transifex
2015-10-17 21:03:30 +02:00
Thijs Wiefferink 50e3e59543 Fix indentation and error message of WorldEdit 6 integration handler 2015-10-15 12:13:15 +02:00
Thijs Wiefferink eb21b9567e Change signtags from [arent] and [abuy] to [asrent] and [asbuy]
Changes #45
2015-10-08 22:49:41 +02:00
Thijs Wiefferink 4dba305f6d Change the default sign tags to something more specific
Note: Change documentation pages to include this.

Fixes #45
2015-10-06 22:41:59 +02:00
Thijs Wiefferink 7481d8287f Retrieve money from landlords when unrenting/selling a region.
Prevents exploits by giving money to landlords, and then
unrenting/selling to get money back from 'the server' (nobody). Now it
will get the money back from the landlord, or if that is not possible
then not give anything back.

Fixes #75
2015-10-06 22:15:09 +02:00
Thijs Wiefferink 4d41decbe5 Config part of week indicators 2015-10-03 21:14:24 +02:00
Thijs Wiefferink 7fc5a5af81 Add weeks time indicators, clean other indicators
The old Dutch time indicators have been removed from the lists, this
might cause problems for people if they regenerate their config but
don't add these tags again.

Added console warnings at startup to indicate incorrect duration
strings.

Fixes #32
2015-10-03 21:12:38 +02:00
Thijs Wiefferink d26fa99b95 Fix using the seconds modifier with /as setduration
AreaShop could correctly read and use all seconds modifiers that are
defined in the config, but the `/as setduration` command would not
accept it as input.

Fixes #82
2015-10-03 20:38:38 +02:00
Thijs Wiefferink 39d755d2db Make removing regions from AreaShop less destructible for region flags
First AreaShop would reset all flags, now it will only reset the
greeting and farewell flags. This is to make sure players do not get
confused about the region, if the greeting is still there then players
might think it is still connected to AreaShop.

Fixes #72
2015-10-03 20:27:19 +02:00
Thijs Wiefferink 48ab46ecf7 Fix indirect breaking of signs causing it to disconnect
If you would break a block behind/below a sign AreaShop would disconnect
it from the region, which is most of the times not the wanted behaviour.
This commit changes it to simply leave a floating sign there, so that it
is still visible and not disconnected from the region.

Fixes #15
2015-10-03 20:10:44 +02:00
Thijs Wiefferink b3fa31e1cc Remove debug message 2015-10-02 20:44:25 +02:00
Thijs Wiefferink 783085fbf7 Cache region variable replacements 2015-10-02 20:41:00 +02:00
Thijs Wiefferink aa093b0c8a Fix sign clicking still executing while event is cancelled. 2015-09-26 01:06:22 +02:00
Thijs Wiefferink 9c357fe929 Remove lastActive from region file when unrented/sold
No problems if it is there, but just keeping the region file clean.
2015-09-11 22:44:12 +02:00
Thijs Wiefferink 4d70571a23 Improve failed file loading
- Detects incorrectly loaded config.yml and default.yml
(YamlConfiguration prints errors to console and continues silently,
returning an empty configuration if something is wrong normally)
- Will go into error state when loading fails
- Improved some error handling to make sure that no extra errors are
thrown because of trying to close non-existing streams.
2015-09-10 21:58:57 +02:00
Thijs Wiefferink 29a4105ece Add Vault to the repo to make it easier to compile 2015-09-06 17:05:38 +02:00
Thijs Wiefferink edc7136063 Fix '/as info' always showing landlord line
It would always show the landlord line, if there was no actual landlord
it would show '<UNKNOWN>' as name, which is very confusing.

Fixes #46
2015-09-06 16:42:16 +02:00
Thijs Wiefferink 6fabc75be4 Fix '/as info' trying to filter by group too much
'/as info region' would also try to filter by group using the region
name, which would almost always cause an error message (group not found)
2015-09-06 16:38:23 +02:00
Thijs Wiefferink 085507bf8b Add required dependencies section 2015-08-30 00:10:12 +02:00
Thijs Wiefferink 73ed3366ae Update README.md 2015-08-29 22:27:14 +02:00
Thijs Wiefferink 9ca029176d Fix '/as find' not getting your balance correctly
- If you search with your balance (and do not give a maxprice) it would
always use 0.0 as your balance, therefore not finding any regions.
- Also fixes the incorrect feedback, it would say it searched with a
maxprice instead of your balance and the other way around if no regions
are found.
- Fixed maxprice and balance display to use correct currency symbols and
layouts (decimals, metric prefixes, separator).

Fixes #59
2015-08-29 20:06:16 +02:00
Thijs Wiefferink bf181d69d7 Update README.md 2015-08-29 19:46:05 +02:00
Thijs Wiefferink 68c57515da Update README.md 2015-08-29 19:44:54 +02:00
Thijs Wiefferink 903d6c309f Update README.md 2015-08-29 19:44:39 +02:00
Thijs Wiefferink 0a02eb3254 Update README.md 2015-08-29 19:42:57 +02:00
Thijs Wiefferink bf04589fab Merge links to issues with the top menu 2015-08-29 19:42:11 +02:00
Thijs Wiefferink 14dd094803 Update README.md 2015-08-27 22:51:49 +02:00
Thijs Wiefferink 02df35304c Update README.md 2015-08-27 22:48:11 +02:00
Thijs Wiefferink 4321667ec5 Merge branch 'master' of https://github.com/NLthijs48/AreaShop 2015-08-26 20:05:03 +02:00
Thijs Wiefferink 5cf5df78c8 Add permissions to prevent buying resell regions
- Permission 'areashop.buynormal' can be negated to only allow buying
regions that are in resell mode
- Permission 'areashop.buyresell' can be negated to only allow buying
regions that are not in resell mode

This change does not affect existing permissions setups (above
permissions are true by default)
2015-08-26 20:04:50 +02:00
Thijs Wiefferink 8608d6ce1d Update README.md 2015-08-25 17:40:08 +02:00
Thijs Wiefferink 614336862e Update README.md 2015-08-25 17:38:02 +02:00
Thijs Wiefferink a4ea175f1b Update README.md 2015-08-25 17:33:52 +02:00
Thijs Wiefferink c96043aa38 Update README.md 2015-08-25 17:30:11 +02:00
Thijs Wiefferink d5a29f6c32 Update README.MD: WIP frontpage
Frontpage like the BukkitDev and Spigot Resources section.
2015-08-25 17:29:21 +02:00
Thijs Wiefferink 5176a1c2c5 Update README.md 2015-08-21 21:45:42 +02:00
Thijs Wiefferink 89569ea182 Update README.md 2015-08-17 23:11:46 +02:00
Thijs Wiefferink f349657a59 Fix bug with teleporting to signs
Fixes #47
2015-08-13 22:04:22 +02:00
Thijs Wiefferink 40d3d4d8af Add group filtering to /as info <rented|forrent|sold|forsale>
- Filter regions by group for the mentioned subcommands of /as info
- Clean/refactor code
- Sort the output
- Add Comparable, equals() and toString() to GeneralRegion

Closes #44
2015-08-11 22:41:30 +02:00
Thijs Wiefferink 0d5db8fa4e Add option to deny extending when over rent/total limits
Turned on by default, added config setting
'allowRegionExtendsWhenAboveLimits' to disable this change. Normally
this is expected behaviour, which pushes users to let the region run out
if they should not be able to rent it anymore (was impossible to do
before).

Closes #41
2015-08-10 21:43:29 +02:00
Thijs Wiefferink 25c56e8ecb Add permissions for landlords to remove regions
Closes #33
2015-07-31 22:56:12 +02:00
Thijs Wiefferink 9f436a7eb4 Fix landlord UUID/name handling
Also changes handling of buyer/renter UUIDs and names, if the playerdata
of a player is not available anymore AreaShop will still be able to
display his name. Also unrenting/selling will still properly pay back
the player through Vault (by name instead of UUID).

Fixes #35
2015-07-30 22:55:49 +02:00
Thijs Wiefferink f76c1b8a9f Save last online time self instead of using the Bukkit API
The Bukkit API returns an incorrect last online time when the player.dat
file is not present (for example when a server saves inventories etc.
somewhere else, or when it is cleaned).

Improves landlord handling when there is no UUID present in the config
files.

Closes #34
2015-07-28 23:02:52 +02:00
Thijs Wiefferink d466658f36 Allow only providing landlord name, instead of UUID 2015-07-28 21:50:28 +02:00
Thijs Wiefferink 04e02c4ce4 Adds a way to change number length for stack region names
Adds dots after all config explaination lines, fixes a couple things
with groups.yml file saving (would save unnecessary sometimes).

Fixes #26
2015-07-26 20:56:44 +02:00
Thijs Wiefferink 3bf493109c Add date/time variables for commands/schematics
Fixes #21
2015-07-26 20:15:45 +02:00
Thijs Wiefferink 2f9b6d3987 Update language files to the latest available versions on Transifex 2015-07-25 16:57:24 +02:00
Thijs Wiefferink 93d5612513 Fix a bug with depositing to players that never joined
Paying to players that never visited before will now fallback to using a
name instead of UUID towards Vault, which prevents problems (for players
that never visited, such as server accounts, you cannot get the name
from the UUID via Bukkit).
2015-07-25 16:56:41 +02:00
Thijs Wiefferink 937db4620d Fix problem with default value 'unlimited' for maxRentTime 2015-06-21 19:29:54 +02:00
Thijs Wiefferink a0239b8837 Fix loading when there is no regions folder 2015-06-21 17:08:11 +02:00
Thijs Wiefferink 401f52e687 Change additional places where the contains is used 2015-06-13 22:56:27 +02:00
Thijs Wiefferink 2f6874a16e Fix contains check for WorldGuard regions not version dependend 2015-06-13 22:50:06 +02:00
Thijs Wiefferink c95f4e1c6c Fix problem with '/as addfriend' denying first-joined players
Before it checked if the player had played before on the server in order
to check if the friend will get accepted, but this fails when the player
is playing for the first time. This has been repaired.
2015-06-13 22:06:34 +02:00
Thijs Wiefferink 1a2d755727 Fix message using incorrect time unit 2015-06-11 15:42:39 +02:00
Thijs Wiefferink c489e6eba4 Commit changes in language file 2015-06-11 15:32:29 +02:00
Thijs Wiefferink b1a56b5230 Fix maxRentTime, inactiveTimeUntilUnrent/-Sell settings
Made a misake while converting these settings to accept human-readable
durations strings instead of only minutes.
2015-06-11 14:11:41 +02:00
Thijs Wiefferink dfbc7805b5 Fix a couple of bugs 2015-06-11 00:51:44 +02:00
Thijs Wiefferink 8f2c95f5c4 Merge branch 'master' of https://github.com/NLthijs48/AreaShop 2015-05-22 19:01:40 +02:00
Thijs Wiefferink 0b9bffe68f Fix bug with changed time settings not loading old values 2015-05-22 19:01:30 +02:00
Thijs Wiefferink 7ac6e34c89 Update README.md 2015-05-12 10:25:07 +02:00
Thijs Wiefferink 5231f6e86e Change all time period settings to readable format
Changed all settings that took minutes or seconds as unit before to use
the format also used on signs (things like '50 seconds', '1 day', '3
months' etc).
Fixed a bug with display of currency numbers being unrounded when not
displayed with SI prefix.
2015-05-03 22:51:19 +02:00
Thijs Wiefferink 791b696aff Add support for Metric prefixes to display large numbers
Indications are used as defined on:
http://en.wikipedia.org/wiki/Metric_prefix, implemented from 'k' to 'Y'.
Added setting 'metricSuffixesAbove' to config.yml to specify from which
number these characters should be used.
Added setting 'decimalMark' to change the character(s) used as decimal
separation (is a comma instead of a dot in certain countries).
2015-05-03 00:15:05 +02:00
Thijs Wiefferink c92bc716dc Change module names to fit project setup
Forgot to rename the folders that contain the interface classes. Cleaned
pom.
2015-05-02 00:33:34 +02:00
Thijs Wiefferink 463b34e952 Merge pull request #13 from Androkai/patch-1
fix typo "targer" --> "target"
2015-05-01 11:02:53 +02:00
Androkai ff6e69196d fix typo "targer" --> "target" 2015-04-30 22:50:43 +02:00
Thijs Wiefferink 76ad952bb6 Remove unnecessary marking as 'to be saved'
Marking as 'to be saved' is already done when a setting change is
written to the YAML file, so it does not have to be called from the
places where settings are changed.
2015-04-28 20:38:44 +02:00
Thijs Wiefferink 0cdff5e143 Move README.md to the correct place. 2015-04-28 18:56:13 +02:00
Thijs Wiefferink 9dc3013215 Update README.md 2015-04-28 18:54:30 +02:00
Thijs Wiefferink 796b95c9f9 Change to a Maven project
Changed project layout to Maven, all dependencies except Vault (does not
have a maven repo) are now included in the pom.xml and will be
automatically downloaded by Maven when building. The project setup uses
modules to support both WorldGuard and WorldEdit version with 1 jar file
instead of having 2 files as the last versions of AreaShop had.

Small bug with boolean settings in the config files has been fixed.
Problem with '/as stack' stacking in the Y direction instead of Z has
been fixed. Plus some refactoring and small changes.
2015-04-28 18:53:42 +02:00
Thijs Wiefferink 2785a72457 Update README.md 2015-04-10 18:50:42 +02:00
Thijs Wiefferink c2df0cd912 Package and classes explanation 2015-04-10 18:47:20 +02:00
Thijs Wiefferink 4cd32a0792 Update README.md 2015-04-10 17:57:45 +02:00
Thijs Wiefferink 354e70af57 Add basic instructions for compiling AreaShop
Intructions to compile AreaShop from the source files provided here at GitHub.
2015-04-10 17:57:00 +02:00
Thijs Wiefferink fde60e2a27 Add permissions for landlords to add regions
Added things:
- "areashop.createrent.owner", "areashop.createrent.member",
"areashop.createbuy.owner" and "areashop.createbuy.member" to let
players add regions to AreaShop when they are member/owner of the
WorldGuard region (because they made the region for example).
- "areashop.setprice.landlord" to give landlords access to setting the
price for their regions
- "areashop.setduration.landlord" to give landlords access to setting
the duration for their regions
- When "default" or "reset" is given as price then the price will be
removed and therefore inherited from a group or default.yml
- When "default" or "reset" is given as duration then the duration will
be removed and therefore inherited from a group or default.yml
2015-03-17 21:22:57 +01:00
Thijs Wiefferink d1a3027e0b Update language files to the current status
Polish is back and 88% translated, Finnish is new and fully translated.
2015-03-13 21:16:44 +01:00
Thijs Wiefferink 4e57f03fc0 Added a command to set the landlord of a region.
The landlord receives all money from rents/buys of the region. Reselling
with '/as resell' does not transfer money to the landlord.
Unrenting/selling will not substract money from the account of the
landlord, so set the 'moneyBack' to 0 to prevent cheating. The
'landlord' setting is also present in the general section of
default.yml, so this means you can also add this setting to a region
group to easily make a group of regions give money to 1 player.
2015-03-13 21:07:59 +01:00
Thijs Wiefferink 83d4efc3a8 Remove redundant setting from the config to enable schematics
The 'enableSchematics' boolean setting from the config.yml file is not
usefull, 'enableRestore' in default.yml already handles the same thing,
and is more flexible (per region or region group instead of general)
2015-03-13 18:25:24 +01:00
Thijs Wiefferink 1395afffe9 Fix a bug with teleporting
Added messages when teleporting automatically changes to teleporting to
a sign instead of to the region or other way around.
2015-03-13 14:41:54 +01:00
Thijs Wiefferink 5094d39a96 Get worlds for WorldEdit the proper way (needs wrapped world) 2015-02-28 19:40:43 +01:00
Thijs Wiefferink e664c1efd9 Load regions at startup, check them at the first tick 2015-02-24 11:48:58 +01:00
Thijs Wiefferink 871eeed29c Change the loading of regions to all at once again
Otherwise it would cause problems with plugins that hook into AreaShop
and try to get regions.
2015-02-23 22:32:54 +01:00
Thijs Wiefferink 0d56762bfc Change to Vault integration to allow custom economies
AreaShop would not use an economy if it would be loaded after it.
2015-02-23 22:21:52 +01:00
Thijs Wiefferink c08763883f Fix a bug with '/as setowner' not saving the region file
Changed the way position the regions are marked as 'to be saved' to
prevent this problem in the future.
2015-02-23 21:48:57 +01:00
Thijs Wiefferink efb534f131 Fix the schematic saving 2015-02-23 19:26:20 +01:00
Thijs Wiefferink d9405a9f49 Make the updatechecker check async
If the updatechecker cannot reach BukkitDev it would slow down the
startup of the server up to 30 seconds (and also if you use /reload),
this will not happen anymore.
2015-02-23 18:11:51 +01:00
Thijs Wiefferink 684add89cd Change the way regions are loaded
Region loading is now started at the first server tick, and will do a
certain number of regions per tick ('loading.regionsPerTick' config
setting). This prevents problems with plugins that load worlds after
AreaShop is loaded. If AreaShop detects that a region does not have a
correct WorldGuard region assigned anymore or the world of the region is
not loaded it will be printed to the console, but it will not delete the
region anymore (which would lead to data loss).
2015-02-23 17:58:10 +01:00
Thijs Wiefferink d1848c0728 Delete .project 2015-02-23 13:32:04 +01:00
Thijs Wiefferink 9fd16290c0 Fix some unclear and wrong messages in the language file
Thanks to qlick for suggesting these language changes. Also fixes a bug
with the '/as info player' command, would cause an error if a region has
an incorrect UUID as owner or an UUID without name.
2015-02-22 23:16:37 +01:00
Thijs Wiefferink 3bbca11cc9 Added the '/as stack' command to easily create and register regions
/as stack <amount> <gap> <name> <rent|buy> [group]
    <amount> Number of regions that will be created
    <gap> Blocks distance between the regions
    <name> Name of the regions (number will be behind it)
    <rent|buy> The type of the region
    [group] A group to add the created regions to
    The regions will be created in the direction you are facing
2015-02-22 17:08:32 +01:00
Thijs Wiefferink b1be87014f Change schematic functions to new WorldGuard 6 classes 2015-02-19 17:22:06 +01:00
Thijs Wiefferink badcd77cfe Changing version number to get ready for a release.
Linksigns feature will be released next version together with other
setup tools.
2015-02-11 11:55:46 +01:00
Thijs Wiefferink 779d340bbb Fix translation of color codes for greeting/farewell messages
Ticket:
http://dev.bukkit.org/bukkit-plugins/regionbuyandrent/tickets/26-color-issue/
Thread at WorldGuard explaining the problem:
http://forum.enginehub.org/threads/color-codes-for-greeting-farewell-flags.15958/
2015-02-11 11:34:15 +01:00
Thijs Wiefferink 4e5061ba54 Added updating regions at plugin startup
Removed the '/as updaterents' and '/as updatebuys' commands, '/as
reload' also updates regions now.
2015-02-10 22:57:09 +01:00
Thijs Wiefferink b0f3bdc560 Fix the English language file
It got cleared by a faulty update script, I have some programs to get
the translated files from Transifix, and that also updates the header of
the English file but that went wrong and therefore it got cleared.
2015-02-10 12:31:21 +01:00
Thijs Wiefferink 5c9fdb6cc9 Added name change detection, updates regions when name is changed.
When a player logs in it will loop through regions owned by this players
and check if the saved playername is still the same as the current
playername and update the regionflags and -signs if necessary. Also
fixed some spelling mistakes in the English language file and updated to
the latest Transifex translations.
2015-02-09 23:46:32 +01:00
Thijs Wiefferink 23ea679cd9 Fixed a small bug with the permissions for the teleport command
The teleport command would refuse to teleport you if you only have
'areashop.teleportfriend' and/or 'areashop.teleportfriendsign'
permissions, while you should actually have access to those.
2015-02-03 22:55:31 +01:00
Thijs Wiefferink 58680c8cc4 Add a bulk sign linking mode for easier setup
When using '/as linksigns' you will get in sign linking mode. With
leftclick you can select a sign (max 100 blocks away) and with
rightclick you can select an AreaShop region (max 100 blocks away). If
you selected both then the sign will be linked to the region and then
you can select both again. This way you can easily link a lot of signs
to regions. Advice: Use WorldEdit or similar to get signs in front of
all regions (//stack), then use sign linking mode to link them all.
2015-01-30 12:12:00 +01:00
Thijs Wiefferink 75b752a235 Adds an option to '/as info' to list regions without group 2015-01-26 13:33:57 +01:00
Thijs Wiefferink fb51da84ae Fix a bug with teleporting to signs
If no signs are connected to the region it will now correctly teleport
to the location set by '/as settp' instead of always using the default
location.
2015-01-26 12:31:50 +01:00
Thijs Wiefferink 22d214e59d Add an option to set where '/as find' should teleport you to
Adds the 'findTeleportToSign' option in the general section of
default.yml, you can let it teleport to a sign or to the '/as settp'
location (if no location is set the default location is used)
2015-01-26 12:27:43 +01:00
Thijs Wiefferink 175b531eb5 Fix an unclear message when trying to create a sign for a region that is
already added to AreaShop.
2015-01-21 13:28:23 +01:00
Thijs Wiefferink 52591d3b6e Adds a blacklist of region that cannot be added
The blacklist consists of a list of regular expressions, by default the
'__global__' region is blocked because it is highly unlikely you want to
add that to AreaShop. The blacklist can for example be used to exclude
the spawn region while adding shops at spawn with the WorldEdit
selection of the '/as add' command.
2015-01-21 13:20:32 +01:00
Thijs Wiefferink 825074479c Cleanup 2015-01-18 16:58:33 +01:00
Thijs Wiefferink cc8cf1e560 Add proper punctuation to all languages (dots at the end) + more
Some preparations are made to later enable proper tab completion for
anyone instead of only OPs. Addfriend command only allows you to add
players that have played on the server before now.
2015-01-18 16:03:21 +01:00
Thijs Wiefferink a4169d127e Adds dots to all language strings and adds Chinese (Taiwan)
(All language files changed because I made a program to download them
all from Transifex and transform them to the format I want. Only
languages that are translated for 70% or more will be added to AreaShop)
2015-01-17 15:39:08 +01:00
Thijs Wiefferink 21340af89f Change the '/as find' command to randomly pick a region that suits
First searches all matching regions (rent/buy, maxprice and group), then
randomly picks one.
2015-01-12 21:55:01 +01:00
Thijs Wiefferink db06eae6c9 Add a message to show resell price when using '/as info region' 2015-01-12 21:42:54 +01:00
Thijs Wiefferink 5bae5ecf67 Fix a bug with buying a region while it is in resell mode 2015-01-12 17:11:08 +01:00
Thijs Wiefferink 679ffe2145 Releasing 1 version for WorldGuard 5.9 and one for 6.0+ now
The code represents the state of the WorldGuard 6.0+ version, the
uploaded version for 5.9 has some minor changes.
2015-01-07 12:01:04 +01:00
Thijs Wiefferink e6c5653073 Changes config version number, adds a file check for schematics 2015-01-06 22:35:08 +01:00
Thijs Wiefferink ea31dfdd65 Update languages (pulled from Transifex) and change version number 2015-01-06 22:03:23 +01:00
Thijs Wiefferink 9da31fed1f Restored compatibility with WorldGuard 5.9
AreaShop will detect if you use a 5.x version or something else, with
5.x it will add players to the regions by name, and otherwise by UUID.
AreaShop will always save UUID's itself, so future upgrading to higher
WorldGuard versions will be no problem.
2015-01-06 16:02:00 +01:00
Thijs Wiefferink 9baf0b7eec Adds an update checker and fixes some possible bugs
The update checker checks for updates at BukkitDev, if an update is
found it will print a message in the console and notifies OPs when
joining the server. It will never download files itself. The update
check can be switched off in the config. Also tried to fix a bug with
the /as me command, which could break when the friends lists is broken.
2015-01-06 11:46:02 +01:00
Thijs Wiefferink a14dc4e541 Fix a bug with the periodic updating of signs
If there is no sign connected to the region it would spam an error to
the console when the periodic update task runs.
2014-12-29 16:39:54 +01:00
Thijs Wiefferink 00d3256716 Fix a bug with inactive player unrent/sell settings
If the 'inactiveTimeUntilUnrent' or 'inactiveTimeUntilSell' settings
would be set to a value above 35000 it would cause an integer overflow,
resulting in a 50% chance that all regions will be unrentend/sold (and
if that does not happen it will still sell/unrent them too early). This
is caused by an integer overflow, switching to long fixed this problem.
2014-12-18 16:21:07 +01:00
Thijs Wiefferink 40338b66df Fix a bug with the '/as settp' command not accepting arguments
The command would always try to detect regions at the location you are
standing and would not consider the region argument.
2014-12-16 20:21:33 +01:00
Thijs Wiefferink 715bbfd9e3 Fix a bug where regions would not update after added to a group
Also applicable for removing regions from a group.
2014-12-10 16:08:52 +01:00
Thijs Wiefferink b679c49405 Update the French language file to the latest version
Adds a little more documentationto all language files, just a minor
note. Now '/as reload' will also load the a new language correctly if
you changed that in the config or language files.
2014-12-10 14:57:34 +01:00
Thijs Wiefferink dd0930bcea Removes excess debug statemements added in previous commit 2014-12-10 13:15:38 +01:00
Thijs Wiefferink 5b961564e1 Fix a bug with settings in groups.yml and region files
Now if a value has been set for a certain setting it will use it for
sure, now if you use getDoubleSetting() the following happends: 15.0 ->
15.0, 7 -> 7.0, '8.0' -> 8.0, 'bs' -> 0.0. While before only 15.0 would
see it as double, and for the others it would continue searching at the
next place (individual files > groups > default.yml).
2014-12-10 13:14:30 +01:00
Thijs Wiefferink c12314fa98 Fixes a bug with setting the owner flag
Now correctly splits the content of the owner flag at ', ' instead of
just a space (members flag already does this).
2014-12-08 18:07:04 +01:00
Thijs Wiefferink e23ad74744 Stops the unnecessary saving of the groups file.
It would mark the groups file as changed every time the groups get
loaded from the file. That would cause a unnecessary save after '/as
reload' and after restart/reload of the server.
2014-12-07 00:04:46 +01:00
Thijs Wiefferink 9957e02e65 Fix a bug with detection of files to convert
Previously it would keep sending 2 messages to console at startup saying
that is is converting files to a new format.
2014-12-06 21:43:07 +01:00
Thijs Wiefferink 07ea919aba Updates the language files to the latest version from Transifex 2014-12-05 16:20:00 +01:00
Thijs Wiefferink 2c1771cc52 Added 'friend regions' to the '/as me' command
And added teleporting to regions you are added as friend (permissions
areashop.teleportfriend and areashop.teleportfriendsign)
2014-12-05 13:48:41 +01:00
Thijs Wiefferink 83778ff803 Changes owners/members handling to WorldGuard to UUID's
Now adding uuid's to the owners/members flag in the flagProfiles section
is default, adding names is possible with 'n:<name>', groups is still
'g:<group>'. Now warnings will be displayed in the console if the size
of a schematic does not match the region size.
2014-12-04 22:56:18 +01:00
Thijs Wiefferink 0c79525144 Prevent actions on regions when it is already deleted from AreaShop
When a region is deleted with '/as del' it wil set a flag in
GeneralRegion to indicate it is deleted (isDeleted() can get it). If
this flag is set then no sign updates, saves to disk etc are being
processed by the tasks anymore. This prevents the following case: #1
task starts saving regions (makes copy of region list). #2 User 
executes '/as del' for a region, removes region file. #3 Task arrives at
the region the user just deleted and saves it to disk again #4 The
region will get loaded again next time the server starts.
2014-12-04 11:50:40 +01:00
Thijs Wiefferink e719930364 Reworks '/as info region' command for buy regions and fixes a bug
'/as info region' for buy regions now also supports more info, like the
same way as it does for rent regions. Fixed a bug with signs, now they
will correctly keep their orientation when placed again after removal
(by for example schematics).
2014-12-03 23:43:24 +01:00
Thijs Wiefferink 5568ee240b Changes the '/as info' command for rent regions to show more info
Some lines will not show up when based on config options (extending, in
advance renting, restoring), some don't show up if empty (friends,
signs) and some don't show up based on permissions (groups, teleport
location, restoring). Also adds a couple of tags to be used in language
files and the config.
2014-12-03 00:38:55 +01:00
Thijs Wiefferink 46abc8f83d Save WorldGuard regions periodically instead of directly
Now uses the saveChanges() method on RegionManager of WorldGuard, that
will only save regions that are actually changed.
2014-12-01 21:26:06 +01:00
Thijs Wiefferink cf3139f373 Changes handling WorldGuard flags, it now actually adds friends
Reworked applying flag settings configured in AreaShop to the WorldGuard
region. Now supports adding the friends to the regions, adding groups to
a region (g:groupname, would allow someone 'unlocking' functionality of
a region for a whole group of players) and adding group restrictions to
other flags (for example: 'entry: deny g:non_owners').
2014-12-01 21:00:27 +01:00
Thijs Wiefferink 59627e1b97 Add the '/as delfriend' command and minor changes the addfriend command 2014-11-29 17:08:54 +01:00
Thijs Wiefferink a25b5a5752 Fix the inactive players options, add the '/as addfriend' command
The unrent/selling of regions for inactive players now correctly checks
the option for rent regions when it is about a rent region, rent regions
also correctly check for OP now.
2014-11-29 16:37:24 +01:00
Thijs Wiefferink aceb6945fd Cleanup for code of commands, preparations for adding friends to regions
Code to dectect regions when a name of a region is not specified as
argument for commands has been cleaned and made the same for all
commands (language file cleanup is still necessary). Some functions to
manage friends for regions have been added to GeneralRegion (commands
and applying friends to regions still has to be done)
2014-11-27 23:59:44 +01:00
Thijs Wiefferink cbeffe9316 Add the stopresell command, fix a bug with reselling
If you put your region into resell mode and then sold it to the server
with /as sell, the next player buying the region would get an error or
his region would be in reselling mode directly. Now this is fixed
2014-11-27 20:38:48 +01:00
Thijs Wiefferink 9ea97fdb5d Cleans old code for replacing %clicker% tag 2014-11-25 16:48:11 +01:00
Thijs Wiefferink ed1f73fdd7 Fixes a problem with the %clicker% tag for use with sign commands
With the previous implementation it would only get replaced for commands
executed as the player, but executing as player is not wanted because
then the player should have permission for that (example: /tellraw). Now
it will properly get replaced for console and player commands attached
to a state of the sign.
2014-11-25 16:47:10 +01:00
Thijs Wiefferink 09af826f88 Add the '/as resell' command to let players sell their region to others
After executing the command the player is still owner and can do
everything like normal. The sign changes to the 'resell' section of the
chosen sign profile. The region flags change to the 'resale' section of
the flag profile (other greeting). When a player buys the region it
transfers the money to the previous owner. New schematic event and
commandevents are available for this action. Previous owner will get a
message if he is online.
A command to stop reselling your region is on the TODO list.
2014-11-24 19:16:55 +01:00
Thijs Wiefferink 1fd24d864d Adds a tag for the player name that clicks the sign
Can be used in the commands that get executed when someone clicks an
AreaShop sign. Tag is %clicker%
2014-11-24 12:58:31 +01:00
Thijs Wiefferink 4125364a96 Add highly configurable rent expire warnings for online players and some
minor changes

Rent expire warnings have profiles in config.yml, the profile can be set
in default.yml. Warning can contain a message to the player if he is
online and also have the possibility to execute certain commands.
Renamed the '/as rentduration' command to '/as setduration'.
2014-11-16 22:41:41 +01:00
Thijs Wiefferink a6f5a2eb5e Expire warning on login for players that rent regions + bugfixes
An option has been added to show a warning to players when their rent
almost runs out on login (so when they login they get a message for each
region that almost runs out, that means lower timeleft than the
'warningOnLoginTime' setting). Also a bug with schematic restoring has
been fixed and some other minor changes done.
2014-11-15 21:57:26 +01:00
Thijs Wiefferink 5eae75fef1 Add current language files again
(They got lost when changing the project setup)
2014-11-14 20:13:47 +01:00
Thijs Wiefferink 7982531e63 Merge branch 'master' of https://github.com/NLthijs48/AreaShop 2014-11-13 23:39:20 +01:00
Thijs Wiefferink 6ce15b27b7 Change the directory layout 2014-11-13 23:38:31 +01:00
Thijs Wiefferink b1809fb265 Update README.md 2014-11-13 23:17:45 +01:00
Thijs Wiefferink 0344391588 Add all changes from after the v2.0.2 release
Committing all changes made since the v2.0.2 release for now, starting
now committing will happen regularly instead of only when a version of
AreaShop is released to the public. This commit includes a large amount
of things that changed, the changelog for the upcoming version will list
them all.
2014-11-13 23:06:00 +01:00
Thijs Wiefferink 8d254e17bb Merge pull request #6 from NLthijs48/AreaShop_V1.4
Adds code of V2.0.2
2014-09-24 21:41:20 +02:00
Thijs Wiefferink 2098b9f4e3 Adds code of V2.0.2 2014-09-24 21:40:23 +02:00
Thijs Wiefferink 95e3a4a120 Update README.md 2014-09-08 12:07:00 +02:00
Thijs Wiefferink 9269279d44 Update README.md 2014-09-08 12:06:49 +02:00
Thijs Wiefferink d8fbeaf53a Merge pull request #5 from NLthijs48/AreaShop_V1.4
Adds the code from version 2.0.1
2014-09-06 22:50:51 +02:00
Thijs Wiefferink 6886db8edc Adds the code from version 2.0.1 2014-09-06 22:49:29 +02:00
Thijs Wiefferink 05df539189 Merge pull request #4 from NLthijs48/AreaShop_V2.0
AreaShop v2.0.0
2014-08-28 12:13:58 +02:00
Thijs Wiefferink f20c573b06 Delete RentRegion.class 2014-08-28 11:50:13 +02:00
Thijs Wiefferink 793e3dfd1b Delete RentRegion$RentEvent.class 2014-08-28 11:50:09 +02:00
Thijs Wiefferink d7eff6c0df Delete GeneralRegion.class 2014-08-28 11:50:05 +02:00
Thijs Wiefferink 911115213f Delete BuyRegion.class 2014-08-28 11:50:02 +02:00
Thijs Wiefferink beeef8c757 Delete BuyRegion$BuyEvent.class 2014-08-28 11:49:59 +02:00
Thijs Wiefferink 60bdd50ab6 Delete UpdaterentsCommand.class 2014-08-28 11:49:55 +02:00
Thijs Wiefferink b5ba813410 Delete UpdatebuysCommand.class 2014-08-28 11:49:52 +02:00
Thijs Wiefferink 7de0b34b3b Delete UnrentCommand.class 2014-08-28 11:49:49 +02:00
Thijs Wiefferink b5077215ec Delete TeleportCommand.class 2014-08-28 11:49:46 +02:00
Thijs Wiefferink 98c45866a3 Delete SetteleportCommand.class 2014-08-28 11:49:43 +02:00
Thijs Wiefferink a96101519a Delete SellCommand.class 2014-08-28 11:49:39 +02:00
Thijs Wiefferink fc18819a95 Delete RentrestoreCommand.class 2014-08-28 11:49:34 +02:00
Thijs Wiefferink 6dd0750bea Delete RentpriceCommand.class 2014-08-28 11:49:30 +02:00
Thijs Wiefferink 36b73f57fd Delete RentdurationCommand.class 2014-08-28 11:49:27 +02:00
Thijs Wiefferink b111110251 Delete RentCommand.class 2014-08-28 11:49:24 +02:00
Thijs Wiefferink 555f648dfe Delete ReloadCommand.class 2014-08-28 11:49:21 +02:00
Thijs Wiefferink 4ac4c9ae35 Delete InfoCommand.class 2014-08-28 11:49:18 +02:00
Thijs Wiefferink 97fe92588c Delete HelpCommand.class 2014-08-28 11:49:15 +02:00
Thijs Wiefferink 8fc03b21f0 Delete CommandAreaShop.class 2014-08-28 11:49:11 +02:00
Thijs Wiefferink a74643d724 Delete BuyrestoreCommand.class 2014-08-28 11:49:08 +02:00
Thijs Wiefferink c309cbbbae Delete BuypriceCommand.class 2014-08-28 11:48:57 +02:00
Thijs Wiefferink 73ceee6f27 Delete BuyCommand.class 2014-08-28 11:48:54 +02:00
Thijs Wiefferink 9c57f434db Delete Metrics$Graph.class 2014-08-28 11:48:50 +02:00
Thijs Wiefferink f41e614d38 Delete SignChangeListener.class 2014-08-28 11:48:46 +02:00
Thijs Wiefferink 4fa1267971 Delete SignBreakListener.class 2014-08-28 11:48:43 +02:00
Thijs Wiefferink e99ca02bcb Delete Metrics$Plotter.class 2014-08-28 11:48:40 +02:00
Thijs Wiefferink 3479bcd0d8 Delete RightClickListener.class 2014-08-28 11:48:37 +02:00
Thijs Wiefferink c0cd528f0e Delete RentCheck.class 2014-08-28 11:48:32 +02:00
Thijs Wiefferink 14f379f7c6 Delete Metrics.class 2014-08-28 11:48:29 +02:00
Thijs Wiefferink 73c1f88d8c Delete CommandManager.class 2014-08-28 11:48:26 +02:00
Thijs Wiefferink 1bbca09fc6 Delete FileManager.class 2014-08-28 11:48:22 +02:00
Thijs Wiefferink 8219269fbb Delete Metrics$1.class 2014-08-28 11:48:19 +02:00
Thijs Wiefferink bf283d52b6 Delete LanguageManager.class 2014-08-28 11:48:16 +02:00
Thijs Wiefferink def6005b92 Delete AreaShop.class 2014-08-28 11:48:13 +02:00
Thijs Wiefferink 62934ceab6 Delete AreaShop$RegionType.class 2014-08-28 11:48:10 +02:00
Thijs Wiefferink 9124de9bb0 Delete AreaShop$RegionEventType.class 2014-08-28 11:48:06 +02:00
Thijs Wiefferink d5da1bb012 Delete .gitignore 2014-08-28 11:47:58 +02:00
Thijs Wiefferink 99d4cdb685 Delete .gitignore 2014-08-28 11:47:43 +02:00
Thijs Wiefferink b3ea7f7e73 Adds all function from version 2.0.0 2014-08-28 11:45:36 +02:00
Thijs Wiefferink 24ee8df215 Update README.md 2014-08-26 16:29:09 +02:00
Thijs Wiefferink 63e8f10e20 Basic functionality is working again after switching to new config
system
2014-07-17 12:30:18 +02:00
Thijs Wiefferink 7c03041ae1 class stuff 2014-06-29 16:38:18 +02:00
Thijs Wiefferink fb03baf3ad Adds command system, tab complete (not permission based) and changes to
Region objects.
2014-06-29 16:35:49 +02:00
NLthijs48 c1ef15193c Delete .gitignore 2014-05-31 00:00:51 +02:00
NLthijs48 c1e89ef75e Delete .gitignore 2014-05-31 00:00:33 +02:00
NLthijs48 56a35d373b Merge pull request #3 from NLthijs48/AreaShop-V1.1
Updates to version 1.3.0
2014-05-31 00:00:11 +02:00
Thijs Wiefferink 5aff3f1ce6 Updates to version 1.3.0 2014-05-30 23:58:24 +02:00
NLthijs48 6a4b8f9d9a Update README.md 2014-05-16 19:52:49 +02:00
NLthijs48 ef4b599897 Delete SignChangeListener.class 2014-04-14 21:36:55 +02:00
NLthijs48 a04b96d452 Delete SignBreakListener.class 2014-04-14 21:36:52 +02:00
NLthijs48 0728ce672d Delete RightClickListener.class 2014-04-14 21:36:48 +02:00
NLthijs48 c42e1ccbe5 Delete RentCheck.class 2014-04-14 21:36:45 +02:00
NLthijs48 dfcd896cab Delete LanguageManager.class 2014-04-14 21:36:42 +02:00
NLthijs48 69ee2d5c7f Delete AreaShop.class 2014-04-14 21:36:30 +02:00
NLthijs48 b42bb38e5f Merge pull request #2 from NLthijs48/AreaShop-V1.1
Updates code to the AreaShop V1.2 release
2014-04-14 21:35:47 +02:00
Thijs Wiefferink 418b736fae Updates code to the AreaShop V1.2 release 2014-04-14 21:35:12 +02:00
NLthijs48 bed4bbac23 Create README.md 2014-04-10 22:44:44 +02:00
NLthijs48 f13534ae33 Merge pull request #1 from NLthijs48/AreaShop-V1.1
AreaShop v1.1
2014-04-10 22:41:39 +02:00
Thijs Wiefferink 3b1522bad8 Throw away trash 2014-04-10 22:37:55 +02:00
Thijs Wiefferink 2995b59070 Adds AreaShop V1.1 code to GitHub 2014-04-10 22:34:51 +02:00
Thijs Wiefferink 0e46f01150 Adds a flexible save/restore system to .schematic files
This release adds a very configurable saving and restoring of regions.
You can let the plugin save and restore the region from/to a .schematic
file on certain events. Commands are added to change the restoring
profile for a rent/buy and the state (true, false, general) which are
respectively enabled, disabled and 'as general config option'.
2014-04-10 22:29:52 +02:00
130 changed files with 11915 additions and 9881 deletions

No files matched your search

-32
View File
@@ -1,32 +0,0 @@
# This workflow will build a Java project with Maven
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
name: Java CI with Maven
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Cache local Maven repository
uses: actions/cache@v2
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- name: Build with Maven
run: mvn -B package --file pom.xml
+206 -20
View File
@@ -1,25 +1,211 @@
# Maven stuff
target
.project
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
# Created by https://www.toptal.com/developers/gitignore/api/macos,windows,intellij,maven,gradle
# Edit at https://www.toptal.com/developers/gitignore?templates=macos,windows,intellij,maven,gradle
# Locally stored "Eclipse launch configurations"
*.launch
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# IntelliJ IDEA
*.iml
.idea
.idea/**
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
# https://plugins.jetbrains.com/plugin/7973-sonarlint
.idea/**/sonarlint/
# SonarQube Plugin
# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin
.idea/**/sonarIssues.xml
# Markdown Navigator plugin
# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced
.idea/**/markdown-navigator.xml
.idea/**/markdown-navigator-enh.xml
.idea/**/markdown-navigator/
# Cache file creation bug
# See https://youtrack.jetbrains.com/issue/JBR-2257
.idea/$CACHE_FILE$
# CodeStream plugin
# https://plugins.jetbrains.com/plugin/12206-codestream
.idea/codestream.xml
### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### Maven ###
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
# https://github.com/takari/maven-wrapper#usage-without-binary-jar
.mvn/wrapper/maven-wrapper.jar
desktop.ini
### Maven Patch ###
# Eclipse m2e generated files
# Eclipse Core
.project
# JDT-specific (Eclipse Java Development Tools)
.classpath
### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
### Gradle ###
.gradle
build/
# Ignore Gradle GUI config
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Cache of project
.gradletasknamecache
# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
# gradle/wrapper/gradle-wrapper.properties
### Gradle Patch ###
**/build/
# Eclipse Gradle plugin generated files
# Eclipse Core
# JDT-specific (Eclipse Java Development Tools)
# End of https://www.toptal.com/developers/gitignore/api/macos,windows,intellij,maven,gradle
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module version="4">
<component name="FacetManager">
<facet type="minecraft" name="Minecraft">
<configuration>
<autoDetectTypes>
<platformType>BUKKIT</platformType>
</autoDetectTypes>
</configuration>
</facet>
</component>
</module>
+108
View File
@@ -0,0 +1,108 @@
import org.apache.tools.ant.filters.ReplaceTokens
plugins {
id 'com.github.johnrengelman.shadow' version '7.1.0'
id 'maven-publish'
id 'java-library'
}
version = "2.7.3"
dependencies {
implementation 'com.github.NLthijs48:InteractiveMessenger:e7749258ca'
implementation 'com.github.NLthijs48:BukkitDo:819d51ec2b'
implementation 'io.papermc:paperlib:1.0.6'
implementation 'io.github.baked-libs:dough-data:1.0.3'
implementation ('com.google.inject:guice:5.0.1') {
exclude group: 'com.google.guava'
}
implementation ('com.google.inject.extensions:guice-assistedinject:5.0.1') {
exclude group: 'com.google.guava'
}
implementation project(':areashop-interface')
implementation project(':areashop-bukkit-1_13')
implementation project(':areashop-nms')
runtimeOnly project(path: ':areashop-nms-1-17', configuration: 'reobf')
runtimeOnly project(path: ':areashop-nms-1-18', configuration: 'reobf')
implementation project(':areashop-worldedit-7')
implementation project(':areashop-worldguard-7')
implementation project(':areashop-fastasyncworldedit')
compileOnly 'org.spigotmc:spigot-api:1.18.1-R0.1-SNAPSHOT'
compileOnly ('com.sk89q.worldedit:worldedit-bukkit:7.2.8') {
exclude group: 'com.google.guava'
}
compileOnly ('com.sk89q.worldguard:worldguard-bukkit:7.0.6') {
exclude group: 'com.google.guava'
}
compileOnly ('com.github.MilkBowl:VaultAPI:1.7')
}
processResources {
from (sourceSets.main.resources) {
filter ReplaceTokens, tokens: [version: project.version]
duplicatesStrategy(DuplicatesStrategy.INCLUDE)
}
}
assemble {
dependsOn(shadowJar)
dependsOn(publishToMavenLocal)
}
jar {
archiveClassifier.set('original')
}
java {
withSourcesJar()
}
shadowJar {
archiveClassifier.set('')
setArchivesBaseName('AreaShop')
String base = "me.wiefferink.areashop.libraries"
relocate('me.wiefferink.interactivemessenger', "${base}.interactivemessenger")
relocate('me.wiefferink.bukkitdo', "${base}.bukkitdo")
relocate('io.papermc.lib', "${base}.paperlib")
relocate('io.github.bakedlibs.dough', "${base}.dough")
relocate("com.google.inject", "${base}.inject")
relocate("org.aopalliance", "${base}.aopalliance")
relocate("javax.inject", "${base}.javax.inject")
include {
include("com.google.inject")
minimize()
}
}
sourcesJar {
classifier('sources')
from sourceSets.main.allSource
}
publishing {
publications {
// ... artifact publications
areaShop(MavenPublication) {
from components.java
pom {
group = "me.wiefferink"
artifactId = "$project.name"
version = "$project.version"
scm {
connection = 'scm:git:git://github.com/md5sha256/AreaShop.git'
developerConnection = 'scm:git:ssh://github.com/md5sha256/AreaShop.git'
url = "https://github.com/md5sha256/AreaShop/tree/dev/bleeding"
}
licenses {
license {
name = 'GNU General Public License v3.0'
url = "https://github.com/md5sha256/AreaShop/blob/dev/bleeding/LICENSE"
}
}
}
}
}
}
description = 'AreaShop'
-300
View File
@@ -1,300 +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>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<version>1.0</version>
</parent>
<artifactId>areashop</artifactId>
<packaging>jar</packaging>
<name>AreaShop</name>
<version>2.7.1-SNAPSHOT</version> <!-- Main plugin version -->
<repositories>
<repository>
<id>papermc</id>
<url>https://papermc.io/repo/repository/maven-public/</url>
</repository>
<repository>
<id>aikar</id>
<url>https://repo.aikar.co/content/groups/aikar/</url>
</repository>
</repositories>
<dependencies>
<!-- Bukkit, AreaShop aims to support 1.13.2+ -->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.13.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!-- InteractiveMessenger library -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>interactivemessenger</artifactId>
<version>1.1-SNAPSHOT</version>
</dependency>
<!-- TaskChain library -->
<dependency>
<groupId>co.aikar</groupId>
<artifactId>taskchain-bukkit</artifactId>
<version>3.7.2</version>
</dependency>
<!-- JetBrains Annotations -->
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>19.0.0</version>
<scope>provided</scope>
</dependency>
<!-- Paper Lib -->
<dependency>
<groupId>io.papermc</groupId>
<artifactId>paperlib</artifactId>
<version>1.0.5</version>
</dependency>
<!-- WorldEdit/WorldGuard -->
<dependency>
<groupId>com.sk89q.worldedit</groupId>
<artifactId>worldedit-bukkit</artifactId>
<version>7.1.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-bukkit</artifactId>
<version>7.0.3</version>
<scope>provided</scope>
</dependency>
<!-- Interfaces that specific WorldGuard and WorldEdit versions are built against -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-interface</artifactId>
<version>latest</version>
<scope>compile</scope>
</dependency>
<!-- WorldGuard implementations -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-worldguard-7</artifactId>
<version>latest</version>
<scope>compile</scope>
</dependency>
<!-- WorldEdit implementations -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-worldedit-7</artifactId>
<version>latest</version>
<scope>compile</scope>
</dependency>
<!-- FAWE compat -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-fawe-1-15</artifactId>
<version>latest</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- Vault -->
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.7</version>
<scope>provided</scope>
</dependency>
<!-- bStats -->
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
<version>1.6</version>
<scope>compile</scope>
</dependency>
</dependencies>
<profiles>
<!-- Copy the jar file to a test server, activate by using -DcopyResult="/path/to/test/server" -->
<profile>
<id>test-locally</id>
<activation>
<property>
<name>copyResult</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<configuration>
<target>
<copy file="./target/${project.build.finalName}.jar"
tofile="${copyResult}\${project.build.finalName}.jar"/>
</target>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<!-- Package the source files in a jar, activate by using -Dsources -->
<profile>
<id>package-sources</id>
<activation>
<property>
<name>sources</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<!-- Produce javadoc files, activate by using -Djavadoc -->
<profile>
<id>generate-javadoc</id>
<activation>
<property>
<name>javadoc</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>package</phase>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
<configuration>
<excludePackageNames>me.wiefferink.areashop.lib</excludePackageNames>
<destDir>${javadoc}</destDir>
<links>
<link>https://hub.spigotmc.org/javadocs/bukkit/</link>
<link>http://docs.sk89q.com/worldedit/apidocs/</link>
<link>http://docs.sk89q.com/worldguard/apidocs/</link>
</links>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<build>
<directory>target</directory>
<finalName>AreaShop</finalName>
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<includes>
<include>plugin.yml</include>
<include>config.yml</include>
<include>hiddenConfig.yml</include>
<include>default.yml</include>
<include>README.md</include>
<include>lang/*.yml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<relocations>
<!-- Relocate TaskChain -->
<relocation>
<pattern>co.aikar.taskchain</pattern>
<shadedPattern>me.wiefferink.areashop.shaded.taskchain</shadedPattern>
</relocation>
<!-- Relocate messaging framework -->
<relocation>
<pattern>me.wiefferink.interactivemessenger</pattern>
<shadedPattern>me.wiefferink.areashop.shaded.interactivemessenger</shadedPattern>
</relocation>
<!-- Relocate bstats -->
<relocation>
<pattern>org.bstats</pattern>
<shadedPattern>me.wiefferink.areashop.shaded.bstats</shadedPattern>
</relocation>
<!-- Relocate PaperLib -->
<relocation>
<pattern>io.papermc</pattern>
<shadedPattern>me.wiefferink.areashop.shaded.paperlib</shadedPattern>
</relocation>
<!-- Relocate Google Guice & Guice-Assisted-Inject -->
<relocation>
<pattern>com.google.inject</pattern>
<shadedPattern>me.wiefferink.areashop.shaded.inject</shadedPattern>
</relocation>
</relocations>
</configuration>
</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>
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,39 @@
package me.wiefferink.areashop;
import me.wiefferink.areashop.features.signs.SignManager;
import me.wiefferink.areashop.interfaces.AreaShopInterface;
import me.wiefferink.areashop.managers.CommandManager;
import me.wiefferink.areashop.managers.FeatureManager;
import me.wiefferink.areashop.managers.SignLinkerManager;
import javax.annotation.Nonnull;
public interface AreaShopApi extends AreaShopInterface {
/**
* Function to get the CommandManager.
*
* @return the CommandManager
*/
@Nonnull CommandManager getCommandManager();
/**
* Get the SignLinkerManager.
* Handles sign linking mode.
*
* @return The SignLinkerManager
*/
@Nonnull SignLinkerManager getSignlinkerManager();
/**
* Get the FeatureManager.
* Manages region specific features.
*
* @return The FeatureManager
*/
@Nonnull FeatureManager getFeatureManager();
@Nonnull SignManager getSignManager();
}
@@ -0,0 +1,21 @@
package me.wiefferink.areashop;
public interface MessageBridge {
/**
* Send a message to a target without a prefix.
*
* @param target The target to send the message to
* @param key The key of the language string
* @param replacements The replacements to insert in the message
*/
void messageNoPrefix(Object target, String key, Object... replacements);
/**
* Send a message to a target, prefixed by the default chat prefix.
*
* @param target The target to send the message to
* @param key The key of the language string
* @param replacements The replacements to insert in the message
*/
void message(Object target, String key, Object... replacements);
}
@@ -2,28 +2,53 @@ package me.wiefferink.areashop.commands;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.events.ask.AddingRegionEvent;
import me.wiefferink.areashop.events.ask.BuyingRegionEvent;
import me.wiefferink.areashop.events.ask.RentingRegionEvent;
import me.wiefferink.areashop.events.notify.BoughtRegionEvent;
import me.wiefferink.areashop.events.notify.RentedRegionEvent;
import me.wiefferink.areashop.interfaces.WorldEditInterface;
import me.wiefferink.areashop.interfaces.WorldEditSelection;
import me.wiefferink.areashop.managers.FileManager;
import me.wiefferink.areashop.interfaces.WorldGuardInterface;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RegionFactory;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import me.wiefferink.bukkitdo.Do;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.*;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.UUID;
import java.util.stream.Collectors;
@Singleton
public class AddCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private AreaShop plugin;
@Inject
private WorldEditInterface worldEditInterface;
@Inject
private WorldGuardInterface worldGuardInterface;
@Inject
private RegionFactory regionFactory;
@Override
public String getCommandStart() {
return "areashop add";
@@ -52,12 +77,12 @@ public class AddCommand extends CommandAreaShop {
&& !sender.hasPermission("areashop.createbuy")
&& !sender.hasPermission("areashop.createbuy.member")
&& !sender.hasPermission("areashop.createbuy.owner")) {
plugin.message(sender, "add-noPermission");
messageBridge.message(sender, "add-noPermission");
return;
}
if(args.length < 2 || args[1] == null || (!"rent".equalsIgnoreCase(args[1]) && !"buy".equalsIgnoreCase(args[1]))) {
plugin.message(sender, "add-help");
messageBridge.message(sender, "add-help");
return;
}
Map<String, ProtectedRegion> regions = new HashMap<>();
@@ -68,18 +93,18 @@ public class AddCommand extends CommandAreaShop {
}
if(args.length == 2) {
if(player == null) {
plugin.message(sender, "cmd-weOnlyByPlayer");
messageBridge.message(sender, "cmd-weOnlyByPlayer");
return;
}
WorldEditSelection selection = plugin.getWorldEditHandler().getPlayerSelection(player);
WorldEditSelection selection = worldEditInterface.getPlayerSelection(player);
if(selection == null) {
plugin.message(player, "cmd-noSelection");
messageBridge.message(player, "cmd-noSelection");
return;
}
world = selection.getWorld();
regions = Utils.getWorldEditRegionsInSelection(selection).stream().collect(Collectors.toMap(ProtectedRegion::getId, region -> region));
if(regions.isEmpty()) {
plugin.message(player, "cmd-noWERegionsFound");
messageBridge.message(player, "cmd-noWERegionsFound");
return;
}
} else {
@@ -87,7 +112,7 @@ public class AddCommand extends CommandAreaShop {
if(args.length == 4) {
world = Bukkit.getWorld(args[3]);
if(world == null) {
plugin.message(sender, "add-incorrectWorld", args[3]);
messageBridge.message(sender, "add-incorrectWorld", args[3]);
return;
}
} else {
@@ -95,19 +120,19 @@ public class AddCommand extends CommandAreaShop {
}
} else {
if(args.length < 4) {
plugin.message(sender, "add-specifyWorld");
messageBridge.message(sender, "add-specifyWorld");
return;
} else {
world = Bukkit.getWorld(args[3]);
if(world == null) {
plugin.message(sender, "add-incorrectWorld", args[3]);
messageBridge.message(sender, "add-incorrectWorld", args[3]);
return;
}
}
}
ProtectedRegion region = plugin.getRegionManager(world).getRegion(args[2]);
if(region == null) {
plugin.message(sender, "cmd-noRegion", args[2]);
messageBridge.message(sender, "cmd-noRegion", args[2]);
return;
}
regions.put(args[2], region);
@@ -124,28 +149,29 @@ public class AddCommand extends CommandAreaShop {
TreeSet<String> namesBlacklisted = new TreeSet<>();
TreeSet<String> namesNoPermission = new TreeSet<>();
TreeSet<String> namesAddCancelled = new TreeSet<>(); // Denied by an event listener
Utils.runAsBatches(regions.entrySet(),
Do.forAll(
plugin.getConfig().getInt("adding.regionsPerTick"),
(regionEntry) -> {
regions.entrySet(),
regionEntry -> {
String regionName = regionEntry.getKey();
ProtectedRegion region = regionEntry.getValue();
// Determine if the player is an owner or member of the region
boolean isMember = finalPlayer != null && plugin.getWorldGuardHandler().containsMember(region, finalPlayer.getUniqueId());
boolean isOwner = finalPlayer != null && plugin.getWorldGuardHandler().containsOwner(region, finalPlayer.getUniqueId());
boolean isMember = finalPlayer != null && worldGuardInterface.containsMember(region, finalPlayer.getUniqueId());
boolean isOwner = finalPlayer != null && worldGuardInterface.containsOwner(region, finalPlayer.getUniqueId());
String type;
if(isRent) {
type = "rent";
} else {
type = "buy";
}
FileManager.AddResult result = plugin.getFileManager().checkRegionAdd(sender, region, world, isRent ? GeneralRegion.RegionType.RENT : GeneralRegion.RegionType.BUY);
if(result == FileManager.AddResult.ALREADYADDED) {
IFileManager.AddResult result = plugin.getFileManager().checkRegionAdd(sender, region, world, isRent ? GeneralRegion.RegionType.RENT : GeneralRegion.RegionType.BUY);
if(result == IFileManager.AddResult.ALREADYADDED) {
regionsAlready.add(plugin.getFileManager().getRegion(regionName));
} else if(result == FileManager.AddResult.ALREADYADDEDOTHERWORLD) {
} else if(result == IFileManager.AddResult.ALREADYADDEDOTHERWORLD) {
regionsAlreadyOtherWorld.add(plugin.getFileManager().getRegion(regionName));
} else if(result == FileManager.AddResult.BLACKLISTED) {
} else if(result == IFileManager.AddResult.BLACKLISTED) {
namesBlacklisted.add(regionName);
} else if(result == FileManager.AddResult.NOPERMISSION) {
} else if(result == IFileManager.AddResult.NOPERMISSION) {
namesNoPermission.add(regionName);
} else {
// Check if the player should be landlord
@@ -153,8 +179,8 @@ public class AddCommand extends CommandAreaShop {
&& ((sender.hasPermission("areashop.create" + type + ".owner") && isOwner)
|| (sender.hasPermission("areashop.create" + type + ".member") && isMember)));
List<UUID> existing = new ArrayList<>();
existing.addAll(plugin.getWorldGuardHandler().getOwners(region).asUniqueIdList());
existing.addAll(plugin.getWorldGuardHandler().getMembers(region).asUniqueIdList());
existing.addAll(worldGuardInterface.getOwners(region).asUniqueIdList());
existing.addAll(worldGuardInterface.getMembers(region).asUniqueIdList());
AreaShop.debug("regionAddLandlordStatus:", regionName,
"landlord:", landlord,
@@ -166,7 +192,7 @@ public class AddCommand extends CommandAreaShop {
"memberPermission:", sender.hasPermission("areashop.create" + type + ".member"));
if(isRent) {
RentRegion rent = new RentRegion(regionName, world);
RentRegion rent = regionFactory.createRentRegion(regionName, world);
// Set landlord
if(landlord) {
rent.setLandlord(finalPlayer.getUniqueId(), finalPlayer.getName());
@@ -209,7 +235,7 @@ public class AddCommand extends CommandAreaShop {
regionsSuccess.add(rent);
} else {
BuyRegion buy = new BuyRegion(regionName, world);
BuyRegion buy = regionFactory.createBuyRegion(regionName, world);
// Set landlord
if(landlord) {
buy.setLandlord(finalPlayer.getUniqueId(), finalPlayer.getName());
@@ -253,39 +279,40 @@ public class AddCommand extends CommandAreaShop {
regionsSuccess.add(buy);
}
}
}, false).thenAccept(
(success) -> {
},
() -> {
if(!regionsSuccess.isEmpty()) {
plugin.message(sender, "add-success", args[1], Utils.combinedMessage(regionsSuccess, "region"));
messageBridge.message(sender, "add-success", args[1], Utils.combinedMessage(regionsSuccess, "region"));
}
if(!regionsAlready.isEmpty()) {
plugin.message(sender, "add-failed", Utils.combinedMessage(regionsAlready, "region"));
messageBridge.message(sender, "add-failed", Utils.combinedMessage(regionsAlready, "region"));
}
if(!regionsAlreadyOtherWorld.isEmpty()) {
plugin.message(sender, "add-failedOtherWorld", Utils.combinedMessage(regionsAlreadyOtherWorld, "region"));
messageBridge.message(sender, "add-failedOtherWorld", Utils.combinedMessage(regionsAlreadyOtherWorld, "region"));
}
if(!regionsRentCancelled.isEmpty()) {
plugin.message(sender, "add-rentCancelled", Utils.combinedMessage(regionsRentCancelled, "region"));
messageBridge.message(sender, "add-rentCancelled", Utils.combinedMessage(regionsRentCancelled, "region"));
}
if(!regionsBuyCancelled.isEmpty()) {
plugin.message(sender, "add-buyCancelled", Utils.combinedMessage(regionsBuyCancelled, "region"));
messageBridge.message(sender, "add-buyCancelled", Utils.combinedMessage(regionsBuyCancelled, "region"));
}
if(!namesBlacklisted.isEmpty()) {
plugin.message(sender, "add-blacklisted", Utils.createCommaSeparatedList(namesBlacklisted));
messageBridge.message(sender, "add-blacklisted", Utils.createCommaSeparatedList(namesBlacklisted));
}
if(!namesNoPermission.isEmpty()) {
plugin.message(sender, "add-noPermissionRegions", Utils.createCommaSeparatedList(namesNoPermission));
plugin.message(sender, "add-noPermissionOwnerMember");
messageBridge.message(sender, "add-noPermissionRegions", Utils.createCommaSeparatedList(namesNoPermission));
messageBridge.message(sender, "add-noPermissionOwnerMember");
}
if(!namesAddCancelled.isEmpty()) {
plugin.message(sender, "add-rentCancelled", Utils.createCommaSeparatedList(namesAddCancelled));
messageBridge.message(sender, "add-rentCancelled", Utils.createCommaSeparatedList(namesAddCancelled));
}
});
}
);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new LinkedList<>();
List<String> result = new ArrayList<>();
if(toComplete == 2) {
if(sender.hasPermission("areashop.createrent")) {
result.add("rent");
@@ -1,5 +1,7 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
@@ -8,12 +10,23 @@ import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class AddfriendCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Inject
private Plugin plugin;
@Override
public String getCommandStart() {
return "areashop addfriend";
@@ -31,12 +44,12 @@ public class AddfriendCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.addfriend") && !sender.hasPermission("areashop.addfriendall")) {
plugin.message(sender, "addfriend-noPermission");
messageBridge.message(sender, "addfriend-noPermission");
return;
}
if(args.length < 2) {
plugin.message(sender, "addfriend-help");
messageBridge.message(sender, "addfriend-help");
return;
}
@@ -46,74 +59,74 @@ public class AddfriendCommand extends CommandAreaShop {
// get the region by location
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
messageBridge.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
messageBridge.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
messageBridge.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
region = fileManager.getRegion(args[2]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[2]);
messageBridge.message(sender, "cmd-notRegistered", args[2]);
return;
}
}
if(sender.hasPermission("areashop.addfriendall")) {
if((region instanceof RentRegion && !((RentRegion)region).isRented())
|| (region instanceof BuyRegion && !((BuyRegion)region).isSold())) {
plugin.message(sender, "addfriend-noOwner", region);
messageBridge.message(sender, "addfriend-noOwner", region);
return;
}
OfflinePlayer friend = Bukkit.getOfflinePlayer(args[1]);
if(friend.getLastPlayed() == 0 && !friend.isOnline() && !plugin.getConfig().getBoolean("addFriendNotExistingPlayers")) {
plugin.message(sender, "addfriend-notVisited", args[1], region);
messageBridge.message(sender, "addfriend-notVisited", args[1], region);
return;
}
if(region.getFriendsFeature().getFriends().contains(friend.getUniqueId())) {
plugin.message(sender, "addfriend-alreadyAdded", friend.getName(), region);
messageBridge.message(sender, "addfriend-alreadyAdded", friend.getName(), region);
return;
}
if(region.isOwner(friend.getUniqueId())) {
plugin.message(sender, "addfriend-self", friend.getName(), region);
messageBridge.message(sender, "addfriend-self", friend.getName(), region);
return;
}
if(region.getFriendsFeature().addFriend(friend.getUniqueId(), sender)) {
region.update();
plugin.message(sender, "addfriend-successOther", friend.getName(), region);
messageBridge.message(sender, "addfriend-successOther", friend.getName(), region);
}
} else {
if(sender.hasPermission("areashop.addfriend") && sender instanceof Player) {
if(region.isOwner((Player)sender)) {
OfflinePlayer friend = Bukkit.getOfflinePlayer(args[1]);
if(friend.getLastPlayed() == 0 && !friend.isOnline() && !plugin.getConfig().getBoolean("addFriendNotExistingPlayers")) {
plugin.message(sender, "addfriend-notVisited", args[1], region);
messageBridge.message(sender, "addfriend-notVisited", args[1], region);
return;
}
if(region.getFriendsFeature().getFriends().contains(friend.getUniqueId())) {
plugin.message(sender, "addfriend-alreadyAdded", friend.getName(), region);
messageBridge.message(sender, "addfriend-alreadyAdded", friend.getName(), region);
return;
}
if(region.isOwner(friend.getUniqueId())) {
plugin.message(sender, "addfriend-self", friend.getName(), region);
messageBridge.message(sender, "addfriend-self", friend.getName(), region);
return;
}
if(region.getFriendsFeature().addFriend(friend.getUniqueId(), sender)) {
region.update();
plugin.message(sender, "addfriend-success", friend.getName(), region);
messageBridge.message(sender, "addfriend-success", friend.getName(), region);
}
} else {
plugin.message(sender, "addfriend-noPermissionOther", region);
messageBridge.message(sender, "addfriend-noPermissionOther", region);
}
} else {
plugin.message(sender, "addfriend-noPermission", region);
messageBridge.message(sender, "addfriend-noPermission", region);
}
}
}
@@ -126,7 +139,7 @@ public class AddfriendCommand extends CommandAreaShop {
result.add(player.getName());
}
} else if(toComplete == 3) {
result.addAll(plugin.getFileManager().getRegionNames());
result.addAll(fileManager.getRegionNames());
}
return result;
}
@@ -1,128 +1,135 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.features.signs.RegionSign;
import me.wiefferink.areashop.features.signs.SignsFeature;
import me.wiefferink.areashop.features.signs.SignManager;
import me.wiefferink.areashop.interfaces.BukkitInterface;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.tools.Materials;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.type.Sign;
import org.bukkit.block.data.type.WallSign;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.BlockIterator;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@Singleton
public class AddsignCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop addsign";
}
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Inject
private SignManager signManager;
@Inject
private Plugin plugin;
@Inject
private BukkitInterface bukkitInterface;
@Override
public String getHelp(CommandSender target) {
if (target.hasPermission("areashop.addsign")) {
return "help-addsign";
}
return null;
}
@Override
public String getCommandStart() {
return "areashop addsign";
}
@Override
public void execute(CommandSender sender, String[] args) {
if (!sender.hasPermission("areashop.addsign")) {
plugin.message(sender, "addsign-noPermission");
return;
}
if (!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
return;
}
Player player = (Player) sender;
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.addsign")) {
return "help-addsign";
}
return null;
}
// Get the sign
Block block = null;
BlockIterator blockIterator = new BlockIterator(player, 100);
while (blockIterator.hasNext() && block == null) {
Block next = blockIterator.next();
if (next.getType() != Material.AIR) {
block = next;
}
}
if (block == null || !Materials.isSign(block.getType())) {
plugin.message(sender, "addsign-noSign");
return;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.addsign")) {
messageBridge.message(sender, "addsign-noPermission");
return;
}
if(!(sender instanceof Player)) {
messageBridge.message(sender, "cmd-onlyByPlayer");
return;
}
Player player = (Player)sender;
GeneralRegion region;
if (args.length > 1) {
// Get region by argument
region = plugin.getFileManager().getRegion(args[1]);
if (region == null) {
plugin.message(sender, "cmd-notRegistered", args[1]);
return;
}
} else {
// Get region by sign position
List<GeneralRegion> regions = Utils.getImportantRegions(block.getLocation());
if (regions.isEmpty()) {
plugin.message(sender, "addsign-noRegions");
return;
} else if (regions.size() > 1) {
plugin.message(sender, "addsign-couldNotDetect", regions.get(0).getName(), regions.get(1).getName());
return;
}
region = regions.get(0);
}
String profile = null;
if (args.length > 2) {
profile = args[2];
Set<String> profiles = plugin.getConfig().getConfigurationSection("signProfiles").getKeys(false);
if (!profiles.contains(profile)) {
plugin.message(sender, "addsign-wrongProfile", Utils.createCommaSeparatedList(profiles), region);
return;
}
}
RegionSign regionSign = SignsFeature.getSignByLocation(block.getLocation());
if (regionSign != null) {
plugin.message(sender, "addsign-alreadyRegistered", regionSign.getRegion());
return;
}
// Get the sign
Block block = null;
BlockIterator blockIterator = new BlockIterator(player, 100);
while(blockIterator.hasNext() && block == null) {
Block next = blockIterator.next();
if(next.getType() != Material.AIR) {
block = next;
}
}
if(block == null || !Materials.isSign(block.getType())) {
messageBridge.message(sender, "addsign-noSign");
return;
}
final BlockData data = block.getBlockData();
final BlockFace rotation;
if (data instanceof Sign) {
rotation = ((Sign) data).getRotation();
} else if (data instanceof WallSign) {
rotation = ((WallSign) data).getFacing();
} else {
rotation = null;
}
region.getSignsFeature().addSign(block.getLocation(), block.getType(), rotation, profile);
if (profile == null) {
plugin.message(sender, "addsign-success", region);
} else {
plugin.message(sender, "addsign-successProfile", profile, region);
}
region.update();
}
GeneralRegion region;
if(args.length > 1) {
// Get region by argument
region = fileManager.getRegion(args[1]);
if(region == null) {
messageBridge.message(sender, "cmd-notRegistered", args[1]);
return;
}
} else {
// Get region by sign position
List<GeneralRegion> regions = Utils.getImportantRegions(block.getLocation());
if(regions.isEmpty()) {
messageBridge.message(sender, "addsign-noRegions");
return;
} else if(regions.size() > 1) {
messageBridge.message(sender, "addsign-couldNotDetect", regions.get(0).getName(), regions.get(1).getName());
return;
}
region = regions.get(0);
}
String profile = null;
if(args.length > 2) {
profile = args[2];
Set<String> profiles = plugin.getConfig().getConfigurationSection("signProfiles").getKeys(false);
if(!profiles.contains(profile)) {
messageBridge.message(sender, "addsign-wrongProfile", Utils.createCommaSeparatedList(profiles), region);
return;
}
}
Optional<RegionSign> optionalRegionSign = signManager.signFromLocation(block.getLocation());
if(optionalRegionSign.isPresent()) {
RegionSign regionSign = optionalRegionSign.get();
messageBridge.message(sender, "addsign-alreadyRegistered", regionSign.getRegion());
return;
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if (toComplete == 2) {
result.addAll(plugin.getFileManager().getRegionNames());
} else if (toComplete == 3) {
result.addAll(plugin.getConfig().getStringList("signProfiles"));
}
return result;
}
region.getSignsFeature().addSign(block.getLocation(), block.getType(), bukkitInterface.getSignFacing(block), profile);
if(profile == null) {
messageBridge.message(sender, "addsign-success", region);
} else {
messageBridge.message(sender, "addsign-successProfile", profile, region);
}
region.update();
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 2) {
result.addAll(fileManager.getRegionNames());
} else if(toComplete == 3) {
result.addAll(plugin.getConfig().getStringList("signProfiles"));
}
return result;
}
}
@@ -1,15 +1,28 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class BuyCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private Plugin plugin;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop buy";
@@ -26,18 +39,18 @@ public class BuyCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.buy")) {
plugin.message(sender, "buy-noPermission");
messageBridge.message(sender, "buy-noPermission");
return;
}
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
messageBridge.message(sender, "cmd-onlyByPlayer");
return;
}
Player player = (Player)sender;
if(args.length > 1 && args[1] != null) {
BuyRegion region = plugin.getFileManager().getBuy(args[1]);
BuyRegion region = fileManager.getBuy(args[1]);
if(region == null) {
plugin.message(player, "buy-notBuyable", args[1]);
messageBridge.message(player, "buy-notBuyable", args[1]);
} else {
region.buy(player);
}
@@ -45,9 +58,9 @@ public class BuyCommand extends CommandAreaShop {
// get the region by location
List<BuyRegion> regions = Utils.getImportantBuyRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
messageBridge.message(sender, "cmd-noRegionsAtLocation");
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
messageBridge.message(sender, "cmd-moreRegionsAtLocation");
} else {
regions.get(0).buy(player);
}
@@ -58,7 +71,7 @@ public class BuyCommand extends CommandAreaShop {
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(BuyRegion region : plugin.getFileManager().getBuys()) {
for(BuyRegion region : fileManager.getBuysRef()) {
if(!region.isSold()) {
result.add(region.getName());
}
@@ -1,6 +1,5 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.interactivemessenger.processing.Message;
import org.apache.commons.lang.StringUtils;
import org.bukkit.command.Command;
@@ -16,11 +15,9 @@ import java.util.Map;
*/
public abstract class CommandAreaShop {
final AreaShop plugin = AreaShop.getInstance();
private final Map<String, CommandTime> lastUsed;
public CommandAreaShop() {
protected CommandAreaShop() {
lastUsed = new HashMap<>();
}
@@ -1,7 +1,10 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.events.ask.DeletingRegionEvent;
import me.wiefferink.areashop.interfaces.WorldEditInterface;
import me.wiefferink.areashop.interfaces.WorldEditSelection;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
@@ -9,12 +12,22 @@ import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
@Singleton
public class DelCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private WorldEditInterface worldEditInterface;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop del";
@@ -35,24 +48,24 @@ public class DelCommand extends CommandAreaShop {
&& !sender.hasPermission("areashop.destroyrent")
&& !sender.hasPermission("areashop.destroyrent.landlord")) {
plugin.message(sender, "del-noPermission");
messageBridge.message(sender, "del-noPermission");
return;
}
if(args.length < 2) {
// Only players can have a selection
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-weOnlyByPlayer");
messageBridge.message(sender, "cmd-weOnlyByPlayer");
return;
}
Player player = (Player)sender;
WorldEditSelection selection = plugin.getWorldEditHandler().getPlayerSelection(player);
WorldEditSelection selection = worldEditInterface.getPlayerSelection(player);
if(selection == null) {
plugin.message(player, "cmd-noSelection");
messageBridge.message(player, "cmd-noSelection");
return;
}
List<GeneralRegion> regions = Utils.getRegionsInSelection(selection);
if(regions == null || regions.isEmpty()) {
plugin.message(player, "cmd-noRegionsFound");
messageBridge.message(player, "cmd-noRegionsFound");
return;
}
// Start removing the regions that he has permission for
@@ -73,7 +86,7 @@ public class DelCommand extends CommandAreaShop {
}
}
DeletingRegionEvent event = plugin.getFileManager().deleteRegion(region, true);
DeletingRegionEvent event = fileManager.deleteRegion(region, true);
if (event.isCancelled()) {
regionsCancelled.add(region);
} else {
@@ -83,44 +96,44 @@ public class DelCommand extends CommandAreaShop {
// Send messages
if(!namesSuccess.isEmpty()) {
plugin.message(sender, "del-success", Utils.createCommaSeparatedList(namesSuccess));
messageBridge.message(sender, "del-success", Utils.createCommaSeparatedList(namesSuccess));
}
if(!regionsFailed.isEmpty()) {
plugin.message(sender, "del-failed", Utils.combinedMessage(regionsFailed, "region"));
messageBridge.message(sender, "del-failed", Utils.combinedMessage(regionsFailed, "region"));
}
if(!regionsCancelled.isEmpty()) {
plugin.message(sender, "del-cancelled", Utils.combinedMessage(regionsCancelled, "region"));
messageBridge.message(sender, "del-cancelled", Utils.combinedMessage(regionsCancelled, "region"));
}
} else {
GeneralRegion region = plugin.getFileManager().getRegion(args[1]);
GeneralRegion region = fileManager.getRegion(args[1]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[1]);
messageBridge.message(sender, "cmd-notRegistered", args[1]);
return;
}
boolean isLandlord = sender instanceof Player && region.isLandlord(((Player)sender).getUniqueId());
if(region instanceof RentRegion) {
// Remove the rent if the player has permission
if(sender.hasPermission("areashop.destroyrent") || (isLandlord && sender.hasPermission("areashop.destroyrent.landlord"))) {
DeletingRegionEvent event = plugin.getFileManager().deleteRegion(region, true);
DeletingRegionEvent event = fileManager.deleteRegion(region, true);
if (event.isCancelled()) {
plugin.message(sender, "general-cancelled", event.getReason());
messageBridge.message(sender, "general-cancelled", event.getReason());
} else {
plugin.message(sender, "destroy-successRent", region);
messageBridge.message(sender, "destroy-successRent", region);
}
} else {
plugin.message(sender, "destroy-noPermissionRent", region);
messageBridge.message(sender, "destroy-noPermissionRent", region);
}
} else if(region instanceof BuyRegion) {
// Remove the buy if the player has permission
if(sender.hasPermission("areashop.destroybuy") || (isLandlord && sender.hasPermission("areashop.destroybuy.landlord"))) {
DeletingRegionEvent event = plugin.getFileManager().deleteRegion(region, true);
DeletingRegionEvent event = fileManager.deleteRegion(region, true);
if (event.isCancelled()) {
plugin.message(sender, "general-cancelled", event.getReason());
messageBridge.message(sender, "general-cancelled", event.getReason());
} else {
plugin.message(sender, "destroy-successBuy", region);
messageBridge.message(sender, "destroy-successBuy", region);
}
} else {
plugin.message(sender, "destroy-noPermissionBuy", region);
messageBridge.message(sender, "destroy-noPermissionBuy", region);
}
}
}
@@ -130,7 +143,7 @@ public class DelCommand extends CommandAreaShop {
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 2) {
result = plugin.getFileManager().getRegionNames();
result = fileManager.getRegionNames();
}
return result;
}
@@ -1,5 +1,7 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
@@ -9,11 +11,19 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class DelfriendCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop delfriend";
@@ -48,11 +58,11 @@ public class DelfriendCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.delfriend") && !sender.hasPermission("areashop.delfriendall")) {
plugin.message(sender, "delfriend-noPermission");
messageBridge.message(sender, "delfriend-noPermission");
return;
}
if(args.length < 2) {
plugin.message(sender, "delfriend-help");
messageBridge.message(sender, "delfriend-help");
return;
}
GeneralRegion region;
@@ -61,57 +71,57 @@ public class DelfriendCommand extends CommandAreaShop {
// get the region by location
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
messageBridge.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
messageBridge.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
messageBridge.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
region = fileManager.getRegion(args[2]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[2]);
messageBridge.message(sender, "cmd-notRegistered", args[2]);
return;
}
}
if(sender.hasPermission("areashop.delfriendall")) {
if((region instanceof RentRegion && !((RentRegion)region).isRented())
|| (region instanceof BuyRegion && !((BuyRegion)region).isSold())) {
plugin.message(sender, "delfriend-noOwner", region);
messageBridge.message(sender, "delfriend-noOwner", region);
return;
}
OfflinePlayer friend = Bukkit.getOfflinePlayer(args[1]);
if(!region.getFriendsFeature().getFriends().contains(friend.getUniqueId())) {
plugin.message(sender, "delfriend-notAdded", friend.getName(), region);
messageBridge.message(sender, "delfriend-notAdded", friend.getName(), region);
return;
}
if(region.getFriendsFeature().deleteFriend(friend.getUniqueId(), sender)) {
region.update();
plugin.message(sender, "delfriend-successOther", friend.getName(), region);
messageBridge.message(sender, "delfriend-successOther", friend.getName(), region);
}
} else {
if(sender.hasPermission("areashop.delfriend") && sender instanceof Player) {
if(region.isOwner((Player)sender)) {
OfflinePlayer friend = Bukkit.getOfflinePlayer(args[1]);
if(!region.getFriendsFeature().getFriends().contains(friend.getUniqueId())) {
plugin.message(sender, "delfriend-notAdded", friend.getName(), region);
messageBridge.message(sender, "delfriend-notAdded", friend.getName(), region);
return;
}
if(region.getFriendsFeature().deleteFriend(friend.getUniqueId(), sender)) {
region.update();
plugin.message(sender, "delfriend-success", friend.getName(), region);
messageBridge.message(sender, "delfriend-success", friend.getName(), region);
}
} else {
plugin.message(sender, "delfriend-noPermissionOther", region);
messageBridge.message(sender, "delfriend-noPermissionOther", region);
}
} else {
plugin.message(sender, "delfriend-noPermission", region);
messageBridge.message(sender, "delfriend-noPermission", region);
}
}
}
@@ -124,7 +134,7 @@ public class DelfriendCommand extends CommandAreaShop {
result.add(player.getName());
}
} else if(toComplete == 3) {
result.addAll(plugin.getFileManager().getRegionNames());
result.addAll(fileManager.getRegionNames());
}
return result;
}
@@ -1,6 +1,8 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.features.signs.RegionSign;
import me.wiefferink.areashop.features.signs.SignManager;
import me.wiefferink.areashop.features.signs.SignsFeature;
import me.wiefferink.areashop.tools.Materials;
import org.bukkit.Material;
@@ -9,11 +11,20 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.BlockIterator;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Singleton
public class DelsignCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private SignManager signManager;
@Override
public String getCommandStart() {
return "areashop delsign";
@@ -30,11 +41,11 @@ public class DelsignCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.delsign")) {
plugin.message(sender, "delsign-noPermission");
messageBridge.message(sender, "delsign-noPermission");
return;
}
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
messageBridge.message(sender, "cmd-onlyByPlayer");
return;
}
Player player = (Player)sender;
@@ -49,15 +60,17 @@ public class DelsignCommand extends CommandAreaShop {
}
}
if(block == null || !Materials.isSign(block.getType())) {
plugin.message(sender, "delsign-noSign");
messageBridge.message(sender, "delsign-noSign");
return;
}
RegionSign regionSign = SignsFeature.getSignByLocation(block.getLocation());
if(regionSign == null) {
plugin.message(sender, "delsign-noRegion");
Optional<RegionSign> optionalSign = signManager.removeSign(block.getLocation());
if(optionalSign.isEmpty()) {
messageBridge.message(sender, "delsign-noRegion");
return;
}
plugin.message(sender, "delsign-success", regionSign.getRegion());
RegionSign regionSign = optionalSign.get();
messageBridge.message(sender, "delsign-success", regionSign.getRegion());
signManager.removeSign(regionSign);
regionSign.remove();
}
@@ -1,20 +1,34 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import me.wiefferink.interactivemessenger.processing.Message;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
@Singleton
public class FindCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private Economy economy;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop find";
@@ -31,21 +45,21 @@ public class FindCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.find")) {
plugin.message(sender, "find-noPermission");
messageBridge.message(sender, "find-noPermission");
return;
}
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
messageBridge.message(sender, "cmd-onlyByPlayer");
return;
}
if(args.length <= 1 || args[1] == null || (!args[1].equalsIgnoreCase("buy") && !args[1].equalsIgnoreCase("rent"))) {
plugin.message(sender, "find-help");
messageBridge.message(sender, "find-help");
return;
}
Player player = (Player)sender;
double balance = 0.0;
if(plugin.getEconomy() != null) {
balance = plugin.getEconomy().getBalance(player);
if(economy != null) {
balance = economy.getBalance(player);
}
double maxPrice = 0;
boolean maxPriceSet = false;
@@ -56,23 +70,23 @@ public class FindCommand extends CommandAreaShop {
maxPrice = Double.parseDouble(args[2]);
maxPriceSet = true;
} catch(NumberFormatException e) {
plugin.message(sender, "find-wrongMaxPrice", args[2]);
messageBridge.message(sender, "find-wrongMaxPrice", args[2]);
return;
}
}
// Parse optional group argument
if(args.length >= 4) {
group = plugin.getFileManager().getGroup(args[3]);
group = fileManager.getGroup(args[3]);
if(group == null) {
plugin.message(sender, "find-wrongGroup", args[3]);
messageBridge.message(sender, "find-wrongGroup", args[3]);
return;
}
}
// Find buy regions
if(args[1].equalsIgnoreCase("buy")) {
List<BuyRegion> regions = plugin.getFileManager().getBuys();
List<BuyRegion> results = new ArrayList<>();
Collection<BuyRegion> regions = fileManager.getBuysRef();
List<BuyRegion> results = new LinkedList<>();
for(BuyRegion region : regions) {
if(!region.isSold()
&& ((region.getPrice() <= balance && !maxPriceSet) || (region.getPrice() <= maxPrice && maxPriceSet))
@@ -83,7 +97,7 @@ public class FindCommand extends CommandAreaShop {
}
if(!results.isEmpty()) {
// Draw a random one
BuyRegion region = results.get(ThreadLocalRandom.current().nextInt(results.size()));
BuyRegion region = results.get(new Random().nextInt(results.size()));
Message onlyInGroup = Message.empty();
if(group != null) {
onlyInGroup = Message.fromKey("find-onlyInGroup").replacements(args[3]);
@@ -91,9 +105,9 @@ public class FindCommand extends CommandAreaShop {
// Teleport
if(maxPriceSet) {
plugin.message(player, "find-successMax", "buy", Utils.formatCurrency(maxPrice), onlyInGroup, region);
messageBridge.message(player, "find-successMax", "buy", Utils.formatCurrency(maxPrice), onlyInGroup, region);
} else {
plugin.message(player, "find-success", "buy", Utils.formatCurrency(balance), onlyInGroup, region);
messageBridge.message(player, "find-success", "buy", Utils.formatCurrency(balance), onlyInGroup, region);
}
region.getTeleportFeature().teleportPlayer(player, region.getBooleanSetting("general.findTeleportToSign"), false);
} else {
@@ -102,17 +116,17 @@ public class FindCommand extends CommandAreaShop {
onlyInGroup = Message.fromKey("find-onlyInGroup").replacements(args[3]);
}
if(maxPriceSet) {
plugin.message(player, "find-noneFoundMax", "buy", Utils.formatCurrency(maxPrice), onlyInGroup);
messageBridge.message(player, "find-noneFoundMax", "buy", Utils.formatCurrency(maxPrice), onlyInGroup);
} else {
plugin.message(player, "find-noneFound", "buy", Utils.formatCurrency(balance), onlyInGroup);
messageBridge.message(player, "find-noneFound", "buy", Utils.formatCurrency(balance), onlyInGroup);
}
}
}
// Find rental regions
else {
List<RentRegion> regions = plugin.getFileManager().getRents();
List<RentRegion> results = new ArrayList<>(regions.size());
Collection<RentRegion> regions = fileManager.getRentsRef();
List<RentRegion> results = new LinkedList<>();
for(RentRegion region : regions) {
if(!region.isRented()
&& ((region.getPrice() <= balance && !maxPriceSet) || (region.getPrice() <= maxPrice && maxPriceSet))
@@ -123,7 +137,7 @@ public class FindCommand extends CommandAreaShop {
}
if(!results.isEmpty()) {
// Draw a random one
RentRegion region = results.get(ThreadLocalRandom.current().nextInt(results.size()));
RentRegion region = results.get(new Random().nextInt(results.size()));
Message onlyInGroup = Message.empty();
if(group != null) {
onlyInGroup = Message.fromKey("find-onlyInGroup").replacements(args[3]);
@@ -131,9 +145,9 @@ public class FindCommand extends CommandAreaShop {
// Teleport
if(maxPriceSet) {
plugin.message(player, "find-successMax", "rent", Utils.formatCurrency(maxPrice), onlyInGroup, region);
messageBridge.message(player, "find-successMax", "rent", Utils.formatCurrency(maxPrice), onlyInGroup, region);
} else {
plugin.message(player, "find-success", "rent", Utils.formatCurrency(balance), onlyInGroup, region);
messageBridge.message(player, "find-success", "rent", Utils.formatCurrency(balance), onlyInGroup, region);
}
region.getTeleportFeature().teleportPlayer(player, region.getBooleanSetting("general.findTeleportToSign"), false);
} else {
@@ -142,9 +156,9 @@ public class FindCommand extends CommandAreaShop {
onlyInGroup = Message.fromKey("find-onlyInGroup").replacements(args[3]);
}
if(maxPriceSet) {
plugin.message(player, "find-noneFoundMax", "rent", Utils.formatCurrency(maxPrice), onlyInGroup);
messageBridge.message(player, "find-noneFoundMax", "rent", Utils.formatCurrency(maxPrice), onlyInGroup);
} else {
plugin.message(player, "find-noneFound", "rent", Utils.formatCurrency(balance), onlyInGroup);
messageBridge.message(player, "find-noneFound", "rent", Utils.formatCurrency(balance), onlyInGroup);
}
}
}
@@ -1,18 +1,35 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.interfaces.WorldEditInterface;
import me.wiefferink.areashop.interfaces.WorldEditSelection;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RegionFactory;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
@Singleton
public class GroupaddCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Inject
private RegionFactory regionFactory;
@Inject
private WorldEditInterface worldEditInterface;
@Override
public String getCommandStart() {
return "areashop groupadd";
@@ -29,32 +46,32 @@ public class GroupaddCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.groupadd")) {
plugin.message(sender, "groupadd-noPermission");
messageBridge.message(sender, "groupadd-noPermission");
return;
}
if(args.length < 2 || args[1] == null) {
plugin.message(sender, "groupadd-help");
messageBridge.message(sender, "groupadd-help");
return;
}
RegionGroup group = plugin.getFileManager().getGroup(args[1]);
RegionGroup group = fileManager.getGroup(args[1]);
if(group == null) {
group = new RegionGroup(plugin, args[1]);
plugin.getFileManager().addGroup(group);
group = regionFactory.createRegionGroup(args[1]);
fileManager.addGroup(group);
}
if(args.length == 2) {
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-weOnlyByPlayer");
messageBridge.message(sender, "cmd-weOnlyByPlayer");
return;
}
Player player = (Player)sender;
WorldEditSelection selection = plugin.getWorldEditHandler().getPlayerSelection(player);
WorldEditSelection selection = worldEditInterface.getPlayerSelection(player);
if(selection == null) {
plugin.message(player, "cmd-noSelection");
messageBridge.message(player, "cmd-noSelection");
return;
}
List<GeneralRegion> regions = Utils.getRegionsInSelection(selection);
if(regions.isEmpty()) {
plugin.message(player, "cmd-noRegionsFound");
messageBridge.message(player, "cmd-noRegionsFound");
return;
}
TreeSet<GeneralRegion> regionsSuccess = new TreeSet<>();
@@ -67,24 +84,24 @@ public class GroupaddCommand extends CommandAreaShop {
}
}
if(!regionsSuccess.isEmpty()) {
plugin.message(player, "groupadd-weSuccess", group.getName(), Utils.combinedMessage(regionsSuccess, "region"));
messageBridge.message(player, "groupadd-weSuccess", group.getName(), Utils.combinedMessage(regionsSuccess, "region"));
}
if(!regionsFailed.isEmpty()) {
plugin.message(player, "groupadd-weFailed", group.getName(), Utils.combinedMessage(regionsFailed, "region"));
messageBridge.message(player, "groupadd-weFailed", group.getName(), Utils.combinedMessage(regionsFailed, "region"));
}
// Update all regions, this does it in a task, updating them without lag
plugin.getFileManager().updateRegions(new ArrayList<>(regionsSuccess), player);
fileManager.updateRegions(new ArrayList<>(regionsSuccess), player);
} else {
GeneralRegion region = plugin.getFileManager().getRegion(args[2]);
GeneralRegion region = fileManager.getRegion(args[2]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[2]);
messageBridge.message(sender, "cmd-notRegistered", args[2]);
return;
}
if(group.addMember(region)) {
region.update();
plugin.message(sender, "groupadd-success", group.getName(), group.getMembers().size(), region);
messageBridge.message(sender, "groupadd-success", group.getName(), group.getMembers().size(), region);
} else {
plugin.message(sender, "groupadd-failed", group.getName(), region);
messageBridge.message(sender, "groupadd-failed", group.getName(), region);
}
}
}
@@ -93,9 +110,9 @@ public class GroupaddCommand extends CommandAreaShop {
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 2) {
result = plugin.getFileManager().getGroupNames();
result = fileManager.getGroupNames();
} else if(toComplete == 3) {
result = plugin.getFileManager().getRegionNames();
result = fileManager.getRegionNames();
}
return result;
}
@@ -1,18 +1,34 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.interfaces.WorldEditInterface;
import me.wiefferink.areashop.interfaces.WorldEditSelection;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RegionFactory;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
@Singleton
public class GroupdelCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Inject
private RegionFactory regionFactory;
@Inject
private WorldEditInterface worldEditInterface;
@Override
public String getCommandStart() {
return "areashop groupdel";
@@ -29,33 +45,33 @@ public class GroupdelCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.groupdel")) {
plugin.message(sender, "groupdel-noPermission");
messageBridge.message(sender, "groupdel-noPermission");
return;
}
if(args.length < 2 || args[1] == null) {
plugin.message(sender, "groupdel-help");
messageBridge.message(sender, "groupdel-help");
return;
}
RegionGroup group = plugin.getFileManager().getGroup(args[1]);
RegionGroup group = fileManager.getGroup(args[1]);
if(group == null) {
plugin.message(sender, "groupdel-wrongGroup", args[1]);
messageBridge.message(sender, "groupdel-wrongGroup", args[1]);
return;
}
if(args.length == 2) {
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-weOnlyByPlayer");
messageBridge.message(sender, "cmd-weOnlyByPlayer");
return;
}
Player player = (Player)sender;
WorldEditSelection selection = plugin.getWorldEditHandler().getPlayerSelection(player);
WorldEditSelection selection = worldEditInterface.getPlayerSelection(player);
if(selection == null) {
plugin.message(player, "cmd-noSelection");
messageBridge.message(player, "cmd-noSelection");
return;
}
List<GeneralRegion> regions = Utils.getRegionsInSelection(selection);
if(regions.isEmpty()) {
plugin.message(player, "cmd-noRegionsFound");
messageBridge.message(player, "cmd-noRegionsFound");
return;
}
TreeSet<GeneralRegion> regionsSuccess = new TreeSet<>();
@@ -68,25 +84,25 @@ public class GroupdelCommand extends CommandAreaShop {
}
}
if(!regionsSuccess.isEmpty()) {
plugin.message(player, "groupdel-weSuccess", group.getName(), Utils.combinedMessage(regionsSuccess, "region"));
messageBridge.message(player, "groupdel-weSuccess", group.getName(), Utils.combinedMessage(regionsSuccess, "region"));
}
if(!regionsFailed.isEmpty()) {
plugin.message(player, "groupdel-weFailed", group.getName(), Utils.combinedMessage(regionsFailed, "region"));
messageBridge.message(player, "groupdel-weFailed", group.getName(), Utils.combinedMessage(regionsFailed, "region"));
}
// Update all regions, this does it in a task, updating them without lag
plugin.getFileManager().updateRegions(new ArrayList<>(regionsSuccess), player);
fileManager.updateRegions(regionsSuccess, player);
group.saveRequired();
} else {
GeneralRegion region = plugin.getFileManager().getRegion(args[2]);
GeneralRegion region = fileManager.getRegion(args[2]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[2]);
messageBridge.message(sender, "cmd-notRegistered", args[2]);
return;
}
if(group.removeMember(region)) {
region.update();
plugin.message(sender, "groupdel-success", group.getName(), group.getMembers().size(), region);
messageBridge.message(sender, "groupdel-success", group.getName(), group.getMembers().size(), region);
} else {
plugin.message(sender, "groupdel-failed", group.getName(), region);
messageBridge.message(sender, "groupdel-failed", group.getName(), region);
}
}
}
@@ -95,9 +111,9 @@ public class GroupdelCommand extends CommandAreaShop {
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 2) {
result = plugin.getFileManager().getGroupNames();
result = fileManager.getGroupNames();
} else if(toComplete == 3) {
result = plugin.getFileManager().getRegionNames();
result = fileManager.getRegionNames();
}
return result;
}
@@ -1,15 +1,25 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@Singleton
public class GroupinfoCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop groupinfo";
@@ -27,23 +37,23 @@ public class GroupinfoCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.groupinfo")) {
plugin.message(sender, "groupinfo-noPermission");
messageBridge.message(sender, "groupinfo-noPermission");
return;
}
if(args.length < 2 || args[1] == null) {
plugin.message(sender, "groupinfo-help");
messageBridge.message(sender, "groupinfo-help");
return;
}
RegionGroup group = plugin.getFileManager().getGroup(args[1]);
RegionGroup group = fileManager.getGroup(args[1]);
if(group == null) {
plugin.message(sender, "groupinfo-noGroup", args[1]);
messageBridge.message(sender, "groupinfo-noGroup", args[1]);
return;
}
Set<String> members = group.getMembers();
if(members.isEmpty()) {
plugin.message(sender, "groupinfo-noMembers", group.getName());
messageBridge.message(sender, "groupinfo-noMembers", group.getName());
} else {
plugin.message(sender, "groupinfo-members", group.getName(), Utils.createCommaSeparatedList(members));
messageBridge.message(sender, "groupinfo-members", group.getName(), Utils.createCommaSeparatedList(members));
}
}
@@ -51,7 +61,7 @@ public class GroupinfoCommand extends CommandAreaShop {
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 2) {
result = plugin.getFileManager().getGroupNames();
result = fileManager.getGroupNames();
}
return result;
}
@@ -1,13 +1,23 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class GrouplistCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop grouplist";
@@ -24,14 +34,14 @@ public class GrouplistCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.grouplist")) {
plugin.message(sender, "grouplist-noPermission");
messageBridge.message(sender, "grouplist-noPermission");
return;
}
List<String> groups = plugin.getFileManager().getGroupNames();
List<String> groups = fileManager.getGroupNames();
if(groups.isEmpty()) {
plugin.message(sender, "grouplist-noGroups");
messageBridge.message(sender, "grouplist-noGroups");
} else {
plugin.message(sender, "grouplist-success", Utils.createCommaSeparatedList(groups));
messageBridge.message(sender, "grouplist-success", Utils.createCommaSeparatedList(groups));
}
}
@@ -1,9 +1,20 @@
package me.wiefferink.areashop.commands;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import me.wiefferink.areashop.managers.CommandManager;
import org.bukkit.command.CommandSender;
import javax.annotation.Nonnull;
public class HelpCommand extends CommandAreaShop {
private final CommandManager commandManager;
public HelpCommand(@Nonnull CommandManager commandManager) {
this.commandManager = commandManager;
}
@Override
public String getCommandStart() {
return "areashop help";
@@ -19,6 +30,6 @@ public class HelpCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
plugin.getCommandManager().showHelp(sender);
commandManager.showHelp(sender);
}
}
@@ -1,11 +1,17 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.regions.ImportJob;
import me.wiefferink.areashop.regions.ImportJobFactory;
import me.wiefferink.interactivemessenger.processing.Message;
import org.bukkit.command.CommandSender;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class ImportCommand extends CommandAreaShop {
/* RegionGroup priority usage:
@@ -13,6 +19,10 @@ public class ImportCommand extends CommandAreaShop {
1: Settings from /worlds/<world>/config.yml
2: Settings from /worlds/<world>/parent-regions.yml (if their priority is set it is added to this value)
*/
@Inject
private MessageBridge messageBridge;
@Inject
private ImportJobFactory importJobFactory;
@Override
public String getCommandStart() {
@@ -36,17 +46,17 @@ public class ImportCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.import")) {
plugin.message(sender, "import-noPermission");
messageBridge.message(sender, "import-noPermission");
return;
}
if(args.length < 2) {
plugin.message(sender, "import-help");
messageBridge.message(sender, "import-help");
return;
}
if(!"RegionForSale".equalsIgnoreCase(args[1])) {
plugin.message(sender, "import-wrongSource");
messageBridge.message(sender, "import-wrongSource");
return;
}
@@ -54,7 +64,7 @@ public class ImportCommand extends CommandAreaShop {
return;
}
new ImportJob(sender);
importJobFactory.createImportJob(sender).execute();
}
@Override
@@ -1,21 +1,35 @@
package me.wiefferink.areashop.commands;
import io.github.bakedlibs.dough.blocks.BlockPosition;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import me.wiefferink.interactivemessenger.processing.Message;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.*;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
// TODO fix '/as info' help message hitting replacement limit (improve depth tracking?)
// TODO add info about autoExtend
@Singleton
public class InfoCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop info";
@@ -46,7 +60,7 @@ public class InfoCommand extends CommandAreaShop {
try {
page = Integer.parseInt(pageInput);
} catch(NumberFormatException e) {
plugin.message(sender, "info-wrongPage", pageInput);
messageBridge.message(sender, "info-wrongPage", pageInput);
return;
}
}
@@ -54,11 +68,11 @@ public class InfoCommand extends CommandAreaShop {
regions.removeIf(generalRegion -> !filterGroup.isMember(generalRegion));
}
if(regions.isEmpty()) {
plugin.message(sender, "info-noRegions");
messageBridge.message(sender, "info-noRegions");
} else {
// First sort by type, then by name
regions.sort((one, two) -> {
int typeCompare = Integer.compare(getTypeOrder(two), getTypeOrder(one));
int typeCompare = getTypeOrder(two).compareTo(getTypeOrder(one));
if(typeCompare != 0) {
return typeCompare;
} else {
@@ -70,7 +84,7 @@ public class InfoCommand extends CommandAreaShop {
if(filterGroup != null) {
limitedToGroup = Message.fromKey("info-limitedToGroup").replacements(filterGroup.getName());
}
plugin.message(sender, keyHeader, limitedToGroup);
messageBridge.message(sender, keyHeader, limitedToGroup);
// Page entries
int totalPages = (int)Math.ceil(regions.size() / (double)itemsPerPage); // Clip page to correct boundaries, not much need to tell the user
if(regions.size() == itemsPerPage + 1) { // 19 total items is mapped to 1 page of 19
@@ -82,24 +96,22 @@ public class InfoCommand extends CommandAreaShop {
for(int i = (page - 1) * itemsPerPage; i < page * itemsPerPage && i < regions.size(); i++) {
String state;
GeneralRegion region = regions.get(i);
if(region instanceof RentRegion) {
if(region.isAvailable()) {
if(region.getType() == GeneralRegion.RegionType.RENT) {
if(region.getOwner() == null) {
state = "Forrent";
} else {
state = "Rented";
}
} else if (region instanceof BuyRegion){
if(region.isAvailable()) {
} else {
if(region.getOwner() == null) {
state = "Forsale";
} else if(!((BuyRegion)region).isInResellingMode()) {
state = "Sold";
} else {
state = "Reselling";
}
} else {
state = region.getState().getValue();
}
plugin.messageNoPrefix(sender, "info-entry" + state, region);
messageBridge.messageNoPrefix(sender, "info-entry" + state, region);
linesPrinted++;
}
Message footer = Message.empty();
@@ -135,15 +147,15 @@ public class InfoCommand extends CommandAreaShop {
* @param region The region to get the order for
* @return An integer for sorting by type
*/
private int getTypeOrder(GeneralRegion region) {
private Integer getTypeOrder(GeneralRegion region) {
if(region.getType() == GeneralRegion.RegionType.RENT) {
if(region.isAvailable()) {
if(region.getOwner() == null) {
return 1;
} else {
return 2;
}
} else {
if(region.isAvailable()) {
if(region.getOwner() == null) {
return 3;
} else if(!((BuyRegion)region).isInResellingMode()) {
return 4;
@@ -156,7 +168,7 @@ public class InfoCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.info")) {
plugin.message(sender, "info-noPermission");
messageBridge.message(sender, "info-noPermission");
return;
}
if(args.length > 1 && args[1] != null) {
@@ -165,9 +177,9 @@ public class InfoCommand extends CommandAreaShop {
Set<String> groupFilters = new HashSet<>(Arrays.asList("all", "rented", "forrent", "sold", "forsale", "reselling"));
if(groupFilters.contains(args[1].toLowerCase()) && args.length > 2) {
if(!Utils.isNumeric(args[2])) {
filterGroup = plugin.getFileManager().getGroup(args[2]);
filterGroup = fileManager.getGroup(args[2]);
if(filterGroup == null) {
plugin.message(sender, "info-noFiltergroup", args[2]);
messageBridge.message(sender, "info-noFiltergroup", args[2]);
return;
}
// Pass page number to args[2] if available
@@ -179,48 +191,48 @@ public class InfoCommand extends CommandAreaShop {
// All regions
if(args[1].equalsIgnoreCase("all")) {
showSortedPagedList(sender, plugin.getFileManager().getRegions(), filterGroup, "info-allHeader", (args.length > 2 ? args[2] : null), "info all");
showSortedPagedList(sender, new ArrayList<>(fileManager.getRegionsRef()), filterGroup, "info-allHeader", (args.length > 2 ? args[2] : null), "info all");
}
// Rented regions
else if(args[1].equalsIgnoreCase("rented")) {
List<RentRegion> regions = plugin.getFileManager().getRents();
List<RentRegion> regions = new ArrayList<>(fileManager.getRentsRef());
regions.removeIf(RentRegion::isAvailable);
showSortedPagedList(sender, regions, filterGroup, "info-rentedHeader", (args.length > 2 ? args[2] : null), "info rented");
}
// Forrent regions
else if(args[1].equalsIgnoreCase("forrent")) {
List<RentRegion> regions = plugin.getFileManager().getRents();
List<RentRegion> regions = new ArrayList<>(fileManager.getRentsRef());
regions.removeIf(RentRegion::isRented);
showSortedPagedList(sender, regions, filterGroup, "info-forrentHeader", (args.length > 2 ? args[2] : null), "info forrent");
}
// Sold regions
else if(args[1].equalsIgnoreCase("sold")) {
List<BuyRegion> regions = plugin.getFileManager().getBuys();
List<BuyRegion> regions = new ArrayList<>(fileManager.getBuysRef());
regions.removeIf(BuyRegion::isAvailable);
showSortedPagedList(sender, regions, filterGroup, "info-soldHeader", (args.length > 2 ? args[2] : null), "info sold");
}
// Forsale regions
else if(args[1].equalsIgnoreCase("forsale")) {
List<BuyRegion> regions = plugin.getFileManager().getBuys();
List<BuyRegion> regions = new ArrayList<>(fileManager.getBuysRef());
regions.removeIf(BuyRegion::isSold);
showSortedPagedList(sender, regions, filterGroup, "info-forsaleHeader", (args.length > 2 ? args[2] : null), "info forsale");
}
// Reselling regions
else if(args[1].equalsIgnoreCase("reselling")) {
List<BuyRegion> regions = plugin.getFileManager().getBuys();
List<BuyRegion> regions = new ArrayList<>(fileManager.getBuysRef());
regions.removeIf(region -> !region.isInResellingMode());
showSortedPagedList(sender, regions, filterGroup, "info-resellingHeader", (args.length > 2 ? args[2] : null), "info reselling");
}
// List of regions without a group
else if(args[1].equalsIgnoreCase("nogroup")) {
List<GeneralRegion> regions = plugin.getFileManager().getRegions();
for(RegionGroup group : plugin.getFileManager().getGroups()) {
List<GeneralRegion> regions = new ArrayList<>(fileManager.getRegionsRef());
for(RegionGroup group : fileManager.getGroups()) {
regions.removeAll(group.getMemberRegions());
}
if(regions.isEmpty()) {
plugin.message(sender, "info-nogroupNone");
messageBridge.message(sender, "info-nogroupNone");
} else {
showSortedPagedList(sender, regions, filterGroup, "info-nogroupHeader", (args.length > 2 ? args[2] : null), "info nogroup");
}
@@ -228,207 +240,211 @@ public class InfoCommand extends CommandAreaShop {
// Region info
else if(args[1].equalsIgnoreCase("region")) {
RentRegion rent = null;
BuyRegion buy = null;
if(args.length > 2) {
rent = plugin.getFileManager().getRent(args[2]);
buy = plugin.getFileManager().getBuy(args[2]);
} else {
if(sender instanceof Player) {
// get the region by location
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
if(regions.get(0) instanceof RentRegion) {
rent = (RentRegion)regions.get(0);
} else if(regions.get(0) instanceof BuyRegion) {
buy = (BuyRegion)regions.get(0);
}
}
if(args.length > 1) {
RentRegion rent = null;
BuyRegion buy = null;
if(args.length > 2) {
rent = fileManager.getRent(args[2]);
buy = fileManager.getBuy(args[2]);
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
if(sender instanceof Player) {
// get the region by location
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
messageBridge.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
messageBridge.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
if(regions.get(0) instanceof RentRegion) {
rent = (RentRegion)regions.get(0);
} else if(regions.get(0) instanceof BuyRegion) {
buy = (BuyRegion)regions.get(0);
}
}
} else {
messageBridge.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
}
if(rent == null && buy == null) {
messageBridge.message(sender, "info-regionNotExisting", args[2]);
return;
}
}
if(rent == null && buy == null) {
plugin.message(sender, "info-regionNotExisting", args[2]);
return;
}
if(rent != null) {
plugin.message(sender, "info-regionHeaderRent", rent);
if(rent.isRented()) {
plugin.messageNoPrefix(sender, "info-regionRented", rent);
plugin.messageNoPrefix(sender, "info-regionExtending", rent);
// Money back
if(UnrentCommand.canUse(sender, rent)) {
plugin.messageNoPrefix(sender, "info-regionMoneyBackRentClick", rent);
} else {
plugin.messageNoPrefix(sender, "info-regionMoneyBackRent", rent);
}
// Friends
if(!rent.getFriendsFeature().getFriendNames().isEmpty()) {
String messagePart = "info-friend";
if(DelfriendCommand.canUse(sender, rent)) {
messagePart = "info-friendRemove";
}
plugin.messageNoPrefix(sender, "info-regionFriends", rent, Utils.combinedMessage(rent.getFriendsFeature().getFriendNames(), messagePart));
}
} else {
plugin.messageNoPrefix(sender, "info-regionCanBeRented", rent);
}
if(rent.getLandlordName() != null) {
plugin.messageNoPrefix(sender, "info-regionLandlord", rent);
}
// Maximum extends
if(rent.getMaxExtends() != -1) {
if(rent.getMaxExtends() == 0) {
plugin.messageNoPrefix(sender, "info-regionNoExtending", rent);
} else if(rent.isRented()) {
plugin.messageNoPrefix(sender, "info-regionExtendsLeft", rent);
} else {
plugin.messageNoPrefix(sender, "info-regionMaxExtends", rent);
}
}
// If maxExtends is zero it does not make sense to show this message
if(rent.getMaxRentTime() != -1 && rent.getMaxExtends() != 0) {
plugin.messageNoPrefix(sender, "info-regionMaxRentTime", rent);
}
if(rent.getInactivityThresholdMillis() != -1) {
plugin.messageNoPrefix(sender, "info-regionInactiveUnrent", rent);
}
// Teleport
Message tp = Message.fromKey("info-prefix");
boolean foundSomething = false;
if(TeleportCommand.canUse(sender, rent)) {
foundSomething = true;
tp.append(Message.fromKey("info-regionTeleport").replacements(rent));
}
if(SetteleportCommand.canUse(sender, rent)) {
if(foundSomething) {
tp.append(", ");
}
foundSomething = true;
tp.append(Message.fromKey("info-setRegionTeleport").replacements(rent));
}
if(foundSomething) {
tp.append(".");
tp.send(sender);
}
// Signs
List<String> signLocations = new ArrayList<>();
for(Location location : rent.getSignsFeature().getSignLocations()) {
signLocations.add(Message.fromKey("info-regionSignLocation").replacements(location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()).getPlain());
}
if(!signLocations.isEmpty()) {
plugin.messageNoPrefix(sender, "info-regionSigns", Utils.createCommaSeparatedList(signLocations));
}
// Groups
if(sender.hasPermission("areashop.groupinfo") && !rent.getGroupNames().isEmpty()) {
plugin.messageNoPrefix(sender, "info-regionGroups", Utils.createCommaSeparatedList(rent.getGroupNames()));
}
// Restoring
if(rent.isRestoreEnabled()) {
plugin.messageNoPrefix(sender, "info-regionRestoringRent", rent);
}
// Restrictions
if(!rent.isRented()) {
if(rent.restrictedToRegion()) {
plugin.messageNoPrefix(sender, "info-regionRestrictedRegionRent", rent);
} else if(rent.restrictedToWorld()) {
plugin.messageNoPrefix(sender, "info-regionRestrictedWorldRent", rent);
}
}
plugin.messageNoPrefix(sender, "info-regionFooterRent", rent);
} else if(buy != null) {
plugin.message(sender, "info-regionHeaderBuy", buy);
if(buy.isSold()) {
if(buy.isInResellingMode()) {
plugin.messageNoPrefix(sender, "info-regionReselling", buy);
plugin.messageNoPrefix(sender, "info-regionReselPrice", buy);
} else {
plugin.messageNoPrefix(sender, "info-regionBought", buy);
}
// Money back
if(!buy.getBooleanSetting("buy.sellDisabled")) {
if (SellCommand.canUse(sender, buy)) {
plugin.messageNoPrefix(sender, "info-regionMoneyBackBuyClick", buy);
if(rent != null) {
messageBridge.message(sender, "info-regionHeaderRent", rent);
if(rent.isRented()) {
messageBridge.messageNoPrefix(sender, "info-regionRented", rent);
messageBridge.messageNoPrefix(sender, "info-regionExtending", rent);
// Money back
if(UnrentCommand.canUse(sender, rent)) {
messageBridge.messageNoPrefix(sender, "info-regionMoneyBackRentClick", rent);
} else {
plugin.messageNoPrefix(sender, "info-regionMoneyBackBuy", buy);
messageBridge.messageNoPrefix(sender, "info-regionMoneyBackRent", rent);
}
// Friends
if(!rent.getFriendsFeature().getFriendNames().isEmpty()) {
String messagePart = "info-friend";
if(DelfriendCommand.canUse(sender, rent)) {
messagePart = "info-friendRemove";
}
messageBridge.messageNoPrefix(sender, "info-regionFriends", rent, Utils.combinedMessage(rent.getFriendsFeature().getFriendNames(), messagePart));
}
} else {
messageBridge.messageNoPrefix(sender, "info-regionCanBeRented", rent);
}
if(rent.getLandlordName() != null) {
messageBridge.messageNoPrefix(sender, "info-regionLandlord", rent);
}
// Maximum extends
if(rent.getMaxExtends() != -1) {
if(rent.getMaxExtends() == 0) {
messageBridge.messageNoPrefix(sender, "info-regionNoExtending", rent);
} else if(rent.isRented()) {
messageBridge.messageNoPrefix(sender, "info-regionExtendsLeft", rent);
} else {
messageBridge.messageNoPrefix(sender, "info-regionMaxExtends", rent);
}
}
// Friends
if(!buy.getFriendsFeature().getFriendNames().isEmpty()) {
String messagePart = "info-friend";
if(DelfriendCommand.canUse(sender, buy)) {
messagePart = "info-friendRemove";
}
plugin.messageNoPrefix(sender, "info-regionFriends", buy, Utils.combinedMessage(buy.getFriendsFeature().getFriendNames(), messagePart));
// If maxExtends is zero it does not make sense to show this message
if(rent.getMaxRentTime() != -1 && rent.getMaxExtends() != 0) {
messageBridge.messageNoPrefix(sender, "info-regionMaxRentTime", rent);
}
if(rent.getInactiveTimeUntilUnrent() != -1) {
messageBridge.messageNoPrefix(sender, "info-regionInactiveUnrent", rent);
}
// Teleport
Message tp = Message.fromKey("info-prefix");
boolean foundSomething = false;
if(TeleportCommand.canUse(sender, rent)) {
foundSomething = true;
tp.append(Message.fromKey("info-regionTeleport").replacements(rent));
}
if(SetteleportCommand.canUse(sender, rent)) {
if(foundSomething) {
tp.append(", ");
}
foundSomething = true;
tp.append(Message.fromKey("info-setRegionTeleport").replacements(rent));
}
} else {
plugin.messageNoPrefix(sender, "info-regionCanBeBought", buy);
}
if(buy.getLandlord() != null) {
plugin.messageNoPrefix(sender, "info-regionLandlord", buy);
}
if(buy.getInactivityThresholdMillis() != -1) {
plugin.messageNoPrefix(sender, "info-regionInactiveSell", buy);
}
// Teleport
Message tp = Message.fromKey("info-prefix");
boolean foundSomething = false;
if(TeleportCommand.canUse(sender, buy)) {
foundSomething = true;
tp.append(Message.fromKey("info-regionTeleport").replacements(buy));
}
if(SetteleportCommand.canUse(sender, buy)) {
if(foundSomething) {
tp.append(", ");
tp.append(".");
tp.send(sender);
}
foundSomething = true;
tp.append(Message.fromKey("info-setRegionTeleport").replacements(buy));
}
if(foundSomething) {
tp.append(".");
tp.send(sender);
}
// Signs
List<String> signLocations = new ArrayList<>();
for(Location location : buy.getSignsFeature().getSignLocations()) {
signLocations.add(Message.fromKey("info-regionSignLocation").replacements(location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()).getPlain());
}
if(!signLocations.isEmpty()) {
plugin.messageNoPrefix(sender, "info-regionSigns", Utils.createCommaSeparatedList(signLocations));
}
// Groups
if(sender.hasPermission("areashop.groupinfo") && !buy.getGroupNames().isEmpty()) {
plugin.messageNoPrefix(sender, "info-regionGroups", Utils.createCommaSeparatedList(buy.getGroupNames()));
}
// Restoring
if(buy.isRestoreEnabled()) {
plugin.messageNoPrefix(sender, "info-regionRestoringBuy", buy);
}
// Restrictions
if(!buy.isSold()) {
if(buy.restrictedToRegion()) {
plugin.messageNoPrefix(sender, "info-regionRestrictedRegionBuy", buy);
} else if(buy.restrictedToWorld()) {
plugin.messageNoPrefix(sender, "info-regionRestrictedWorldBuy", buy);
// Signs
List<String> signLocations = new ArrayList<>();
for(BlockPosition location : rent.getSignsFeature().signManager().allSignLocations()) {
signLocations.add(Message.fromKey("info-regionSignLocation").replacements(location.getWorld().getName(), location.getX(), location.getY(), location.getZ()).getPlain());
}
if(!signLocations.isEmpty()) {
messageBridge.messageNoPrefix(sender, "info-regionSigns", Utils.createCommaSeparatedList(signLocations));
}
// Groups
if(sender.hasPermission("areashop.groupinfo") && !rent.getGroupNames().isEmpty()) {
messageBridge.messageNoPrefix(sender, "info-regionGroups", Utils.createCommaSeparatedList(rent.getGroupNames()));
}
// Restoring
if(rent.isRestoreEnabled()) {
messageBridge.messageNoPrefix(sender, "info-regionRestoringRent", rent);
}
// Restrictions
if(!rent.isRented()) {
if(rent.restrictedToRegion()) {
messageBridge.messageNoPrefix(sender, "info-regionRestrictedRegionRent", rent);
} else if(rent.restrictedToWorld()) {
messageBridge.messageNoPrefix(sender, "info-regionRestrictedWorldRent", rent);
}
}
messageBridge.messageNoPrefix(sender, "info-regionFooterRent", rent);
} else if(buy != null) {
messageBridge.message(sender, "info-regionHeaderBuy", buy);
if(buy.isSold()) {
if(buy.isInResellingMode()) {
messageBridge.messageNoPrefix(sender, "info-regionReselling", buy);
messageBridge.messageNoPrefix(sender, "info-regionReselPrice", buy);
} else {
messageBridge.messageNoPrefix(sender, "info-regionBought", buy);
}
// Money back
if(!buy.getBooleanSetting("buy.sellDisabled")) {
if (SellCommand.canUse(sender, buy)) {
messageBridge.messageNoPrefix(sender, "info-regionMoneyBackBuyClick", buy);
} else {
messageBridge.messageNoPrefix(sender, "info-regionMoneyBackBuy", buy);
}
}
// Friends
if(!buy.getFriendsFeature().getFriendNames().isEmpty()) {
String messagePart = "info-friend";
if(DelfriendCommand.canUse(sender, buy)) {
messagePart = "info-friendRemove";
}
messageBridge.messageNoPrefix(sender, "info-regionFriends", buy, Utils.combinedMessage(buy.getFriendsFeature().getFriendNames(), messagePart));
}
} else {
messageBridge.messageNoPrefix(sender, "info-regionCanBeBought", buy);
}
if(buy.getLandlord() != null) {
messageBridge.messageNoPrefix(sender, "info-regionLandlord", buy);
}
if(buy.getInactiveTimeUntilSell() != -1) {
messageBridge.messageNoPrefix(sender, "info-regionInactiveSell", buy);
}
// Teleport
Message tp = Message.fromKey("info-prefix");
boolean foundSomething = false;
if(TeleportCommand.canUse(sender, buy)) {
foundSomething = true;
tp.append(Message.fromKey("info-regionTeleport").replacements(buy));
}
if(SetteleportCommand.canUse(sender, buy)) {
if(foundSomething) {
tp.append(", ");
}
foundSomething = true;
tp.append(Message.fromKey("info-setRegionTeleport").replacements(buy));
}
if(foundSomething) {
tp.append(".");
tp.send(sender);
}
// Signs
List<String> signLocations = new ArrayList<>();
for(BlockPosition location : buy.getSignsFeature().signManager().allSignLocations()) {
signLocations.add(Message.fromKey("info-regionSignLocation").replacements(location.getWorld().getName(), location.getX(), location.getY(), location.getZ()).getPlain());
}
if(!signLocations.isEmpty()) {
messageBridge.messageNoPrefix(sender, "info-regionSigns", Utils.createCommaSeparatedList(signLocations));
}
// Groups
if(sender.hasPermission("areashop.groupinfo") && !buy.getGroupNames().isEmpty()) {
messageBridge.messageNoPrefix(sender, "info-regionGroups", Utils.createCommaSeparatedList(buy.getGroupNames()));
}
// Restoring
if(buy.isRestoreEnabled()) {
messageBridge.messageNoPrefix(sender, "info-regionRestoringBuy", buy);
}
// Restrictions
if(!buy.isSold()) {
if(buy.restrictedToRegion()) {
messageBridge.messageNoPrefix(sender, "info-regionRestrictedRegionBuy", buy);
} else if(buy.restrictedToWorld()) {
messageBridge.messageNoPrefix(sender, "info-regionRestrictedWorldBuy", buy);
}
}
messageBridge.messageNoPrefix(sender, "info-regionFooterBuy", buy);
}
plugin.messageNoPrefix(sender, "info-regionFooterBuy", buy);
} else {
messageBridge.message(sender, "info-regionHelp");
}
} else {
plugin.message(sender, "info-help");
messageBridge.message(sender, "info-help");
}
} else {
plugin.message(sender, "info-help");
messageBridge.message(sender, "info-help");
}
}
@@ -443,8 +459,8 @@ public class InfoCommand extends CommandAreaShop {
result.add(player.getName());
}
} else if(start[2].equalsIgnoreCase("region")) {
result.addAll(plugin.getFileManager().getBuyNames());
result.addAll(plugin.getFileManager().getRentNames());
result.addAll(fileManager.getBuyNames());
result.addAll(fileManager.getRentNames());
}
}
return result;
@@ -1,5 +1,10 @@
package me.wiefferink.areashop.commands;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.SignLinkerManager;
import me.wiefferink.interactivemessenger.processing.Message;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
@@ -8,10 +13,17 @@ import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;
@Singleton
public class LinksignsCommand extends CommandAreaShop {
@Inject
private SignLinkerManager signLinkerManager;
@Inject
private AreaShop plugin;
@Inject
private MessageBridge messageBridge;
@Override
public String getCommandStart() {
return "areashop linksigns";
@@ -28,17 +40,17 @@ public class LinksignsCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.linksigns")) {
plugin.message(sender, "linksigns-noPermission");
messageBridge.message(sender, "linksigns-noPermission");
return;
}
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
messageBridge.message(sender, "cmd-onlyByPlayer");
return;
}
Player player = (Player)sender;
if(plugin.getSignlinkerManager().isInSignLinkMode(player)) {
plugin.getSignlinkerManager().exitSignLinkMode(player);
if(signLinkerManager.isInSignLinkMode(player)) {
signLinkerManager.exitSignLinkMode(player);
} else {
// Get the profile
String profile = null;
@@ -48,16 +60,19 @@ public class LinksignsCommand extends CommandAreaShop {
if(signProfilesSection != null) {
Set<String> profiles = signProfilesSection.getKeys(false);
if(!profiles.contains(profile)) {
StringJoiner joiner = new StringJoiner(", ");
ArrayList<String> message = new ArrayList<>();
for(String p : profiles) {
Message.fromKey("addsign-profile").replacements(p).get().forEach(joiner::add);
if(!message.isEmpty()) {
message.add(", ");
}
message.addAll(Message.fromKey("addsign-profile").replacements(p).get());
}
plugin.message(sender, "addsign-wrongProfile", joiner.toString());
messageBridge.message(sender, "addsign-wrongProfile", Message.fromList(message));
return;
}
}
}
plugin.getSignlinkerManager().enterSignLinkMode(player, profile);
signLinkerManager.enterSignLinkMode(player, profile);
}
}
@@ -1,5 +1,7 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
@@ -9,13 +11,21 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Singleton
public class MeCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop me";
@@ -32,13 +42,13 @@ public class MeCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.me")) {
plugin.message(sender, "me-noPermission");
messageBridge.message(sender, "me-noPermission");
return;
}
OfflinePlayer player = null;
if(!(sender instanceof Player)) {
if(args.length <= 1) {
plugin.message(sender, "me-notAPlayer");
messageBridge.message(sender, "me-notAPlayer");
return;
}
} else {
@@ -46,31 +56,31 @@ public class MeCommand extends CommandAreaShop {
}
if(args.length > 1) {
player = Bukkit.getOfflinePlayer(args[1]);
if(player == null) {
plugin.message(sender, "me-noPlayer", args[1]);
if(!player.hasPlayedBefore()) {
messageBridge.message(sender, "me-noPlayer", args[1]);
return;
}
}
if(player == null) {
if(!player.hasPlayedBefore()) {
return;
}
// Get the regions owned by the player
Set<RentRegion> rentRegions = new HashSet<>();
for(RentRegion region : plugin.getFileManager().getRents()) {
for(RentRegion region : fileManager.getRentsRef()) {
if(region.isOwner(player)) {
rentRegions.add(region);
}
}
Set<BuyRegion> buyRegions = new HashSet<>();
for(BuyRegion region : plugin.getFileManager().getBuys()) {
for(BuyRegion region : fileManager.getBuysRef()) {
if(region.isOwner(player)) {
buyRegions.add(region);
}
}
// Get the regions the player is added as friend
Set<GeneralRegion> friendRegions = new HashSet<>();
for(GeneralRegion region : plugin.getFileManager().getRegions()) {
for(GeneralRegion region : fileManager.getRegionsRef()) {
if(region.getFriendsFeature().getFriends().contains(player.getUniqueId())) {
friendRegions.add(region);
}
@@ -79,28 +89,28 @@ public class MeCommand extends CommandAreaShop {
// Send messages
boolean foundSome = !rentRegions.isEmpty() || !buyRegions.isEmpty() || !friendRegions.isEmpty();
if(foundSome) {
plugin.message(sender, "me-header", player.getName());
messageBridge.message(sender, "me-header", player.getName());
}
if(!rentRegions.isEmpty()) {
for(RentRegion region : rentRegions) {
plugin.messageNoPrefix(sender, "me-rentLine", region);
messageBridge.messageNoPrefix(sender, "me-rentLine", region);
}
}
if(!buyRegions.isEmpty()) {
for(BuyRegion region : buyRegions) {
plugin.messageNoPrefix(sender, "me-buyLine", region);
messageBridge.messageNoPrefix(sender, "me-buyLine", region);
}
}
if(!friendRegions.isEmpty()) {
for(GeneralRegion region : friendRegions) {
plugin.messageNoPrefix(sender, "me-friendLine", region);
messageBridge.messageNoPrefix(sender, "me-friendLine", region);
}
}
if(!foundSome) {
plugin.message(sender, "me-nothing", player.getName());
messageBridge.message(sender, "me-nothing", player.getName());
} else {
plugin.messageNoPrefix(sender, "me-clickHint");
messageBridge.messageNoPrefix(sender, "me-clickHint");
}
}
@@ -1,5 +1,6 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.tools.Utils;
import me.wiefferink.interactivemessenger.processing.Message;
import org.apache.commons.lang.StringUtils;
@@ -7,11 +8,17 @@ import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class MessageCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Override
public String getCommandStart() {
return "areashop message";
@@ -26,18 +33,18 @@ public class MessageCommand extends CommandAreaShop {
@Override
public void execute(final CommandSender sender, final String[] args) {
if(!sender.hasPermission("areashop.message")) {
plugin.message(sender, "message-noPermission");
messageBridge.message(sender, "message-noPermission");
return;
}
if(args.length < 3) {
plugin.message(sender, "message-help");
messageBridge.message(sender, "message-help");
return;
}
Player player = Bukkit.getPlayer(args[1]);
if(player == null) {
plugin.message(sender, "message-notOnline", args[1]);
messageBridge.message(sender, "message-notOnline", args[1]);
return;
}
@@ -1,9 +1,20 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.MessageBridge;
import org.bukkit.command.CommandSender;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public class ReloadCommand extends CommandAreaShop {
@Inject
private AreaShop plugin;
@Inject
private MessageBridge messageBridge;
@Override
public String getCommandStart() {
return "areashop reload";
@@ -23,7 +34,7 @@ public class ReloadCommand extends CommandAreaShop {
// Reload the configuration files and update all region flags/signs
plugin.reload(sender);
} else {
plugin.message(sender, "reload-noPermission");
messageBridge.message(sender, "reload-noPermission");
}
}
}
@@ -1,15 +1,25 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class RentCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop rent";
@@ -26,18 +36,18 @@ public class RentCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.rent")) {
plugin.message(sender, "rent-noPermission");
messageBridge.message(sender, "rent-noPermission");
return;
}
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
messageBridge.message(sender, "cmd-onlyByPlayer");
return;
}
Player player = (Player)sender;
if(args.length > 1 && args[1] != null) {
RentRegion rent = plugin.getFileManager().getRent(args[1]);
RentRegion rent = fileManager.getRent(args[1]);
if(rent == null) {
plugin.message(sender, "rent-notRentable", args[1]);
messageBridge.message(sender, "rent-notRentable", args[1]);
} else {
rent.rent(player);
}
@@ -45,9 +55,9 @@ public class RentCommand extends CommandAreaShop {
// get the region by location
List<RentRegion> regions = Utils.getImportantRentRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
messageBridge.message(sender, "cmd-noRegionsAtLocation");
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
messageBridge.message(sender, "cmd-moreRegionsAtLocation");
} else {
regions.get(0).rent(player);
}
@@ -58,7 +68,7 @@ public class RentCommand extends CommandAreaShop {
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(RentRegion region : plugin.getFileManager().getRents()) {
for(RentRegion region : fileManager.getRentsRef()) {
if(!region.isRented()) {
result.add(region.getName());
}
@@ -1,15 +1,25 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class ResellCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop resell";
@@ -26,24 +36,24 @@ public class ResellCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.resell") && !sender.hasPermission("areashop.resellall")) {
plugin.message(sender, "resell-noPermissionOther");
messageBridge.message(sender, "resell-noPermissionOther");
return;
}
if(args.length <= 1) {
plugin.message(sender, "resell-help");
messageBridge.message(sender, "resell-help");
return;
}
double price;
try {
price = Double.parseDouble(args[1]);
} catch(NumberFormatException e) {
plugin.message(sender, "resell-wrongPrice", args[1]);
messageBridge.message(sender, "resell-wrongPrice", args[1]);
return;
}
if(price < 0) {
plugin.message(sender, "resell-wrongPrice", args[1]);
messageBridge.message(sender, "resell-wrongPrice", args[1]);
return;
}
@@ -53,53 +63,53 @@ public class ResellCommand extends CommandAreaShop {
// get the region by location
List<BuyRegion> regions = Utils.getImportantBuyRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
messageBridge.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
messageBridge.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
buy = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
messageBridge.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
buy = plugin.getFileManager().getBuy(args[2]);
buy = fileManager.getBuy(args[2]);
if(buy == null) {
plugin.message(sender, "resell-notRegistered", args[2]);
messageBridge.message(sender, "resell-notRegistered", args[2]);
return;
}
}
if(buy == null) {
plugin.message(sender, "cmd-noRegionsAtLocation");
messageBridge.message(sender, "cmd-noRegionsAtLocation");
return;
}
if(!buy.isSold()) {
plugin.message(sender, "resell-notBought", buy);
messageBridge.message(sender, "resell-notBought", buy);
return;
}
if(sender.hasPermission("areashop.resellall")) {
buy.enableReselling(price);
buy.update();
plugin.message(sender, "resell-success", buy);
messageBridge.message(sender, "resell-success", buy);
} else if(sender.hasPermission("areashop.resell") && sender instanceof Player) {
if(!buy.isTransactionHolder((Player)sender)) {
plugin.message(sender, "resell-noPermissionOther", buy);
if(!buy.isOwner((Player)sender)) {
messageBridge.message(sender, "resell-noPermissionOther", buy);
return;
}
if(buy.getBooleanSetting("buy.resellDisabled")) {
plugin.message(sender, "resell-disabled", buy);
messageBridge.message(sender, "resell-disabled", buy);
return;
}
buy.enableReselling(price);
buy.update();
plugin.message(sender, "resell-success", buy);
messageBridge.message(sender, "resell-success", buy);
} else {
plugin.message(sender, "resell-noPermission", buy);
messageBridge.message(sender, "resell-noPermission", buy);
}
}
@@ -107,7 +117,7 @@ public class ResellCommand extends CommandAreaShop {
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 3) {
for(BuyRegion region : plugin.getFileManager().getBuys()) {
for(BuyRegion region : fileManager.getBuysRef()) {
if(region.isSold() && !region.isInResellingMode()) {
result.add(region.getName());
}
@@ -1,17 +1,27 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Singleton
public class SchematiceventCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop schemevent";
@@ -28,21 +38,21 @@ public class SchematiceventCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.schematicevents")) {
plugin.message(sender, "schemevent-noPermission");
messageBridge.message(sender, "schemevent-noPermission");
return;
}
if(args.length < 3 || args[1] == null || args[2] == null) {
plugin.message(sender, "schemevent-help");
messageBridge.message(sender, "schemevent-help");
return;
}
GeneralRegion region = plugin.getFileManager().getRegion(args[1]);
GeneralRegion region = fileManager.getRegion(args[1]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[1]);
messageBridge.message(sender, "cmd-notRegistered", args[1]);
return;
}
if(region.getRegion() == null) {
plugin.message(sender, "general-noRegion", region);
messageBridge.message(sender, "general-noRegion", region);
return;
}
GeneralRegion.RegionEvent event = null;
@@ -58,21 +68,21 @@ public class SchematiceventCommand extends CommandAreaShop {
for(GeneralRegion.RegionEvent value : GeneralRegion.RegionEvent.values()) {
values.add(value.getValue().toLowerCase());
}
plugin.message(sender, "schemevent-wrongEvent", args[2], Utils.createCommaSeparatedList(values), region);
messageBridge.message(sender, "schemevent-wrongEvent", args[2], Utils.createCommaSeparatedList(values), region);
return;
}
region.handleSchematicEvent(event);
region.update();
plugin.message(sender, "schemevent-success", args[2], region);
messageBridge.message(sender, "schemevent-success", args[2], region);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
result.addAll(plugin.getFileManager().getRegionNames());
result.addAll(fileManager.getRegionNames());
} else if(toComplete == 3) {
GeneralRegion region = plugin.getFileManager().getRegion(start[2]);
GeneralRegion region = fileManager.getRegion(start[2]);
if(region != null) {
if(region instanceof RentRegion) {
result.addAll(Arrays.asList("created", "deleted", "rented", "unrented"));
@@ -1,98 +1,106 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.TransactionalRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class SellCommand extends CommandAreaShop {
/**
* Check if a person can sell the region.
*
* @param person The person to check
* @param region The region to check for
* @return true if the person can sell it, otherwise false
*/
public static boolean canUse(CommandSender person, GeneralRegion region) {
if (person.hasPermission("areashop.sell")) {
return true;
}
if (person instanceof Player && region instanceof TransactionalRegion) {
Player player = (Player) person;
return ((TransactionalRegion) region).isTransactionHolder(player) && person.hasPermission("areashop.sellown");
}
return false;
}
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop sell";
}
@Override
public String getCommandStart() {
return "areashop sell";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.sell") || target.hasPermission("areashop.sellown")) {
return "help-sell";
}
return null;
}
@Override
public String getHelp(CommandSender target) {
if (target.hasPermission("areashop.sell") || target.hasPermission("areashop.sellown")) {
return "help-sell";
}
return null;
}
/**
* Check if a person can sell the region.
* @param person The person to check
* @param region The region to check for
* @return true if the person can sell it, otherwise false
*/
public static boolean canUse(CommandSender person, GeneralRegion region) {
if(person.hasPermission("areashop.sell")) {
return true;
}
if(person instanceof Player) {
Player player = (Player)person;
return region.isOwner(player) && person.hasPermission("areashop.sellown");
}
return false;
}
@Override
public void execute(CommandSender sender, String[] args) {
if (!sender.hasPermission("areashop.sell") && !sender.hasPermission("areashop.sellown")) {
plugin.message(sender, "sell-noPermission");
return;
}
BuyRegion buy;
if (args.length <= 1) {
if (sender instanceof Player) {
// get the region by location
List<BuyRegion> regions = Utils.getImportantBuyRegions(((Player) sender).getLocation());
if (regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if (regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
buy = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
buy = plugin.getFileManager().getBuy(args[1]);
}
if (buy == null) {
plugin.message(sender, "sell-notRegistered");
return;
}
if (!buy.isSold()) {
plugin.message(sender, "sell-notBought", buy);
return;
}
buy.sell(true, sender);
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.sell") && !sender.hasPermission("areashop.sellown")) {
messageBridge.message(sender, "sell-noPermission");
return;
}
BuyRegion buy;
if(args.length <= 1) {
if(sender instanceof Player) {
// get the region by location
List<BuyRegion> regions = Utils.getImportantBuyRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
messageBridge.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
messageBridge.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
buy = regions.get(0);
}
} else {
messageBridge.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
buy = fileManager.getBuy(args[1]);
}
if(buy == null) {
messageBridge.message(sender, "sell-notRegistered");
return;
}
if(!buy.isSold()) {
messageBridge.message(sender, "sell-notBought", buy);
return;
}
buy.sell(true, sender);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if (toComplete == 2) {
for (BuyRegion region : plugin.getFileManager().getBuys()) {
if (region.isSold()) {
result.add(region.getName());
}
}
}
return result;
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(BuyRegion region : fileManager.getBuysRef()) {
if(region.isSold()) {
result.add(region.getName());
}
}
}
return result;
}
}
@@ -1,15 +1,28 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class SetdurationCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Inject
private Plugin plugin;
@Override
public String getCommandStart() {
return "areashop setduration";
@@ -26,11 +39,11 @@ public class SetdurationCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.setduration") && (!sender.hasPermission("areashop.setduration.landlord") && sender instanceof Player)) {
plugin.message(sender, "setduration-noPermission");
messageBridge.message(sender, "setduration-noPermission");
return;
}
if(args.length < 3 || args[1] == null || args[2] == null) {
plugin.message(sender, "setduration-help");
messageBridge.message(sender, "setduration-help");
return;
}
int regionArgument = 3;
@@ -43,48 +56,48 @@ public class SetdurationCommand extends CommandAreaShop {
// get the region by location
List<RentRegion> regions = Utils.getImportantRentRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
messageBridge.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
messageBridge.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
rent = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
messageBridge.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
rent = plugin.getFileManager().getRent(args[regionArgument]);
rent = fileManager.getRent(args[regionArgument]);
}
if(rent == null) {
plugin.message(sender, "setduration-notRegistered", args[regionArgument]);
messageBridge.message(sender, "setduration-notRegistered", args[regionArgument]);
return;
}
if(!sender.hasPermission("areashop.setduration") && !(sender instanceof Player && rent.isLandlord(((Player)sender).getUniqueId()))) {
plugin.message(sender, "setduration-noLandlord", rent);
messageBridge.message(sender, "setduration-noLandlord", rent);
return;
}
if("default".equalsIgnoreCase(args[1]) || "reset".equalsIgnoreCase(args[1])) {
rent.setDuration(null);
rent.update();
plugin.message(sender, "setduration-successRemoved", rent);
messageBridge.message(sender, "setduration-successRemoved", rent);
return;
}
try {
Integer.parseInt(args[1]);
} catch(NumberFormatException e) {
plugin.message(sender, "setduration-wrongAmount", args[1], rent);
messageBridge.message(sender, "setduration-wrongAmount", args[1], rent);
return;
}
if(!Utils.checkTimeFormat(args[1] + " " + args[2])) {
plugin.message(sender, "setduration-wrongFormat", args[1] + " " + args[2], rent);
messageBridge.message(sender, "setduration-wrongFormat", args[1] + " " + args[2], rent);
return;
}
rent.setDuration(args[1] + " " + args[2]);
rent.update();
plugin.message(sender, "setduration-success", rent);
messageBridge.message(sender, "setduration-success", rent);
}
@Override
@@ -97,7 +110,7 @@ public class SetdurationCommand extends CommandAreaShop {
result.addAll(plugin.getConfig().getStringList("months"));
result.addAll(plugin.getConfig().getStringList("years"));
} else if(toComplete == 4) {
result = plugin.getFileManager().getRentNames();
result = fileManager.getRentNames();
}
return result;
}
@@ -1,5 +1,7 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Bukkit;
@@ -7,11 +9,19 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class SetlandlordCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop setlandlord";
@@ -28,11 +38,11 @@ public class SetlandlordCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.setlandlord")) {
plugin.message(sender, "setlandlord-noPermission");
messageBridge.message(sender, "setlandlord-noPermission");
return;
}
if(args.length < 2) {
plugin.message(sender, "setlandlord-help");
messageBridge.message(sender, "setlandlord-help");
return;
}
@SuppressWarnings("deprecation")
@@ -43,23 +53,23 @@ public class SetlandlordCommand extends CommandAreaShop {
// get the region by location
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
messageBridge.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
messageBridge.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
messageBridge.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
region = fileManager.getRegion(args[2]);
}
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[2]);
messageBridge.message(sender, "cmd-notRegistered", args[2]);
return;
}
String playerName = player.getName();
@@ -68,7 +78,7 @@ public class SetlandlordCommand extends CommandAreaShop {
}
region.setLandlord(player.getUniqueId(), playerName);
region.update();
plugin.message(sender, "setlandlord-success", playerName, region);
messageBridge.message(sender, "setlandlord-success", playerName, region);
}
@Override
@@ -79,7 +89,7 @@ public class SetlandlordCommand extends CommandAreaShop {
result.add(player.getName());
}
} else if(toComplete == 3) {
result.addAll(plugin.getFileManager().getRegionNames());
result.addAll(fileManager.getRegionNames());
}
return result;
}
@@ -1,22 +1,31 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.regions.TransactionalRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;
@Singleton
public class SetownerCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop setowner";
@@ -33,12 +42,12 @@ public class SetownerCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.setownerrent") && !sender.hasPermission("areashop.setownerbuy")) {
plugin.message(sender, "setowner-noPermission");
messageBridge.message(sender, "setowner-noPermission");
return;
}
GeneralRegion region;
if(args.length < 2) {
plugin.message(sender, "setowner-help");
messageBridge.message(sender, "setowner-help");
return;
}
if(args.length == 2) {
@@ -46,69 +55,68 @@ public class SetownerCommand extends CommandAreaShop {
// get the region by location
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
messageBridge.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
messageBridge.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
messageBridge.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
region = fileManager.getRegion(args[2]);
}
if(region == null) {
plugin.message(sender, "setowner-notRegistered");
messageBridge.message(sender, "setowner-notRegistered");
return;
}
if(region instanceof RentRegion && !sender.hasPermission("areashop.setownerrent")) {
plugin.message(sender, "setowner-noPermissionRent", region);
messageBridge.message(sender, "setowner-noPermissionRent", region);
return;
}
if(region instanceof BuyRegion && !sender.hasPermission("areashop.setownerbuy")) {
plugin.message(sender, "setowner-noPermissionBuy", region);
messageBridge.message(sender, "setowner-noPermissionBuy", region);
return;
}
UUID uuid = null;
@SuppressWarnings("deprecation")
OfflinePlayer player = Bukkit.getOfflinePlayer(args[1]);
if(player.hasPlayedBefore()) {
if(player != null) {
uuid = player.getUniqueId();
}
if(uuid == null) {
plugin.message(sender, "setowner-noPlayer", args[1], region);
messageBridge.message(sender, "setowner-noPlayer", args[1], region);
return;
}
if(region instanceof RentRegion) {
RentRegion rent = (RentRegion)region;
if(rent.isTransactionHolder(uuid)) {
if(rent.isRenter(uuid)) {
// extend
rent.setRentedUntil(rent.getRentedUntil() + rent.getDuration());
plugin.message(sender, "setowner-succesRentExtend", region);
rent.setRenter(uuid);
messageBridge.message(sender, "setowner-succesRentExtend", region);
} else {
// change
if(!rent.isRented()) {
rent.setRentedUntil(System.currentTimeMillis() + rent.getDuration());
rent.setRentedUntil(Calendar.getInstance().getTimeInMillis() + rent.getDuration());
}
plugin.message(sender, "setowner-succesRent", region);
rent.setRenter(uuid);
messageBridge.message(sender, "setowner-succesRent", region);
}
rent.setTransactionHolder(uuid);
}
if(region instanceof BuyRegion) {
BuyRegion buy = (BuyRegion)region;
buy.setTransactionHolder(uuid);
plugin.message(sender, "setowner-succesBuy", region);
}
if (region instanceof TransactionalRegion) {
region.getFriendsFeature().deleteFriend(((TransactionalRegion) region).getTransactionHolder(), null);
buy.setBuyer(uuid);
messageBridge.message(sender, "setowner-succesBuy", region);
}
region.getFriendsFeature().deleteFriend(region.getOwner(), null);
region.update();
region.saveRequired();
}
@@ -121,7 +129,7 @@ public class SetownerCommand extends CommandAreaShop {
result.add(player.getName());
}
} else if(toComplete == 3) {
result.addAll(plugin.getFileManager().getRegionNames());
result.addAll(fileManager.getRegionNames());
}
return result;
}
@@ -1,5 +1,7 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
@@ -7,11 +9,19 @@ import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class SetpriceCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop setprice";
@@ -28,11 +38,11 @@ public class SetpriceCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.setprice") && (!sender.hasPermission("areashop.setprice.landlord") && sender instanceof Player)) {
plugin.message(sender, "setprice-noPermission");
messageBridge.message(sender, "setprice-noPermission");
return;
}
if(args.length < 2 || args[1] == null) {
plugin.message(sender, "setprice-help");
messageBridge.message(sender, "setprice-help");
return;
}
GeneralRegion region;
@@ -41,52 +51,52 @@ public class SetpriceCommand extends CommandAreaShop {
// get the region by location
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
messageBridge.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
messageBridge.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
messageBridge.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
region = fileManager.getRegion(args[2]);
}
if(region == null) {
plugin.message(sender, "setprice-notRegistered", args[2]);
messageBridge.message(sender, "setprice-notRegistered", args[2]);
return;
}
if(!sender.hasPermission("areashop.setprice") && !(sender instanceof Player && region.isLandlord(((Player)sender).getUniqueId()))) {
plugin.message(sender, "setprice-noLandlord", region);
messageBridge.message(sender, "setprice-noLandlord", region);
return;
}
if("default".equalsIgnoreCase(args[1]) || "reset".equalsIgnoreCase(args[1])) {
if(region instanceof RentRegion) {
((RentRegion)region).setPrice(0);
((RentRegion)region).setPrice(null);
} else if(region instanceof BuyRegion) {
((BuyRegion)region).setPrice(0);
((BuyRegion)region).setPrice(null);
}
region.update();
plugin.message(sender, "setprice-successRemoved", region);
messageBridge.message(sender, "setprice-successRemoved", region);
return;
}
double price;
try {
price = Double.parseDouble(args[1]);
} catch(NumberFormatException e) {
plugin.message(sender, "setprice-wrongPrice", args[1], region);
messageBridge.message(sender, "setprice-wrongPrice", args[1], region);
return;
}
if(region instanceof RentRegion) {
((RentRegion)region).setPrice(price);
plugin.message(sender, "setprice-successRent", region);
messageBridge.message(sender, "setprice-successRent", region);
} else if(region instanceof BuyRegion) {
((BuyRegion)region).setPrice(price);
plugin.message(sender, "setprice-successBuy", region);
messageBridge.message(sender, "setprice-successBuy", region);
}
region.update();
}
@@ -95,7 +105,7 @@ public class SetpriceCommand extends CommandAreaShop {
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 3) {
result = plugin.getFileManager().getRegionNames();
result = fileManager.getRegionNames();
}
return result;
}
@@ -1,13 +1,26 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.GeneralRegion;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class SetrestoreCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Inject
private Plugin plugin;
@Override
public String getCommandStart() {
return "areashop setrestore";
@@ -24,16 +37,16 @@ public class SetrestoreCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.setrestore")) {
plugin.message(sender, "setrestore-noPermission");
messageBridge.message(sender, "setrestore-noPermission");
return;
}
if(args.length <= 2 || args[1] == null || args[2] == null) {
plugin.message(sender, "setrestore-help");
messageBridge.message(sender, "setrestore-help");
return;
}
GeneralRegion region = plugin.getFileManager().getRegion(args[1]);
GeneralRegion region = fileManager.getRegion(args[1]);
if(region == null) {
plugin.message(sender, "setrestore-notRegistered", args[1]);
messageBridge.message(sender, "setrestore-notRegistered", args[1]);
return;
}
Boolean value = null;
@@ -49,9 +62,9 @@ public class SetrestoreCommand extends CommandAreaShop {
}
if(args.length > 3) {
region.setSchematicProfile(args[3]);
plugin.message(sender, "setrestore-successProfile", valueString, args[3], region);
messageBridge.message(sender, "setrestore-successProfile", valueString, args[3], region);
} else {
plugin.message(sender, "setrestore-success", valueString, region);
messageBridge.message(sender, "setrestore-success", valueString, region);
}
region.update();
}
@@ -60,7 +73,7 @@ public class SetrestoreCommand extends CommandAreaShop {
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 2) {
result = plugin.getFileManager().getRegionNames();
result = fileManager.getRegionNames();
} else if(toComplete == 3) {
result.add("true");
result.add("false");
@@ -1,6 +1,8 @@
package me.wiefferink.areashop.commands;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
@@ -8,11 +10,19 @@ import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class SetteleportCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop settp";
@@ -44,11 +54,11 @@ public class SetteleportCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.setteleport") && !sender.hasPermission("areashop.setteleportall")) {
plugin.message(sender, "setteleport-noPermission");
messageBridge.message(sender, "setteleport-noPermission");
return;
}
if(!(sender instanceof Player)) {
plugin.message(sender, "onlyByPlayer");
messageBridge.message(sender, "onlyByPlayer");
return;
}
Player player = (Player)sender;
@@ -57,22 +67,22 @@ public class SetteleportCommand extends CommandAreaShop {
// get the region by location
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
messageBridge.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
messageBridge.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
region = plugin.getFileManager().getRegion(args[1]);
region = fileManager.getRegion(args[1]);
}
boolean owner;
if(region == null) {
plugin.message(player, "setteleport-noRentOrBuy", args[1]);
messageBridge.message(player, "setteleport-noRentOrBuy", args[1]);
return;
}
if(region instanceof RentRegion) {
@@ -81,10 +91,10 @@ public class SetteleportCommand extends CommandAreaShop {
owner = player.getUniqueId().equals(((BuyRegion)region).getBuyer());
}
if(!player.hasPermission("areashop.setteleport")) {
plugin.message(player, "setteleport-noPermission", region);
messageBridge.message(player, "setteleport-noPermission", region);
return;
} else if(!owner && !player.hasPermission("areashop.setteleportall")) {
plugin.message(player, "setteleport-noPermissionOther", region);
messageBridge.message(player, "setteleport-noPermissionOther", region);
return;
}
@@ -92,23 +102,23 @@ public class SetteleportCommand extends CommandAreaShop {
if(args.length > 2 && args[2] != null && (args[2].equalsIgnoreCase("reset") || args[2].equalsIgnoreCase("yes") || args[2].equalsIgnoreCase("true"))) {
region.getTeleportFeature().setTeleport(null);
region.update();
plugin.message(player, "setteleport-reset", region);
messageBridge.message(player, "setteleport-reset", region);
return;
}
if(!player.hasPermission("areashop.setteleportoutsideregion") && (wgRegion == null || !wgRegion.contains(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()))) {
plugin.message(player, "setteleport-notInside", region);
messageBridge.message(player, "setteleport-notInside", region);
return;
}
region.getTeleportFeature().setTeleport(player.getLocation());
region.update();
plugin.message(player, "setteleport-success", region);
messageBridge.message(player, "setteleport-success", region);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
result.addAll(plugin.getFileManager().getRegionNames());
result.addAll(fileManager.getRegionNames());
} else if(toComplete == 3) {
result.add("reset");
}
@@ -3,26 +3,46 @@ package me.wiefferink.areashop.commands;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.events.ask.AddingRegionEvent;
import me.wiefferink.areashop.interfaces.WorldEditInterface;
import me.wiefferink.areashop.interfaces.WorldEditSelection;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.interfaces.WorldGuardInterface;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RegionFactory;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import me.wiefferink.interactivemessenger.processing.Message;
import org.bukkit.Location;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class StackCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Inject
private WorldEditInterface worldEditInterface;
@Inject
private WorldGuardInterface worldGuardInterface;
@Inject
private RegionFactory regionFactory;
@Inject
private Plugin plugin;
@Override
public String getCommandStart() {
return "areashop stack";
@@ -40,18 +60,18 @@ public class StackCommand extends CommandAreaShop {
public void execute(CommandSender sender, String[] args) {
// Check permission
if(!sender.hasPermission("areashop.stack")) {
plugin.message(sender, "stack-noPermission");
messageBridge.message(sender, "stack-noPermission");
return;
}
// Only from ingame
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
messageBridge.message(sender, "cmd-onlyByPlayer");
return;
}
final Player player = (Player)sender;
// Specify enough arguments
if(args.length < 5) {
plugin.message(sender, "stack-help");
messageBridge.message(sender, "stack-help");
return;
}
// Check amount
@@ -62,7 +82,7 @@ public class StackCommand extends CommandAreaShop {
// Incorrect number
}
if(tempAmount <= 0) {
plugin.message(player, "stack-wrongAmount", args[1]);
messageBridge.message(player, "stack-wrongAmount", args[1]);
return;
}
// Check gap
@@ -70,27 +90,27 @@ public class StackCommand extends CommandAreaShop {
try {
gap = Integer.parseInt(args[2]);
} catch(NumberFormatException e) {
plugin.message(player, "stack-wrongGap", args[2]);
messageBridge.message(player, "stack-wrongGap", args[2]);
return;
}
// Check region type
if(!"rent".equalsIgnoreCase(args[4]) && !"buy".equalsIgnoreCase(args[4])) {
plugin.message(sender, "stack-help");
messageBridge.message(sender, "stack-help");
return;
}
// Get WorldEdit selection
final WorldEditSelection selection = plugin.getWorldEditHandler().getPlayerSelection(player);
final WorldEditSelection selection = worldEditInterface.getPlayerSelection(player);
if(selection == null) {
plugin.message(player, "stack-noSelection");
messageBridge.message(player, "stack-noSelection");
return;
}
// Get or create group
RegionGroup group = null;
if(args.length > 5) {
group = plugin.getFileManager().getGroup(args[5]);
group = fileManager.getGroup(args[5]);
if(group == null) {
group = new RegionGroup(plugin, args[5]);
plugin.getFileManager().addGroup(group);
group = regionFactory.createRegionGroup(args[5]);
fileManager.addGroup(group);
}
}
// Get facing of the player (must be clearly one of the four directions to make sure it is no mistake)
@@ -101,7 +121,7 @@ public class StackCommand extends CommandAreaShop {
facing = BlockFace.UP;
}
if(!(facing == BlockFace.NORTH || facing == BlockFace.EAST || facing == BlockFace.SOUTH || facing == BlockFace.WEST || facing == BlockFace.UP || facing == BlockFace.DOWN)) {
plugin.message(player, "stack-unclearDirection", facing.toString().toLowerCase().replace('_', '-'));
messageBridge.message(player, "stack-unclearDirection", facing.toString().toLowerCase().replace('_', '-'));
return;
}
Vector shift = new Vector(0, 0, 0);
@@ -138,8 +158,8 @@ public class StackCommand extends CommandAreaShop {
if(group != null) {
groupsMessage = Message.fromKey("stack-addToGroup").replacements(group.getName());
}
plugin.message(player, "stack-accepted", amount, type, gap, nameTemplate, groupsMessage);
plugin.message(player, "stack-addStart", amount, regionsPerTick * 20);
messageBridge.message(player, "stack-accepted", amount, type, gap, nameTemplate, groupsMessage);
messageBridge.message(player, "stack-addStart", amount, regionsPerTick * 20);
Location minimumLocation = selection.getMinimumLocation();
Vector minimumVector = new Vector(minimumLocation.getX(), minimumLocation.getY(), minimumLocation.getZ());
@@ -176,24 +196,24 @@ public class StackCommand extends CommandAreaShop {
tooHigh++;
continue;
}
ProtectedCuboidRegion region = plugin.getWorldGuardHandler().createCuboidRegion(regionName, minimum,maximum);
ProtectedCuboidRegion region = worldGuardInterface.createCuboidRegion(regionName, minimum,maximum);
manager.addRegion(region);
// Add the region to AreaShop
GeneralRegion newRegion;
if(rentRegions) {
newRegion = new RentRegion(regionName, selection.getWorld());
newRegion = regionFactory.createRentRegion(regionName, selection.getWorld());
} else {
newRegion = new BuyRegion(regionName, selection.getWorld());
newRegion = regionFactory.createBuyRegion(regionName, selection.getWorld());
}
if(finalGroup != null) {
finalGroup.addMember(newRegion);
}
AddingRegionEvent event = plugin.getFileManager().addRegion(newRegion);
AddingRegionEvent event = fileManager.addRegion(newRegion);
if (event.isCancelled()) {
plugin.message(player, "general-cancelled", event.getReason());
messageBridge.message(player, "general-cancelled", event.getReason());
continue;
}
newRegion.handleSchematicEvent(GeneralRegion.RegionEvent.CREATED);
@@ -210,7 +230,7 @@ public class StackCommand extends CommandAreaShop {
if(tooLow > 0) {
wrong.append(Message.fromKey("stack-tooLow").replacements(tooLow));
}
plugin.message(player, "stack-addComplete", added, wrong);
messageBridge.message(player, "stack-addComplete", added, wrong);
}
this.cancel();
}
@@ -245,7 +265,7 @@ public class StackCommand extends CommandAreaShop {
result.add("rent");
result.add("buy");
} else if(toComplete == 6) {
result.addAll(plugin.getFileManager().getGroupNames());
result.addAll(fileManager.getGroupNames());
}
return result;
}
@@ -1,15 +1,25 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class StopresellCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop stopresell";
@@ -26,7 +36,7 @@ public class StopresellCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.stopresell") && !sender.hasPermission("areashop.stopresellall")) {
plugin.message(sender, "stopresell-noPermissionOther");
messageBridge.message(sender, "stopresell-noPermissionOther");
return;
}
@@ -36,47 +46,47 @@ public class StopresellCommand extends CommandAreaShop {
// get the region by location
List<BuyRegion> regions = Utils.getImportantBuyRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
messageBridge.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
messageBridge.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
buy = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
messageBridge.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
buy = plugin.getFileManager().getBuy(args[1]);
buy = fileManager.getBuy(args[1]);
if(buy == null) {
plugin.message(sender, "stopresell-notRegistered", args[1]);
messageBridge.message(sender, "stopresell-notRegistered", args[1]);
return;
}
}
if(buy == null) {
plugin.message(sender, "cmd-noRegionsAtLocation");
messageBridge.message(sender, "cmd-noRegionsAtLocation");
return;
}
if(!buy.isInResellingMode()) {
plugin.message(sender, "stopresell-notResell", buy);
messageBridge.message(sender, "stopresell-notResell", buy);
return;
}
if(sender.hasPermission("areashop.stopresellall")) {
buy.disableReselling();
buy.update();
plugin.message(sender, "stopresell-success", buy);
messageBridge.message(sender, "stopresell-success", buy);
} else if(sender.hasPermission("areashop.stopresell") && sender instanceof Player) {
if(buy.isOwner((Player)sender)) {
buy.disableReselling();
buy.update();
plugin.message(sender, "stopresell-success", buy);
messageBridge.message(sender, "stopresell-success", buy);
} else {
plugin.message(sender, "stopresell-noPermissionOther", buy);
messageBridge.message(sender, "stopresell-noPermissionOther", buy);
}
} else {
plugin.message(sender, "stopresell-noPermission", buy);
messageBridge.message(sender, "stopresell-noPermission", buy);
}
}
@@ -84,7 +94,7 @@ public class StopresellCommand extends CommandAreaShop {
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(BuyRegion region : plugin.getFileManager().getBuys()) {
for(BuyRegion region : fileManager.getBuysRef()) {
if(region.isSold() && region.isInResellingMode()) {
result.add(region.getName());
}
@@ -1,14 +1,24 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.GeneralRegion;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class TeleportCommand extends CommandAreaShop {
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop tp";
@@ -42,21 +52,21 @@ public class TeleportCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.teleport") && !sender.hasPermission("areashop.teleportall") && !sender.hasPermission("areashop.teleportavailable") && !sender.hasPermission("areashop.teleportavailablesign") && !sender.hasPermission("areashop.teleportsign") && !sender.hasPermission("areashop.teleportsignall") && !sender.hasPermission("areashop.teleportfriend") && !sender.hasPermission("teleportfriendsign")) {
plugin.message(sender, "teleport-noPermission");
messageBridge.message(sender, "teleport-noPermission");
return;
}
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
messageBridge.message(sender, "cmd-onlyByPlayer");
return;
}
if(args.length <= 1 || args[1] == null) {
plugin.message(sender, "teleport-help");
messageBridge.message(sender, "teleport-help");
return;
}
Player player = (Player)sender;
GeneralRegion region = plugin.getFileManager().getRegion(args[1]);
GeneralRegion region = fileManager.getRegion(args[1]);
if(region == null) {
plugin.message(player, "teleport-noRentOrBuy", args[1]);
messageBridge.message(player, "teleport-noRentOrBuy", args[1]);
return;
}
@@ -65,14 +75,14 @@ public class TeleportCommand extends CommandAreaShop {
|| args[2].equalsIgnoreCase("yes")
|| args[2].equalsIgnoreCase("true")
);
region.getTeleportFeature().teleportPlayer(player, toSign, true);
region.getTeleportFeature().teleportPlayer(player, toSign);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
result.addAll(plugin.getFileManager().getRegionNames());
result.addAll(fileManager.getRegionNames());
} else if(toComplete == 3) {
result.add("sign");
}
@@ -1,31 +0,0 @@
package me.wiefferink.areashop.commands;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import me.wiefferink.areashop.AreaShop;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class TestCommand implements CommandExecutor {
private AreaShop areaShop = AreaShop.getInstance();
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (sender instanceof Player) {
final Player player = (Player) sender;
final Location location = player.getLocation();
ApplicableRegionSet region = areaShop.getRegionManager(player.getWorld()).getApplicableRegions(BlockVector3.at(location.getX(), location.getY(), location.getZ()));
for (ProtectedRegion r : region.getRegions()) {
player.sendMessage(r.getId());
}
}
return true;
}
}
@@ -1,98 +1,106 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.regions.TransactionalRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class UnrentCommand extends CommandAreaShop {
/**
* Check if a person can unrent the region.
*
* @param person The person to check
* @param region The region to check for
* @return true if the person can unrent it, otherwise false
*/
public static boolean canUse(CommandSender person, GeneralRegion region) {
if (person.hasPermission("areashop.unrent")) {
return true;
}
if (person instanceof Player && region instanceof TransactionalRegion) {
Player player = (Player) person;
return ((TransactionalRegion) region).isTransactionHolder(player) && person.hasPermission("areashop.unrentown");
}
return false;
}
@Inject
private MessageBridge messageBridge;
@Inject
private IFileManager fileManager;
@Override
public String getCommandStart() {
return "areashop unrent";
}
@Override
public String getCommandStart() {
return "areashop unrent";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.unrent") || target.hasPermission("areashop.unrentown")) {
return "help-unrent";
}
return null;
}
@Override
public String getHelp(CommandSender target) {
if (target.hasPermission("areashop.unrent") || target.hasPermission("areashop.unrentown")) {
return "help-unrent";
}
return null;
}
/**
* Check if a person can unrent the region.
* @param person The person to check
* @param region The region to check for
* @return true if the person can unrent it, otherwise false
*/
public static boolean canUse(CommandSender person, GeneralRegion region) {
if(person.hasPermission("areashop.unrent")) {
return true;
}
if(person instanceof Player) {
Player player = (Player)person;
return region.isOwner(player) && person.hasPermission("areashop.unrentown");
}
return false;
}
@Override
public void execute(CommandSender sender, String[] args) {
if (!sender.hasPermission("areashop.unrent") && !sender.hasPermission("areashop.unrentown")) {
plugin.message(sender, "unrent-noPermission");
return;
}
RentRegion rent;
if (args.length <= 1) {
if (sender instanceof Player) {
// get the region by location
List<RentRegion> regions = Utils.getImportantRentRegions(((Player) sender).getLocation());
if (regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if (regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
rent = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
rent = plugin.getFileManager().getRent(args[1]);
}
if (rent == null) {
plugin.message(sender, "unrent-notRegistered");
return;
}
if (!rent.isRented()) {
plugin.message(sender, "unrent-notRented", rent);
return;
}
rent.unRent(true, sender);
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.unrent") && !sender.hasPermission("areashop.unrentown")) {
messageBridge.message(sender, "unrent-noPermission");
return;
}
RentRegion rent;
if(args.length <= 1) {
if(sender instanceof Player) {
// get the region by location
List<RentRegion> regions = Utils.getImportantRentRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
messageBridge.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
messageBridge.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
rent = regions.get(0);
}
} else {
messageBridge.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
rent = fileManager.getRent(args[1]);
}
if(rent == null) {
messageBridge.message(sender, "unrent-notRegistered");
return;
}
if(!rent.isRented()) {
messageBridge.message(sender, "unrent-notRented", rent);
return;
}
rent.unRent(true, sender);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if (toComplete == 2) {
for (RentRegion region : plugin.getFileManager().getRents()) {
if (region.isRented()) {
result.add(region.getName());
}
}
}
return result;
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(RentRegion region : fileManager.getRentsRef()) {
if(region.isRented()) {
result.add(region.getName());
}
}
}
return result;
}
}
@@ -1,5 +1,6 @@
package me.wiefferink.areashop.features;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.events.ask.AddingRegionEvent;
import me.wiefferink.areashop.events.ask.BuyingRegionEvent;
import me.wiefferink.areashop.events.ask.DeletingRegionEvent;
@@ -20,10 +21,18 @@ import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
@Singleton
public class CommandsFeature extends RegionFeature {
@Inject
CommandsFeature(AreaShop plugin) {
super(plugin);
}
/**
* Run command for a certain event.
* @param region Region to execute the events for
@@ -36,7 +45,7 @@ public class CommandsFeature extends RegionFeature {
return;
}
List<String> commands = eventCommandProfileSection.getStringList(event.getValue() + "." + (before ? "before" : "after"));
if(commands == null || commands.isEmpty()) {
if(commands.isEmpty()) {
return;
}
region.runCommands(Bukkit.getConsoleSender(), commands);
@@ -19,8 +19,18 @@ import me.wiefferink.areashop.events.notify.UpdateRegionEvent;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.event.EventHandler;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public class DebugFeature extends RegionFeature {
@Inject
DebugFeature(@Nonnull AreaShop plugin) {
super(plugin);
}
@EventHandler
public void buyingRegion(BuyingRegionEvent event) {
AreaShop.debug("BuyingRegionEvent: " + event.getPlayer().getName() + " is trying to buy " + event.getRegion().getName());
@@ -0,0 +1,19 @@
package me.wiefferink.areashop.features;
import me.wiefferink.areashop.features.signs.SignsFeature;
import me.wiefferink.areashop.regions.GeneralRegion;
import javax.annotation.Nonnull;
public interface FeatureFactory {
@Nonnull
SignsFeature createSignsFeature(@Nonnull GeneralRegion generalRegion);
@Nonnull
TeleportFeature createTeleportFeature(@Nonnull GeneralRegion generalRegion);
@Nonnull
FriendsFeature createFriendsFeature(@Nonnull GeneralRegion generalRegion);
}
@@ -1,5 +1,10 @@
package me.wiefferink.areashop.features;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.events.askandnotify.AddedFriendEvent;
import me.wiefferink.areashop.events.askandnotify.DeletedFriendEvent;
import me.wiefferink.areashop.regions.GeneralRegion;
@@ -7,6 +12,7 @@ import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
@@ -15,7 +21,12 @@ import java.util.UUID;
public class FriendsFeature extends RegionFeature {
public FriendsFeature(GeneralRegion region) {
@Inject
private MessageBridge messageBridge;
@AssistedInject
public FriendsFeature(@Nonnull AreaShop plugin, @Assisted @Nonnull GeneralRegion region) {
super(plugin);
setRegion(region);
}
@@ -30,7 +41,7 @@ public class FriendsFeature extends RegionFeature {
AddedFriendEvent event = new AddedFriendEvent(getRegion(), Bukkit.getOfflinePlayer(player), by);
Bukkit.getPluginManager().callEvent(event);
if(event.isCancelled()) {
plugin.message(by, "general-cancelled", event.getReason(), this);
messageBridge.message(by, "general-cancelled", event.getReason(), this);
return false;
}
@@ -52,16 +63,17 @@ public class FriendsFeature extends RegionFeature {
DeletedFriendEvent event = new DeletedFriendEvent(getRegion(), Bukkit.getOfflinePlayer(player), by);
Bukkit.getPluginManager().callEvent(event);
if(event.isCancelled()) {
plugin.message(by, "general-cancelled", event.getReason(), this);
messageBridge.message(by, "general-cancelled", event.getReason(), this);
return false;
}
List<String> friends = getRegion().getConfig().getStringList("general.friends");
Set<String> friends = new HashSet<>(getRegion().getConfig().getStringList("general.friends"));
friends.remove(player.toString());
if(friends.isEmpty()) {
List<String> list = new ArrayList<>(friends);
if(list.isEmpty()) {
getRegion().setSetting("general.friends", null);
} else {
getRegion().setSetting("general.friends", friends);
getRegion().setSetting("general.friends", list);
}
return true;
}
@@ -2,10 +2,11 @@ package me.wiefferink.areashop.features;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.regions.GeneralRegion;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import javax.annotation.Nonnull;
/*
Possible future feature classes:
- RestrictedToRegion feature
@@ -28,11 +29,14 @@ Possible future feature classes:
*/
public abstract class RegionFeature implements Listener {
public static final AreaShop plugin = AreaShop.getInstance();
protected YamlConfiguration config = plugin.getConfig();
protected final AreaShop plugin;
private GeneralRegion region;
protected RegionFeature(@Nonnull AreaShop plugin) {
this.plugin = plugin;
}
/**
* Set the region for this feature.
* @param region Feature region
File diff suppressed because it is too large. Load diff
@@ -8,17 +8,31 @@ import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.events.notify.UpdateRegionEvent;
import me.wiefferink.areashop.interfaces.RegionAccessSet;
import me.wiefferink.areashop.interfaces.WorldGuardInterface;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.interactivemessenger.processing.Message;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.event.EventHandler;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
@Singleton
public class WorldGuardRegionFlagsFeature extends RegionFeature {
@Inject
private WorldGuardInterface worldGuardInterface;
@Inject
private WorldGuardPlugin worldGuard;
@Inject
WorldGuardRegionFlagsFeature(@Nonnull AreaShop plugin) {
super(plugin);
}
@EventHandler
public void regionUpdate(UpdateRegionEvent event) {
@@ -69,7 +83,6 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
boolean result = true;
Set<String> flagNames = flags.getKeys(false);
WorldGuardPlugin worldGuard = plugin.getWorldGuard();
// Get the region
ProtectedRegion worldguardRegion = region.getRegion();
@@ -81,14 +94,14 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
for(String flagName : flagNames) {
String value = Message.fromString(flags.getString(flagName)).replacements(region).getPlain();
// In the config normal Bukkit color codes are used, those only need to be translated on 5.X WorldGuard versions
if(plugin.getWorldGuard().getDescription().getVersion().startsWith("5.")) {
if(worldGuard.getDescription().getVersion().startsWith("5.")) {
value = translateBukkitToWorldGuardColors(value);
}
if(flagName.equalsIgnoreCase("members")) {
plugin.getWorldGuardHandler().setMembers(worldguardRegion, parseAccessSet(value));
worldGuardInterface.setMembers(worldguardRegion, parseAccessSet(value));
//AreaShop.debug(" Flag " + flagName + " set: " + members.toUserFriendlyString());
} else if(flagName.equalsIgnoreCase("owners")) {
plugin.getWorldGuardHandler().setOwners(worldguardRegion, parseAccessSet(value));
worldGuardInterface.setOwners(worldguardRegion, parseAccessSet(value));
//AreaShop.debug(" Flag " + flagName + " set: " + owners.toUserFriendlyString());
} else if(flagName.equalsIgnoreCase("priority")) {
try {
@@ -123,7 +136,7 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
String flagSetting = null;
com.sk89q.worldguard.protection.flags.RegionGroup groupValue = null;
Flag<?> foundFlag = plugin.getWorldGuardHandler().fuzzyMatchFlag(flagName);
Flag<?> foundFlag = worldGuardInterface.fuzzyMatchFlag(flagName);
if(foundFlag == null) {
AreaShop.warn("Found wrong flag in flagProfiles section: " + flagName + ", check if that is the correct WorldGuard flag");
continue;
@@ -145,7 +158,7 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
if(part.startsWith("g:")) {
if(part.length() > 2) {
try {
groupValue = plugin.getWorldGuardHandler().parseFlagGroupInput(groupFlag, part.substring(2));
groupValue = worldGuardInterface.parseFlagGroupInput(groupFlag, part.substring(2));
} catch(InvalidFlagFormat e) {
AreaShop.warn("Found wrong group value for flag " + flagName);
}
@@ -229,7 +242,7 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
*/
private <V> void setFlag(ProtectedRegion region, Flag<V> flag, String value) throws InvalidFlagFormat {
V current = region.getFlag(flag);
V next = plugin.getWorldGuardHandler().parseFlagInput(flag, value);
V next = worldGuardInterface.parseFlagInput(flag, value);
if(!Objects.equals(current, next)) {
region.setFlag(flag, next);
@@ -1,7 +1,14 @@
package me.wiefferink.areashop.features.signs;
import com.google.common.base.Objects;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import io.github.bakedlibs.dough.blocks.BlockPosition;
import io.papermc.lib.PaperLib;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.interfaces.BukkitInterface;
import me.wiefferink.areashop.managers.SignErrorLogger;
import me.wiefferink.areashop.nms.BlockBehaviourHelper;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.tools.Materials;
import me.wiefferink.areashop.tools.Utils;
@@ -11,6 +18,7 @@ import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.Sign;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.type.WallSign;
@@ -18,6 +26,7 @@ import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
@@ -26,259 +35,261 @@ import java.util.List;
*/
public class RegionSign {
private final SignsFeature signsFeature;
private final String key;
private final BlockBehaviourHelper blockHelper;
private final SignErrorLogger errorLogger;
private final BukkitInterface bukkitInterface;
public RegionSign(SignsFeature signsFeature, String key) {
this.signsFeature = signsFeature;
this.key = key;
}
private final SignsFeature signsFeature;
private final String key;
/**
* Get the location of this sign.
*
* @return The location of this sign
*/
public Location getLocation() {
return Utils.configToLocation(getRegion().getConfig().getConfigurationSection("general.signs." + key + ".location"));
}
/**
* Location string to be used as key in maps.
*
* @return Location string
*/
public String getStringLocation() {
return SignsFeature.locationToString(getLocation());
}
@AssistedInject
RegionSign(
@Nonnull BlockBehaviourHelper blockBehaviourHelper,
@Nonnull SignErrorLogger signErrorLogger,
@Nonnull BukkitInterface bukkitInterface,
@Assisted @Nonnull SignsFeature signsFeature,
@Assisted @Nonnull String key
) {
this.blockHelper = blockBehaviourHelper;
this.errorLogger = signErrorLogger;
this.bukkitInterface = bukkitInterface;
this.signsFeature = signsFeature;
this.key = key;
}
/**
* Chunk string to be used as key in maps.
*
* @return Chunk string
*/
public String getStringChunk() {
return SignsFeature.chunkToString(getLocation());
}
public BlockPosition getPosition() {
return new BlockPosition(getLocation());
}
/**
* Get the region this sign is linked to.
*
* @return The region this sign is linked to
*/
public GeneralRegion getRegion() {
return signsFeature.getRegion();
}
/**
* Get the location of this sign.
* @return The location of this sign
*/
public Location getLocation() {
return Utils.configToLocation(getRegion().getConfig().getConfigurationSection("general.signs." + key + ".location"));
}
/**
* Remove this sign from the region.
*/
public void remove() {
getLocation().getBlock().setType(Material.AIR);
signsFeature.getSignsRef().remove(getStringLocation());
SignsFeature.getAllSigns().remove(getStringLocation());
SignsFeature.getSignsByChunk().get(getStringChunk()).remove(this);
getRegion().setSetting("general.signs." + key, null);
}
/**
* Location string to be used as key in maps.
* @return Location string
*/
public String getStringLocation() {
return SignsFeature.locationToString(getLocation());
}
/**
* Get the ConfigurationSection defining the sign layout.
*
* @return The sign layout config
*/
public ConfigurationSection getProfile() {
return getRegion().getConfigurationSectionSetting("general.signProfile", "signProfiles", getRegion().getConfig().get("general.signs." + key + ".profile"));
}
/**
* Chunk string to be used as key in maps.
* @return Chunk string
*/
public String getStringChunk() {
return SignsFeature.chunkToString(getLocation());
}
/**
* Get the facing of the sign as saved in the config.
*
* @return BlockFace the sign faces, or null if unknown
*/
public BlockFace getFacing() {
try {
return BlockFace.valueOf(getRegion().getConfig().getString("general.signs." + key + ".facing"));
} catch (NullPointerException | IllegalArgumentException e) {
return null;
}
}
/**
* Get the region this sign is linked to.
* @return The region this sign is linked to
*/
public GeneralRegion getRegion() {
return signsFeature.getRegion();
}
/**
* Get the material of the sign as saved in the config.
*
* @return Material of the sign, usually {@link Material#WALL_SIGN}, {@link Material#SIGN}, or one of the other wood types (different result for 1.13-), Material.AIR if none.
*/
public Material getMaterial() {
String name = getRegion().getConfig().getString("general.signs." + key + ".signType");
Material result = Materials.signNameToMaterial(name);
return result == null ? Material.AIR : result;
}
/**
* Remove this sign from the region.
*/
public void remove() {
getLocation().getBlock().setType(Material.AIR);
this.signsFeature.signManager().removeSign(this);
getRegion().setSetting("general.signs." + key, null);
// Remove the sign from the region's sign manager
}
/**
* Update this sign.
*
* @return true if the update was successful, otherwise false
*/
public boolean update() {
// Ignore updates of signs in chunks that are not loaded
Location signLocation = getLocation();
if (signLocation == null
|| signLocation.getWorld() == null
|| !signLocation.getWorld().isChunkLoaded(signLocation.getBlockX() >> 4, signLocation.getBlockZ() >> 4)) {
return false;
}
/**
* Get the ConfigurationSection defining the sign layout.
* @return The sign layout config
*/
public ConfigurationSection getProfile() {
return getRegion().getConfigurationSectionSetting("general.signProfile", "signProfiles", getRegion().getConfig().get("general.signs." + key + ".profile"));
}
if (getRegion().isDeleted()) {
return false;
}
/**
* Get the facing of the sign as saved in the config.
* @return BlockFace the sign faces, or null if unknown
*/
public BlockFace getFacing() {
try {
return BlockFace.valueOf(getRegion().getConfig().getString("general.signs." + key + ".facing"));
} catch(NullPointerException | IllegalArgumentException e) {
return null;
}
}
YamlConfiguration regionConfig = getRegion().getConfig();
ConfigurationSection signConfig = getProfile();
Block block = signLocation.getBlock();
if (signConfig == null || !signConfig.isSet(getRegion().getState().getValue())) {
block.setType(Material.AIR);
return true;
}
/**
* Get the material of the sign as saved in the config.
* @return Material of the sign,Material.AIR if none.
*/
public Material getMaterial() {
String name = getRegion().getConfig().getString("general.signs." + key + ".signType");
Material result = Materials.signNameToMaterial(name);
return result == null ? Material.AIR : result;
}
ConfigurationSection stateConfig = signConfig.getConfigurationSection(getRegion().getState().getValue());
/**
* Update this sign.
* @return true if the update was successful, otherwise false
*/
public boolean update() {
// Ignore updates of signs in chunks that are not loaded
Location signLocation = getLocation();
if(signLocation == null
|| signLocation.getWorld() == null
|| !signLocation.getWorld().isChunkLoaded(signLocation.getBlockX() >> 4, signLocation.getBlockZ() >> 4)) {
return false;
}
// Get the lines
String[] signLines = new String[4];
boolean signEmpty = true;
for (int i = 0; i < 4; i++) {
signLines[i] = stateConfig.getString("line" + (i + 1));
signEmpty &= (signLines[i] == null || signLines[i].isEmpty());
}
if (signEmpty) {
block.setType(Material.AIR);
return true;
}
if(getRegion().isDeleted()) {
return false;
}
// Place the sign back (with proper rotation and type) after it has been hidden or (indirectly) destroyed
if (!Materials.isSign(block.getType())) {
Material signType = getMaterial();
if (signType.name().contains("SIGN")) {
// Don't do physics here, we first need to update the direction
block.setType(signType, false);
BlockData data = block.getBlockData();
if (data instanceof WallSign) {
((WallSign) data).setFacing(getFacing());
} else if (data instanceof Sign) {
((org.bukkit.block.data.type.Sign) data).setRotation(getFacing());
}
block.setBlockData(data, true);
YamlConfiguration regionConfig = getRegion().getConfig();
ConfigurationSection signConfig = getProfile();
Block block = signLocation.getBlock();
if(signConfig == null || !signConfig.isSet(getRegion().getState().getValue())) {
block.setType(Material.AIR);
return true;
}
// Check if the sign has popped
if (!Materials.isSign(block.getType())) {
AreaShop.warn("Setting sign", key, "of region", getRegion().getName(), "failed, could not set sign block back");
return false;
}
} else {
AreaShop.warn("Setting sign", key, "of region", getRegion().getName(), "failed, RegionSign material was: " + signType.name());
}
}
ConfigurationSection stateConfig = signConfig.getConfigurationSection(getRegion().getState().getValue());
// Save current rotation and type
if (!regionConfig.isString("general.signs." + key + ".signType")) {
getRegion().setSetting("general.signs." + key + ".signType", block.getType().name());
}
if (!regionConfig.isString("general.signs." + key + ".facing")) {
final BlockFace rotation;
if (Materials.isSign(block.getType())) {
BlockData data = block.getBlockData();
if (data instanceof org.bukkit.block.data.type.Sign) {
rotation = ((org.bukkit.block.data.type.Sign) block.getBlockData()).getRotation();
} else if (data instanceof WallSign) {
rotation = ((WallSign) data).getFacing();
} else {
rotation = null;
}
} else {
rotation = null;
}
getRegion().setSetting("general.signs." + key + ".facing", rotation == null ? null : rotation.toString());
}
// Get the lines
String[] signLines = new String[4];
boolean signEmpty = true;
for(int i = 0; i < 4; i++) {
signLines[i] = stateConfig.getString("line" + (i + 1));
signEmpty &= (signLines[i] == null || signLines[i].isEmpty());
}
if(signEmpty) {
block.setType(Material.AIR);
return true;
}
// Apply replacements and color and then set it on the sign
Sign signState = (Sign) block.getState();
for (int i = 0; i < signLines.length; i++) {
if (signLines[i] == null) {
signState.setLine(i, "");
continue;
}
signLines[i] = Message.fromString(signLines[i]).replacements(getRegion()).getSingle();
signLines[i] = Utils.applyColors(signLines[i]);
signState.setLine(i, signLines[i]);
}
signState.update();
return true;
}
// Place the sign back (with proper rotation and type) after it has been hidden or (indirectly) destroyed
if(!Materials.isSign(block.getType())) {
Material signType = getMaterial();
if (!blockHelper.canPlace(block.getLocation(), Bukkit.createBlockData(signType))) {
errorLogger.submitWarning("Setting sign" + key + "of region" + getRegion().getName() + "failed, could not set sign block back");
this.remove();
return false;
}
// Don't do physics here, we first need to update the direction
block.setType(signType, false);
/**
* Check if the sign needs to update periodically.
*
* @return true if it needs periodic updates, otherwise false
*/
public boolean needsPeriodicUpdate() {
ConfigurationSection signConfig = getProfile();
if (signConfig == null || !signConfig.isSet(getRegion().getState().getValue().toLowerCase())) {
return false;
}
BlockState blockState = PaperLib.getBlockState(block, false).getState();
BlockData blockData = blockState.getBlockData();
ConfigurationSection stateConfig = signConfig.getConfigurationSection(getRegion().getState().getValue().toLowerCase());
if (stateConfig == null) {
return false;
}
if(blockData instanceof WallSign) {
((WallSign) blockData).setFacing(getFacing());
} else if(blockData instanceof org.bukkit.block.data.type.Sign) {
((org.bukkit.block.data.type.Sign) blockData).setRotation(getFacing());
} else {
errorLogger.submitWarning("Failed to update the facing direction of the sign at" + getStringLocation() + "to " + getFacing() + ", region:" + getRegion().getName());
return false;
}
block.setBlockData(blockData);
// Check the lines for the timeleft tag
for (int i = 1; i <= 4; i++) {
String line = stateConfig.getString("line" + i);
if (line != null && !line.isEmpty() && line.contains(Message.VARIABLE_START + AreaShop.tagTimeLeft + Message.VARIABLE_END)) {
return true;
}
}
return false;
}
// Check if the sign has popped
if(!Materials.isSign(block.getType())) {
return false;
}
}
/**
* Run commands when a player clicks a sign.
*
* @param clicker The player that clicked the sign
* @param clickType The type of clicking
* @return true if the commands ran successfully, false if any of them failed
*/
public boolean runSignCommands(Player clicker, GeneralRegion.ClickType clickType) {
ConfigurationSection signConfig = getProfile();
if (signConfig == null) {
return false;
}
ConfigurationSection stateConfig = signConfig.getConfigurationSection(getRegion().getState().getValue().toLowerCase());
// Save current rotation and type
if(!regionConfig.isString("general.signs." + key + ".signType")) {
getRegion().setSetting("general.signs." + key + ".signType", block.getType().name());
}
if(!regionConfig.isString("general.signs." + key + ".facing")) {
BlockFace signFacing = bukkitInterface.getSignFacing(block);
getRegion().setSetting("general.signs." + key + ".facing", signFacing == null ? null : signFacing.toString());
}
// Run player commands if specified
List<String> playerCommands = new ArrayList<>();
for (String command : stateConfig.getStringList(clickType.getValue() + "Player")) {
// TODO move variable checking code to InteractiveMessenger?
playerCommands.add(command.replace(Message.VARIABLE_START + AreaShop.tagClicker + Message.VARIABLE_END, clicker.getName()));
}
getRegion().runCommands(clicker, playerCommands);
// Apply replacements and color and then set it on the sign
Sign signState = (Sign) PaperLib.getBlockState(block, false).getState();
for(int i = 0; i < signLines.length; i++) {
if(signLines[i] == null) {
signState.setLine(i, "");
continue;
}
signLines[i] = Message.fromString(signLines[i]).replacements(getRegion()).getSingle();
signLines[i] = Utils.applyColors(signLines[i]);
signState.setLine(i, signLines[i]);
}
signState.update(false, false);
return true;
}
// Run console commands if specified
List<String> consoleCommands = new ArrayList<>();
for (String command : stateConfig.getStringList(clickType.getValue() + "Console")) {
consoleCommands.add(command.replace(Message.VARIABLE_START + AreaShop.tagClicker + Message.VARIABLE_END, clicker.getName()));
}
getRegion().runCommands(Bukkit.getConsoleSender(), consoleCommands);
/**
* Check if the sign needs to update periodically.
* @return true if it needs periodic updates, otherwise false
*/
public boolean needsPeriodicUpdate() {
ConfigurationSection signConfig = getProfile();
if(signConfig == null || !signConfig.isSet(getRegion().getState().getValue().toLowerCase())) {
return false;
}
return !playerCommands.isEmpty() || !consoleCommands.isEmpty();
}
ConfigurationSection stateConfig = signConfig.getConfigurationSection(getRegion().getState().getValue().toLowerCase());
if(stateConfig == null) {
return false;
}
@Override
public boolean equals(Object object) {
return object instanceof RegionSign && ((RegionSign) object).getRegion().equals(this.getRegion()) && ((RegionSign) object).key.equals(this.key);
}
// Check the lines for the timeleft tag
for(int i = 1; i <= 4; i++) {
String line = stateConfig.getString("line" + i);
if(line != null && line.contains(Message.VARIABLE_START + AreaShop.tagTimeLeft + Message.VARIABLE_END)) {
return true;
}
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(key, getRegion().getName());
}
/**
* Run commands when a player clicks a sign.
* @param clicker The player that clicked the sign
* @param clickType The type of clicking
* @return true if the commands ran successfully, false if any of them failed
*/
public boolean runSignCommands(Player clicker, GeneralRegion.ClickType clickType) {
ConfigurationSection signConfig = getProfile();
if(signConfig == null) {
return false;
}
ConfigurationSection stateConfig = signConfig.getConfigurationSection(getRegion().getState().getValue().toLowerCase());
// Run player commands if specified
List<String> playerCommands = new ArrayList<>();
for(String command : stateConfig.getStringList(clickType.getValue() + "Player")) {
// TODO move variable checking code to InteractiveMessenger?
playerCommands.add(command.replace(Message.VARIABLE_START + AreaShop.tagClicker + Message.VARIABLE_END, clicker.getName()));
}
getRegion().runCommands(clicker, playerCommands);
// Run console commands if specified
List<String> consoleCommands = new ArrayList<>();
for(String command : stateConfig.getStringList(clickType.getValue() + "Console")) {
consoleCommands.add(command.replace(Message.VARIABLE_START + AreaShop.tagClicker + Message.VARIABLE_END, clicker.getName()));
}
getRegion().runCommands(Bukkit.getConsoleSender(), consoleCommands);
return !playerCommands.isEmpty() || !consoleCommands.isEmpty();
}
@Override
public boolean equals(Object object) {
return object instanceof RegionSign && ((RegionSign)object).getRegion().equals(this.getRegion()) && ((RegionSign)object).key.equals(this.key);
}
@Override
public int hashCode() {
return Objects.hashCode(key, getRegion().getName());
}
}
@@ -0,0 +1,80 @@
package me.wiefferink.areashop.features.signs;
import io.github.bakedlibs.dough.blocks.BlockPosition;
import io.github.bakedlibs.dough.blocks.ChunkPosition;
import org.bukkit.Location;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class SignCache {
private final Map<Long, RegionSign> allSigns = new HashMap<>();
private final Map<Long, Collection<RegionSign>> signsByChunk = new HashMap<>();
public Optional<RegionSign> signAtLocation(long position) {
return Optional.ofNullable(this.allSigns.get(position));
}
public Collection<RegionSign> signsAtChunk(long position) {
return Collections.unmodifiableCollection(this.signsByChunk.getOrDefault(position, Collections.emptyList()));
}
public Collection<RegionSign> allSigns() {
return Collections.unmodifiableCollection(this.allSigns.values());
}
public Collection<BlockPosition> allSignLocations() {
Collection<BlockPosition> positions = new ArrayList<>(this.signsByChunk.size());
for (RegionSign sign : this.allSigns.values()) {
positions.add(sign.getPosition());
}
return positions;
}
public void addSign(RegionSign regionSign) {
BlockPosition blockPosition = regionSign.getPosition();
this.allSigns.put(blockPosition.getPosition(), regionSign);
ChunkPosition chunkPosition = new ChunkPosition(blockPosition.getChunk());
Collection<RegionSign> signs = this.signsByChunk.computeIfAbsent(chunkPosition.getPosition(), x -> new ArrayList<>());
signs.add(regionSign);
}
public Optional<RegionSign> removeSign(Location location) {
return removeSign(new BlockPosition(location));
}
public Optional<RegionSign> removeSign(BlockPosition position) {
RegionSign removed = this.allSigns.remove(position.getPosition());
if (removed != null) {
Location location = position.toLocation();
this.signsByChunk.remove(new ChunkPosition(location).getPosition());
// Remove the sign from the region
}
return Optional.ofNullable(removed);
}
public void removeSign(RegionSign regionSign) {
BlockPosition blockPosition = regionSign.getPosition();
this.allSigns.remove(blockPosition.getPosition());
ChunkPosition chunkPosition = new ChunkPosition(blockPosition.getChunk());
long packedChunkPos = chunkPosition.getPosition();
Collection<RegionSign> signs = this.signsByChunk.get(packedChunkPos);
if (signs != null) {
signs.remove(regionSign);
if (signs.isEmpty()) {
this.signsByChunk.remove(packedChunkPos);
}
}
}
public void clear() {
this.allSigns.clear();
this.signsByChunk.clear();
}
}
@@ -0,0 +1,10 @@
package me.wiefferink.areashop.features.signs;
import javax.annotation.Nonnull;
public interface SignFactory {
@Nonnull RegionSign createRegionSign(@Nonnull SignsFeature signsFeature, @Nonnull String key);
}
@@ -0,0 +1,453 @@
package me.wiefferink.areashop.features.signs;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import io.github.bakedlibs.dough.blocks.ChunkPosition;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.events.ask.AddingRegionEvent;
import me.wiefferink.areashop.events.notify.UpdateRegionEvent;
import me.wiefferink.areashop.interfaces.BukkitInterface;
import me.wiefferink.areashop.interfaces.WorldGuardInterface;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.managers.SignLinkerManager;
import me.wiefferink.areashop.nms.BlockBehaviourHelper;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RegionFactory;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Materials;
import me.wiefferink.areashop.tools.Utils;
import me.wiefferink.bukkitdo.Do;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
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.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;
public class SignListener implements Listener {
private final BlockBehaviourHelper behaviourHelper;
private final AreaShop plugin;
private final MessageBridge messageBridge;
private final SignManager signManager;
private final SignLinkerManager signLinkerManager;
private final BukkitInterface bukkitInterface;
private final WorldGuardInterface worldGuardInterface;
private final RegionFactory regionFactory;
private final IFileManager fileManager;
public SignListener(
@Nonnull AreaShop plugin,
@Nonnull BlockBehaviourHelper behaviourHelper,
@Nonnull RegionFactory regionFactory,
@Nonnull MessageBridge messageBridge,
@Nonnull SignLinkerManager signLinkerManager,
@Nonnull BukkitInterface bukkitInterface,
@Nonnull WorldGuardInterface worldGuardInterface,
@Nonnull SignManager signManager,
@Nonnull IFileManager fileManager) {
this.fileManager = fileManager;
this.signManager = signManager;
this.signLinkerManager = signLinkerManager;
this.regionFactory = regionFactory;
this.behaviourHelper = behaviourHelper;
this.plugin = plugin;
this.bukkitInterface = bukkitInterface;
this.worldGuardInterface = worldGuardInterface;
this.messageBridge = messageBridge;
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void regionUpdate(UpdateRegionEvent event) {
Optional<SignsFeature> signsFeature = event.getRegion().getFeature(SignsFeature.class);
signsFeature.map(SignsFeature::signManager).ifPresent(SignManager::update);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onChunkLoad(ChunkLoadEvent event) {
Chunk chunk = event.getChunk();
Optional<SignCache> optional = this.signManager.getCacheForWorld(chunk.getWorld());
if (optional.isEmpty()) {
return;
}
final SignCache signCache = optional.get();
Collection<RegionSign> chunkSigns = new ArrayList<>(signCache.signsAtChunk(ChunkPosition.getAsLong(chunk.getX(), chunk.getZ())));
if(chunkSigns.isEmpty()) {
return;
}
chunkSigns.remove(null);
Do.forAll(chunkSigns, RegionSign::update);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onIndirectSignBreak(BlockPhysicsEvent event) {
// Check if the block is a sign
if(!Materials.isSign(event.getBlock().getType()) || behaviourHelper.isBlockValid(event.getBlock())) {
return;
}
// Check if the sign is really the same as a saved rent
final Optional<RegionSign> optionalSign = this.signManager.signFromLocation(event.getBlock().getLocation());
if(optionalSign.isEmpty()) {
return;
}
RegionSign regionSign = optionalSign.get();
// Remove the sign so that it does not fall on the floor as an item (next region update will place it back when possible)
AreaShop.debug("onIndirectSignBreak: Removed block of sign for", regionSign.getRegion().getName(), "at", regionSign.getStringLocation());
event.getBlock().setType(Material.AIR);
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGH)
public void onSignBreak(BlockBreakEvent event) {
if(event.isCancelled()) {
return;
}
Block block = event.getBlock();
// Check if it is a sign
if(Materials.isSign(block.getType())) {
// Check if the rent sign is really the same as a saved rent
Optional<RegionSign> optional = signManager.signFromLocation(block.getLocation());
if(optional.isEmpty()) {
return;
}
RegionSign regionSign = optional.get();
// Remove the sign of the rental region if the player has permission
if(event.getPlayer().hasPermission("areashop.delsign")) {
signManager.removeSign(regionSign);
messageBridge.message(event.getPlayer(), "delsign-success", regionSign.getRegion());
} else { // Cancel the breaking of the sign
event.setCancelled(true);
messageBridge.message(event.getPlayer(), "delsign-noPermission", regionSign.getRegion());
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onSignClick(PlayerInteractEvent event) {
Block block = event.getClickedBlock();
if (block == null) {
return;
}
// Only listen to left and right clicks on blocks
if (!(event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_BLOCK)) {
return;
}
// Only care about clicking blocks
if(!Materials.isSign(block.getType())) {
return;
}
// Check if this sign belongs to a region
Optional<RegionSign> optional = signManager.signFromLocation(block.getLocation());
if(optional.isEmpty()) {
return;
}
RegionSign regionSign = optional.get();
// Ignore players that are in sign link mode (which will handle the event itself)
Player player = event.getPlayer();
if(signLinkerManager.isInSignLinkMode(player)) {
return;
}
// Get the clicktype
GeneralRegion.ClickType clickType = null;
if(player.isSneaking() && event.getAction() == Action.LEFT_CLICK_BLOCK) {
clickType = GeneralRegion.ClickType.SHIFTLEFTCLICK;
} else if(!player.isSneaking() && event.getAction() == Action.LEFT_CLICK_BLOCK) {
clickType = GeneralRegion.ClickType.LEFTCLICK;
} else if(player.isSneaking() && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
clickType = GeneralRegion.ClickType.SHIFTRIGHTCLICK;
} else if(!player.isSneaking() && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
clickType = GeneralRegion.ClickType.RIGHTCLICK;
}
boolean ran = regionSign.runSignCommands(player, clickType);
// Only cancel event if at least one command has been executed
event.setCancelled(ran);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onSignChange(SignChangeEvent event) {
Player player = event.getPlayer();
if(!plugin.isReady()) {
messageBridge.message(player, "general-notReady");
return;
}
// Check if the sign is meant for this plugin
if(event.getLine(0).contains(plugin.getConfig().getString("signTags.rent"))) {
if(!player.hasPermission("areashop.createrent") && !player.hasPermission("areashop.createrent.member") && !player.hasPermission("areashop.createrent.owner")) {
messageBridge.message(player, "setup-noPermissionRent");
return;
}
// Get the other lines
String secondLine = event.getLine(1);
String thirdLine = event.getLine(2);
String fourthLine = event.getLine(3);
// Get the regionManager for accessing regions
RegionManager regionManager = plugin.getRegionManager(event.getPlayer().getWorld());
// If the secondLine does not contain a name try to find the region by location
if(secondLine == null || secondLine.isEmpty()) {
Set<ProtectedRegion> regions = worldGuardInterface.getApplicableRegionsSet(event.getBlock().getLocation());
if(regions != null) {
boolean first = true;
ProtectedRegion candidate = null;
for(ProtectedRegion pr : regions) {
if(first) {
candidate = pr;
first = false;
} else {
if(pr.getPriority() > candidate.getPriority()) {
candidate = pr;
} else if(pr.getParent() != null && pr.getParent().equals(candidate)) {
candidate = pr;
} else {
messageBridge.message(player, "setup-couldNotDetect", candidate.getId(), pr.getId());
return;
}
}
}
if(candidate != null) {
secondLine = candidate.getId();
}
}
}
boolean priceSet = fourthLine != null && !fourthLine.isEmpty();
boolean durationSet = thirdLine != null && !thirdLine.isEmpty();
// check if all the lines are correct
if(secondLine == null || secondLine.isEmpty()) {
messageBridge.message(player, "setup-noRegion");
return;
}
ProtectedRegion region = regionManager.getRegion(secondLine);
if(region == null) {
messageBridge.message(player, "cmd-noRegion", secondLine);
return;
}
IFileManager.AddResult addResult = fileManager.checkRegionAdd(player, regionManager.getRegion(secondLine), event.getPlayer().getWorld(), GeneralRegion.RegionType.RENT);
if(addResult == IFileManager.AddResult.BLACKLISTED) {
messageBridge.message(player, "setup-blacklisted", secondLine);
} else if(addResult == IFileManager.AddResult.ALREADYADDED) {
messageBridge.message(player, "setup-alreadyRentSign");
} else if(addResult == IFileManager.AddResult.ALREADYADDEDOTHERWORLD) {
messageBridge.message(player, "setup-alreadyOtherWorld");
} else if(addResult == IFileManager.AddResult.NOPERMISSION) {
messageBridge.message(player, "setup-noPermission", secondLine);
} else if(thirdLine != null && !thirdLine.isEmpty() && !Utils.checkTimeFormat(thirdLine)) {
messageBridge.message(player, "setup-wrongDuration");
} else {
double price = 0.0;
if(priceSet) {
// Check the fourth line
try {
price = Double.parseDouble(fourthLine);
} catch(NumberFormatException e) {
messageBridge.message(player, "setup-wrongPrice");
return;
}
}
// Add rent to the FileManager
final RentRegion rent = regionFactory.createRentRegion(secondLine, event.getPlayer().getWorld());
boolean isMember = worldGuardInterface.containsMember(rent.getRegion(), player.getUniqueId());
boolean isOwner = worldGuardInterface.containsOwner(rent.getRegion(), player.getUniqueId());
boolean landlord = (!player.hasPermission("areashop.createrent")
&& ((player.hasPermission("areashop.createrent.owner") && isOwner)
|| (player.hasPermission("areashop.createrent.member") && isMember)));
if(landlord) {
rent.setLandlord(player.getUniqueId(), player.getName());
}
if(priceSet) {
rent.setPrice(price);
}
if(durationSet) {
rent.setDuration(thirdLine);
}
rent.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), bukkitInterface.getSignFacing(event.getBlock()), null);
AddingRegionEvent addingRegionEvent = plugin.getFileManager().addRegion(rent);
if (addingRegionEvent.isCancelled()) {
messageBridge.message(player, "general-cancelled", addingRegionEvent.getReason());
return;
}
rent.handleSchematicEvent(GeneralRegion.RegionEvent.CREATED);
messageBridge.message(player, "setup-rentSuccess", rent);
// Update the region after the event has written its lines
Do.sync(rent::update);
}
} else if(event.getLine(0).contains(plugin.getConfig().getString("signTags.buy"))) {
// Check for permission
if(!player.hasPermission("areashop.createbuy") && !player.hasPermission("areashop.createbuy.member") && !player.hasPermission("areashop.createbuy.owner")) {
messageBridge.message(player, "setup-noPermissionBuy");
return;
}
// Get the other lines
String secondLine = event.getLine(1);
String thirdLine = event.getLine(2);
// Get the regionManager for accessing regions
RegionManager regionManager = plugin.getRegionManager(event.getPlayer().getWorld());
// If the secondLine does not contain a name try to find the region by location
if(secondLine == null || secondLine.isEmpty()) {
Set<ProtectedRegion> regions = worldGuardInterface.getApplicableRegionsSet(event.getBlock().getLocation());
if(regions != null) {
boolean first = true;
ProtectedRegion candidate = null;
for(ProtectedRegion pr : regions) {
if(first) {
candidate = pr;
first = false;
} else {
if(pr.getPriority() > candidate.getPriority()) {
candidate = pr;
} else if(pr.getParent() != null && pr.getParent().equals(candidate)) {
candidate = pr;
} else {
messageBridge.message(player, "setup-couldNotDetect", candidate.getId(), pr.getId());
return;
}
}
}
if(candidate != null) {
secondLine = candidate.getId();
}
}
}
boolean priceSet = thirdLine != null && !thirdLine.isEmpty();
// Check if all the lines are correct
if(secondLine == null || secondLine.isEmpty()) {
messageBridge.message(player, "setup-noRegion");
return;
}
ProtectedRegion region = regionManager.getRegion(secondLine);
if(region == null) {
messageBridge.message(player, "cmd-noRegion", secondLine);
return;
}
IFileManager.AddResult addResult = plugin.getFileManager().checkRegionAdd(player, region, event.getPlayer().getWorld(), GeneralRegion.RegionType.BUY);
if(addResult == IFileManager.AddResult.BLACKLISTED) {
messageBridge.message(player, "setup-blacklisted", secondLine);
} else if(addResult == IFileManager.AddResult.ALREADYADDED) {
messageBridge.message(player, "setup-alreadyRentSign");
} else if(addResult == IFileManager.AddResult.ALREADYADDEDOTHERWORLD) {
messageBridge.message(player, "setup-alreadyOtherWorld");
} else if(addResult == IFileManager.AddResult.NOPERMISSION) {
messageBridge.message(player, "setup-noPermission", secondLine);
} else {
double price = 0.0;
if(priceSet) {
// Check the fourth line
try {
price = Double.parseDouble(thirdLine);
} catch(NumberFormatException e) {
messageBridge.message(player, "setup-wrongPrice");
return;
}
}
// Add buy to the FileManager
final BuyRegion buy = regionFactory.createBuyRegion(secondLine, event.getPlayer().getWorld());
boolean isMember = worldGuardInterface.containsMember(buy.getRegion(), player.getUniqueId());
boolean isOwner = worldGuardInterface.containsOwner(buy.getRegion(), player.getUniqueId());
boolean landlord = (!player.hasPermission("areashop.createbuy")
&& ((player.hasPermission("areashop.createbuy.owner") && isOwner)
|| (player.hasPermission("areashop.createbuy.member") && isMember)));
if(landlord) {
buy.setLandlord(player.getUniqueId(), player.getName());
}
if(priceSet) {
buy.setPrice(price);
}
buy.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), bukkitInterface.getSignFacing(event.getBlock()), null);
AddingRegionEvent addingRegionEvent = plugin.getFileManager().addRegion(buy);
if (addingRegionEvent.isCancelled()) {
messageBridge.message(player, "general-cancelled", addingRegionEvent.getReason());
return;
}
buy.handleSchematicEvent(GeneralRegion.RegionEvent.CREATED);
messageBridge.message(player, "setup-buySuccess", buy);
// Update the region after the event has written its lines
Do.sync(buy::update);
}
} else if(event.getLine(0).contains(plugin.getConfig().getString("signTags.add"))) {
// Check for permission
if(!player.hasPermission("areashop.addsign")) {
messageBridge.message(player, "addsign-noPermission");
return;
}
// Get the other lines
String secondLine = event.getLine(1);
String thirdLine = event.getLine(2);
GeneralRegion region;
if(secondLine != null && !secondLine.isEmpty()) {
// Get region by secondLine of the sign
region = fileManager.getRegion(secondLine);
if(region == null) {
messageBridge.message(player, "addSign-notRegistered", secondLine);
return;
}
} else {
// Get region by sign position
List<GeneralRegion> regions = Utils.getImportantRegions(event.getBlock().getLocation());
if(regions.isEmpty()) {
messageBridge.message(player, "addsign-noRegions");
return;
} else if(regions.size() > 1) {
messageBridge.message(player, "addsign-couldNotDetectSign", regions.get(0).getName(), regions.get(1).getName());
return;
}
region = regions.get(0);
}
if(thirdLine == null || thirdLine.isEmpty()) {
region.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), bukkitInterface.getSignFacing(event.getBlock()), null);
messageBridge.message(player, "addsign-success", region);
} else {
region.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), bukkitInterface.getSignFacing(event.getBlock()), thirdLine);
messageBridge.message(player, "addsign-successProfile", thirdLine, region);
}
// Update the region later because this event will do it first
Do.sync(region::update);
}
}
}
@@ -0,0 +1,101 @@
package me.wiefferink.areashop.features.signs;
import io.github.bakedlibs.dough.blocks.BlockPosition;
import me.wiefferink.areashop.managers.Manager;
import org.bukkit.Location;
import org.bukkit.World;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
public class SignManager extends Manager {
private final Map<World, SignCache> signCacheMap = new HashMap<>();
public Collection<BlockPosition> allSignLocations() {
final Set<BlockPosition> set = new HashSet<>(signCacheMap.size());
for (SignCache signCache : signCacheMap.values()) {
set.addAll(signCache.allSignLocations());
}
return set;
}
public Collection<RegionSign> allSigns() {
final Set<RegionSign> signs = new HashSet<>(signCacheMap.size());
for (SignCache signCache : signCacheMap.values()) {
signs.addAll(signCache.allSigns());
}
return signs;
}
public SignCache cacheForWorld(World world) {
return this.signCacheMap.computeIfAbsent(world, x -> new SignCache());
}
public Optional<SignCache> getCacheForWorld(World world) {
return Optional.ofNullable(this.signCacheMap.get(world));
}
public Optional<RegionSign> signFromLocation(Location location) {
final World world = location.getWorld();
return getCacheForWorld(world)
.flatMap(cache -> cache.signAtLocation(BlockPosition.getAsLong(location)));
}
public void addSign(RegionSign regionSign) {
Location location = regionSign.getLocation();
cacheForWorld(location.getWorld()).addSign(regionSign);
}
public void removeSign(RegionSign regionSign) {
removeSign(regionSign.getLocation());
}
public Optional<RegionSign> removeSign(Location location) {
return getCacheForWorld(location.getWorld()).flatMap(cache -> cache.removeSign(location));
}
/**
* Update all signs connected to this region.
* @return true if all signs are updated correctly, false if one or more updates failed
*/
public boolean update() {
boolean result = true;
for (SignCache signCache : this.signCacheMap.values())
for(RegionSign sign : signCache.allSigns()) {
result &= sign.update();
}
return result;
}
/**
* Check if any of the signs need periodic updating.
* @return true if one or more of the signs need periodic updating, otherwise false
*/
public boolean needsPeriodicUpdate() {
boolean result = false;
for (SignCache signCache : this.signCacheMap.values()) {
for (RegionSign sign : signCache.allSigns()) {
if (result) {
break;
}
if (sign.needsPeriodicUpdate()) {
result = true;
break;
}
}
}
return result;
}
public void shutdown() {
this.signCacheMap.values().forEach(SignCache::clear);
this.signCacheMap.clear();
}
}
@@ -1,636 +1,103 @@
package me.wiefferink.areashop.features.signs;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.events.ask.AddingRegionEvent;
import me.wiefferink.areashop.events.notify.UpdateRegionEvent;
import me.wiefferink.areashop.features.RegionFeature;
import me.wiefferink.areashop.managers.FileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Materials;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.type.Sign;
import org.bukkit.block.data.type.WallSign;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nonnull;
public class SignsFeature extends RegionFeature {
private static final Map<String, RegionSign> allSigns = new ConcurrentHashMap<>();
private static final Map<String, List<RegionSign>> signsByChunk = new ConcurrentHashMap<>();
private final SignManager internalSignManager = new SignManager();
private final SignManager globalSignManager;
private final SignFactory signFactory;
/**
* Constructor.
* @param region The region to bind to
*/
@AssistedInject
SignsFeature(@Nonnull AreaShop plugin,
@Nonnull SignManager signManager,
@Nonnull SignFactory signFactory,
@Assisted @Nonnull GeneralRegion region
) {
super(plugin);
this.globalSignManager = signManager;
this.signFactory = signFactory;
setRegion(region);
// Setup current signs
ConfigurationSection signSection = region.getConfig().getConfigurationSection("general.signs");
if(signSection != null) {
for(String signKey : signSection.getKeys(false)) {
RegionSign sign = signFactory.createRegionSign(this, signKey);
Location location = sign.getLocation();
if(location == null) {
AreaShop.warn("Sign with key " + signKey + " of region " + region.getName() + " does not have a proper location");
continue;
}
this.globalSignManager.cacheForWorld(location.getWorld()).addSign(sign);
this.internalSignManager.addSign(sign);
}
}
}
private Map<String, RegionSign> signs;
/**
* Convert a location to a string to use as map key.
* @param location The location to get the key for
* @return A string to use in a map for a location
*/
public static String locationToString(Location location) {
return location.getWorld().getName() + ";" + location.getBlockX() + ";" + location.getBlockY() + ";" + location.getBlockZ();
}
public SignsFeature() {
/**
* Convert a chunk to a string to use as map key.
* @param location The location to get the key for
* @return A string to use in a map for a chunk
*/
public static String chunkToString(Location location) {
return location.getWorld().getName() + ";" + (location.getBlockX() >> 4) + ";" + (location.getBlockZ() >> 4);
}
}
@Override
public void shutdown() {
/**
* Constructor.
*
* @param region The region to bind to
*/
public SignsFeature(GeneralRegion region) {
setRegion(region);
signs = new HashMap<>();
// Setup current signs
ConfigurationSection signSection = region.getConfig().getConfigurationSection("general.signs");
if (signSection != null) {
for (String signKey : signSection.getKeys(false)) {
RegionSign sign = new RegionSign(this, signKey);
Location location = sign.getLocation();
if (location == null) {
AreaShop.warn("Sign with key " + signKey + " of region " + region.getName() + " does not have a proper location");
continue;
}
signs.put(sign.getStringLocation(), sign);
signsByChunk.computeIfAbsent(sign.getStringChunk(), key -> new ArrayList<>())
.add(sign);
}
allSigns.putAll(signs);
}
}
}
/**
* Convert a location to a string to use as map key.
*
* @param location The location to get the key for
* @return A string to use in a map for a location
*/
public static String locationToString(Location location) {
return location.getWorld().getName() + ";" + location.getBlockX() + ";" + location.getBlockY() + ";" + location.getBlockZ();
}
public SignManager signManager() {
return this.internalSignManager;
}
/**
* Convert a chunk to a string to use as map key.
*
* @param location The location to get the key for
* @return A string to use in a map for a chunk
*/
public static String chunkToString(Location location) {
return location.getWorld().getName() + ";" + (location.getBlockX() >> 4) + ";" + (location.getBlockZ() >> 4);
}
/**
* Convert a chunk to a string to use as map key.
* Use a Location argument to prevent chunk loading!
*
* @param chunk The location to get the key for
* @return A string to use in a map for a chunk
*/
public static String chunkToString(Chunk chunk) {
return chunk.getWorld().getName() + ";" + chunk.getX() + ";" + chunk.getZ();
}
/**
* Get a sign by a location.
*
* @param location The location to get the sign for
* @return The RegionSign that is at the location, or null if none
*/
public static RegionSign getSignByLocation(Location location) {
return allSigns.get(locationToString(location));
}
/**
* Get the map with all signs.
*
* @return Map with all signs: locationString -&gt; RegionSign
*/
public static Map<String, RegionSign> getAllSigns() {
return allSigns;
}
/**
* Get the map with signs by chunk.
*
* @return Map with signs by chunk: chunkString -&gt; List&lt;RegionSign&gt;
*/
public static Map<String, List<RegionSign>> getSignsByChunk() {
return signsByChunk;
}
@Override
public void shutdown() {
// Deregister signs from the registry
if (signs != null) {
for (Map.Entry<String, RegionSign> entry : signs.entrySet()) {
allSigns.remove(entry.getKey());
signsByChunk.get(entry.getValue().getStringChunk()).remove(entry.getValue());
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onSignBreak(BlockBreakEvent event) {
if (event.isCancelled()) {
return;
}
Block block = event.getBlock();
// Check if it is a sign
if (Materials.isSign(block.getType())) {
// Check if the rent sign is really the same as a saved rent
RegionSign regionSign = SignsFeature.getSignByLocation(block.getLocation());
if (regionSign == null) {
return;
}
// Remove the sign of the rental region if the player has permission
if (event.getPlayer().hasPermission("areashop.delsign")) {
regionSign.remove();
plugin.message(event.getPlayer(), "delsign-success", regionSign.getRegion());
} else { // Cancel the breaking of the sign
event.setCancelled(true);
plugin.message(event.getPlayer(), "delsign-noPermission", regionSign.getRegion());
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onIndirectSignBreak(BlockPhysicsEvent event) {
// Check if the block is a sign
if (!Materials.isSign(event.getBlock().getType())) {
return;
}
final Block block = event.getBlock();
final BlockData blockData = block.getBlockData();
final Block attachedBlock;
if (blockData instanceof WallSign) {
attachedBlock = block.getRelative(((WallSign) blockData).getFacing().getOppositeFace());
} else if (blockData instanceof Sign) {
attachedBlock = block.getRelative(BlockFace.DOWN);
} else {
attachedBlock = null;
}
// Check if still attached to a block
// TODO: signs cannot be placed on all blocks, improve this check to isSolid()?
if (attachedBlock == null || attachedBlock.getType() != Material.AIR) {
return;
}
// Check if the sign is really the same as a saved rent
RegionSign regionSign = SignsFeature.getSignByLocation(event.getBlock().getLocation());
if (regionSign == null) {
return;
}
// Remove the sign so that it does not fall on the floor as an item (next region update will place it back when possible)
AreaShop.debug("onIndirectSignBreak: Removed block of sign for", regionSign.getRegion().getName(), "at", regionSign.getStringLocation());
event.getBlock().setType(Material.AIR);
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onSignClick(PlayerInteractEvent event) {
Block block = event.getClickedBlock();
if (block == null) {
return;
}
// Only listen to left and right clicks on blocks
if (!(event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_BLOCK)) {
return;
}
// Only care about clicking blocks
if (!Materials.isSign(block.getType())) {
return;
}
// Check if this sign belongs to a region
RegionSign regionSign = SignsFeature.getSignByLocation(block.getLocation());
if (regionSign == null) {
return;
}
// Ignore players that are in sign link mode (which will handle the event itself)
Player player = event.getPlayer();
if (plugin.getSignlinkerManager().isInSignLinkMode(player)) {
return;
}
// Get the clicktype
GeneralRegion.ClickType clickType = null;
if (player.isSneaking() && event.getAction() == Action.LEFT_CLICK_BLOCK) {
clickType = GeneralRegion.ClickType.SHIFTLEFTCLICK;
} else if (!player.isSneaking() && event.getAction() == Action.LEFT_CLICK_BLOCK) {
clickType = GeneralRegion.ClickType.LEFTCLICK;
} else if (player.isSneaking() && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
clickType = GeneralRegion.ClickType.SHIFTRIGHTCLICK;
} else if (!player.isSneaking() && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
clickType = GeneralRegion.ClickType.RIGHTCLICK;
}
boolean ran = regionSign.runSignCommands(player, clickType);
// Only cancel event if at least one command has been executed
event.setCancelled(ran);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onSignChange(SignChangeEvent event) {
if (event.isCancelled()) {
return;
}
Player player = event.getPlayer();
if (!plugin.isReady()) {
plugin.message(player, "general-notReady");
return;
}
final BlockFace rotation;
final BlockData data = event.getBlock().getBlockData();
if (data instanceof Sign) {
rotation = ((Sign) data).getRotation();
} else if (data instanceof WallSign) {
rotation = ((WallSign) data).getFacing();
} else {
rotation = null;
}
final String line0 = event.getLine(0) == null ? "" : event.getLine(0);
// Check if the sign is meant for this plugin
if (line0.contains(plugin.getConfig().getString("signTags.rent"))) {
if (!player.hasPermission("areashop.createrent") && !player.hasPermission("areashop.createrent.member") && !player.hasPermission("areashop.createrent.owner")) {
plugin.message(player, "setup-noPermissionRent");
return;
}
// Get the other lines
String secondLine = event.getLine(1);
String thirdLine = event.getLine(2);
String fourthLine = event.getLine(3);
// Get the regionManager for accessing regions
RegionManager regionManager = plugin.getRegionManager(event.getPlayer().getWorld());
// If the secondLine does not contain a name try to find the region by location
if (secondLine == null || secondLine.isEmpty()) {
Set<ProtectedRegion> regions = plugin.getWorldGuardHandler().getApplicableRegionsSet(event.getBlock().getLocation());
if (regions != null) {
boolean first = true;
ProtectedRegion candidate = null;
for (ProtectedRegion pr : regions) {
if (first) {
candidate = pr;
first = false;
} else {
if (pr.getPriority() > candidate.getPriority()) {
candidate = pr;
} else if (pr.getParent() != null && pr.getParent().equals(candidate)) {
candidate = pr;
} else {
plugin.message(player, "setup-couldNotDetect", candidate.getId(), pr.getId());
return;
}
}
}
if (candidate != null) {
secondLine = candidate.getId();
}
}
}
boolean priceSet = fourthLine != null && !fourthLine.isEmpty();
boolean durationSet = thirdLine != null && !thirdLine.isEmpty();
// check if all the lines are correct
if (secondLine == null || secondLine.isEmpty()) {
plugin.message(player, "setup-noRegion");
return;
}
ProtectedRegion region = regionManager.getRegion(secondLine);
if (region == null) {
plugin.message(player, "cmd-noRegion", secondLine);
return;
}
FileManager.AddResult addResult = plugin.getFileManager().checkRegionAdd(player, regionManager.getRegion(secondLine), event.getPlayer().getWorld(), GeneralRegion.RegionType.RENT);
switch (addResult) {
case BLACKLISTED:
plugin.message(player, "setup-blacklisted", secondLine);
break;
case ALREADYADDED:
plugin.message(player, "setup-alreadyRentSign");
break;
case ALREADYADDEDOTHERWORLD:
plugin.message(player, "setup-alreadyOtherWorld");
break;
case NOPERMISSION:
plugin.message(player, "setup-noPermission", secondLine);
break;
default:
if (thirdLine != null && !thirdLine.isEmpty() && !Utils.checkTimeFormat(thirdLine)) {
plugin.message(player, "setup-wrongDuration");
break;
}
double price = 0.0;
if (priceSet) {
// Check the fourth line
try {
price = Double.parseDouble(fourthLine);
} catch (NumberFormatException e) {
plugin.message(player, "setup-wrongPrice");
return;
}
}
// Add rent to the FileManager
final RentRegion rent = new RentRegion(secondLine, event.getPlayer().getWorld());
boolean isMember = plugin.getWorldGuardHandler().containsMember(rent.getRegion(), player.getUniqueId());
boolean isOwner = plugin.getWorldGuardHandler().containsOwner(rent.getRegion(), player.getUniqueId());
boolean landlord = (!player.hasPermission("areashop.createrent")
&& ((player.hasPermission("areashop.createrent.owner") && isOwner)
|| (player.hasPermission("areashop.createrent.member") && isMember)));
if (landlord) {
rent.setLandlord(player.getUniqueId(), player.getName());
}
if (priceSet) {
rent.setPrice(price);
}
if (durationSet) {
rent.setDuration(thirdLine);
}
rent.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), rotation, null);
AddingRegionEvent addingRegionEvent = plugin.getFileManager().addRegion(rent);
if (addingRegionEvent.isCancelled()) {
plugin.message(player, "general-cancelled", addingRegionEvent.getReason());
return;
}
rent.handleSchematicEvent(GeneralRegion.RegionEvent.CREATED);
plugin.message(player, "setup-rentSuccess", rent);
// Update the region after the event has written its lines
Bukkit.getScheduler().runTask(plugin, rent::update);
}
} else if (line0.contains(plugin.getConfig().getString("signTags.buy"))) {
// Check for permission
if (!player.hasPermission("areashop.createbuy") && !player.hasPermission("areashop.createbuy.member") && !player.hasPermission("areashop.createbuy.owner")) {
plugin.message(player, "setup-noPermissionBuy");
return;
}
// Get the other lines
String secondLine = event.getLine(1);
String thirdLine = event.getLine(2);
// Get the regionManager for accessing regions
RegionManager regionManager = plugin.getRegionManager(event.getPlayer().getWorld());
// If the secondLine does not contain a name try to find the region by location
if (secondLine == null || secondLine.isEmpty()) {
Set<ProtectedRegion> regions = plugin.getWorldGuardHandler().getApplicableRegionsSet(event.getBlock().getLocation());
if (regions != null) {
boolean first = true;
ProtectedRegion candidate = null;
for (ProtectedRegion pr : regions) {
if (first) {
candidate = pr;
first = false;
} else {
if (pr.getPriority() > candidate.getPriority()) {
candidate = pr;
} else if (pr.getParent() != null && pr.getParent().equals(candidate)) {
candidate = pr;
} else {
plugin.message(player, "setup-couldNotDetect", candidate.getId(), pr.getId());
return;
}
}
}
if (candidate != null) {
secondLine = candidate.getId();
}
}
}
boolean priceSet = thirdLine != null && !thirdLine.isEmpty();
// Check if all the lines are correct
if (secondLine == null || secondLine.isEmpty()) {
plugin.message(player, "setup-noRegion");
return;
}
ProtectedRegion region = regionManager.getRegion(secondLine);
if (region == null) {
plugin.message(player, "cmd-noRegion", secondLine);
return;
}
FileManager.AddResult addResult = plugin.getFileManager().checkRegionAdd(player, region, event.getPlayer().getWorld(), GeneralRegion.RegionType.BUY);
if (addResult == FileManager.AddResult.BLACKLISTED) {
plugin.message(player, "setup-blacklisted", secondLine);
} else if (addResult == FileManager.AddResult.ALREADYADDED) {
plugin.message(player, "setup-alreadyRentSign");
} else if (addResult == FileManager.AddResult.ALREADYADDEDOTHERWORLD) {
plugin.message(player, "setup-alreadyOtherWorld");
} else if (addResult == FileManager.AddResult.NOPERMISSION) {
plugin.message(player, "setup-noPermission", secondLine);
} else {
double price = 0.0;
if (priceSet) {
// Check the fourth line
try {
price = Double.parseDouble(thirdLine);
} catch (NumberFormatException e) {
plugin.message(player, "setup-wrongPrice");
return;
}
}
// Add buy to the FileManager
final BuyRegion buy = new BuyRegion(secondLine, event.getPlayer().getWorld());
boolean isMember = plugin.getWorldGuardHandler().containsMember(buy.getRegion(), player.getUniqueId());
boolean isOwner = plugin.getWorldGuardHandler().containsOwner(buy.getRegion(), player.getUniqueId());
boolean landlord = (!player.hasPermission("areashop.createbuy")
&& ((player.hasPermission("areashop.createbuy.owner") && isOwner)
|| (player.hasPermission("areashop.createbuy.member") && isMember)));
if (landlord) {
buy.setLandlord(player.getUniqueId(), player.getName());
}
if (priceSet) {
buy.setPrice(price);
}
buy.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), rotation, null);
AddingRegionEvent addingRegionEvent = plugin.getFileManager().addRegion(buy);
if (addingRegionEvent.isCancelled()) {
plugin.message(player, "general-cancelled", addingRegionEvent.getReason());
return;
}
buy.handleSchematicEvent(GeneralRegion.RegionEvent.CREATED);
plugin.message(player, "setup-buySuccess", buy);
// Update the region after the event has written its lines
Bukkit.getScheduler().runTask(plugin, buy::update);
}
} else if (event.getLine(0).contains(plugin.getConfig().getString("signTags.add"))) {
// Check for permission
if (!player.hasPermission("areashop.addsign")) {
plugin.message(player, "addsign-noPermission");
return;
}
// Get the other lines
String secondLine = event.getLine(1);
String thirdLine = event.getLine(2);
GeneralRegion region;
if (secondLine != null && !secondLine.isEmpty()) {
// Get region by secondLine of the sign
region = plugin.getFileManager().getRegion(secondLine);
if (region == null) {
plugin.message(player, "addSign-notRegistered", secondLine);
return;
}
} else {
// Get region by sign position
List<GeneralRegion> regions = Utils.getImportantRegions(event.getBlock().getLocation());
if (regions.isEmpty()) {
plugin.message(player, "addsign-noRegions");
return;
} else if (regions.size() > 1) {
plugin.message(player, "addsign-couldNotDetectSign", regions.get(0).getName(), regions.get(1).getName());
return;
}
region = regions.get(0);
}
String profile = thirdLine == null || thirdLine.isEmpty() ? null : thirdLine;
region.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), rotation, profile);
if (profile == null) {
plugin.message(player, "addsign-success", region);
} else {
plugin.message(player, "addsign-successProfile", thirdLine, region);
}
// Update the region later because this event will do it first
Bukkit.getScheduler().runTask(plugin, region::update);
}
}
@EventHandler
public void regionUpdate(UpdateRegionEvent event) {
event.getRegion().getSignsFeature().update();
}
@EventHandler(priority = EventPriority.MONITOR)
public void onChunkLoad(ChunkLoadEvent event) {
List<RegionSign> chunkSigns = signsByChunk.get(chunkToString(event.getChunk()));
if (chunkSigns == null) {
return;
}
int batchSize = Math.max(chunkSigns.size() / 10, 10);
Utils.runAsBatches(chunkSigns, batchSize, RegionSign::update, false);
}
/**
* Update all signs connected to this region.
*
* @return true if all signs are updated correctly, false if one or more updates failed
*/
public boolean update() {
boolean result = true;
for (RegionSign sign : signs.values()) {
result &= sign.update();
}
return result;
}
/**
* Check if any of the signs need periodic updating.
*
* @return true if one or more of the signs need periodic updating, otherwise false
*/
public boolean needsPeriodicUpdate() {
for (RegionSign sign : signs.values()) {
if (sign.needsPeriodicUpdate()) {
return true;
}
}
return false;
}
/**
* Get the signs of this region.
*
* @return List of signs
*/
public Collection<RegionSign> getSigns() {
return new HashSet<>(signs.values());
}
/**
* Get the signs of this region.
*
* @return Map with signs: locationString -&gt; RegionSign
*/
Map<String, RegionSign> getSignsRef() {
return signs;
}
/**
* Get a list with all sign locations.
*
* @return A List with all sign locations
*/
public List<Location> getSignLocations() {
List<Location> result = new ArrayList<>();
for (RegionSign sign : signs.values()) {
result.add(sign.getLocation());
}
return result;
}
/**
* Add a sign to this region.
*
* @param location The location of the sign
* @param signType The type of the sign (WALL_SIGN or SIGN_POST)
* @param facing The orientation of the sign
* @param profile The profile to use with this sign (null for default)
*/
public void addSign(Location location, Material signType, BlockFace facing, String profile) {
int i = 0;
while (getRegion().getConfig().isSet("general.signs." + i)) {
i++;
}
String signPath = "general.signs." + i + ".";
getRegion().setSetting(signPath + "location", Utils.locationToConfig(location));
getRegion().setSetting(signPath + "facing", facing != null ? facing.name() : null);
getRegion().setSetting(signPath + "signType", signType != null ? signType.name() : null);
if (profile != null && !profile.isEmpty()) {
getRegion().setSetting(signPath + "profile", profile);
}
// Add to the map
RegionSign sign = new RegionSign(this, i + "");
signs.put(sign.getStringLocation(), sign);
allSigns.put(sign.getStringLocation(), sign);
signsByChunk.computeIfAbsent(sign.getStringChunk(), key -> new ArrayList<>())
.add(sign);
}
/**
* Add a sign to this region.
* @param location The location of the sign
* @param signType The type of the sign (WALL_SIGN or SIGN_POST)
* @param facing The orientation of the sign
* @param profile The profile to use with this sign (null for default)
*/
public void addSign(Location location, Material signType, BlockFace facing, String profile) {
int i = 0;
while(getRegion().getConfig().isSet("general.signs." + i)) {
i++;
}
String signPath = "general.signs." + i + ".";
getRegion().setSetting(signPath + "location", Utils.locationToConfig(location));
getRegion().setSetting(signPath + "facing", facing != null ? facing.name() : null);
getRegion().setSetting(signPath + "signType", signType != null ? signType.name() : null);
if(profile != null && !profile.isEmpty()) {
getRegion().setSetting(signPath + "profile", profile);
}
// Add to the map
RegionSign regionSign = this.signFactory.createRegionSign(this, String.valueOf(i));
this.globalSignManager.addSign(regionSign);
this.internalSignManager.addSign(regionSign);
}
}
@@ -0,0 +1,53 @@
package me.wiefferink.areashop.features.signs;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.interfaces.BukkitInterface;
import me.wiefferink.areashop.interfaces.WorldGuardInterface;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.managers.SignLinkerManager;
import me.wiefferink.areashop.nms.BlockBehaviourHelper;
import me.wiefferink.areashop.regions.RegionFactory;
import javax.annotation.Nonnull;
public class SignsModule extends AbstractModule {
@Override
protected void configure() {
bind(SignManager.class).asEagerSingleton();
install(new FactoryModuleBuilder().build(SignFactory.class));
}
@Provides
@Singleton
public SignListener provideSignListener(@Nonnull AreaShop plugin,
@Nonnull BlockBehaviourHelper behaviourHelper,
@Nonnull RegionFactory regionFactory,
@Nonnull MessageBridge messageBridge,
@Nonnull SignLinkerManager signLinkerManager,
@Nonnull BukkitInterface bukkitInterface,
@Nonnull WorldGuardInterface worldGuardInterface,
@Nonnull SignManager signManager,
@Nonnull IFileManager fileManager
) {
final SignListener signListener = new SignListener(
plugin,
behaviourHelper,
regionFactory,
messageBridge,
signLinkerManager,
bukkitInterface,
worldGuardInterface,
signManager,
fileManager
);
plugin.getServer().getPluginManager().registerEvents(signListener, plugin);
return signListener;
}
}
@@ -1,11 +1,12 @@
package me.wiefferink.areashop.listeners;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.regions.TransactionalRegion;
import me.wiefferink.areashop.tools.Utils;
import me.wiefferink.bukkitdo.Do;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@@ -15,121 +16,123 @@ import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.event.player.PlayerQuitEvent;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* Notify region expiry and track activity time.
*/
public final class PlayerLoginLogoutListener implements Listener {
private final AreaShop plugin;
/**
* Constructor.
*
* @param plugin The AreaShop plugin
*/
public PlayerLoginLogoutListener(AreaShop plugin) {
this.plugin = plugin;
}
private final AreaShop plugin;
private final MessageBridge messageBridge;
/**
* Called when a sign is changed.
*
* @param event The event
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerLogin(PlayerLoginEvent event) {
if (event.getResult() != Result.ALLOWED) {
return;
}
final Player player = event.getPlayer();
/**
* Constructor.
* @param plugin The AreaShop plugin
*/
public PlayerLoginLogoutListener(@Nonnull AreaShop plugin, @Nonnull MessageBridge messageBridge) {
this.plugin = plugin;
this.messageBridge = messageBridge;
}
// Schedule task to check for notifications, prevents a lag spike at login
Utils.runCancellingTaskTimer(() -> {
// Delay until all regions are loaded
if (!plugin.isReady()) {
return true;
}
if (!player.isOnline()) {
return false;
}
// Notify for rents that almost run out
for (GeneralRegion generalRegion : plugin.getFileManager().getRegions()) {
if (!(generalRegion instanceof RentRegion)) {
continue;
}
final RentRegion region = (RentRegion) generalRegion;
if (region.isTransactionHolder(player)) {
String warningSetting = region.getStringSetting("rent.warningOnLoginTime");
if (warningSetting == null || warningSetting.isEmpty()) {
continue;
}
long warningTime = Utils.durationStringToLong(warningSetting);
if (region.getTimeLeft() < warningTime) {
// Send the warning message later to let it appear after general MOTD messages
AreaShop.getInstance().message(player, "rent-expireWarning", region);
}
}
}
/**
* Called when a sign is changed.
* @param event The event
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerLogin(PlayerLoginEvent event) {
if(event.getResult() != Result.ALLOWED) {
return;
}
final Player player = event.getPlayer();
// Notify admins for plugin updates
AreaShop.getInstance().notifyUpdate(player);
return false;
}, 25, 25, false);
// Schedule task to check for notifications, prevents a lag spike at login
Do.syncTimerLater(25, 25, () -> {
// Delay until all regions are loaded
if(!plugin.isReady()) {
return true;
}
if(!player.isOnline()) {
return false;
}
// Notify for rents that almost run out
for(RentRegion region : plugin.getFileManager().getRentsRef()) {
if(region.isRenter(player)) {
String warningSetting = region.getStringSetting("rent.warningOnLoginTime");
if(warningSetting == null || warningSetting.isEmpty()) {
continue;
}
long warningTime = Utils.durationStringToLong(warningSetting);
if(region.getTimeLeft() < warningTime) {
// Send the warning message later to let it appear after general MOTD messages
messageBridge.message(player, "rent-expireWarning", region);
}
}
}
// Check if the player has regions that use an old name of him and update them
Utils.runCancellingTaskTimer(() -> {
if (!plugin.isReady()) {
return true;
}
// Notify admins for plugin updates
this.plugin.notifyUpdate(player);
return false;
});
List<GeneralRegion> regions = new LinkedList<>();
for (GeneralRegion region : plugin.getFileManager().getRegions()) {
if (region instanceof TransactionalRegion && ((TransactionalRegion) region).isTransactionHolder(player)) {
regions.add(region);
}
}
final String name = player.getName();
Utils.runAsBatches(regions,
plugin.getConfig().getInt("nameupdate.regionsPerTick"),
(region) -> {
if (region instanceof BuyRegion || region instanceof RentRegion) {
String key = region instanceof BuyRegion ? "buy.buyerName" : "rent.renterName";
if (!name.equals(region.getStringSetting("buy.buyerName"))) {
region.setSetting(key, player.getName());
region.update();
}
}
}, false);
return false;
}, 22, 10, false);
}
// Check if the player has regions that use an old name of him and update them
Do.syncTimerLater(22, 10, () -> {
if(!plugin.isReady()) {
return true;
}
// Active time updates
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerLogout(PlayerQuitEvent event) {
updateLastActive(event.getPlayer());
}
List<GeneralRegion> regions = new ArrayList<>();
for(GeneralRegion region : plugin.getFileManager().getRegionsRef()) {
if(region.isOwner(player)) {
regions.add(region);
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerKick(PlayerKickEvent event) {
updateLastActive(event.getPlayer());
}
Do.forAll(
plugin.getConfig().getInt("nameupdate.regionsPerTick"),
regions,
region -> {
if(region instanceof BuyRegion) {
if(!player.getName().equals(region.getStringSetting("buy.buyerName"))) {
region.setSetting("buy.buyerName", player.getName());
region.update();
}
} else if(region instanceof RentRegion) {
if(!player.getName().equals(region.getStringSetting("rent.renterName"))) {
region.setSetting("rent.renterName", player.getName());
region.update();
}
}
}
);
return false;
});
}
/**
* Update the last active time for all regions the player is owner off.
*
* @param player The player to update the active times for
*/
private void updateLastActive(Player player) {
for (GeneralRegion region : plugin.getFileManager().getRegions()) {
if (region instanceof TransactionalRegion && ((TransactionalRegion) region).isTransactionHolder(player)) {
region.updateLastActiveTime();
}
}
}
// Active time updates
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerLogout(PlayerQuitEvent event) {
updateLastActive(event.getPlayer());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerKick(PlayerKickEvent event) {
updateLastActive(event.getPlayer());
}
/**
* Update the last active time for all regions the player is owner off.
* @param player The player to update the active times for
*/
private void updateLastActive(Player player) {
for(GeneralRegion region : plugin.getFileManager().getRegionsRef()) {
if(region.isOwner(player)) {
region.updateLastActiveTime();
}
}
}
}
@@ -1,5 +1,8 @@
package me.wiefferink.areashop.managers;
import com.google.inject.Injector;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.commands.AddCommand;
import me.wiefferink.areashop.commands.AddfriendCommand;
import me.wiefferink.areashop.commands.AddsignCommand;
@@ -39,52 +42,62 @@ import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
@Singleton
public class CommandManager extends Manager implements CommandExecutor, TabCompleter {
private final ArrayList<CommandAreaShop> commands;
private final List<CommandAreaShop> commands;
private final AreaShop plugin;
private final MessageBridge messageBridge;
/**
* Constructor.
*/
public CommandManager() {
commands = new ArrayList<>();
commands.add(new HelpCommand());
commands.add(new RentCommand());
commands.add(new UnrentCommand());
commands.add(new BuyCommand());
commands.add(new SellCommand());
commands.add(new MeCommand());
commands.add(new InfoCommand());
commands.add(new TeleportCommand());
commands.add(new SetteleportCommand());
commands.add(new AddfriendCommand());
commands.add(new DelfriendCommand());
commands.add(new FindCommand());
commands.add(new ResellCommand());
commands.add(new StopresellCommand());
commands.add(new SetrestoreCommand());
commands.add(new SetpriceCommand());
commands.add(new SetownerCommand());
commands.add(new SetdurationCommand());
commands.add(new ReloadCommand());
commands.add(new GroupaddCommand());
commands.add(new GroupdelCommand());
commands.add(new GrouplistCommand());
commands.add(new GroupinfoCommand());
commands.add(new SchematiceventCommand());
commands.add(new AddCommand());
commands.add(new DelCommand());
commands.add(new AddsignCommand());
commands.add(new DelsignCommand());
commands.add(new LinksignsCommand());
commands.add(new StackCommand());
commands.add(new SetlandlordCommand());
commands.add(new MessageCommand());
commands.add(new ImportCommand());
@Inject
CommandManager(@Nonnull AreaShop plugin, @Nonnull MessageBridge messageBridge, @Nonnull
Injector injector) {
this.plugin = plugin;
this.messageBridge = messageBridge;
commands = new ArrayList<>(34);
commands.add(new HelpCommand(this));
commands.add(injector.getInstance(RentCommand.class));
commands.add(injector.getInstance(UnrentCommand.class));
commands.add(injector.getInstance(BuyCommand.class));
commands.add(injector.getInstance(SellCommand.class));
commands.add(injector.getInstance(MeCommand.class));
commands.add(injector.getInstance(InfoCommand.class));
commands.add(injector.getInstance(TeleportCommand.class));
commands.add(injector.getInstance(SetteleportCommand.class));
commands.add(injector.getInstance(AddfriendCommand.class));
commands.add(injector.getInstance(DelfriendCommand.class));
commands.add(injector.getInstance(FindCommand.class));
commands.add(injector.getInstance(ResellCommand.class));
commands.add(injector.getInstance(StopresellCommand.class));
commands.add(injector.getInstance(SetrestoreCommand.class));
commands.add(injector.getInstance(SetpriceCommand.class));
commands.add(injector.getInstance(SetownerCommand.class));
commands.add(injector.getInstance(SetdurationCommand.class));
commands.add(injector.getInstance(ReloadCommand.class));
commands.add(injector.getInstance(GroupaddCommand.class));
commands.add(injector.getInstance(GroupdelCommand.class));
commands.add(injector.getInstance(GrouplistCommand.class));
commands.add(injector.getInstance(GroupinfoCommand.class));
commands.add(injector.getInstance(SchematiceventCommand.class));
commands.add(injector.getInstance(AddCommand.class));
commands.add(injector.getInstance(DelCommand.class));
commands.add(injector.getInstance(AddsignCommand.class));
commands.add(injector.getInstance(DelsignCommand.class));
commands.add(injector.getInstance(LinksignsCommand.class));
commands.add(injector.getInstance(StackCommand.class));
commands.add(injector.getInstance(SetlandlordCommand.class));
commands.add(injector.getInstance(MessageCommand.class));
commands.add(injector.getInstance(ImportCommand.class));
// Register commands in bukkit
plugin.getCommand("AreaShop").setExecutor(this);
@@ -105,13 +118,13 @@ public class CommandManager extends Manager implements CommandExecutor, TabCompl
*/
public void showHelp(CommandSender target) {
if(!target.hasPermission("areashop.help")) {
plugin.message(target, "help-noPermission");
messageBridge.message(target, "help-noPermission");
return;
}
// Add all messages to a list
ArrayList<String> messages = new ArrayList<>();
plugin.message(target, "help-header");
plugin.message(target, "help-alias");
messageBridge.message(target, "help-header");
messageBridge.message(target, "help-alias");
for(CommandAreaShop command : commands) {
String help = command.getHelp(target);
if(help != null && !help.isEmpty()) {
@@ -120,14 +133,14 @@ public class CommandManager extends Manager implements CommandExecutor, TabCompl
}
// Send the messages to the target
for(String message : messages) {
plugin.messageNoPrefix(target, message);
messageBridge.messageNoPrefix(target, message);
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) {
if(!plugin.isReady()) {
plugin.message(sender, "general-notReady");
messageBridge.message(sender, "general-notReady");
return true;
}
@@ -153,9 +166,9 @@ public class CommandManager extends Manager implements CommandExecutor, TabCompl
} else {
// Indicate that the '/as updaterents' and '/as updatebuys' commands are removed
if("updaterents".equalsIgnoreCase(args[0]) || "updatebuys".equalsIgnoreCase(args[0])) {
plugin.message(sender, "reload-updateCommandChanged");
messageBridge.message(sender, "reload-updateCommandChanged");
} else {
plugin.message(sender, "cmd-notValid");
messageBridge.message(sender, "cmd-notValid");
}
}
}
@@ -1,8 +1,11 @@
package me.wiefferink.areashop.managers;
import com.google.inject.Injector;
import com.google.inject.ProvisionException;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.features.CommandsFeature;
import me.wiefferink.areashop.features.DebugFeature;
import me.wiefferink.areashop.features.FeatureFactory;
import me.wiefferink.areashop.features.FriendsFeature;
import me.wiefferink.areashop.features.RegionFeature;
import me.wiefferink.areashop.features.TeleportFeature;
@@ -10,57 +13,63 @@ import me.wiefferink.areashop.features.WorldGuardRegionFlagsFeature;
import me.wiefferink.areashop.features.signs.SignsFeature;
import me.wiefferink.areashop.regions.GeneralRegion;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
@Singleton
public class FeatureManager extends Manager {
// List of defined features
private static final Set<Class<? extends RegionFeature>> featureClasses = new HashSet<>(Arrays.asList(
DebugFeature.class,
SignsFeature.class,
FriendsFeature.class,
private static final Collection<Class<? extends RegionFeature>> globalFeatureClasses = Arrays.asList(
CommandsFeature.class,
WorldGuardRegionFlagsFeature.class,
TeleportFeature.class,
CommandsFeature.class
));
DebugFeature.class
);
// One instance of each feature, registered for event handling
private final Set<RegionFeature> globalFeatures;
private final Map<Class<? extends RegionFeature>, Constructor<? extends RegionFeature>> regionFeatureConstructors;
private final Set<RegionFeature> globalFeatures = new HashSet<>();
private final Map<Class<? extends RegionFeature>, Function<GeneralRegion, ? extends RegionFeature>> regionFeatureConstructors = new HashMap<>();
/**
* Constructor.
*/
public FeatureManager() {
@Inject
FeatureManager(@Nonnull FeatureFactory featureFactory) {
// Setup constructors for region specific features
regionFeatureConstructors.put(SignsFeature.class, wrapInstantiator(SignsFeature.class, featureFactory::createSignsFeature));
regionFeatureConstructors.put(TeleportFeature.class, wrapInstantiator(TeleportFeature.class, featureFactory::createTeleportFeature));
regionFeatureConstructors.put(FriendsFeature.class, wrapInstantiator(FriendsFeature.class, featureFactory::createFriendsFeature));
}
public void initializeFeatures(@Nonnull Injector injector) {
// Instantiate and register global features (one per type, for event handling)
globalFeatures = new HashSet<>();
for(Class<? extends RegionFeature> clazz : featureClasses) {
for(Class<? extends RegionFeature> clazz : globalFeatureClasses) {
try {
Constructor<? extends RegionFeature> constructor = clazz.getConstructor();
RegionFeature feature = constructor.newInstance();
RegionFeature feature = injector.getInstance(clazz);
feature.listen();
globalFeatures.add(feature);
} catch(InstantiationException | IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
} catch(ProvisionException e) {
AreaShop.error("Failed to instantiate global feature:", clazz, e);
} catch(NoSuchMethodException e) {
// Feature does not have a global part
}
}
}
// Setup constructors for region specific features
regionFeatureConstructors = new HashMap<>();
for(Class<? extends RegionFeature> clazz : featureClasses) {
private <T extends RegionFeature> Function<GeneralRegion, T> wrapInstantiator(Class<T> clazz, Function<GeneralRegion, T> function
) {
return region -> {
try {
regionFeatureConstructors.put(clazz, clazz.getConstructor(GeneralRegion.class));
} catch(NoSuchMethodException | IllegalArgumentException e) {
// The feature does not have a region specific part
return function.apply(region);
} catch (Throwable e) {
AreaShop.error("Failed to instantiate feature", clazz, "for region", region, e, e.getCause());
return null;
}
}
};
}
@Override
@@ -77,12 +86,7 @@ public class FeatureManager extends Manager {
* @return The feature class
*/
public RegionFeature getRegionFeature(GeneralRegion region, Class<? extends RegionFeature> featureClazz) {
try {
return regionFeatureConstructors.get(featureClazz).newInstance(region);
} catch(InstantiationException | InvocationTargetException | IllegalAccessException | IllegalArgumentException e) {
AreaShop.error("Failed to instantiate feature", featureClazz, "for region", region, e, e.getCause());
}
return null;
return regionFeatureConstructors.get(featureClazz).apply(region);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,395 @@
package me.wiefferink.areashop.managers;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import me.wiefferink.areashop.events.ask.AddingRegionEvent;
import me.wiefferink.areashop.events.ask.DeletingRegionEvent;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.regions.RentRegion;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.List;
public interface IFileManager {
/**
* Get the folder where schematics are stored.
*
* @return The folder where schematics are stored
*/
String getSchematicFolder();
/**
* Get a group.
*
* @param name The name of the group to get (will be normalized)
* @return The group if found, otherwise null
*/
RegionGroup getGroup(String name);
/**
* Get all groups.
*
* @return Collection with all groups (safe to modify)
*/
Collection<RegionGroup> getGroups();
/**
* Get the default region settings as provided by the user (default.yml).
*
* @return YamlConfiguration with the settings (might miss settings, which should be filled in with {@link #getFallbackRegionSettings()})
*/
YamlConfiguration getRegionSettings();
/**
* Get the default regions settings as provided by AreaShop (default.yml).
*
* @return YamlConfiguration with the default settings
*/
YamlConfiguration getFallbackRegionSettings();
/**
* Get the config file (config.yml).
*
* @return YamlConfiguration with the settings of users, with fallback to the settings provided by AreaShop
*/
YamlConfiguration getConfig();
/**
* Get a region.
*
* @param name The name of the region to get (will be normalized)
* @return The region if found, otherwise null
*/
@Nullable
GeneralRegion getRegion(String name);
/**
* Get a rental region.
*
* @param name The name of the rental region (will be normalized)
* @return RentRegion if it could be found, otherwise null
*/
@Nullable
RentRegion getRent(String name);
/**
* Get a buy region.
*
* @param name The name of the buy region (will be normalized)
* @return BuyRegion if it could be found, otherwise null
*/
@Nullable
BuyRegion getBuy(String name);
/**
* Get all rental regions.
*
* @return List of all rental regions
*/
Collection<RentRegion> getRents();
/**
* Get all rental regions.
*
* @return List of all rental regions
*/
Collection<RentRegion> getRentsRef();
/**
* Get all buy regions.
*
* @return List of all buy regions
*/
List<BuyRegion> getBuys();
Collection<BuyRegion> getBuysRef();
/**
* Get all regions.
*
* @return List of all regions (it is safe to modify the list)
*/
List<GeneralRegion> getRegions();
/**
* Get all regions.
*
* @return List of all regions (it is safe to modify the list)
*/
Collection<GeneralRegion> getRegionsRef();
/**
* Get a list of names of all buy regions.
*
* @return A String list with all the names
*/
List<String> getBuyNames();
/**
* Get a list of names of all rent regions.
*
* @return A String list with all the names
*/
List<String> getRentNames();
/**
* Get a list of names of all regions.
*
* @return A String list with all the names
*/
List<String> getRegionNames();
/**
* Get a list of names of all groups.
*
* @return A String list with all the names
*/
List<String> getGroupNames();
/**
* Add a region to the list and mark it as to-be-saved.
*
* @param region Then region to add
* @return true when successful, otherwise false (denied by an event listener)
*/
AddingRegionEvent addRegion(GeneralRegion region);
/**
* Add a region to the list without saving it to disk (useful for loading at startup).
*
* @param region The region to add
* @return true when successful, otherwise false (denied by an event listener)
*/
AddingRegionEvent addRegionNoSave(GeneralRegion region);
/**
* Mark all RegionGroups that they should regenerate regions.
*/
void markGroupsAutoDirty();
/**
* Add a RegionGroup.
*
* @param group The RegionGroup to add
*/
void addGroup(RegionGroup group);
/**
* Check if a player can add a certain region as rent or buy region.
*
* @param sender The player/console that wants to add a region
* @param region The WorldGuard region to add
* @param world The world the ProtectedRegion is located in
* @param type The type the region should have in AreaShop
* @return The result if a player would want to add this region
*/
AddResult checkRegionAdd(CommandSender sender,
ProtectedRegion region,
World world,
GeneralRegion.RegionType type);
/**
* Remove a region from the list.
*
* @param region The region to remove
* @param giveMoneyBack use true to give money back to the player if someone is currently holding this region, otherwise false
* @return true if the region has been removed, false otherwise
*/
DeletingRegionEvent deleteRegion(GeneralRegion region, boolean giveMoneyBack);
/**
* Remove a group.
*
* @param group Group to remove
*/
void removeGroup(RegionGroup group);
/**
* Update all signs that need periodic updating.
*/
void performPeriodicSignUpdate();
/**
* Send out rent expire warnings.
*/
void sendRentExpireWarnings();
/**
* Update regions in a task to minimize lag.
*
* @param regions Regions to update
* @param confirmationReceiver The CommandSender that should be notified at completion
*/
void updateRegions(Collection<GeneralRegion> regions, CommandSender confirmationReceiver);
/**
* Update a list of regions.
*
* @param regions The list of regions to update.
*/
void updateRegions(Collection<GeneralRegion> regions);
/**
* Update all regions, happens in a task to minimize lag.
*/
void updateAllRegions();
/**
* Update all regions.
*
* @param confirmationReceiver Optional CommandSender that should receive progress messages
*/
void updateAllRegions(CommandSender confirmationReceiver);
/**
* Save the group file to disk.
*/
void saveGroupsIsRequired();
/**
* Check if saving the groups file is required.
*
* @return true if changes are made and saving is required, otherwise false
*/
boolean isSaveGroupsRequired();
/**
* Save the groups file to disk synchronously.
*/
void saveGroupsNow();
/**
* Save all region related files spread over time (low load).
*/
void saveRequiredFiles();
/**
* Save all region related files directly (only for cases like onDisable()).
*/
void saveRequiredFilesAtOnce();
/**
* Indicates that a/multiple WorldGuard regions need to be saved.
*
* @param worldName The world where the regions that should be saved is in
*/
void saveIsRequiredForRegionWorld(String worldName);
/**
* Save all worldGuard regions that need saving.
*/
void saveWorldGuardRegions();
/**
* Get the folder the region files are located in.
*
* @return The folder where the region.yml files are in
*/
String getRegionFolder();
/**
* Check if a region is on the adding blacklist.
*
* @param region The region name to check
* @return true if the region may not be added, otherwise false
*/
boolean isBlacklisted(String region);
/**
* Unrent regions that have no time left, regions to check per tick is in the config.
*/
void checkRents();
/**
* Check all regions and unrent/sell them if the player is inactive for too long.
*/
void checkForInactiveRegions();
/**
* Load the file with the versions, used to check if the other files need conversion.
*/
@SuppressWarnings("unchecked")
void loadVersions();
/**
* Save the versions file to disk.
*/
void saveVersions();
/**
* Load all files from disk.
*
* @param thisTick Load files in the current tick or a tick later
* @return true if the files are loaded correctly, otherwise false
*/
boolean loadFiles(boolean thisTick);
/**
* Load the default.yml file
*
* @return true if it has been loaded successfully, otherwise false
*/
boolean loadDefaultFile();
/**
* Load the default.yml file
*
* @return true if it has been loaded successfully, otherwise false
*/
boolean loadConfigFile();
/**
* Load the groups.yml file from disk
*
* @return true if succeeded, otherwise false
*/
boolean loadGroupsFile();
/**
* Load all region files.
*/
void loadRegionFiles();
/**
* Get the settings of a group.
*
* @param groupName Name of the group to get the settings from
* @return The settings of the group
*/
ConfigurationSection getGroupSettings(String groupName);
/**
* Set a setting for a group.
*
* @param group The group to set it for
* @param path The path to set
* @param setting The value to set
*/
void setGroupSetting(RegionGroup group, String path, Object setting);
// Enum for region types
public enum AddResult {
BLACKLISTED("blacklisted"),
NOPERMISSION("nopermission"),
ALREADYADDED("alreadyadded"),
ALREADYADDEDOTHERWORLD("alreadyaddedotherworld"),
SUCCESS("success");
private final String value;
AddResult(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
}
@@ -1,11 +1,7 @@
package me.wiefferink.areashop.managers;
import me.wiefferink.areashop.AreaShop;
public abstract class Manager {
final AreaShop plugin = AreaShop.getInstance();
/**
* Called at shutdown of the plugin.
*/
@@ -0,0 +1,79 @@
package me.wiefferink.areashop.managers;
import me.wiefferink.areashop.AreaShop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.concurrent.atomic.AtomicBoolean;
public class SignErrorLogger {
public static final String PREFIX_WARN = "[Warning] [Sign Feature] ";
public static final DateFormat FORMAT = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
private final List<String> cache = new LinkedList<>();
private final AtomicBoolean needsSaving = new AtomicBoolean(false);
private final File file;
public SignErrorLogger(File file) {
this.file = Objects.requireNonNull(file);
}
public void clearCache() {
synchronized (this.cache) {
this.cache.clear();
}
}
public SignErrorLogger submitWarning(String message) {
final String actual = FORMAT.format(Date.from(Instant.now())) + PREFIX_WARN + message;
synchronized (this.cache) {
this.cache.add(actual);
}
return this;
}
public void queueSave() {
this.needsSaving.set(true);
}
public void saveIfDirty() {
if (this.needsSaving.get()) {
save();
}
}
public synchronized void save() {
AreaShop.debugTask("[Sign Feature] Dumping sign errors to disk...");
final String[] copy;
synchronized (this.cache) {
copy = cache.toArray(new String[0]);
}
final StringJoiner joiner = new StringJoiner(System.lineSeparator());
for (String s : copy) {
joiner.add(s);
}
try (OutputStream os = new FileOutputStream(file);
OutputStreamWriter writer = new OutputStreamWriter(os, StandardCharsets.UTF_8)) {
writer.write(joiner.toString());
} catch (IOException ex) {
ex.printStackTrace();
AreaShop.error("Failed to update the sign error log!");
} finally {
AreaShop.debugTask("[Sign Feature] Error dump complete.");
}
}
}
@@ -1,7 +1,10 @@
package me.wiefferink.areashop.managers;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.features.signs.RegionSign;
import me.wiefferink.areashop.features.signs.SignsFeature;
import me.wiefferink.areashop.features.signs.SignManager;
import me.wiefferink.areashop.interfaces.BukkitInterface;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.tools.Materials;
import me.wiefferink.areashop.tools.Utils;
@@ -10,9 +13,6 @@ import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.type.Sign;
import org.bukkit.block.data.type.WallSign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@@ -23,18 +23,31 @@ import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.util.BlockIterator;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
@Singleton
public class SignLinkerManager extends Manager implements Listener {
private final Map<UUID, SignLinker> signLinkers;
private boolean eventsRegistered;
public SignLinkerManager() {
@Inject
private AreaShop plugin;
@Inject
private BukkitInterface bukkitInterface;
@Inject
private SignManager signManager;
@Inject
private MessageBridge messageBridge;
SignLinkerManager() {
signLinkers = new HashMap<>();
eventsRegistered = false;
}
@@ -53,8 +66,8 @@ public class SignLinkerManager extends Manager implements Listener {
*/
public void enterSignLinkMode(Player player, String profile) {
signLinkers.put(player.getUniqueId(), new SignLinker(player, profile));
plugin.message(player, "linksigns-first");
plugin.message(player, "linksigns-next");
messageBridge.message(player, "linksigns-first");
messageBridge.message(player, "linksigns-next");
if(!eventsRegistered) {
eventsRegistered = true;
plugin.getServer().getPluginManager().registerEvents(this, plugin);
@@ -71,7 +84,7 @@ public class SignLinkerManager extends Manager implements Listener {
eventsRegistered = false;
HandlerList.unregisterAll(this);
}
plugin.message(player, "linksigns-stopped");
messageBridge.message(player, "linksigns-stopped");
}
/**
@@ -107,13 +120,13 @@ public class SignLinkerManager extends Manager implements Listener {
for(GeneralRegion region : regions) {
names.add(region.getName());
}
plugin.message(player, "linksigns-multipleRegions", Utils.createCommaSeparatedList(names));
plugin.message(player, "linksigns-multipleRegionsAdvice");
messageBridge.message(player, "linksigns-multipleRegions", Utils.createCommaSeparatedList(names));
messageBridge.message(player, "linksigns-multipleRegionsAdvice");
return;
}
}
// No regions found within the maximum range
plugin.message(player, "linksigns-noRegions");
messageBridge.message(player, "linksigns-noRegions");
} else if(event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK) {
Block block = null;
BlockIterator blockIterator = new BlockIterator(player, 100);
@@ -124,25 +137,17 @@ public class SignLinkerManager extends Manager implements Listener {
}
}
if(block == null || !Materials.isSign(block.getType())) {
plugin.message(player, "linksigns-noSign");
messageBridge.message(player, "linksigns-noSign");
return;
}
RegionSign regionSign = SignsFeature.getSignByLocation(block.getLocation());
if(regionSign != null) {
plugin.message(player, "linksigns-alreadyRegistered", regionSign.getRegion());
Optional<RegionSign> optional = signManager.signFromLocation(block.getLocation());
if(optional.isPresent()) {
RegionSign regionSign = optional.get();
messageBridge.message(player, "linksigns-alreadyRegistered", regionSign.getRegion());
return;
}
final BlockData blockData = block.getBlockData();
final BlockFace rotation;
if (blockData instanceof Sign) {
rotation = ((Sign) blockData).getRotation();
} else if (blockData instanceof WallSign) {
rotation = ((WallSign) blockData).getFacing();
} else {
rotation = null;
}
linker.setSign(block.getLocation(), block.getType(), rotation);
linker.setSign(block.getLocation(), block.getType(), bukkitInterface.getSignFacing(block));
}
}
}
@@ -181,7 +186,7 @@ public class SignLinkerManager extends Manager implements Listener {
this.region = region;
hasRegion = true;
if(!isComplete()) {
plugin.message(linker, "linksigns-regionFound", region);
messageBridge.message(linker, "linksigns-regionFound", region);
}
finish();
}
@@ -192,7 +197,7 @@ public class SignLinkerManager extends Manager implements Listener {
this.facing = facing;
hasSign = true;
if(!isComplete()) {
plugin.message(linker, "linksigns-signFound", location.getBlockX(), location.getBlockY(), location.getBlockZ());
messageBridge.message(linker, "linksigns-signFound", location.getBlockX(), location.getBlockY(), location.getBlockZ());
}
finish();
}
@@ -201,14 +206,14 @@ public class SignLinkerManager extends Manager implements Listener {
if(isComplete()) {
region.getSignsFeature().addSign(location, type, facing, profile);
if(profile == null) {
plugin.message(linker, "addsign-success", region);
messageBridge.message(linker, "addsign-success", region);
} else {
plugin.message(linker, "addsign-successProfile", region, profile);
messageBridge.message(linker, "addsign-successProfile", region, profile);
}
region.update();
reset();
plugin.message(linker, "linksigns-next");
messageBridge.message(linker, "linksigns-next");
}
}
@@ -0,0 +1,81 @@
package me.wiefferink.areashop.modules;
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.features.FeatureFactory;
import me.wiefferink.areashop.features.signs.SignsModule;
import me.wiefferink.areashop.interfaces.BukkitInterface;
import me.wiefferink.areashop.interfaces.WorldEditInterface;
import me.wiefferink.areashop.interfaces.WorldGuardInterface;
import me.wiefferink.areashop.managers.CommandManager;
import me.wiefferink.areashop.managers.FeatureManager;
import me.wiefferink.areashop.managers.IFileManager;
import me.wiefferink.areashop.managers.FileManager;
import me.wiefferink.areashop.managers.SignErrorLogger;
import me.wiefferink.areashop.managers.SignLinkerManager;
import me.wiefferink.areashop.nms.BlockBehaviourHelper;
import me.wiefferink.areashop.nms.NMS;
import me.wiefferink.areashop.regions.ImportJobFactory;
import me.wiefferink.areashop.regions.RegionModule;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.plugin.Plugin;
import javax.annotation.Nonnull;
public class AreaShopModule extends AbstractModule {
private final AreaShop instance;
private final BukkitInterface bukkitInterface;
private final WorldGuardInterface worldGuardInterface;
private final WorldEditInterface worldEditInterface;
private final NMS nms;
private final MessageBridge messageBridge;
private final SignErrorLogger signErrorLogger;
private final DependencyModule dependencyModule;
public AreaShopModule(@Nonnull AreaShop instance,
@Nonnull MessageBridge messageBridge,
@Nonnull NMS nms,
@Nonnull BukkitInterface bukkitInterface,
@Nonnull WorldEditInterface worldEditInterface,
@Nonnull WorldGuardInterface worldGuardInterface,
@Nonnull SignErrorLogger signErrorLogger,
@Nonnull DependencyModule dependencyModule
) {
this.instance = instance;
this.messageBridge = messageBridge;
this.nms = nms;
this.signErrorLogger = signErrorLogger;
this.bukkitInterface = bukkitInterface;
this.worldEditInterface = worldEditInterface;
this.worldGuardInterface = worldGuardInterface;
this.dependencyModule = dependencyModule;
}
@Override
protected void configure() {
install(this.dependencyModule);
bind(Plugin.class).toInstance(this.instance);
bind(AreaShop.class).toInstance(this.instance);
bind(MessageBridge.class).toInstance(this.messageBridge);
bind(NMS.class).toInstance(this.nms);
bind(BlockBehaviourHelper.class).toInstance(this.nms.blockBehaviourHelper());
bind(BukkitInterface.class).toInstance(this.bukkitInterface);
bind(WorldGuardInterface.class).toInstance(this.worldGuardInterface);
bind(WorldEditInterface.class).toInstance(this.worldEditInterface);
bind(SignErrorLogger.class).toInstance(this.signErrorLogger);
// Setup managers
bind(IFileManager.class).to(FileManager.class).asEagerSingleton();
bind(FeatureManager.class).in(Singleton.class);
bind(CommandManager.class).in(Singleton.class);
bind(SignLinkerManager.class).in(Singleton.class);
install(new SignsModule());
install(new RegionModule());
install(new FactoryModuleBuilder().build(FeatureFactory.class));
install(new FactoryModuleBuilder().build(ImportJobFactory.class));
requestStaticInjection(Utils.class);
}
}
@@ -0,0 +1,34 @@
package me.wiefferink.areashop.modules;
import com.google.inject.AbstractModule;
import org.bukkit.Server;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.inventory.ItemFactory;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.ServicesManager;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scoreboard.ScoreboardManager;
import javax.annotation.Nonnull;
public class BukkitModule extends AbstractModule {
private final Server server;
public BukkitModule(@Nonnull Server server) {
this.server = server;
}
@Override
protected void configure() {
bind(Server.class).toInstance(this.server);
bind(PluginManager.class).toInstance(this.server.getPluginManager());
bind(BukkitScheduler.class).toInstance(this.server.getScheduler());
bind(PluginManager.class).toInstance(this.server.getPluginManager());
bind(ServicesManager.class).toInstance(this.server.getServicesManager());
bind(ItemFactory.class).toInstance(this.server.getItemFactory());
bind(ConsoleCommandSender.class).toInstance(this.server.getConsoleSender());
bind(ScoreboardManager.class).toInstance(this.server.getScoreboardManager());
}
}
@@ -0,0 +1,37 @@
package me.wiefferink.areashop.modules;
import com.google.inject.AbstractModule;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class DependencyModule extends AbstractModule {
private final WorldEditPlugin worldEditPlugin;
private final WorldGuardPlugin worldGuardPlugin;
private final Economy economy;
private final Permission permission;
public DependencyModule(@Nonnull WorldEditPlugin worldEditPlugin,
@Nonnull WorldGuardPlugin worldGuardPlugin,
@Nullable Economy economy,
@Nullable Permission permission
) {
this.worldEditPlugin = worldEditPlugin;
this.worldGuardPlugin = worldGuardPlugin;
this.economy = economy;
this.permission = permission;
}
@Override
protected void configure() {
bind(WorldEditPlugin.class).toInstance(this.worldEditPlugin);
bind(WorldGuardPlugin.class).toInstance(this.worldGuardPlugin);
bind(Economy.class).toInstance(this.economy);
bind(Permission.class).toInstance(this.permission);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,16 +1,17 @@
package me.wiefferink.areashop.commands;
package me.wiefferink.areashop.regions;
import com.google.common.base.Charsets;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.areashop.events.ask.AddingRegionEvent;
import me.wiefferink.areashop.features.signs.RegionSign;
import me.wiefferink.areashop.features.signs.SignsFeature;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.features.signs.SignManager;
import me.wiefferink.areashop.interfaces.WorldGuardInterface;
import me.wiefferink.areashop.managers.IFileManager;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
@@ -20,33 +21,52 @@ import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public class ImportJob {
private final AreaShop plugin;
private final IFileManager fileManager;
private final SignManager signManager;
private final WorldGuardInterface worldGuardInterface;
private final CommandSender sender;
private final MessageBridge messageBridge;
private final RegionFactory regionFactory;
/**
* Create and execute the import.
* @param sender CommandSender that should receive progress updates
*/
public ImportJob(CommandSender sender) {
@AssistedInject
ImportJob(
@Nonnull AreaShop plugin,
@Nonnull IFileManager fileManager,
@Nonnull SignManager signManager,
@Nonnull WorldGuardInterface worldGuardInterface,
@Nonnull MessageBridge messageBridge,
@Nonnull RegionFactory regionFactory,
@Assisted @Nonnull CommandSender sender) {
this.regionFactory = regionFactory;
this.sender = sender;
this.plugin = AreaShop.getInstance();
execute();
this.plugin = plugin;
this.signManager = signManager;
this.fileManager = fileManager;
this.worldGuardInterface = worldGuardInterface;
this.messageBridge = messageBridge;
}
/**
* Execute the job.
*/
private void execute() {
public void execute() {
// Check for RegionForSale data
File regionForSaleFolder = new File(plugin.getDataFolder().getParentFile().getAbsolutePath(), "RegionForSale");
if(!regionForSaleFolder.exists()) {
@@ -70,8 +90,8 @@ public class ImportJob {
message("import-start");
// Group with settings for all imported regions
RegionGroup regionForSaleGroup = new RegionGroup(plugin, "RegionForSale");
plugin.getFileManager().addGroup(regionForSaleGroup);
RegionGroup regionForSaleGroup = regionFactory.createRegionGroup("RegionForSale");
fileManager.addGroup(regionForSaleGroup);
// Import /RegionForSale/config.yml settings
File regionForSaleConfigFile = new File(regionForSaleFolder.getAbsolutePath(), "config.yml");
@@ -149,11 +169,11 @@ public class ImportJob {
worldConfig = new YamlConfiguration();
} else {
// RegionGroup with all world settings
RegionGroup worldGroup = new RegionGroup(plugin, "RegionForSale-" + worldFolder.getName());
RegionGroup worldGroup = regionFactory.createRegionGroup("RegionForSale-" + worldFolder.getName());
importRegionSettings(worldConfig, worldGroup.getSettings(), null, false);
worldGroup.setSetting("priority", 1);
worldGroup.addWorld(worldFolder.getName());
plugin.getFileManager().addGroup(regionForSaleGroup);
fileManager.addGroup(regionForSaleGroup);
worldGroup.saveRequired();
}
@@ -185,7 +205,7 @@ public class ImportJob {
}
// Import parent region settings into a RegionGroup
RegionGroup parentRegionGroup = new RegionGroup(plugin, "RegionForSale-" + worldFolder.getName() + "-" + parentRegionName);
RegionGroup parentRegionGroup = regionFactory.createRegionGroup( "RegionForSale-" + worldFolder.getName() + "-" + parentRegionName);
importRegionSettings(parentRegionSection, parentRegionGroup.getSettings(), null, false);
parentRegionGroup.setSetting("priority", 2 + parentRegionSection.getLong("info.priority", 0));
parentRegionGroup.saveRequired();
@@ -197,7 +217,7 @@ public class ImportJob {
// Read and import regions
for(String regionKey : regions.getKeys(false)) {
GeneralRegion existingRegion = plugin.getFileManager().getRegion(regionKey);
GeneralRegion existingRegion = fileManager.getRegion(regionKey);
if(existingRegion != null) {
if(world.getName().equalsIgnoreCase(existingRegion.getWorldName())) {
messageNoPrefix("import-alreadyAdded", regionKey);
@@ -240,9 +260,9 @@ public class ImportJob {
// Create region
GeneralRegion region;
if(rentable || (owner != null && !isBought)) {
region = new RentRegion(regionKey, world);
region = regionFactory.createRentRegion(regionKey, world);
} else {
region = new BuyRegion(regionKey, world);
region = regionFactory.createBuyRegion(regionKey, world);
}
AddingRegionEvent event = plugin.getFileManager().addRegion(region);
if (event.isCancelled()) {
@@ -263,12 +283,12 @@ public class ImportJob {
existing.add(offlinePlayer.getUniqueId());
}
}
for(UUID uuid : plugin.getWorldGuardHandler().getOwners(worldGuardRegion).asUniqueIdList()) {
for(UUID uuid : worldGuardInterface.getOwners(worldGuardRegion).asUniqueIdList()) {
if(!existing.contains(uuid)) {
existing.add(uuid);
}
}
for(UUID uuid : plugin.getWorldGuardHandler().getMembers(worldGuardRegion).asUniqueIdList()) {
for(UUID uuid : worldGuardInterface.getMembers(worldGuardRegion).asUniqueIdList()) {
if(!existing.contains(uuid)) {
existing.add(uuid);
}
@@ -290,9 +310,9 @@ public class ImportJob {
}
// Update all regions
plugin.getFileManager().updateAllRegions(sender);
fileManager.updateAllRegions(sender);
// Write all imported regions and settings to disk
plugin.getFileManager().saveRequiredFiles();
fileManager.saveRequiredFiles();
}
/**
@@ -338,7 +358,9 @@ public class ImportJob {
// Determine unit and add that to the price
String unitSuffix = "";
if("m3".equalsIgnoreCase(unit)) {
if("region".equalsIgnoreCase(unit)) {
// add nothing
} else if("m3".equalsIgnoreCase(unit)) {
unitSuffix = "*%volume%";
} else { // m2 or nothing (in case not set, we should actually look in parent files to correctly set this...)
unitSuffix = "*(%volume%/%height%)"; // This is better than width*depth because of polygon regions
@@ -397,8 +419,9 @@ public class ImportJob {
}
// Check if this location is already added to a region
RegionSign regionSign = SignsFeature.getSignByLocation(location);
if(regionSign != null) {
Optional<RegionSign> optionalRegionSign = signManager.signFromLocation(location);
if(optionalRegionSign.isPresent()) {
RegionSign regionSign = optionalRegionSign.get();
if(!regionSign.getRegion().equals(region)) {
message("import-signAlreadyAdded", region.getName(), signLocation, regionSign.getRegion().getName());
}
@@ -457,10 +480,10 @@ public class ImportJob {
* @param replacements The replacements to insert in the message
*/
public void messageNoPrefix(String key, Object... replacements) {
plugin.messageNoPrefix(sender, key, replacements);
messageBridge.messageNoPrefix(sender, key, replacements);
if(!(sender instanceof ConsoleCommandSender)) {
plugin.messageNoPrefix(Bukkit.getConsoleSender(), key, replacements);
messageBridge.messageNoPrefix(Bukkit.getConsoleSender(), key, replacements);
}
}
@@ -470,10 +493,10 @@ public class ImportJob {
* @param replacements The replacements to insert in the message
*/
public void message(String key, Object... replacements) {
plugin.message(sender, key, replacements);
messageBridge.message(sender, key, replacements);
if(!(sender instanceof ConsoleCommandSender)) {
plugin.message(Bukkit.getConsoleSender(), key, replacements);
messageBridge.message(Bukkit.getConsoleSender(), key, replacements);
}
}
}
@@ -0,0 +1,11 @@
package me.wiefferink.areashop.regions;
import org.bukkit.command.CommandSender;
import javax.annotation.Nonnull;
public interface ImportJobFactory {
@Nonnull ImportJob createImportJob(@Nonnull CommandSender commandSender);
}
@@ -0,0 +1,20 @@
package me.wiefferink.areashop.regions;
import org.bukkit.World;
import org.bukkit.configuration.file.YamlConfiguration;
import javax.annotation.Nonnull;
public interface RegionFactory {
@Nonnull BuyRegion createBuyRegion(@Nonnull YamlConfiguration yamlConfiguration);
@Nonnull BuyRegion createBuyRegion(@Nonnull String name, @Nonnull World world);
@Nonnull RentRegion createRentRegion(@Nonnull YamlConfiguration yamlConfiguration);
@Nonnull RentRegion createRentRegion(@Nonnull String name, @Nonnull World world);
@Nonnull RegionGroup createRegionGroup(@Nonnull String name);
}
@@ -1,9 +1,13 @@
package me.wiefferink.areashop.regions;
import me.wiefferink.areashop.AreaShop;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import me.wiefferink.areashop.managers.IFileManager;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
@@ -11,7 +15,8 @@ import java.util.Set;
// TODO consider switching to saving lowercase regions
public class RegionGroup {
private final AreaShop plugin;
private final Plugin plugin;
private final IFileManager fileManager;
private final String name;
private final Set<String> regions;
private Set<String> autoRegions;
@@ -23,8 +28,10 @@ public class RegionGroup {
* @param plugin The AreaShop plugin
* @param name Name of the group, has to be unique
*/
public RegionGroup(AreaShop plugin, String name) {
@AssistedInject
RegionGroup(@Nonnull Plugin plugin, @Nonnull IFileManager fileManager, @Assisted String name) {
this.plugin = plugin;
this.fileManager = fileManager;
this.name = name;
this.autoDirty = true;
setSetting("name", name);
@@ -41,7 +48,7 @@ public class RegionGroup {
public Set<String> getAutoRegions() {
if(autoDirty) {
autoRegions = new HashSet<>();
for(GeneralRegion region : plugin.getFileManager().getRegions()) {
for(GeneralRegion region : fileManager.getRegionsRef()) {
if(worlds.contains(region.getWorldName())) {
autoRegions.add(region.getName());
}
@@ -149,7 +156,7 @@ public class RegionGroup {
public Set<GeneralRegion> getMemberRegions() {
Set<GeneralRegion> result = new HashSet<>();
for(String playerName : getMembers()) {
result.add(plugin.getFileManager().getRegion(playerName));
result.add(fileManager.getRegion(playerName));
}
return result;
}
@@ -192,7 +199,7 @@ public class RegionGroup {
* @return The ConfigurationSection with the settings of the group
*/
public ConfigurationSection getSettings() {
ConfigurationSection result = plugin.getFileManager().getGroupSettings(name);
ConfigurationSection result = fileManager.getGroupSettings(name);
if(result != null) {
return result;
} else {
@@ -206,20 +213,20 @@ public class RegionGroup {
* @param setting The value to set
*/
public void setSetting(String path, Object setting) {
plugin.getFileManager().setGroupSetting(this, path, setting);
fileManager.setGroupSetting(this, path, setting);
}
/**
* Indicates this file needs to be saved, will actually get saved later by a task.
*/
public void saveRequired() {
plugin.getFileManager().saveGroupsIsRequired();
fileManager.saveGroupsIsRequired();
}
/**
* Save the groups to disk now, normally saveRequired() is preferred because of performance.
*/
public void saveNow() {
plugin.getFileManager().saveGroupsNow();
fileManager.saveGroupsNow();
}
}
@@ -0,0 +1,12 @@
package me.wiefferink.areashop.regions;
import com.google.inject.AbstractModule;
import com.google.inject.assistedinject.FactoryModuleBuilder;
public class RegionModule extends AbstractModule {
@Override
protected void configure() {
install(new FactoryModuleBuilder().build(RegionFactory.class));
}
}
File diff suppressed because it is too large. Load diff
@@ -1,240 +0,0 @@
package me.wiefferink.areashop.regions;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.configuration.file.YamlConfiguration;
import java.util.UUID;
public abstract class TransactionalRegion extends GeneralRegion {
private final String key;
private final RegionType type;
private UUID transactionHolder;
private String transactionHolderName;
private double price;
private double moneyBackPercentage;
private long inactivityThresholdMillis;
public TransactionalRegion(YamlConfiguration config, RegionType regionType) {
super(config);
this.type = regionType;
this.key = regionType.name().toLowerCase() + ".";
this.moneyBackPercentage = config.getDouble(this.key + "moneyBack");
}
public TransactionalRegion(String name, World world, RegionType type) {
super(name, world);
this.type = type;
this.key = type.name().toLowerCase() + ".";
}
protected final void setInactivityThresholdMillis(long inactivityThresholdMillis) {
this.inactivityThresholdMillis = inactivityThresholdMillis;
}
@Override
public RegionType getType() {
return type;
}
@Override
public boolean isAvailable() {
return !isSold();
}
/**
* Get the UUID of the owner of this region.
*
* @return The UUID of the owner of this region
*/
public UUID getTransactionHolder() {
return transactionHolder;
}
/**
* Set the buyer of this region. WARNING - May trigger disk lookup for offline players!
*
* @param transactionHolder The UUID of the player that should be set as buyer
*/
public void setTransactionHolder(UUID transactionHolder) {
if (transactionHolder == null) {
this.transactionHolder = null;
this.transactionHolderName = null;
} else {
this.transactionHolder = transactionHolder;
String name = Utils.toName(transactionHolder);
this.transactionHolderName = name.isEmpty() ? null : name;
}
}
/**
* Set the buyer of this region.
*
* @param player The instance of the player.
*/
public void setTransactionHolder(final OfflinePlayer player) {
if (player == null) {
this.transactionHolder = null;
this.transactionHolderName = null;
} else {
String name = player.getName();
this.transactionHolderName = name == null || name.isEmpty() ? null : name;
}
}
@Override
public void setOwner(UUID player) {
setTransactionHolder(player);
}
/**
* Check if a player is the buyer/holder of this region.
*
* @param player Player to check
* @return true if this player owns this region, otherwise false
*/
public boolean isTransactionHolder(OfflinePlayer player) {
return player != null && player.getUniqueId().equals(transactionHolder);
}
public boolean isTransactionHolder(UUID player) {
UUID buyer = getTransactionHolder();
return !(buyer == null || player == null) && buyer.equals(player);
}
/**
* Get the name of the player that owns this region.
*
* @return The name of the player that owns this region, if unavailable by UUID it will return the old cached name, if that is unavailable it will return &lt;UNKNOWN&gt;
*/
public String getPlayerName() {
return this.transactionHolderName == null ? "<UNKNOWN>" : transactionHolderName;
}
/**
* Check if the region is sold.
*
* @return true if the region is sold, otherwise false
*/
public boolean isSold() {
return this.transactionHolder != null;
}
/**
* Get the price of the region.
*
* @return The price of the region
*/
public double getPrice() {
return price;
}
/**
* Change the price of the region.
*
* @param price The price to set this region to
*/
public void setPrice(double price) {
this.price = price;
super.config.set(key + "price", price);
}
/**
* Get the formatted string of the price (includes prefix and suffix).
*
* @return The formatted string of the price
*/
public String getFormattedPrice() {
return Utils.formatCurrency(getPrice());
}
/**
* Get the moneyBack percentage.
*
* @return The % of money the player will get back when selling
*/
public double getMoneyBackPercentage() {
return moneyBackPercentage;
}
/**
* Get the amount of money that should be paid to the player when selling the region.
*
* @return The amount of money the player should get back
*/
public double getMoneyBackAmount() {
return getPrice() * (moneyBackPercentage / 100D);
}
/**
* Get the formatted string of the amount of the moneyBack amount.
*
* @return String with currency symbols and proper fractional part
*/
public String getFormattedMoneyBackAmount() {
return Utils.formatCurrency(getMoneyBackAmount());
}
@Override
public Object provideReplacement(String variable) {
switch (variable) {
case AreaShop.tagPrice:
return getFormattedPrice();
case AreaShop.tagRawPrice:
return getPrice();
case AreaShop.tagPlayerName:
return getPlayerName();
case AreaShop.tagPlayerUUID:
return getTransactionHolder();
case AreaShop.tagMoneyBackAmount:
return getFormattedMoneyBackAmount();
case AreaShop.tagRawMoneyBackAmount:
return getMoneyBackAmount();
case AreaShop.tagMoneyBackPercentage:
return getMoneyBackPercentage() % 1.0 == 0.0 ? (int) getMoneyBackPercentage() : getMoneyBackPercentage();
case AreaShop.tagMaxInactiveTime:
return this.getFormattedInactivityThreshold();
default:
return super.provideReplacement(variable);
}
}
public long getInactivityThresholdMillis() {
return this.inactivityThresholdMillis;
}
/**
* Get a human readable string indicating how long the player can be offline until automatic unrent.
*
* @return String indicating the inactive time until unrent
*/
public String getFormattedInactivityThreshold() {
return Utils.millisToHumanFormat(this.inactivityThresholdMillis);
}
@Override
public boolean checkInactivity(final OfflinePlayer player) {
if (isDeleted() || !isSold()) {
return false;
}
long inactiveSetting = getInactivityThresholdMillis();
if (inactiveSetting <= 0) {
return false;
}
if (player.isOnline()) {
return false;
}
long lastPlayed = getLastActiveTime();
long now = System.currentTimeMillis();
if (now > (lastPlayed + inactiveSetting)) {
AreaShop.info("Region " + getName() + " unrented because of inactivity for player " + getPlayerName());
AreaShop.debug("currentTime=" + now + ", getLastPlayed()=" + lastPlayed + ", timeInactive=" + (now - player.getLastPlayed()) + ", inactiveSetting=" + inactiveSetting);
return true;
}
return false;
}
}
@@ -1,103 +0,0 @@
package me.wiefferink.areashop.tools;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import org.bstats.bukkit.Metrics;
import java.util.HashMap;
import java.util.Map;
public class Analytics {
private Analytics() {
}
/**
* Start analytics tracking.
*/
public static void start() {
// bStats statistics
try {
Metrics metrics = new Metrics(AreaShop.getInstance());
// Number of regions
metrics.addCustomChart(new Metrics.SingleLineChart("region_count", () -> AreaShop.getInstance().getFileManager().getRegions().size()));
// Number of rental regions
metrics.addCustomChart(new Metrics.SingleLineChart("rental_region_count", () -> {
return AreaShop.getInstance().getFileManager().getRents().size();
}));
// Number of buy regions
metrics.addCustomChart(new Metrics.SingleLineChart("buy_region_count", () -> AreaShop.getInstance().getFileManager().getBuys().size()));
// Language
metrics.addCustomChart(new Metrics.SimplePie("language", () -> AreaShop.getInstance().getConfig().getString("language")));
// Pie with region states
metrics.addCustomChart(new Metrics.AdvancedPie("region_state", () -> {
Map<String, Integer> map = new HashMap<>();
RegionStateStats stats = getStateStats();
map.put("For Rent", stats.forrent);
map.put("Rented", stats.rented);
map.put("For Sale", stats.forsale);
map.put("Sold", stats.sold);
map.put("Reselling", stats.reselling);
return map;
}));
// Time series of each region state
metrics.addCustomChart(new Metrics.SingleLineChart("forrent_region_count", () -> getStateStats().forrent));
metrics.addCustomChart(new Metrics.SingleLineChart("rented_region_count", () -> getStateStats().rented));
metrics.addCustomChart(new Metrics.SingleLineChart("forsale_region_count", () -> getStateStats().forsale));
metrics.addCustomChart(new Metrics.SingleLineChart("sold_region_count", () -> getStateStats().sold));
metrics.addCustomChart(new Metrics.SingleLineChart("reselling_region_count", () -> getStateStats().reselling));
// TODO track rent/buy/unrent/sell/resell actions (so that it can be reported per collection interval)
AreaShop.debug("Started bstats.org statistics service");
} catch (Exception e) {
AreaShop.debug("Could not start bstats.org statistics service");
}
}
private static RegionStateStats getStateStats() {
RegionStateStats result = new RegionStateStats();
for (GeneralRegion region : AreaShop.getInstance().getFileManager().getRegions()) {
if (region instanceof RentRegion) {
RentRegion rent = (RentRegion) region;
if (rent.isAvailable()) {
result.forrent++;
} else {
result.rented++;
}
} else if (region instanceof BuyRegion) {
BuyRegion buy = (BuyRegion) region;
if (buy.isAvailable()) {
result.forsale++;
} else if (buy.isInResellingMode()) {
result.reselling++;
} else {
result.sold++;
}
}
}
return result;
}
private static class RegionStateStats {
int forrent = 0;
int forsale = 0;
int rented = 0;
int sold = 0;
int reselling = 0;
}
}
@@ -1,28 +0,0 @@
package me.wiefferink.areashop.tools;
import org.bukkit.Chunk;
public class ChunkUtils {
private final long twoPower32 = Integer.MAX_VALUE + 1L;
public static long getPackedChunkCoords(Chunk chunk) {
return packToLong(chunk.getX(), chunk.getZ());
}
public static long packToLong(int primary, int secondary) {
return (long) primary & 0xffffffffL | ((long) secondary & 0xffffffffL) << 32;
}
public static int getChunkX(long packed) {
return (int) packed;
}
public static int getChunkZ(long packed) {
return (int) (packed >> 32);
}
public static int[] getChunkCoords(long packed) {
return new int[]{(int) packed, (int) (packed >> 32)};
}
}
@@ -1,62 +1,11 @@
package me.wiefferink.areashop.tools;
import me.wiefferink.areashop.AreaShop;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.bukkit.Tag;
public class Materials {
private Materials() {
}
private static final HashSet<String> WALL_SIGN_TYPES = new HashSet<>(Arrays.asList(
// 1.14+ types
"ACACIA_WALL_SIGN",
"BIRCH_WALL_SIGN",
"DARK_OAK_WALL_SIGN",
"JUNGLE_WALL_SIGN",
"OAK_WALL_SIGN",
"SPRUCE_WALL_SIGN",
// Legacy types
"LEGACY_WALL_SIGN",
"WALL_SIGN"
));
private static final HashSet<String> FLOOR_SIGN_TYPES = new HashSet<>(Arrays.asList(
// 1.14+ types
"ACACIA_SIGN",
"BIRCH_SIGN",
"DARK_OAK_SIGN",
"JUNGLE_SIGN",
"OAK_SIGN",
"SPRUCE_SIGN",
// Legacy types
"LEGACY_SIGN",
"LEGACY_SIGN_POST",
"SIGN",
"SIGN_POST"
));
private static boolean legacyMaterials = false;
static {
List<String> legacyMaterialVersions = Arrays.asList("1.7", "1.8", "1.9", "1.10", "1.11", "1.12");
for(String legacyMaterialVersion : legacyMaterialVersions) {
String version = Bukkit.getBukkitVersion();
// Detects '1.8', '1.8.3', '1.8-pre1' style versions
if(version.equals(legacyMaterialVersion)
|| version.startsWith(legacyMaterialVersion + ".")
|| version.startsWith(legacyMaterialVersion + "-")) {
legacyMaterials = true;
break;
}
}
}
/**
@@ -69,46 +18,12 @@ public class Materials {
if (!isSign(name)) {
return null;
}
Material result = null;
if (legacyMaterials) {
// 1.12 and lower just know SIGN_POST, WALL_SIGN and SIGN
if (FLOOR_SIGN_TYPES.contains(name)) {
result = Material.getMaterial("SIGN_POST");
} else if (WALL_SIGN_TYPES.contains(name)) {
result = Material.getMaterial("WALL_SIGN");
if (result == null) {
result = Material.getMaterial("SIGN");
}
}
} else {
// Try saved name (works for wood types on 1.14, regular types for below)
result = Material.getMaterial(name);
if (result == null) {
// Cases for 1.13, which don't know wood types, but need new materials
if (FLOOR_SIGN_TYPES.contains(name)) {
// SIGN -> OAK_SIGN for 1.14
result = Material.getMaterial("OAK_SIGN");
// Fallback for 1.13
if (result == null) {
result = Material.getMaterial("SIGN");
}
} else if (WALL_SIGN_TYPES.contains(name)) {
// WALL_SIGN -> OAK_WALL_SIGN for 1.14
result = Material.getMaterial("OAK_WALL_SIGN");
// Fallback for 1.13
if (result == null) {
result = Material.getMaterial("WALL_SIGN");
}
}
}
try {
return Material.getMaterial(name);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
if (result == null) {
AreaShop.debug("Materials.get() null result:", name, "legacyMaterials:", legacyMaterials);
}
return result;
return null;
}
/**
@@ -117,7 +32,7 @@ public class Materials {
* @return true if the given material is a sign
*/
public static boolean isSign(Material material) {
return isSign(material.name());
return Tag.SIGNS.isTagged(material);
}
/**
@@ -126,7 +41,11 @@ public class Materials {
* @return true if the given material is a sign
*/
public static boolean isSign(String name) {
return name != null && name.toUpperCase().contains("SIGN");
try {
return isSign(Material.getMaterial(name));
} catch (IllegalArgumentException ex) {
return false;
}
}
}
@@ -0,0 +1,152 @@
package me.wiefferink.areashop.tools;
/**
* Parse math from a string
* Adapted from:
* https://stackoverflow.com/questions/3422673/how-to-evaluate-a-math-expression-given-in-string-form
*/
public final class OperandParser {
private final String str;
private OperandParser(final String str) {
this.str = str;
}
public static double parse(final String str) throws ParseException {
return new OperandParser(str).parse();
}
private int pos = -1, ch;
private void nextChar() {
ch = (++pos < str.length()) ? str.charAt(pos) : -1;
}
private boolean eat(int charToEat) {
while (ch == ' ') nextChar();
if (ch == charToEat) {
nextChar();
return true;
}
return false;
}
private double parse() throws ParseException {
nextChar();
double x = parseExpression();
if (pos < str.length())
{
throw new ParseException("Unexpected: " + (char) ch);
}
return x;
}
// Grammar:
// expression = term | expression `+` term | expression `-` term
// term = factor | term `*` factor | term `/` factor
// factor = `+` factor | `-` factor | `(` expression `)`
// | number | functionName factor | factor `^` factor
private double parseExpression() throws ParseException {
double x = parseTerm();
for (; ; ) {
if (eat('+')) {
// addition
x += parseTerm();
}
else if (eat('-')) {
// subtraction
x -= parseTerm();
}
else return x;
}
}
private double parseTerm() throws ParseException {
double x = parseFactor();
for (; ; ) {
if (eat('*')) {
// multiplication
x *= parseFactor();
}
else if (eat('/')) {
// division
x /= parseFactor();
}
else return x;
}
}
private double parseFactor() throws ParseException {
if (eat('+')) {
// unary plus
return parseFactor();
}
if (eat('-')) {
// unary minus
return -parseFactor();
}
double x;
int startPos = this.pos;
if (eat('(')) {
// parentheses
x = parseExpression();
eat(')');
} else if ((ch >= '0' && ch <= '9') || ch == '.') {
// numbers
while ((ch >= '0' && ch <= '9') || ch == '.') {
nextChar();
}
x = Double.parseDouble(str.substring(startPos, this.pos));
} else if (ch >= 'a' && ch <= 'z') {
// functions
while (ch >= 'a' && ch <= 'z') {
nextChar();
}
String func = str.substring(startPos, this.pos);
x = parseFactor();
x = switch (func) {
case "sqrt" -> Math.sqrt(x);
case "sin" -> Math.sin(Math.toRadians(x));
case "cos" -> Math.cos(Math.toRadians(x));
case "tan" -> Math.tan(Math.toRadians(x));
default -> throw new ParseException("Unknown function: " + func);
};
} else {
throw new ParseException("Unexpected: " + (char) ch);
}
if (eat('^')) {
// exponentiation
x = Math.pow(x, parseFactor());
}
return x;
}
public static class ParseException extends Exception {
public ParseException() {
}
public ParseException(String message) {
super(message);
}
public ParseException(String message, Throwable cause) {
super(message, cause);
}
public ParseException(Throwable cause) {
super(cause);
}
public ParseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
}
@@ -0,0 +1,32 @@
package me.wiefferink.areashop.tools;
import com.google.inject.Singleton;
import me.wiefferink.areashop.MessageBridge;
import me.wiefferink.interactivemessenger.processing.Message;
@Singleton
public class SimpleMessageBridge implements MessageBridge {
/**
* Send a message to a target without a prefix.
* @param target The target to send the message to
* @param key The key of the language string
* @param replacements The replacements to insert in the message
*/
@Override
public void messageNoPrefix(Object target, String key, Object... replacements) {
Message.fromKey(key).replacements(replacements).send(target);
}
/**
* Send a message to a target, prefixed by the default chat prefix.
* @param target The target to send the message to
* @param key The key of the language string
* @param replacements The replacements to insert in the message
*/
@Override
public void message(Object target, String key, Object... replacements) {
Message.fromKey(key).prefix().replacements(replacements).send(target);
}
}
File diff suppressed because it is too large. Load diff
+181 -181
View File
@@ -1,181 +1,181 @@
# ╔════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╗
# ║ config.yml file of the AreaShop plugin created by NLThijs48, Github can be found at https://github.com/NLthijs48/AreaShop. ║
# ║ This file contains options to change the working of the plugin, the profiles defined here can be used in default.yml. ║
# ║ More information and tutorials can be found on the wiki: https://github.com/NLthijs48/AreaShop/wiki ║
# ╚════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╝
# ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
# │ GENERAL: Options that influence the global state of the plugin │
# └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
# Chat prefix used for all messages in the chat, also changes the greeting messages.
chatPrefix:
- '[darkgreen][AreaShop][reset]'
- ' hover: AreaShop region management plugin'
- ' hover: %lang:action|Click to check the available commands|%'
- ' command: /areashop help'
- ' '
# The language file that should be used, check the 'lang' folder for build-in languages (use the filename without .yml here).
# More information can be found here: https://github.com/NLthijs48/AreaShop/wiki/Language-support.
language: EN
# The tags that need to be written on the first line of a sign to add it to AreaShop.
signTags:
# Add a rental region.
rent: '[asrent]'
# Add a buy region.
buy: '[asbuy]'
# Add a sign to an existing region.
add: '[as]'
# ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
# │ ECONOMY: Options to change the display of prices. │
# └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
# The characters displayed before a price.
moneyCharacter: '$'
# The characters displayed after a price.
moneyCharacterAfter: ''
# The character(s) to use as decimal mark.
decimalMark: '.'
# How many numbers behind the dot should be shown (2 will make numbers like '8.55', '9.01', '5.20').
fractionalNumbers: 2
# How many numbers behind the dot should be shown when using a metric symbol suffix.
fractionalNumbersShort: 3
# Set this to true if you want to hide '.0' for a number like '15.0' ('4.50' will still stay '4.50').
hideEmptyFractionalPart: true
# Use a suffix if the price is above a certain number (use 1.00M instead of 1000000.00 etc.)
metricSymbols:
#1000: "k"
1000000: "M"
1000000000: "G"
1000000000000: "T"
1000000000000000: "P"
1000000000000000000: "E"
1000000000000000000000: "Z"
1000000000000000000000000: "Y"
# ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
# │ RENTING: Options that apply to all rent regions. │
# └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
# Timeformat to use on the signs, default is like '30-06 14:52', US format: 'MM-dd KK:mm a'.
# Search for 'java SimpleDateFormat' for more options and documentation.
timeFormatSign: 'dd-MM HH:mm'
# Timeformat used in the chat, default is like '30 june 2014 14:52', US format: 'MMMMMMMMMMMMMMMMM dd yyyy KK:mm a'.
# Search for 'java SimpleDateFormat' for more options and documentation.
timeFormatChat: 'dd MMMMMMMMMMMMMMMMM yyyy HH:mm'
# Time indicators, used for specifing time periods (for example rent duration).
seconds: [s, sec, secs, second, seconds]
minutes: [m, min, mins, minute, minutes]
hours: [h, hour, hours]
days: [d, day, days]
weeks: [w, week, weeks]
months: [M, month, months]
years: [y, year, years]
# ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
# │ PERMISSION GROUPS: Assigned by giving players certain permissions. │
# └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
# Configure the max total regions, max rent regions and max buy regions with different groups (-1 is unlimited).
# Assign a group to players by giving them the permission 'areashop.limits.<group>'.
# Every player already has the group 'default', OPs bypass the limits because of the 'areashop.limitbypass' permission.
# All the groups applied to the player will be checked and only if they all allow an extra region it will be allowed.
# More information like limits for regions of a certain group or in a certain word can be found here:
# https://github.com/NLthijs48/AreaShop/wiki/Limitgroups-information-and-examples.
limitGroups:
default:
total: 1
rents: 1
buys: 1
# ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
# │ ADVANCED AND DEBUG: Specific options to tweak the plugin precisely and check if it functions correctly. │
# └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
# Blacklist of region names that cannot be added to AreaShop for renting or buying. Regular expressions can be used, search
# for 'java regex pattern' to find documentation about how to use it.
# Example: Blocking all regions that have a name like 'house_1', 'house_2', etc. would be done with 'house_\d+'.
# The '\d' represents the numerical digits 0-9, the + symbol represents 1 or more times repeated.
# This means it would also block 'house_123' and 'house_000456'. It will not block 'ahouse_1' or 'house_'.
blacklist:
- '__global__'
# Minimum length of the numbers that are suffixed for region names generated by the '/as stack' command.
# When having this at 3 it will generate names like this: 'region-001', 'region-014', 'region-4567'.
stackRegionNumberLength: 3
# Allow/disallow adding players that did not visit the server yet as friend of a region.
addFriendNotExistingPlayers: false
# Enable sending stats to http://mcstats.org/ (Metrics plugin).
# This information will give me an indication about how much the plugin is used and encourages me to continue development.
sendStats: true
# If enabled it will check for updates when loading the plugin, it will never download files, it will only notify about it.
checkForUpdates: true
# Use colors when sending messages to console and log files.
useColorsInConsole: false
# Use tellraw style messages, which can be interacted with by players
useFancyMessages: true
# Update all region flags and signs after starting the plugin.
# This ensures that changes to the config are directly visible after restarting the server.
updateRegionsOnStartup: true
# Enables / disables debug messages in the console, could be useful to figure out where errors come from.
debug: false
# Version of the config, do not change!
version: ${project.version}
# Maximum number of blocks to save to or restore from a .schemetic file.
maximumBlocks: 1000000
# Maximum number of locations the teleport function should check to find a safe spot.
maximumTries: 50000
# ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
# │ VARIABLES: Variables that can be used in messages and settings where a region is available. │
# └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
# If a tag has no value (for example %player% when the region is not rented/bought) then the tag will not get replaced.
# %region% The region name (with correct capitalization).
# %player% The name of the player that rents/buys the region (with correct capitalization).
# %uuid% The UUID of the player that rents/buys the region.
# %friends% The names of friends added to this region separated by ', '.
# %friendsuuid% The UUID's of friends added to this region separated by ', '.
# %landlord% The name of the landlord.
# %landlorduuid% The UUID of the landlord.
# %price% The price of the region formatted with the configured characters before and after the number.
# %rawprice% The price without formatting, like '10.0' or '7.77'.
# %duration% The duration of a rent region, for example '1 d', '4 minutes' or '2 years'.
# %world% The name of the world that the region is in.
# %type% The type of the region, 'rent' or 'buy'.
# %until% The end time of a rent formatted as configured with 'timeFormatChat'.
# %untilshort% The end time of a rent formatted as configured with 'timeFormatSign'.
# %width% The width of the region (number of blocks on the x-axis).
# %depth% The depth of the region (number of blocks on the z-axis).
# %volume% The number of blocks in a region (accounting for polygon shaped regions).
# %height% The height of the region (number of blocks on the y-axis).
# %timeleft% The time left on the rent (uses the unit of time that fits best, minutes used from 121 seconds till 120 minutes).
# %clicker% The name of the player that clicked the sign (only to be used in the signProfiles section).
# %resellprice% The price of a region when it is in resell mode.
# %rawresellprice% The resellprice without formatting.
# %moneyback% The amount of money the player will get back when unrenting/selling the region (formatted with currency layout).
# %rawmoneyback% The moneyback without formatting.
# %moneybackpercent% The percentage of the price the player will get back when unrenting the region.
# %timesExtended% The number of times the region has been extended (zero when first rented)
# %maxextends% The maximum number of extends a player can do on the region.
# %extendsleft% The number of extends that are left (maxextends - timesextended).
# %maxrenttime% The maximum time you can rent a region in advance (human readable).
# %inactivetime% The maximum time a player may be inactive before unrent/sell (human readable).
# %year% The current year.
# %month% The current month in the year.
# %day% The current day in the month.
# %hour% The current hour in the day (0-23).
# %minute% The current minute of the hour.
# %second% The current second of the minute.
# %millisecond% The current millisecond of the second.
# %epoch% The number of milliseconds since January 1, 1970 (Unix Epoch).
# %tpx% The exact x coordinate of the location that the teleport is set to
# %tpy% The exact y coordinate of the location that the teleport is set to
# %tpz% The exact z coordinate of the location that the teleport is set to
# %tpblockx% The rounded x coordinate of the location that the teleport is set to
# %tpblocky% The rounded y coordinate of the location that the teleport is set to
# %tpblockz% The rounded z coordinate of the location that the teleport is set to
# %tppitch% The exact pitch of the teleport location
# %tppitchround% The rounded pitch of the teleport location
# %tpyaw% The exact yaw of the teleport location
# %tpyawround% The rounded yaw of the teleport location
# %tpworld% The world name of the teleport location
# %lang:<languageKey>|Optional arguments|% Insert a message from EN.yml, for example: '%lang:timeleft-ended%' or '%lang:timeleft-years|15|%'
# ╔════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╗
# ║ config.yml file of the AreaShop plugin created by NLThijs48, Github can be found at https://github.com/NLthijs48/AreaShop. ║
# ║ This file contains options to change the working of the plugin, the profiles defined here can be used in default.yml. ║
# ║ More information and tutorials can be found on the wiki: https://github.com/NLthijs48/AreaShop/wiki ║
# ╚════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╝
# ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
# │ GENERAL: Options that influence the global state of the plugin │
# └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
# Chat prefix used for all messages in the chat, also changes the greeting messages.
chatPrefix:
- '[darkgreen][AreaShop][reset]'
- ' hover: AreaShop region management plugin'
- ' hover: %lang:action|Click to check the available commands|%'
- ' command: /areashop help'
- ' '
# The language file that should be used, check the 'lang' folder for build-in languages (use the filename without .yml here).
# More information can be found here: https://github.com/NLthijs48/AreaShop/wiki/Language-support.
language: EN
# The tags that need to be written on the first line of a sign to add it to AreaShop.
signTags:
# Add a rental region.
rent: '[asrent]'
# Add a buy region.
buy: '[asbuy]'
# Add a sign to an existing region.
add: '[as]'
# ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
# │ ECONOMY: Options to change the display of prices. │
# └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
# The characters displayed before a price.
moneyCharacter: '$'
# The characters displayed after a price.
moneyCharacterAfter: ''
# The character(s) to use as decimal mark.
decimalMark: '.'
# How many numbers behind the dot should be shown (2 will make numbers like '8.55', '9.01', '5.20').
fractionalNumbers: 2
# How many numbers behind the dot should be shown when using a metric symbol suffix.
fractionalNumbersShort: 3
# Set this to true if you want to hide '.0' for a number like '15.0' ('4.50' will still stay '4.50').
hideEmptyFractionalPart: true
# Use a suffix if the price is above a certain number (use 1.00M instead of 1000000.00 etc.)
metricSymbols:
#1000: "k"
1000000: "M"
1000000000: "G"
1000000000000: "T"
1000000000000000: "P"
1000000000000000000: "E"
1000000000000000000000: "Z"
1000000000000000000000000: "Y"
# ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
# │ RENTING: Options that apply to all rent regions. │
# └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
# Timeformat to use on the signs, default is like '30-06 14:52', US format: 'MM-dd KK:mm a'.
# Search for 'java SimpleDateFormat' for more options and documentation.
timeFormatSign: 'dd-MM HH:mm'
# Timeformat used in the chat, default is like '30 june 2014 14:52', US format: 'MMMMMMMMMMMMMMMMM dd yyyy KK:mm a'.
# Search for 'java SimpleDateFormat' for more options and documentation.
timeFormatChat: 'dd MMMMMMMMMMMMMMMMM yyyy HH:mm'
# Time indicators, used for specifing time periods (for example rent duration).
seconds: [s, sec, secs, second, seconds]
minutes: [m, min, mins, minute, minutes]
hours: [h, hour, hours]
days: [d, day, days]
weeks: [w, week, weeks]
months: [M, month, months]
years: [y, year, years]
# ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
# │ PERMISSION GROUPS: Assigned by giving players certain permissions. │
# └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
# Configure the max total regions, max rent regions and max buy regions with different groups (-1 is unlimited).
# Assign a group to players by giving them the permission 'areashop.limits.<group>'.
# Every player already has the group 'default', OPs bypass the limits because of the 'areashop.limitbypass' permission.
# All the groups applied to the player will be checked and only if they all allow an extra region it will be allowed.
# More information like limits for regions of a certain group or in a certain word can be found here:
# https://github.com/NLthijs48/AreaShop/wiki/Limitgroups-information-and-examples.
limitGroups:
default:
total: 1
rents: 1
buys: 1
# ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
# │ ADVANCED AND DEBUG: Specific options to tweak the plugin precisely and check if it functions correctly. │
# └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
# Blacklist of region names that cannot be added to AreaShop for renting or buying. Regular expressions can be used, search
# for 'java regex pattern' to find documentation about how to use it.
# Example: Blocking all regions that have a name like 'house_1', 'house_2', etc. would be done with 'house_\d+'.
# The '\d' represents the numerical digits 0-9, the + symbol represents 1 or more times repeated.
# This means it would also block 'house_123' and 'house_000456'. It will not block 'ahouse_1' or 'house_'.
blacklist:
- '__global__'
# Minimum length of the numbers that are suffixed for region names generated by the '/as stack' command.
# When having this at 3 it will generate names like this: 'region-001', 'region-014', 'region-4567'.
stackRegionNumberLength: 3
# Allow/disallow adding players that did not visit the server yet as friend of a region.
addFriendNotExistingPlayers: false
# Enable sending stats to http://mcstats.org/ (Metrics plugin).
# This information will give me an indication about how much the plugin is used and encourages me to continue development.
sendStats: true
# If enabled it will check for updates when loading the plugin, it will never download files, it will only notify about it.
checkForUpdates: true
# Use colors when sending messages to console and log files.
useColorsInConsole: false
# Use tellraw style messages, which can be interacted with by players
useFancyMessages: true
# Update all region flags and signs after starting the plugin.
# This ensures that changes to the config are directly visible after restarting the server.
updateRegionsOnStartup: true
# Enables / disables debug messages in the console, could be useful to figure out where errors come from.
debug: false
# Version of the config, do not change!
version: ${project.version}
# Maximum number of blocks to save to or restore from a .schemetic file.
maximumBlocks: 1000000
# Maximum number of locations the teleport function should check to find a safe spot.
maximumTries: 50000
# ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
# │ VARIABLES: Variables that can be used in messages and settings where a region is available. │
# └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
# If a tag has no value (for example %player% when the region is not rented/bought) then the tag will not get replaced.
# %region% The region name (with correct capitalization).
# %player% The name of the player that rents/buys the region (with correct capitalization).
# %uuid% The UUID of the player that rents/buys the region.
# %friends% The names of friends added to this region separated by ', '.
# %friendsuuid% The UUID's of friends added to this region separated by ', '.
# %landlord% The name of the landlord.
# %landlorduuid% The UUID of the landlord.
# %price% The price of the region formatted with the configured characters before and after the number.
# %rawprice% The price without formatting, like '10.0' or '7.77'.
# %duration% The duration of a rent region, for example '1 d', '4 minutes' or '2 years'.
# %world% The name of the world that the region is in.
# %type% The type of the region, 'rent' or 'buy'.
# %until% The end time of a rent formatted as configured with 'timeFormatChat'.
# %untilshort% The end time of a rent formatted as configured with 'timeFormatSign'.
# %width% The width of the region (number of blocks on the x-axis).
# %depth% The depth of the region (number of blocks on the z-axis).
# %volume% The number of blocks in a region (accounting for polygon shaped regions).
# %height% The height of the region (number of blocks on the y-axis).
# %timeleft% The time left on the rent (uses the unit of time that fits best, minutes used from 121 seconds till 120 minutes).
# %clicker% The name of the player that clicked the sign (only to be used in the signProfiles section).
# %resellprice% The price of a region when it is in resell mode.
# %rawresellprice% The resellprice without formatting.
# %moneyback% The amount of money the player will get back when unrenting/selling the region (formatted with currency layout).
# %rawmoneyback% The moneyback without formatting.
# %moneybackpercent% The percentage of the price the player will get back when unrenting the region.
# %timesExtended% The number of times the region has been extended (zero when first rented)
# %maxextends% The maximum number of extends a player can do on the region.
# %extendsleft% The number of extends that are left (maxextends - timesextended).
# %maxrenttime% The maximum time you can rent a region in advance (human readable).
# %inactivetime% The maximum time a player may be inactive before unrent/sell (human readable).
# %year% The current year.
# %month% The current month in the year.
# %day% The current day in the month.
# %hour% The current hour in the day (0-23).
# %minute% The current minute of the hour.
# %second% The current second of the minute.
# %millisecond% The current millisecond of the second.
# %epoch% The number of milliseconds since January 1, 1970 (Unix Epoch).
# %tpx% The exact x coordinate of the location that the teleport is set to
# %tpy% The exact y coordinate of the location that the teleport is set to
# %tpz% The exact z coordinate of the location that the teleport is set to
# %tpblockx% The rounded x coordinate of the location that the teleport is set to
# %tpblocky% The rounded y coordinate of the location that the teleport is set to
# %tpblockz% The rounded z coordinate of the location that the teleport is set to
# %tppitch% The exact pitch of the teleport location
# %tppitchround% The rounded pitch of the teleport location
# %tpyaw% The exact yaw of the teleport location
# %tpyawround% The rounded yaw of the teleport location
# %tpworld% The world name of the teleport location
# %lang:<languageKey>|Optional arguments|% Insert a message from EN.yml, for example: '%lang:timeleft-ended%' or '%lang:timeleft-years|15|%'
+273 -276
View File
@@ -1,276 +1,273 @@
name: AreaShop
main: me.wiefferink.areashop.AreaShop
version: "${project.version}${build.number}"
description: "Selling and renting WorldGuard regions to your players, highly configurable."
depend: [Vault, WorldGuard, WorldEdit]
softdepend: [Multiverse-Core, FastAsyncWorldEdit]
author: NLThijs48
website: https://github.com/NLthijs48/AreaShop
commands:
AreaShop:
description: 'For all commands use /as help.'
usage: 'AreaShop has not started correctly, check the log file (or console) and correct any errors.'
aliases: [as]
test:
awareness:
- !@UTF8
api-version: 1.13
permissions:
areashop.*:
description: Give access to all commands of AreaShop
children:
areashop.help: true
areashop.createrent: true
areashop.createbuy: true
areashop.destroyrent: true
areashop.destroybuy: true
areashop.rent: true
areashop.buy: true
areashop.buyresell: true
areashop.buynormal: true
areashop.unrent: true
areashop.info: true
areashop.reload: true
areashop.setrestore: true
areashop.setprice: true
areashop.setduration: true
areashop.teleport: true
areashop.teleportall: true
areashop.setteleportall: true
areashop.teleportsign: true
areashop.teleportsignall: true
areashop.tabcomplete: true
areashop.setteleportoutsideregion: true
areashop.find: true
areashop.groupadd: true
areashop.groupdel: true
areashop.grouplist: true
areashop.groupinfo: true
areashop.limitbypass: true
areashop.schematicevents: true
areashop.addsign: true
areashop.delsign: true
areashop.renttimebypass: true
areashop.me: true
areashop.resellall: true
areashop.stopresellall: true
areashop.addfriendall: true
areashop.delfriendall: true
areashop.notifyupdate: true
areashop.stack: true
areashop.setlandlord: true
areashop.linksigns: true
areashop.message: true
areashop.import: true
areashop.landlord.*:
description: Give access to all landlord features
children:
areashop.createrent.owner: true
areashop.createbuy.owner: true
areashop.setprice.landlord: true
areashop.setduration.landlord: true
areashop.destroyrent.landlord: true
areashop.destroybuy.landlord: true
areashop.help:
description: Allows you to see the help pages
default: true
areashop.rent:
description: Allows you to rent a region
default: true
areashop.buy:
description: Allows you to buy a region
default: true
areashop.buyresell:
description: Allows you to buy a region that is in resell mode
default: true
areashop.buynormal:
description: Allows you to buy a region that is not in resell mode
default: true
areashop.unrent:
description: Allows you to unrent a specific region
default: op
areashop.unrentown:
description: Allows you to unrent your own region
default: true
areashop.sell:
description: Allows you to sell a specific region
default: op
areashop.sellown:
description: Allows you to sell your own region
default: true
areashop.createrent:
description: Allows you to add rent regions to AreaShop
default: op
areashop.createrent.member:
description: Allows you to add rent regions to AreaShop for which you are registered as member
default: false
areashop.createrent.owner:
description: Allows you to add rent regions to AreaShop for which you are registered as owner
default: false
areashop.createbuy:
description: Allows you to add buy regions to AreaShop
default: op
areashop.createbuy.member:
description: Allows you to add buy regions to AreaShop for which you are registered as member
default: false
areashop.createbuy.owner:
description: Allows you to add buy regions to AreaShop for which you are registered as owner
default: false
areashop.destroyrent:
description: Allows you remove rental regions from AreaShop
default: op
areashop.destroyrent.landlord:
description: Allows you to remove rental regions from AreaShop when you are the landlord
default: false
areashop.destroybuy:
description: Allows you to remove buy regions from AreaShop
default: op
areashop.destroybuy.landlord:
description: Allows you to remove buy regions from AreaShop when you are the landlord
default: false
areashop.info:
description: Allows you check the status of regions and players
default: true
areashop.reload:
description: Allows you to reload the config and update all region flags and signs
default: op
areashop.setrestore:
description: Allows you to change the restore settings
default: op
areashop.setprice:
description: Allows you to change the price
default: op
areashop.setprice.landlord:
description: Allows you to change the price of a region that you are landlord of
default: false
areashop.setduration:
description: Allows you to change the duration of a rent
default: op
areashop.setduration.landlord:
description: Allows you to change the duration of a region that you are landlord of
default: false
areashop.teleport:
description: Teleport to your region
default: true
areashop.teleportall:
description: Teleport to all regions
default: op
areashop.teleportsign:
description: Teleport to signs of regions you own
default: true
areashop.teleportsignall:
description: Teleport to signs of all regions
default: op
areashop.teleportfriend:
description: Teleport to regions where you are added as friend
default: true
areashop.teleportfriendsign:
description: Teleport to the sign of regions where you are added as friend
default: true
areashop.teleportavailable:
description: Teleport to regions which are available
default: true
areashop.teleportavailablesign:
description: Teleport to the sign of regions which are available
default: true
areashop.setteleport:
description: Set the teleport spot for your region
default: true
areashop.setteleportall:
description: Set the teleport for other regions
default: op
areashop.setteleportoutsideregion:
description: Set the teleport location outside the WorldGuard region
default: op
areashop.tabcomplete:
description: Allows you to tabcomplete all commands (also where you dont have permission)
default: op
areashop.find:
description: Allows you to teleport to a free region (/as find)
default: true
areashop.groupadd:
description: Allows you to add regions to groups
default: op
areashop.groupdel:
description: Allows you to delete regions from groups
default: op
areashop.grouplist:
description: Allows you to list all the groups currently created
default: op
areashop.groupinfo:
description: Allows you to display information about a group (all members)
default: op
areashop.rentextendbypass:
description: Bypass the extend limit on rents
default: op
areashop.limits.default:
description: Assign limits as set in the 'default' group in the 'limitGroups' section of the config
default: true
areashop.limitbypass:
description: Bypass the limits for renting/buying regions (how many you can have at the same time)
default: op
areashop.schematicevents:
description: Allows you to trigger schematic events for regions
default: op
areashop.addsign:
description: Allows you to add signs to existing regions
default: op
areashop.delsign:
description: Allows you to delete signs from existing regions
default: op
areashop.renttimebypass:
description: Bypass the maximum rent time you can have in advance
default: op
areashop.me:
description: Allows you to get information about your regions
default: true
areashop.setownerrent:
description: Allows you to set the owner of rent regions
default: op
areashop.setownerbuy:
description: Allows you to set the owner of buy regions
default: op
areashop.resell:
description: Allows you to set your region to sell mode for selling to other players
default: true
areashop.resellall:
description: Allows you to set any region into selling mode
default: op
areashop.stopresell:
description: Allows you to set your region into normal mode if it is in sell mode
default: true
areashop.stopresellall:
description: Allows you to set any region into normal mode if it is in sell mode
default: op
areashop.addfriend:
description: Allows you to add friends to your regions
default: true
areashop.addfriendall:
description: Allows you to add friends to all regions
default: op
areashop.delfriend:
description: Allows you to delete friends from your regions
default: true
areashop.delfriendall:
description: Allows you to delete friends from all regions
default: op
areashop.notifyupdate:
description: Will notify this player when an update is available
default: op
areashop.linksigns:
description: Allows you to enter sign linking mode
default: op
areashop.stack:
description: Allows you to create regions and add them to AreaShop like the WorldEdit //stack command
default: op
areashop.setlandlord:
description: Allows you to set the landlord of a region, the landlord receives all revenue
default: op
areashop.message:
description: Allows you to send AreaShop messages to players
default: op
areashop.import:
description: Allows importing regions from other plugins
default: op
name: AreaShop
main: me.wiefferink.areashop.AreaShop
version: "@version@"
description: "Selling and renting WorldGuard regions to your players, highly configurable."
depend: [Vault, WorldGuard, WorldEdit]
softdepend: [Multiverse-Core, FastAsyncWorldEdit]
author: NLThijs48
website: https://github.com/NLthijs48/AreaShop
commands:
AreaShop:
description: 'For all commands use /as help.'
usage: 'AreaShop has not started correctly, check the log file (or console) and correct any errors.'
aliases: [as]
awareness:
- !@UTF8
api-version: 1.13
permissions:
areashop.*:
description: Give access to all commands of AreaShop
children:
areashop.help: true
areashop.createrent: true
areashop.createbuy: true
areashop.destroyrent: true
areashop.destroybuy: true
areashop.rent: true
areashop.buy: true
areashop.buyresell: true
areashop.buynormal: true
areashop.unrent: true
areashop.info: true
areashop.reload: true
areashop.setrestore: true
areashop.setprice: true
areashop.setduration: true
areashop.teleport: true
areashop.teleportall: true
areashop.setteleportall: true
areashop.teleportsign: true
areashop.teleportsignall: true
areashop.tabcomplete: true
areashop.setteleportoutsideregion: true
areashop.find: true
areashop.groupadd: true
areashop.groupdel: true
areashop.grouplist: true
areashop.groupinfo: true
areashop.limitbypass: true
areashop.schematicevents: true
areashop.addsign: true
areashop.delsign: true
areashop.renttimebypass: true
areashop.me: true
areashop.resellall: true
areashop.stopresellall: true
areashop.addfriendall: true
areashop.delfriendall: true
areashop.notifyupdate: true
areashop.stack: true
areashop.setlandlord: true
areashop.linksigns: true
areashop.message: true
areashop.import: true
areashop.landlord.*:
description: Give access to all landlord features
children:
areashop.createrent.owner: true
areashop.createbuy.owner: true
areashop.setprice.landlord: true
areashop.setduration.landlord: true
areashop.destroyrent.landlord: true
areashop.destroybuy.landlord: true
areashop.help:
description: Allows you to see the help pages
default: true
areashop.rent:
description: Allows you to rent a region
default: true
areashop.buy:
description: Allows you to buy a region
default: true
areashop.buyresell:
description: Allows you to buy a region that is in resell mode
default: true
areashop.buynormal:
description: Allows you to buy a region that is not in resell mode
default: true
areashop.unrent:
description: Allows you to unrent a specific region
default: op
areashop.unrentown:
description: Allows you to unrent your own region
default: true
areashop.sell:
description: Allows you to sell a specific region
default: op
areashop.sellown:
description: Allows you to sell your own region
default: true
areashop.createrent:
description: Allows you to add rent regions to AreaShop
default: op
areashop.createrent.member:
description: Allows you to add rent regions to AreaShop for which you are registered as member
default: false
areashop.createrent.owner:
description: Allows you to add rent regions to AreaShop for which you are registered as owner
default: false
areashop.createbuy:
description: Allows you to add buy regions to AreaShop
default: op
areashop.createbuy.member:
description: Allows you to add buy regions to AreaShop for which you are registered as member
default: false
areashop.createbuy.owner:
description: Allows you to add buy regions to AreaShop for which you are registered as owner
default: false
areashop.destroyrent:
description: Allows you remove rental regions from AreaShop
default: op
areashop.destroyrent.landlord:
description: Allows you to remove rental regions from AreaShop when you are the landlord
default: false
areashop.destroybuy:
description: Allows you to remove buy regions from AreaShop
default: op
areashop.destroybuy.landlord:
description: Allows you to remove buy regions from AreaShop when you are the landlord
default: false
areashop.info:
description: Allows you check the status of regions and players
default: true
areashop.reload:
description: Allows you to reload the config and update all region flags and signs
default: op
areashop.setrestore:
description: Allows you to change the restore settings
default: op
areashop.setprice:
description: Allows you to change the price
default: op
areashop.setprice.landlord:
description: Allows you to change the price of a region that you are landlord of
default: false
areashop.setduration:
description: Allows you to change the duration of a rent
default: op
areashop.setduration.landlord:
description: Allows you to change the duration of a region that you are landlord of
default: false
areashop.teleport:
description: Teleport to your region
default: true
areashop.teleportall:
description: Teleport to all regions
default: op
areashop.teleportsign:
description: Teleport to signs of regions you own
default: true
areashop.teleportsignall:
description: Teleport to signs of all regions
default: op
areashop.teleportfriend:
description: Teleport to regions where you are added as friend
default: true
areashop.teleportfriendsign:
description: Teleport to the sign of regions where you are added as friend
default: true
areashop.teleportavailable:
description: Teleport to regions which are available
default: true
areashop.teleportavailablesign:
description: Teleport to the sign of regions which are available
default: true
areashop.setteleport:
description: Set the teleport spot for your region
default: true
areashop.setteleportall:
description: Set the teleport for other regions
default: op
areashop.setteleportoutsideregion:
description: Set the teleport location outside the WorldGuard region
default: op
areashop.tabcomplete:
description: Allows you to tabcomplete all commands (also where you dont have permission)
default: op
areashop.find:
description: Allows you to teleport to a free region (/as find)
default: true
areashop.groupadd:
description: Allows you to add regions to groups
default: op
areashop.groupdel:
description: Allows you to delete regions from groups
default: op
areashop.grouplist:
description: Allows you to list all the groups currently created
default: op
areashop.groupinfo:
description: Allows you to display information about a group (all members)
default: op
areashop.rentextendbypass:
description: Bypass the extend limit on rents
default: op
areashop.limits.default:
description: Assign limits as set in the 'default' group in the 'limitGroups' section of the config
default: true
areashop.limitbypass:
description: Bypass the limits for renting/buying regions (how many you can have at the same time)
default: op
areashop.schematicevents:
description: Allows you to trigger schematic events for regions
default: op
areashop.addsign:
description: Allows you to add signs to existing regions
default: op
areashop.delsign:
description: Allows you to delete signs from existing regions
default: op
areashop.renttimebypass:
description: Bypass the maximum rent time you can have in advance
default: op
areashop.me:
description: Allows you to get information about your regions
default: true
areashop.setownerrent:
description: Allows you to set the owner of rent regions
default: op
areashop.setownerbuy:
description: Allows you to set the owner of buy regions
default: op
areashop.resell:
description: Allows you to set your region to sell mode for selling to other players
default: true
areashop.resellall:
description: Allows you to set any region into selling mode
default: op
areashop.stopresell:
description: Allows you to set your region into normal mode if it is in sell mode
default: true
areashop.stopresellall:
description: Allows you to set any region into normal mode if it is in sell mode
default: op
areashop.addfriend:
description: Allows you to add friends to your regions
default: true
areashop.addfriendall:
description: Allows you to add friends to all regions
default: op
areashop.delfriend:
description: Allows you to delete friends from your regions
default: true
areashop.delfriendall:
description: Allows you to delete friends from all regions
default: op
areashop.notifyupdate:
description: Will notify this player when an update is available
default: op
areashop.linksigns:
description: Allows you to enter sign linking mode
default: op
areashop.stack:
description: Allows you to create regions and add them to AreaShop like the WorldEdit //stack command
default: op
areashop.setlandlord:
description: Allows you to set the landlord of a region, the landlord receives all revenue
default: op
areashop.message:
description: Allows you to send AreaShop messages to players
default: op
areashop.import:
description: Allows importing regions from other plugins
default: op
+5 -5
View File
@@ -64,11 +64,11 @@ For a preview join 'mc.go-craft.com' and go to the Survival server, the shops ar
Old video for AreaShop v1.0: [Tutorial by VariationVault](https://www.youtube.com/watch?v=k2HMCxCCOYo)
### Required dependencies
* Java 8 or higher (latest recommended)
* Bukkit/Spigot 1.13.2 or higher (modded servers often include Bukkit/Spigot support, so it should also work on that, but it is not specifically tested for it)
* [WorldGuard](http://dev.bukkit.org/bukkit-plugins/worldguard/): 7.0.3 or higher
* [WorldEdit](http://dev.bukkit.org/bukkit-plugins/worldedit/): 7.0.1 or higher
* [Vault](http://dev.bukkit.org/bukkit-plugins/vault/): 1.7 or higher
* Java 7 or higher (latest recommended)
* Bukkit/Spigot 1.7.9 or higher (modded servers often include Bukkit/Spigot support, so it should also work on that, but it is not specifically tested for it)
* [WorldGuard](http://dev.bukkit.org/bukkit-plugins/worldguard/): 5.9 or higher (6.0+ recommended)
* [WorldEdit](http://dev.bukkit.org/bukkit-plugins/worldedit/): 5.6.3 or higher (6.0+ recommended)
* [Vault](http://dev.bukkit.org/bukkit-plugins/vault/): 1.4.1 or higher
* An economy plugin supported by Vault (check the [Vault page](http://dev.bukkit.org/bukkit-plugins/vault/) for a list of these)
### Metrics
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module version="4">
<component name="FacetManager">
<facet type="minecraft" name="Minecraft">
<configuration>
<autoDetectTypes>
<platformType>BUKKIT</platformType>
</autoDetectTypes>
</configuration>
</facet>
</component>
</module>
+31
View File
@@ -0,0 +1,31 @@
dependencies {
compileOnly 'org.spigotmc:spigot-api:1.17.1-R0.1-SNAPSHOT'
compileOnly project(':areashop-interface')
}
description = 'AreaShop Bukkit 1.13 and higher'
publishing {
publications {
// ... artifact publications
areaShop(MavenPublication) {
from components.java
pom {
group = "me.wiefferink"
artifactId = "$project.name"
version = "$project.version"
scm {
connection = 'scm:git:git://github.com/md5sha256/AreaShop.git'
developerConnection = 'scm:git:ssh://github.com/md5sha256/AreaShop.git'
url = "https://github.com/md5sha256/AreaShop/tree/dev/bleeding"
}
licenses {
license {
name = 'GNU General Public License v3.0'
url = "https://github.com/md5sha256/AreaShop/blob/dev/bleeding/LICENSE"
}
}
}
}
}
}
@@ -0,0 +1,77 @@
package me.wiefferink.areashop.handlers;
import me.wiefferink.areashop.interfaces.AreaShopInterface;
import me.wiefferink.areashop.interfaces.BukkitInterface;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.type.Sign;
import org.bukkit.block.data.type.WallSign;
public class BukkitHandler1_13 extends BukkitInterface {
public BukkitHandler1_13(AreaShopInterface pluginInterface) {
super(pluginInterface);
}
// Uses BlockData, which does not yet exist in 1.12-
@Override
public BlockFace getSignFacing(Block block) {
if (block == null) {
return null;
}
BlockState blockState = block.getState();
BlockData blockData = blockState.getBlockData();
if(blockData instanceof WallSign) {
return ((WallSign) blockData).getFacing();
} else if(blockData instanceof Sign) {
return ((Sign) blockData).getRotation();
}
return null;
}
// Uses BlockData, WallSign and Sign which don't exist in 1.12-
@Override
public boolean setSignFacing(Block block, BlockFace facing) {
if (block == null || facing == null) {
return false;
}
BlockState blockState = block.getState();
BlockData blockData = blockState.getBlockData();
if(blockData instanceof WallSign) {
((WallSign) blockData).setFacing(facing);
} else if(blockData instanceof Sign) {
((Sign) blockData).setRotation(facing);
} else {
return false;
}
block.setBlockData(blockData);
return true;
}
@Override
public Block getSignAttachedTo(Block block) {
if (block == null) {
return null;
}
BlockState blockState = block.getState();
BlockData blockData = blockState.getBlockData();
if(blockData instanceof WallSign) {
return block.getRelative(((WallSign) blockData).getFacing().getOppositeFace());
} else if(blockData instanceof Sign) {
return block.getRelative(BlockFace.DOWN);
}
return null;
}
}
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module version="4">
<component name="FacetManager">
<facet type="minecraft" name="Minecraft">
<configuration>
<autoDetectTypes>
<platformType>BUKKIT</platformType>
</autoDetectTypes>
</configuration>
</facet>
</component>
</module>
+32
View File
@@ -0,0 +1,32 @@
dependencies {
compileOnly 'org.spigotmc:spigot-api:1.18.1-R0.1-SNAPSHOT'
compileOnly 'com.sk89q.worldedit:worldedit-bukkit:7.2.8'
compileOnly 'com.sk89q.worldguard:worldguard-bukkit:7.0.6'
}
description = 'AreaShop Interface'
publishing {
publications {
// ... artifact publications
areaShop(MavenPublication) {
from components.java
pom {
group = "me.wiefferink"
artifactId = "$project.name"
version = "$project.version"
scm {
connection = 'scm:git:git://github.com/md5sha256/AreaShop.git'
developerConnection = 'scm:git:ssh://github.com/md5sha256/AreaShop.git'
url = "https://github.com/md5sha256/AreaShop/tree/dev/bleeding"
}
licenses {
license {
name = 'GNU General Public License v3.0'
url = "https://github.com/md5sha256/AreaShop/blob/dev/bleeding/LICENSE"
}
}
}
}
}
}
@@ -0,0 +1,35 @@
package me.wiefferink.areashop.interfaces;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
public abstract class BukkitInterface {
protected final AreaShopInterface pluginInterface;
public BukkitInterface(AreaShopInterface pluginInterface) {
this.pluginInterface = pluginInterface;
}
/**
* Get the direciton a sign is facing.
* @param block Sign block to get the facing from
* @return direction the sign is facing
*/
public abstract BlockFace getSignFacing(Block block);
/**
* Set the direction a sign is facing.
* @param block Sign block to update
* @param facing direction to let the sign face
* @return true when successful, otherwise false
*/
public abstract boolean setSignFacing(Block block, BlockFace facing);
/**
* Get the block a sign is attached to.
* @param block Sign block
* @return Block the sign is attached to, or null when not a sign or not attached
*/
public abstract Block getSignAttachedTo(Block block);
}
@@ -56,7 +56,7 @@ public class RegionAccessSet {
result.addAll(playerUniqueIds);
for(String playerName : playerNames) {
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(playerName);
if (offlinePlayer.hasPlayedBefore()) {
if(offlinePlayer != null && offlinePlayer.getUniqueId() != null) {
result.add(offlinePlayer.getUniqueId());
}
}
+55
View File
@@ -0,0 +1,55 @@
plugins {
id 'java-library'
id 'maven-publish'
id 'io.papermc.paperweight.userdev' version '1.3.3' apply false
}
group = 'me.wiefferink'
version = '2.7.3'
subprojects {
plugins.apply('java-library')
plugins.apply('maven-publish')
version = '2.7.1'
repositories {
mavenCentral()
maven {
name = 'oss-sonatype'
url = uri("https://oss.sonatype.org/content/groups/public/")
}
maven {
name = 'paper-repo'
url = uri('https://papermc.io/repo/repository/maven-public/')
}
maven {
name = 'spigot-repo'
url = uri('https://hub.spigotmc.org/nexus/content/repositories/snapshots/')
}
maven {
name = 'jitpack'
url = uri('https://jitpack.io')
content {
includeGroupByRegex("com\\.github.*")
}
}
maven {
name = 'aikar-repo'
url = uri('https://repo.aikar.co/content/groups/aikar/')
}
maven {
name = 'enginehub-repo'
url = uri('https://maven.enginehub.org/repo/')
}
}
tasks.withType(JavaCompile) {
java.toolchain.languageVersion.set(JavaLanguageVersion.of(17))
options.release.set(17)
options.encoding = 'UTF-8'
options.fork = true
options.deprecation = true
}
}
+1
View File
@@ -0,0 +1 @@
org.gradle.parallel=true
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff. Show more