86 Commits
Author SHA1 Message Date
Intelli 40ee11f644 CoreProtect v21.0 release 2022-03-08 08:39:38 -07:00
Intelli 02dcc873d6 Added hidden "exclude-tnt" rollback option to exclude TNT blocks (default: false) 2022-03-07 16:39:21 -07:00
Intelli 2b96daa422 Change items crafted at crafting tables to log at table location 2022-03-07 15:25:27 -07:00
Intelli d472879dec Added interaction logging for crafting tables, enchanting tables, smithing tables, and stonecutters 2022-03-07 15:16:03 -07:00
EEstarandIntelli dbcf79cd46 Add CoreProtectTNT to tools-integrations.md (#163)
* Update tools-integrations.md

* Updated CoreProtect TNT description

Co-authored-by: Intelli <6790859+Intelli@users.noreply.github.com>
2022-03-07 14:26:09 -07:00
Intelli c69ea79329 Fixed rollbacks not skipping processing for identical blocks 2022-03-06 17:05:18 -07:00
Intelli 83fc221bf2 Added logging for items traded with villagers (MC 1.18+) 2022-03-03 15:22:37 -07:00
Intelli 7bc95931d2 Added hidden "enable-awe" option for AWE logging (default: false) 2022-03-02 16:24:56 -07:00
Intelli 2fa5af64ca Updated Gradle build file to match Maven 2022-03-02 13:14:30 -07:00
Intelli 1be82111ed Changed entities killed via /kill command to log under #command 2022-03-01 20:34:12 -07:00
Intelli a6869176be Minor refactoring in EntityDeathListener 2022-03-01 20:17:12 -07:00
Intelli 7c7fd200d2 Fixed all listener classes not being final 2022-03-01 20:05:13 -07:00
Intelli 6714ded600 Improved logging to skip unnecessary data from newly generated chunks 2022-03-01 17:41:46 -07:00
Intelli 6a22903240 Re-enabled BlocksHub & disabled logging integration with AWE 2022-03-01 16:49:22 -07:00
Intelli 0bbeee65e8 Added support for time ranges in the time parameter 2022-03-01 15:58:15 -07:00
Intelli a596dd66a9 Blocked access to BlocksHub to prevent duplicate data from being logged 2022-02-28 18:49:20 -07:00
Intelli 1aaff4e2b0 Enabled write-ahead logging for SQLite 2022-02-28 17:47:07 -07:00
Intelli 1c476408e9 Fixed rare instances of lookups displaying negative time values 2022-02-28 17:11:24 -07:00
Intelli 5530a89189 Improved index handling when targeting a specific location 2022-02-27 17:19:37 -07:00
Intelli c69a5a58c0 Fixed instances of NullPointerException in CraftItemEvent 2022-02-27 16:29:17 -07:00
Intelli f0702339f2 Migrated language code documentation to docs.coreprotect.net 2022-02-27 16:17:44 -07:00
Intelli 3774e6748d Improved Spanish translation (implements #161) 2022-02-27 15:59:04 -07:00
Intelli 596a39c965 Fixed all firework metadata not being correctly logged 2022-02-25 19:34:23 -07:00
Intelli 42c6deff8a Added logging and inventory rollback support for throwing snowballs and lingering potions 2022-02-25 19:23:53 -07:00
Intelli f5d13f8818 Fixed backwards compatibility with older server software/versions 2022-02-25 19:16:06 -07:00
Intelli 659fe649ed Changed minimum required Java version to Java 11 2022-02-25 16:53:05 -07:00
Intelli 9bdac6db4d Added entity counts to #preview confirmation page 2022-02-25 16:33:41 -07:00
Intelli 42233f1f72 Fixed phantom fire blocks being logged adjacent to lava 2022-02-25 16:14:35 -07:00
Intelli 900cad643f Fixed inventory lookups not returning correct item for planted seeds 2022-02-24 20:52:30 -07:00
Intelli ddb804ce99 Fixed farmland displaying in inventory rollbacks 2022-02-24 20:15:48 -07:00
Intelli 45f9f4316e Added logging and inventory rollback support for players breaking items 2022-02-24 20:03:28 -07:00
Intelli 5494bce0fc Added logging and rollback support for players crafting items 2022-02-24 19:52:19 -07:00
Intelli 30c1921968 Fixed inventory rollbacks not restoring shulker boxes with items 2022-02-23 19:36:08 -07:00
Intelli 262f27da3e Changed doors and beds to no longer log data as two separate blocks 2022-02-23 18:56:00 -07:00
Intelli f9083053b2 Fixed rolling back double blocks dropping an item in the world 2022-02-23 17:27:47 -07:00
Intelli 3b93046731 Fixed ClassCastException when rolling back banner inventory transactions 2022-02-22 21:41:11 -07:00
Intelli 4445c3c4a7 Fixed inventory rollbacks not always returning correct item for placed blocks 2022-02-22 21:15:45 -07:00
Intelli c95bf3cc30 Fixed fire/water displaying in inventory lookups 2022-02-22 20:10:55 -07:00
Intelli 2a8e4f9797 Fixed "/co undo" not functioning when targeting a container 2022-02-22 19:49:02 -07:00
Intelli f80c6ab5cd Fixed IllegalArgumentException when performing rollbacks on armor stand contents 2022-02-22 19:40:39 -07:00
Intelli b96f47cbac Added logging and inventory rollback support for thrown/shot items 2022-02-22 19:26:17 -07:00
Intelli 0d7fa2dd59 Added logging for players picking up arrows and tridents 2022-02-21 18:54:50 -07:00
Intelli a238045287 Moved BlockLookupAPI to net.coreprotect.api.BlockAPI 2022-02-21 18:22:55 -07:00
Intelli 167b8dfabd Display correct error message if a user isn't specified on an inventory rollback 2022-02-21 18:12:43 -07:00
Intelli d365eb498b Re-sort language file after upgrading 2022-02-18 20:47:18 -07:00
Intelli 585d8b275a Fixed inventory lookups/rollbacks missing block placement actions 2022-02-18 20:29:45 -07:00
Intelli 527be90249 Fixed item frame transactions not logging BlockFace data 2022-02-18 17:31:35 -07:00
Intelli c652ce852f Added interaction logging for players clicking item frames 2022-02-17 21:10:49 -07:00
Intelli fb79071ee7 Added container transaction support for item frames (...)
Fixed ClassCastException when targeting an armor stand with #container
2022-02-17 20:56:20 -07:00
Intelli e462e68806 Fixed item frames and paintings not logging directional data 2022-02-16 19:16:56 -07:00
Intelli 7398f7dfe6 Added "/co consumer <pause|resume>" console command 2022-02-16 16:09:43 -07:00
Intelli eb5b3b5bcc Added "inspector" as alias for inspect command 2022-02-16 15:01:20 -07:00
Intelli abfecda8d0 Added queueLookup method to API 2022-02-15 21:29:33 -07:00
Intelli c5d5308753 Minor cleanup in SessionLookup class 2022-02-15 20:20:46 -07:00
Intelli 50689604dd Renamed api/versions to api/version 2022-02-15 19:59:56 -07:00
Intelli 25b03511c2 Added sessionLookup method to API 2022-02-15 19:59:25 -07:00
Intelli d69d762bf4 Added API v7 documentation 2022-02-15 17:45:32 -07:00
Intelli d9eea32b19 Improved WorldEdit logging and added compatibility with FAWE 2022-02-15 16:47:50 -07:00
Intelli a2353afd0a Added inventory rollback support for online players 2022-02-11 21:45:33 -07:00
Intelli 29d55e6ba9 Fixed blocks placing when using shift+click to inspect trapdoors (#134) 2022-02-10 21:08:11 -07:00
Intelli 21eefff53f Added hidden "log-cancelled-chat" option (default: true) (#154) 2022-02-10 20:49:10 -07:00
Intelli b1c2795289 Fixed "coreprotect.inspect" permission not being checked at the time of inspection (fixes #133) 2022-02-10 20:36:38 -07:00
Intelli fdb98bd329 Fixed missing safety checks when inspecting certain blocks 2022-02-10 20:33:12 -07:00
Intelli dc359a1be3 Added "+container" and "-container" to tab-complete 2022-02-10 19:59:44 -07:00
Intelli d5c2b908d3 Fixed a:+/-inventory displaying mixed results 2022-02-10 19:57:30 -07:00
Intelli 54da739c1d Inverted action tags for deposits/withdraws 2022-02-10 19:36:23 -07:00
Intelli 01e6351194 Fixed "drop/pickup/deposit/withdraw" actions being incorrectly mapped 2022-02-10 19:26:27 -07:00
Intelli 855a2e5ae2 Renamed "a:inventory" to "a:item" in lookups 2022-02-10 19:21:30 -07:00
Intelli 971de8c078 Changed a:inventory to only display player inventory transactions 2022-02-10 19:18:32 -07:00
Intelli cd8ef0d273 Improved permission handling for "inventory" and "item" actions 2022-02-10 17:32:11 -07:00
Intelli 02afc6c530 Changed a:item to no longer include container transactions 2022-02-10 17:19:29 -07:00
Intelli 748490b8f0 Added "logins", "logouts", "blocks", and "signs" as new action aliases 2022-02-09 19:43:29 -07:00
Intelli 40561e41c0 Fixed player disconnections not being logged on server shutdown 2022-02-09 19:34:06 -07:00
Intelli 6a978128af Improved performance of rollback/restore previews 2022-02-09 18:14:46 -07:00
Intelli 635a2b0d95 Fixed IllegalArgumentException when performing a rollback preview containing an end crystal 2022-02-09 17:28:49 -07:00
Intelli ea69bf0dc5 UI improvements & action colours 2022-02-08 20:17:40 -07:00
Intelli 19efdeff89 Added clickable page numbers to lookup pagination 2022-02-08 19:25:07 -07:00
Intelli 673529df54 Fixed coordinates in lookups not always being properly aligned 2022-02-07 18:03:53 -07:00
Intelli 3a0c86a614 Fixed some lookups being slow when specifying an action 2022-02-07 17:39:33 -07:00
Intelli 70f74ced0f Added tooltips for clickable commands in lookup results 2022-02-03 20:36:27 -07:00
Intelli 2c8e289c43 Added "/co page" alias command for page lookups 2022-02-03 20:18:17 -07:00
Intelli b0d14f4d2b Fixed SQLiteException on lookups 2022-02-03 18:16:35 -07:00
Intelli 29d01a158a Added internal caching of table names & table counts 2022-02-02 21:19:06 -07:00
Intelli 67d9f2f832 Improved rollback speeds, now up to 2,000% faster 2022-01-31 21:49:44 -07:00
Intelli 591110cbb2 Improved lookup query performance 2022-01-31 20:03:07 -07:00
Intelli 286cf2afb9 Manually load SQLite JDBC driver 2022-01-19 15:11:11 -07:00
120 changed files with 5106 additions and 2114 deletions

No files matched your search

+1 -1
View File
@@ -41,7 +41,7 @@ Maven
<dependency>
<groupId>net.coreprotect</groupId>
<artifactId>coreprotect</artifactId>
<version>20.4</version>
<version>21.0</version>
<scope>provided</scope>
</dependency>
```
+6 -7
View File
@@ -2,16 +2,16 @@ import org.apache.tools.ant.filters.ReplaceTokens
plugins {
id 'java'
id 'com.github.johnrengelman.shadow' version '6.0.0'
id 'com.palantir.git-version' version '0.12.3'
id 'com.github.johnrengelman.shadow' version '7.1.2'
id 'com.palantir.git-version' version '0.13.0'
}
group = 'net.coreprotect'
String projectVersion = '20.4'
String projectVersion = '21.0'
String projectBranch = ''
version = projectVersion // `version` might be modified, we don't always want that (e.g. plugin.yml)
description = 'Provides block protection for your server.'
sourceCompatibility = '1.8'
sourceCompatibility = '17'
if (System.getenv("BUILD_NUMBER") != null) {
// Being built in Jenkins, append Build ID
@@ -25,17 +25,16 @@ logger.info("Building version $version")
repositories {
jcenter()
maven { url = 'https://hub.spigotmc.org/nexus/content/groups/public/' }
maven { url = 'https://oss.sonatype.org/content/repositories/snapshots/' }
maven { url = 'https://papermc.io/repo/repository/maven-public/' }
maven { url = 'https://repo.codemc.org/repository/maven-public/' }
maven { url = 'https://maven.sk89q.com/repo/' }
maven { url = 'https://maven.enginehub.org/repo/' }
}
dependencies {
compileOnly('com.sk89q.worldedit:worldedit-bukkit:7.0.0-SNAPSHOT') {
exclude group: 'org.bukkit'
}
compileOnly 'org.spigotmc:spigot-api:1.17-R0.1-SNAPSHOT'
compileOnly 'io.papermc.paper:paper-api:1.18.1-R0.1-SNAPSHOT'
implementation 'org.bstats:bstats-bukkit-lite:1.8'
implementation 'com.zaxxer:HikariCP:4.0.3'
}
+3 -456
View File
@@ -4,461 +4,8 @@ The CoreProtect API enables you to log your own block changes, perform lookups,
| API Details | |
| --- | --- |
| **API Version:** | 8 |
| **Plugin Version:** | v20.2+ |
| **API Version:** | 9 |
| **Plugin Version:** | v21.0+ |
| **Maven:** | [maven.playpro.com](https://maven.playpro.com) |
*Documentation for the previous API version can be found [here](https://www.minerealm.com/community/viewtopic.php?f=32&t=16687).*
---
## Upgrading from API v6
The changes from the previous API version are as follows:
- The following methods have been added:
```java
parseResult(String[] result).getTimestamp()
```
---
- The following methods have been deprecated:
```java
parseResult(String[] result).getTime()
```
---
- The following methods have been removed:
```java
parseResult(String[] result).getTypeId()
```
---
## Getting Started
Ensure you're using CoreProtect 20.2 or higher. Add it as an external jar to your plugin in your IDE.
Alternatively, if using Maven, you can add it via the repository [https://maven.playpro.com](https://maven.playpro.com) (net.coreprotect, 20.2).
The first thing you need to do is get access to CoreProtect. You can do this by using code similar to the following:
```java
import net.coreprotect.CoreProtect;
import net.coreprotect.CoreProtectAPI;
private CoreProtectAPI getCoreProtect() {
Plugin plugin = getServer().getPluginManager().getPlugin("CoreProtect");
// Check that CoreProtect is loaded
if (plugin == null || !(plugin instanceof CoreProtect)) {
return null;
}
// Check that the API is enabled
CoreProtectAPI CoreProtect = ((CoreProtect) plugin).getAPI();
if (CoreProtect.isEnabled() == false) {
return null;
}
// Check that a compatible version of the API is loaded
if (CoreProtect.APIVersion() < 7) {
return null;
}
return CoreProtect;
}
```
With this code, you can then access the API with a call like the following:
```java
CoreProtectAPI api = getCoreProtect();
if (api != null){ // Ensure we have access to the API
api.testAPI(); // Will print out "[CoreProtect] API test successful." in the console.
}
```
Yay, you're now using the CoreProtect API!
---
## API Overview
### Available Methods
```java
boolean isEnabled()
void testAPI()
List<String[]> performLookup(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)
List<String[]> performRollback(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)
List<String[]> performRestore(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)
List<String[]> blockLookup(Block block, int time)
ParseResult parseResult(String[] result)
boolean logChat(Player player, String message)
boolean logCommand(Player player, String command)
boolean logPlacement(String user, Location location, Material type, BlockData blockData)
boolean logRemoval(String user, Location location, Material type, BlockData blockData)
boolean logContainerTransaction(String user, Location location)
boolean logInteraction(String user, Location location)
boolean hasPlaced(String user, Block block, int time, int offset)
boolean hasRemoved(String user, Block block, int time, int offset)
void performPurge(int time)
```
---
### Available Events
*The following events are emitted by CoreProtect.*
#### CoreProtectPreLogEvent
Fired when a CoreProtect logger is about to log an action. Not cancellable.
| Property | Description | Mutable |
| --- | --- | --- |
| User | The name of the user under which this action will be logged. | Yes |
---
### Method Usage
*Detailed method information is listed below.*
#### `isEnabled()`
Calling this will return true if the server has the CoreProtect API enabled, and false if it does not.
---
#### `testAPI()`
Running this will print out "[CoreProtect] API Test Successful." in the server console.
---
#### `performLookup(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)`
This will perform a lookup.
* **time:** Specify the amount of time to search back. "5" would return results from the last 5 seconds.
* **restrict_users:** Specify any usernames to perform the lookup on. Can be set to "null" if both a radius and a location are specified.
* **exclude_users:** Specify any usernames to exclude from the lookup. Can be set to "null".
* **restrict_blocks:** Specify a list of EntityType's or Material's to restrict the search to. Can be set to "null".
* **exclude_blocks:** Specify a list of EntityType's or Material's to exclude from the search. Can be set to "null".
* **action_list:** Specify a list of action types to restrict the search to. Can be set to "null"
* **radius:** Specify a radius to restrict the search to. A location must be specified if using this. Set to "0" to disable.
* **radius_location:** Specify a location to search around. Can be set to "null" if no radius is specified, and a user is specified.
---
#### `performRollback(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)`
This will perform a rollback. Method must be called async.
* **time:** Specify the amount of time to rollback. "5" would return results from the last 5 seconds.
* **restrict_users:** Specify any usernames to perform the rollback on. Can be set to "null" if both a radius and a location are specified.
* **exclude_users:** Specify any usernames to exclude from the rollback. Can be set to "null".
* **restrict_blocks:** Specify a list of EntityType's or Material's to restrict the rollback to. Can be set to "null".
* **exclude_blocks:** Specify a list of EntityType's or Material's to exclude from the rollback. Can be set to "null".
* **action_list:** Specify a list of action types to restrict the rollback to. Can be set to "null"
* **radius:** Specify a radius to restrict the rollback to. A location must be specified if using this. Set to "0" to disable.
* **radius_location:** Specify a location to rollback around. Can be set to "null" if no radius is specified, and a user is specified.
---
#### `performRestore(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)`
This will perform a restore.
* **time:** Specify the amount of time to restore. "5" would return results from the last 5 seconds.
* **restrict_users:** Specify any usernames to perform the restore on. Can be set to "null" if both a radius and a location are specified.
* **exclude_users:** Specify any usernames to exclude from the restore. Can be set to "null".
* **restrict_blocks:** Specify a list of EntityType's or Material's to restrict the restore to. Can be set to "null".
* **exclude_blocks:** Specify a list of EntityType's or Material's to exclude from the restore. Can be set to "null".
* **action_list:** Specify a list of action types to restrict the restore to. Can be set to "null"
* **radius:** Specify a radius to restrict the restore to. A location must be specified if using this. Set to "0" to disable.
* **radius_location:** Specify a location to restore around. Can be set to "null" if no radius is specified, and a user is specified.
---
#### `blockLookup(Block block, int time)`
This will perform a full lookup on a single block.
* **block:** The block to perform the lookup on.
* **time:** Specify the amount of time to lookup. "5" would return results from the last 5 seconds.
---
#### `ParseResult parseResult(String[] result)`
This will parse results from a lookup. You'll then be able to view the following:
* **getX():** Get the X coordinate of the block.
* **getY():** Get the Y coordinate of the block.
* **getZ():** Get the Z coordinate of the block.
* **getType():** Get the Material of the block.
* **getBlockData():** Get the BlockData of the block.
* **getPlayer():** Get the username as a string..
* **getTimestamp():** Get the time of the action.
* **getActionId():** Get the action ID. (0=removed, 1=placed, 2=interaction)
* **getActionString():** Get the action as a string. (Removal, Placement, Interaction)
* **isRolledBack():** If the block is currently rolled back or not.
* **worldName():** The name of the world the block is located in.
---
#### `logPlacement(String user, Location location, Material type, BlockData blockData)`
This will log a block as being placed.
* **user:** Specify the username to log as having placed the block.
* **location:** Specify the location of the block you're logging.
* **type:** Specify the Material of the block you're logging.
* **blockData:** Specify the BlockData of the block you're logging. Can be set to "null".
---
#### `logRemoval(String user, Location location, Material type, BlockData blockData)`
This will log a block as being removed/broken, and will log the block's inventory (if applicable).
* **user:** Specify the username to log as having removed the block.
* **location:** Specify the location of the block you're logging.
* **type:** Specify the Material of the block you're logging.
* **blockData:** Specify the BlockData of the block you're logging. Can be set to "null".
---
#### `logContainerTransaction(String user, Location location)`
This will log any transactions made to a block's inventory immediately after calling the method.
* **user:** Specify the username to log as having added/removed the items.
* **location:** Specify the location of the block inventory you're logging.
---
#### `logInteraction(String user, Location location)`
This will log a block as having been interacted with.
* **user:** Specify the username to log as having caused the interaction.
* **location:** Specify the location of the interaction you're logging.
---
#### `hasPlaced(String user, Block block, int time, int offset)`
This will return true if a user has already placed a block at the location within the specified time limit.
* **user:** The username you're checking to see if they've placed a block already.
* **block:** The block you're checking.
* **time:** How far back to check. "5" would only check through the last 5 seconds of logged blocks.
* **offset:** A time offset. "2" would ignore the last 2 seconds of most recently ignored data. (0=no offset)
---
#### `hasRemoved(String user, Block block, int time, int offset)`
This will return true if a user has already removed a block at the location within the specified time limit.
* **user:** The username you're checking to see if they've removed a block already.
* **block:** The block you're checking.
* **time:** How far back to check. "5" would only check through the last 5 seconds of logged blocks.
* **offset:** A time offset. "2" would ignore the last 2 seconds of most recently ignored data. (0=no offset)
---
#### `performPurge(int time)`
This will perform a purge on the CoreProtect database.
* **time:** Purge any data earlier than this. "120" would purge any data older than 120 seconds (2 minutes).
---
### Examples
- Get the last 60 seconds of block data for the user "Notch".
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
List<String[]> lookup = CoreProtect.performLookup(60, Arrays.asList("Notch"), null, null, null, null, 0, null);
if (lookup!=null){
for (String[] result : lookup){
ParseResult parseResult = CoreProtect.parseResult(result);
int x = parseResult.getX();
int y = parseResult.getY();
int z = parseResult.getZ();
//...
}
}
}
```
---
- Get the last 60 seconds of block data for the user "Notch", excluding dirt and grass blocks.
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
List<Object> exclude = Arrays.asList(Material.DIRT, Material.GRASS);
List<String[]> lookup = CoreProtect.performLookup(60, Arrays.asList("Notch"), null, null, exclude, null, 0, null);
if (lookup!=null){
for (String[] value : lookup){
ParseResult result = CoreProtect.parseResult(value);
int x = result.getX();
int y = result.getY();
int z = result.getZ();
//...
}
}
}
```
---
- Get the last 60 seconds of block data within 5 blocks of a location.
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
List<String[]> lookup = CoreProtect.performLookup(60, null, null, null, null, null, 5, location);
if (lookup!=null){
for (String[] value : lookup){
ParseResult result = CoreProtect.parseResult(value);
int x = result.getX();
int y = result.getY();
int z = result.getZ();
//...
}
}
}
```
---
- Rollbacks / restores use the same code structure as the above examples. For example:
```java
class BasicThread implements Runnable {
@Override
public void run() {
try {
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
List<String[]> lookup = CoreProtect.performRollback(60, Arrays.asList("Notch"), null, null, null, null, 0, null);
if (lookup!=null){
for (String[] value : lookup){
ParseResult result = CoreProtect.parseResult(value);
int x = result.getX();
int y = result.getY();
int z = result.getZ();
//...
}
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
thread.start();
```
---
- Check if the user "Notch" has already placed a block at a location within the last 60 seconds.
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
boolean hasPlaced = CoreProtect.HasPlaced("Notch", block, 60, 0);
}
```
---
- Get the last 60 seconds of block data for a specific block.
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
List<String[]> lookup = CoreProtect.blockLookup(block, 60);
if (lookup!=null){
for (String[] result : lookup){
ParseResult parseResult = CoreProtect.parseResult(value);
int x = parseResult.getX();
int y = parseResult.getY();
int z = parseResult.getZ();
//...
}
}
}
```
---
- Log the placement of a block at a location by the user "Notch".
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
boolean success = CoreProtect.logPlacement("Notch", block.getLocation(), block.getType(), block.getData());
}
```
---
- Log adding/remove items in a chest (or some other block inventory).
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
boolean success = CoreProtect.logContainerTransaction("Notch", inventory.getLocation());
// modify your container contents immediately after (e.g. [i]inventory.addItem(itemStack);[/i])
}
```
---
- Perform a multi-threaded placement check to see if the user "Notch" has already placed a block at a location within the last 60 seconds. This ignores the most recent 1 second of logged data, to account for the fact that that new block data may have already been logged, depending on your code.
```java
final Block block = null; //Should be an actual block
class BasicThread implements Runnable {
@Override
public void run() {
try {
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
boolean hasPlaced = CoreProtect.hasPlaced("Notch", block, 60, 1);
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
thread.start();
```
---
*Documentation for the API version 9 can be found [here](/api/version/v9/).*
+450
View File
@@ -0,0 +1,450 @@
# API Version 7
The CoreProtect API enables you to log your own block changes, perform lookups, rollbacks, restores, and more.
| API Details | |
| --- | --- |
| **API Version:** | 7 |
| **Plugin Version:** | v20.0+ |
| **Maven:** | [maven.playpro.com](https://maven.playpro.com) |
<span style="color:red;">*Documentation for the latest API version can be found [here](/api/).*</span>
---
## Upgrading from API v6
The changes from the previous API version are as follows:
- The following methods have been added:
```java
parseResult(String[] result).getTimestamp()
```
---
- The following methods have been deprecated:
```java
parseResult(String[] result).getTime()
```
---
- The following methods have been removed:
```java
parseResult(String[] result).getTypeId()
```
---
## Getting Started
Ensure you're using CoreProtect 20.0 or higher. Add it as an external jar to your plugin in your IDE.
Alternatively, if using Maven, you can add it via the repository [https://maven.playpro.com](https://maven.playpro.com) (net.coreprotect, 20.0).
The first thing you need to do is get access to CoreProtect. You can do this by using code similar to the following:
```java
import net.coreprotect.CoreProtect;
import net.coreprotect.CoreProtectAPI;
private CoreProtectAPI getCoreProtect() {
Plugin plugin = getServer().getPluginManager().getPlugin("CoreProtect");
// Check that CoreProtect is loaded
if (plugin == null || !(plugin instanceof CoreProtect)) {
return null;
}
// Check that the API is enabled
CoreProtectAPI CoreProtect = ((CoreProtect) plugin).getAPI();
if (CoreProtect.isEnabled() == false) {
return null;
}
// Check that a compatible version of the API is loaded
if (CoreProtect.APIVersion() < 7) {
return null;
}
return CoreProtect;
}
```
With this code, you can then access the API with a call like the following:
```java
CoreProtectAPI api = getCoreProtect();
if (api != null){ // Ensure we have access to the API
api.testAPI(); // Will print out "[CoreProtect] API test successful." in the console.
}
```
Yay, you're now using the CoreProtect API!
---
## API Overview
### Available Methods
```java
boolean isEnabled()
void testAPI()
List<String[]> performLookup(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)
List<String[]> performRollback(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)
List<String[]> performRestore(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)
List<String[]> blockLookup(Block block, int time)
ParseResult parseResult(String[] result)
boolean logChat(Player player, String message)
boolean logCommand(Player player, String command)
boolean logPlacement(String user, Location location, Material type, BlockData blockData)
boolean logRemoval(String user, Location location, Material type, BlockData blockData)
boolean logContainerTransaction(String user, Location location)
boolean logInteraction(String user, Location location)
boolean hasPlaced(String user, Block block, int time, int offset)
boolean hasRemoved(String user, Block block, int time, int offset)
void performPurge(int time)
```
---
### Method Usage
*Detailed method information is listed below.*
#### `isEnabled()`
Calling this will return true if the server has the CoreProtect API enabled, and false if it does not.
---
#### `testAPI()`
Running this will print out "[CoreProtect] API Test Successful." in the server console.
---
#### `performLookup(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)`
This will perform a lookup.
* **time:** Specify the amount of time to search back. "5" would return results from the last 5 seconds.
* **restrict_users:** Specify any usernames to perform the lookup on. Can be set to "null" if both a radius and a location are specified.
* **exclude_users:** Specify any usernames to exclude from the lookup. Can be set to "null".
* **restrict_blocks:** Specify a list of EntityType's or Material's to restrict the search to. Can be set to "null".
* **exclude_blocks:** Specify a list of EntityType's or Material's to exclude from the search. Can be set to "null".
* **action_list:** Specify a list of action types to restrict the search to. Can be set to "null"
* **radius:** Specify a radius to restrict the search to. A location must be specified if using this. Set to "0" to disable.
* **radius_location:** Specify a location to search around. Can be set to "null" if no radius is specified, and a user is specified.
---
#### `performRollback(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)`
This will perform a rollback. Method must be called async.
* **time:** Specify the amount of time to rollback. "5" would return results from the last 5 seconds.
* **restrict_users:** Specify any usernames to perform the rollback on. Can be set to "null" if both a radius and a location are specified.
* **exclude_users:** Specify any usernames to exclude from the rollback. Can be set to "null".
* **restrict_blocks:** Specify a list of EntityType's or Material's to restrict the rollback to. Can be set to "null".
* **exclude_blocks:** Specify a list of EntityType's or Material's to exclude from the rollback. Can be set to "null".
* **action_list:** Specify a list of action types to restrict the rollback to. Can be set to "null"
* **radius:** Specify a radius to restrict the rollback to. A location must be specified if using this. Set to "0" to disable.
* **radius_location:** Specify a location to rollback around. Can be set to "null" if no radius is specified, and a user is specified.
---
#### `performRestore(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)`
This will perform a restore.
* **time:** Specify the amount of time to restore. "5" would return results from the last 5 seconds.
* **restrict_users:** Specify any usernames to perform the restore on. Can be set to "null" if both a radius and a location are specified.
* **exclude_users:** Specify any usernames to exclude from the restore. Can be set to "null".
* **restrict_blocks:** Specify a list of EntityType's or Material's to restrict the restore to. Can be set to "null".
* **exclude_blocks:** Specify a list of EntityType's or Material's to exclude from the restore. Can be set to "null".
* **action_list:** Specify a list of action types to restrict the restore to. Can be set to "null"
* **radius:** Specify a radius to restrict the restore to. A location must be specified if using this. Set to "0" to disable.
* **radius_location:** Specify a location to restore around. Can be set to "null" if no radius is specified, and a user is specified.
---
#### `blockLookup(Block block, int time)`
This will perform a full lookup on a single block.
* **block:** The block to perform the lookup on.
* **time:** Specify the amount of time to lookup. "5" would return results from the last 5 seconds.
---
#### `ParseResult parseResult(String[] result)`
This will parse results from a lookup. You'll then be able to view the following:
* **getX():** Get the X coordinate of the block.
* **getY():** Get the Y coordinate of the block.
* **getZ():** Get the Z coordinate of the block.
* **getType():** Get the Material of the block.
* **getBlockData():** Get the BlockData of the block.
* **getPlayer():** Get the username as a string..
* **getTimestamp():** Get the time of the action.
* **getActionId():** Get the action ID. (0=removed, 1=placed, 2=interaction)
* **getActionString():** Get the action as a string. (Removal, Placement, Interaction)
* **isRolledBack():** If the block is currently rolled back or not.
* **worldName():** The name of the world the block is located in.
---
#### `logPlacement(String user, Location location, Material type, BlockData blockData)`
This will log a block as being placed.
* **user:** Specify the username to log as having placed the block.
* **location:** Specify the location of the block you're logging.
* **type:** Specify the Material of the block you're logging.
* **blockData:** Specify the BlockData of the block you're logging. Can be set to "null".
---
#### `logRemoval(String user, Location location, Material type, BlockData blockData)`
This will log a block as being removed/broken, and will log the block's inventory (if applicable).
* **user:** Specify the username to log as having removed the block.
* **location:** Specify the location of the block you're logging.
* **type:** Specify the Material of the block you're logging.
* **blockData:** Specify the BlockData of the block you're logging. Can be set to "null".
---
#### `logContainerTransaction(String user, Location location)`
This will log any transactions made to a block's inventory immediately after calling the method.
* **user:** Specify the username to log as having added/removed the items.
* **location:** Specify the location of the block inventory you're logging.
---
#### `logInteraction(String user, Location location)`
This will log a block as having been interacted with.
* **user:** Specify the username to log as having caused the interaction.
* **location:** Specify the location of the interaction you're logging.
---
#### `hasPlaced(String user, Block block, int time, int offset)`
This will return true if a user has already placed a block at the location within the specified time limit.
* **user:** The username you're checking to see if they've placed a block already.
* **block:** The block you're checking.
* **time:** How far back to check. "5" would only check through the last 5 seconds of logged blocks.
* **offset:** A time offset. "2" would ignore the last 2 seconds of most recently ignored data. (0=no offset)
---
#### `hasRemoved(String user, Block block, int time, int offset)`
This will return true if a user has already removed a block at the location within the specified time limit.
* **user:** The username you're checking to see if they've removed a block already.
* **block:** The block you're checking.
* **time:** How far back to check. "5" would only check through the last 5 seconds of logged blocks.
* **offset:** A time offset. "2" would ignore the last 2 seconds of most recently ignored data. (0=no offset)
---
#### `performPurge(int time)`
This will perform a purge on the CoreProtect database.
* **time:** Purge any data earlier than this. "120" would purge any data older than 120 seconds (2 minutes).
---
### Examples
- Get the last 60 seconds of block data for the user "Notch".
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
List<String[]> lookup = CoreProtect.performLookup(60, Arrays.asList("Notch"), null, null, null, null, 0, null);
if (lookup!=null){
for (String[] result : lookup){
ParseResult parseResult = CoreProtect.parseResult(result);
int x = parseResult.getX();
int y = parseResult.getY();
int z = parseResult.getZ();
//...
}
}
}
```
---
- Get the last 60 seconds of block data for the user "Notch", excluding dirt and grass blocks.
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
List<Object> exclude = Arrays.asList(Material.DIRT, Material.GRASS);
List<String[]> lookup = CoreProtect.performLookup(60, Arrays.asList("Notch"), null, null, exclude, null, 0, null);
if (lookup!=null){
for (String[] value : lookup){
ParseResult result = CoreProtect.parseResult(value);
int x = result.getX();
int y = result.getY();
int z = result.getZ();
//...
}
}
}
```
---
- Get the last 60 seconds of block data within 5 blocks of a location.
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
List<String[]> lookup = CoreProtect.performLookup(60, null, null, null, null, null, 5, location);
if (lookup!=null){
for (String[] value : lookup){
ParseResult result = CoreProtect.parseResult(value);
int x = result.getX();
int y = result.getY();
int z = result.getZ();
//...
}
}
}
```
---
- Rollbacks / restores use the same code structure as the above examples. For example:
```java
class BasicThread implements Runnable {
@Override
public void run() {
try {
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
List<String[]> lookup = CoreProtect.performRollback(60, Arrays.asList("Notch"), null, null, null, null, 0, null);
if (lookup!=null){
for (String[] value : lookup){
ParseResult result = CoreProtect.parseResult(value);
int x = result.getX();
int y = result.getY();
int z = result.getZ();
//...
}
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
thread.start();
```
---
- Check if the user "Notch" has already placed a block at a location within the last 60 seconds.
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
boolean hasPlaced = CoreProtect.HasPlaced("Notch", block, 60, 0);
}
```
---
- Get the last 60 seconds of block data for a specific block.
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
List<String[]> lookup = CoreProtect.blockLookup(block, 60);
if (lookup!=null){
for (String[] result : lookup){
ParseResult parseResult = CoreProtect.parseResult(value);
int x = parseResult.getX();
int y = parseResult.getY();
int z = parseResult.getZ();
//...
}
}
}
```
---
- Log the placement of a block at a location by the user "Notch".
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
boolean success = CoreProtect.logPlacement("Notch", block.getLocation(), block.getType(), block.getData());
}
```
---
- Log adding/remove items in a chest (or some other block inventory).
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
boolean success = CoreProtect.logContainerTransaction("Notch", inventory.getLocation());
// modify your container contents immediately after (e.g. [i]inventory.addItem(itemStack);[/i])
}
```
---
- Perform a multi-threaded placement check to see if the user "Notch" has already placed a block at a location within the last 60 seconds. This ignores the most recent 1 second of logged data, to account for the fact that that new block data may have already been logged, depending on your code.
```java
final Block block = null; //Should be an actual block
class BasicThread implements Runnable {
@Override
public void run() {
try {
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
boolean hasPlaced = CoreProtect.hasPlaced("Notch", block, 60, 1);
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
thread.start();
```
---
+450
View File
@@ -0,0 +1,450 @@
# API Version 8
The CoreProtect API enables you to log your own block changes, perform lookups, rollbacks, restores, and more.
| API Details | |
| --- | --- |
| **API Version:** | 8 |
| **Plugin Version:** | v20.2+ |
| **Maven:** | [maven.playpro.com](https://maven.playpro.com) |
<span style="color:red;">*Documentation for the latest API version can be found [here](/api/).*</span>
---
## Upgrading from API v7
The changes from the previous API version are as follows:
- The following events have been added:
```java
CoreProtectPreLogEvent
```
---
## Getting Started
Ensure you're using CoreProtect 20.2 or higher. Add it as an external jar to your plugin in your IDE.
Alternatively, if using Maven, you can add it via the repository [https://maven.playpro.com](https://maven.playpro.com) (net.coreprotect, 20.2).
The first thing you need to do is get access to CoreProtect. You can do this by using code similar to the following:
```java
import net.coreprotect.CoreProtect;
import net.coreprotect.CoreProtectAPI;
private CoreProtectAPI getCoreProtect() {
Plugin plugin = getServer().getPluginManager().getPlugin("CoreProtect");
// Check that CoreProtect is loaded
if (plugin == null || !(plugin instanceof CoreProtect)) {
return null;
}
// Check that the API is enabled
CoreProtectAPI CoreProtect = ((CoreProtect) plugin).getAPI();
if (CoreProtect.isEnabled() == false) {
return null;
}
// Check that a compatible version of the API is loaded
if (CoreProtect.APIVersion() < 8) {
return null;
}
return CoreProtect;
}
```
With this code, you can then access the API with a call like the following:
```java
CoreProtectAPI api = getCoreProtect();
if (api != null){ // Ensure we have access to the API
api.testAPI(); // Will print out "[CoreProtect] API test successful." in the console.
}
```
Yay, you're now using the CoreProtect API!
---
## API Overview
### Available Methods
```java
boolean isEnabled()
void testAPI()
List<String[]> performLookup(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)
List<String[]> performRollback(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)
List<String[]> performRestore(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)
List<String[]> blockLookup(Block block, int time)
ParseResult parseResult(String[] result)
boolean logChat(Player player, String message)
boolean logCommand(Player player, String command)
boolean logPlacement(String user, Location location, Material type, BlockData blockData)
boolean logRemoval(String user, Location location, Material type, BlockData blockData)
boolean logContainerTransaction(String user, Location location)
boolean logInteraction(String user, Location location)
boolean hasPlaced(String user, Block block, int time, int offset)
boolean hasRemoved(String user, Block block, int time, int offset)
void performPurge(int time)
```
---
### Available Events
*The following events are emitted by CoreProtect.*
#### CoreProtectPreLogEvent
Fired when a CoreProtect logger is about to log an action. Not cancellable.
| Property | Description | Mutable |
| --- | --- | --- |
| User | The name of the user under which this action will be logged. | Yes |
---
### Method Usage
*Detailed method information is listed below.*
#### `isEnabled()`
Calling this will return true if the server has the CoreProtect API enabled, and false if it does not.
---
#### `testAPI()`
Running this will print out "[CoreProtect] API Test Successful." in the server console.
---
#### `performLookup(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)`
This will perform a lookup.
* **time:** Specify the amount of time to search back. "5" would return results from the last 5 seconds.
* **restrict_users:** Specify any usernames to perform the lookup on. Can be set to "null" if both a radius and a location are specified.
* **exclude_users:** Specify any usernames to exclude from the lookup. Can be set to "null".
* **restrict_blocks:** Specify a list of EntityType's or Material's to restrict the search to. Can be set to "null".
* **exclude_blocks:** Specify a list of EntityType's or Material's to exclude from the search. Can be set to "null".
* **action_list:** Specify a list of action types to restrict the search to. Can be set to "null"
* **radius:** Specify a radius to restrict the search to. A location must be specified if using this. Set to "0" to disable.
* **radius_location:** Specify a location to search around. Can be set to "null" if no radius is specified, and a user is specified.
---
#### `performRollback(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)`
This will perform a rollback. Method must be called async.
* **time:** Specify the amount of time to rollback. "5" would return results from the last 5 seconds.
* **restrict_users:** Specify any usernames to perform the rollback on. Can be set to "null" if both a radius and a location are specified.
* **exclude_users:** Specify any usernames to exclude from the rollback. Can be set to "null".
* **restrict_blocks:** Specify a list of EntityType's or Material's to restrict the rollback to. Can be set to "null".
* **exclude_blocks:** Specify a list of EntityType's or Material's to exclude from the rollback. Can be set to "null".
* **action_list:** Specify a list of action types to restrict the rollback to. Can be set to "null"
* **radius:** Specify a radius to restrict the rollback to. A location must be specified if using this. Set to "0" to disable.
* **radius_location:** Specify a location to rollback around. Can be set to "null" if no radius is specified, and a user is specified.
---
#### `performRestore(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)`
This will perform a restore.
* **time:** Specify the amount of time to restore. "5" would return results from the last 5 seconds.
* **restrict_users:** Specify any usernames to perform the restore on. Can be set to "null" if both a radius and a location are specified.
* **exclude_users:** Specify any usernames to exclude from the restore. Can be set to "null".
* **restrict_blocks:** Specify a list of EntityType's or Material's to restrict the restore to. Can be set to "null".
* **exclude_blocks:** Specify a list of EntityType's or Material's to exclude from the restore. Can be set to "null".
* **action_list:** Specify a list of action types to restrict the restore to. Can be set to "null"
* **radius:** Specify a radius to restrict the restore to. A location must be specified if using this. Set to "0" to disable.
* **radius_location:** Specify a location to restore around. Can be set to "null" if no radius is specified, and a user is specified.
---
#### `blockLookup(Block block, int time)`
This will perform a full lookup on a single block.
* **block:** The block to perform the lookup on.
* **time:** Specify the amount of time to lookup. "5" would return results from the last 5 seconds.
---
#### `ParseResult parseResult(String[] result)`
This will parse results from a lookup. You'll then be able to view the following:
* **getX():** Get the X coordinate of the block.
* **getY():** Get the Y coordinate of the block.
* **getZ():** Get the Z coordinate of the block.
* **getType():** Get the Material of the block.
* **getBlockData():** Get the BlockData of the block.
* **getPlayer():** Get the username as a string..
* **getTimestamp():** Get the time of the action.
* **getActionId():** Get the action ID. (0=removed, 1=placed, 2=interaction)
* **getActionString():** Get the action as a string. (Removal, Placement, Interaction)
* **isRolledBack():** If the block is currently rolled back or not.
* **worldName():** The name of the world the block is located in.
---
#### `logPlacement(String user, Location location, Material type, BlockData blockData)`
This will log a block as being placed.
* **user:** Specify the username to log as having placed the block.
* **location:** Specify the location of the block you're logging.
* **type:** Specify the Material of the block you're logging.
* **blockData:** Specify the BlockData of the block you're logging. Can be set to "null".
---
#### `logRemoval(String user, Location location, Material type, BlockData blockData)`
This will log a block as being removed/broken, and will log the block's inventory (if applicable).
* **user:** Specify the username to log as having removed the block.
* **location:** Specify the location of the block you're logging.
* **type:** Specify the Material of the block you're logging.
* **blockData:** Specify the BlockData of the block you're logging. Can be set to "null".
---
#### `logContainerTransaction(String user, Location location)`
This will log any transactions made to a block's inventory immediately after calling the method.
* **user:** Specify the username to log as having added/removed the items.
* **location:** Specify the location of the block inventory you're logging.
---
#### `logInteraction(String user, Location location)`
This will log a block as having been interacted with.
* **user:** Specify the username to log as having caused the interaction.
* **location:** Specify the location of the interaction you're logging.
---
#### `hasPlaced(String user, Block block, int time, int offset)`
This will return true if a user has already placed a block at the location within the specified time limit.
* **user:** The username you're checking to see if they've placed a block already.
* **block:** The block you're checking.
* **time:** How far back to check. "5" would only check through the last 5 seconds of logged blocks.
* **offset:** A time offset. "2" would ignore the last 2 seconds of most recently ignored data. (0=no offset)
---
#### `hasRemoved(String user, Block block, int time, int offset)`
This will return true if a user has already removed a block at the location within the specified time limit.
* **user:** The username you're checking to see if they've removed a block already.
* **block:** The block you're checking.
* **time:** How far back to check. "5" would only check through the last 5 seconds of logged blocks.
* **offset:** A time offset. "2" would ignore the last 2 seconds of most recently ignored data. (0=no offset)
---
#### `performPurge(int time)`
This will perform a purge on the CoreProtect database.
* **time:** Purge any data earlier than this. "120" would purge any data older than 120 seconds (2 minutes).
---
### Examples
- Get the last 60 seconds of block data for the user "Notch".
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
List<String[]> lookup = CoreProtect.performLookup(60, Arrays.asList("Notch"), null, null, null, null, 0, null);
if (lookup!=null){
for (String[] result : lookup){
ParseResult parseResult = CoreProtect.parseResult(result);
int x = parseResult.getX();
int y = parseResult.getY();
int z = parseResult.getZ();
//...
}
}
}
```
---
- Get the last 60 seconds of block data for the user "Notch", excluding dirt and grass blocks.
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
List<Object> exclude = Arrays.asList(Material.DIRT, Material.GRASS);
List<String[]> lookup = CoreProtect.performLookup(60, Arrays.asList("Notch"), null, null, exclude, null, 0, null);
if (lookup!=null){
for (String[] value : lookup){
ParseResult result = CoreProtect.parseResult(value);
int x = result.getX();
int y = result.getY();
int z = result.getZ();
//...
}
}
}
```
---
- Get the last 60 seconds of block data within 5 blocks of a location.
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
List<String[]> lookup = CoreProtect.performLookup(60, null, null, null, null, null, 5, location);
if (lookup!=null){
for (String[] value : lookup){
ParseResult result = CoreProtect.parseResult(value);
int x = result.getX();
int y = result.getY();
int z = result.getZ();
//...
}
}
}
```
---
- Rollbacks / restores use the same code structure as the above examples. For example:
```java
class BasicThread implements Runnable {
@Override
public void run() {
try {
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
List<String[]> lookup = CoreProtect.performRollback(60, Arrays.asList("Notch"), null, null, null, null, 0, null);
if (lookup!=null){
for (String[] value : lookup){
ParseResult result = CoreProtect.parseResult(value);
int x = result.getX();
int y = result.getY();
int z = result.getZ();
//...
}
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
thread.start();
```
---
- Check if the user "Notch" has already placed a block at a location within the last 60 seconds.
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
boolean hasPlaced = CoreProtect.HasPlaced("Notch", block, 60, 0);
}
```
---
- Get the last 60 seconds of block data for a specific block.
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
List<String[]> lookup = CoreProtect.blockLookup(block, 60);
if (lookup!=null){
for (String[] result : lookup){
ParseResult parseResult = CoreProtect.parseResult(value);
int x = parseResult.getX();
int y = parseResult.getY();
int z = parseResult.getZ();
//...
}
}
}
```
---
- Log the placement of a block at a location by the user "Notch".
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
boolean success = CoreProtect.logPlacement("Notch", block.getLocation(), block.getType(), block.getData());
}
```
---
- Log adding/remove items in a chest (or some other block inventory).
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
boolean success = CoreProtect.logContainerTransaction("Notch", inventory.getLocation());
// modify your container contents immediately after (e.g. [i]inventory.addItem(itemStack);[/i])
}
```
---
- Perform a multi-threaded placement check to see if the user "Notch" has already placed a block at a location within the last 60 seconds. This ignores the most recent 1 second of logged data, to account for the fact that that new block data may have already been logged, depending on your code.
```java
final Block block = null; //Should be an actual block
class BasicThread implements Runnable {
@Override
public void run() {
try {
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect!=null){ //Ensure we have access to the API
boolean hasPlaced = CoreProtect.hasPlaced("Notch", block, 60, 1);
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
thread.start();
```
---
+501
View File
@@ -0,0 +1,501 @@
# API Version 9
The CoreProtect API enables you to log your own block changes, perform lookups, rollbacks, restores, and more.
| API Details | |
| --- | --- |
| **API Version:** | 9 |
| **Plugin Version:** | v21.0+ |
| **Maven:** | [maven.playpro.com](https://maven.playpro.com) |
---
## Upgrading from API v8
The changes from the previous API version are as follows:
- The following methods have been added:
```java
sessionLookup(String user, int time)
queueLookup(Block block)
```
---
## Getting Started
Ensure you're using CoreProtect 21.0 or higher. Add it as an external jar to your plugin in your IDE.
Alternatively, if using Maven, you can add it via the repository [https://maven.playpro.com](https://maven.playpro.com) (net.coreprotect, 21.0).
The first thing you need to do is get access to CoreProtect. You can do this by using code similar to the following:
```java
import net.coreprotect.CoreProtect;
import net.coreprotect.CoreProtectAPI;
private CoreProtectAPI getCoreProtect() {
Plugin plugin = getServer().getPluginManager().getPlugin("CoreProtect");
// Check that CoreProtect is loaded
if (plugin == null || !(plugin instanceof CoreProtect)) {
return null;
}
// Check that the API is enabled
CoreProtectAPI CoreProtect = ((CoreProtect) plugin).getAPI();
if (CoreProtect.isEnabled() == false) {
return null;
}
// Check that a compatible version of the API is loaded
if (CoreProtect.APIVersion() < 9) {
return null;
}
return CoreProtect;
}
```
With this code, you can then access the API with a call like the following:
```java
CoreProtectAPI api = getCoreProtect();
if (api != null){ // Ensure we have access to the API
api.testAPI(); // Will print out "[CoreProtect] API test successful." in the console.
}
```
Yay, you're now using the CoreProtect API!
---
## API Overview
### Available Methods
```java
boolean isEnabled()
void testAPI()
List<String[]> performLookup(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)
List<String[]> performRollback(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)
List<String[]> performRestore(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)
List<String[]> blockLookup(Block block, int time)
List<String[]> sessionLookup(String user, int time)
ParseResult parseResult(String[] result)
boolean logChat(Player player, String message)
boolean logCommand(Player player, String command)
boolean logPlacement(String user, Location location, Material type, BlockData blockData)
boolean logRemoval(String user, Location location, Material type, BlockData blockData)
boolean logContainerTransaction(String user, Location location)
boolean logInteraction(String user, Location location)
boolean hasPlaced(String user, Block block, int time, int offset)
boolean hasRemoved(String user, Block block, int time, int offset)
void performPurge(int time)
```
---
### Available Events
*The following events are emitted by CoreProtect.*
#### CoreProtectPreLogEvent
Fired when a CoreProtect logger is about to log an action. Not cancellable.
| Property | Description | Mutable |
| --- | --- | --- |
| User | The name of the user under which this action will be logged. | Yes |
---
### Method Usage
*Detailed method information is listed below.*
#### `isEnabled()`
Calling this will return true if the server has the CoreProtect API enabled, and false if it does not.
---
#### `testAPI()`
Running this will print out "[CoreProtect] API Test Successful." in the server console.
---
#### `performLookup(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)`
This will perform a lookup.
* **time:** Specify the amount of time to search back. "5" would return results from the last 5 seconds.
* **restrict_users:** Specify any usernames to perform the lookup on. Can be set to "null" if both a radius and a location are specified.
* **exclude_users:** Specify any usernames to exclude from the lookup. Can be set to "null".
* **restrict_blocks:** Specify a list of EntityType's or Material's to restrict the search to. Can be set to "null".
* **exclude_blocks:** Specify a list of EntityType's or Material's to exclude from the search. Can be set to "null".
* **action_list:** Specify a list of action types to restrict the search to. Can be set to "null"
* **radius:** Specify a radius to restrict the search to. A location must be specified if using this. Set to "0" to disable.
* **radius_location:** Specify a location to search around. Can be set to "null" if no radius is specified, and a user is specified.
---
#### `performRollback(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)`
This will perform a rollback. Method must be called async.
* **time:** Specify the amount of time to rollback. "5" would return results from the last 5 seconds.
* **restrict_users:** Specify any usernames to perform the rollback on. Can be set to "null" if both a radius and a location are specified.
* **exclude_users:** Specify any usernames to exclude from the rollback. Can be set to "null".
* **restrict_blocks:** Specify a list of EntityType's or Material's to restrict the rollback to. Can be set to "null".
* **exclude_blocks:** Specify a list of EntityType's or Material's to exclude from the rollback. Can be set to "null".
* **action_list:** Specify a list of action types to restrict the rollback to. Can be set to "null"
* **radius:** Specify a radius to restrict the rollback to. A location must be specified if using this. Set to "0" to disable.
* **radius_location:** Specify a location to rollback around. Can be set to "null" if no radius is specified, and a user is specified.
---
#### `performRestore(int time, List<String> restrict_users, List<String> exclude_users, List<Object> restrict_blocks, List<Object> exclude_blocks, List<Integer> action_list, int radius, Location radius_location)`
This will perform a restore.
* **time:** Specify the amount of time to restore. "5" would return results from the last 5 seconds.
* **restrict_users:** Specify any usernames to perform the restore on. Can be set to "null" if both a radius and a location are specified.
* **exclude_users:** Specify any usernames to exclude from the restore. Can be set to "null".
* **restrict_blocks:** Specify a list of EntityType's or Material's to restrict the restore to. Can be set to "null".
* **exclude_blocks:** Specify a list of EntityType's or Material's to exclude from the restore. Can be set to "null".
* **action_list:** Specify a list of action types to restrict the restore to. Can be set to "null"
* **radius:** Specify a radius to restrict the restore to. A location must be specified if using this. Set to "0" to disable.
* **radius_location:** Specify a location to restore around. Can be set to "null" if no radius is specified, and a user is specified.
---
#### `blockLookup(Block block, int time)`
This will perform a full lookup on a single block.
* **block:** The block to perform the lookup on.
* **time:** Specify the amount of time to lookup. "5" would return results from the last 5 seconds.
---
#### `queueLookup(Block block)`
This will search the consumer queue for changes on a block not yet saved in the database.
* **block:** The block to perform the lookup on.
---
#### `sessionLookup(String user, int time)`
This will perform a session lookup on a single player.
* **user:** The username to perform the lookup on.
* **time:** Specify the amount of time to lookup. "5" would return results from the last 5 seconds.
---
#### `ParseResult parseResult(String[] result)`
This will parse results from a lookup. You'll then be able to view the following:
* **getX():** Get the X coordinate of the block.
* **getY():** Get the Y coordinate of the block.
* **getZ():** Get the Z coordinate of the block.
* **getType():** Get the Material of the block.
* **getBlockData():** Get the BlockData of the block.
* **getPlayer():** Get the username as a string..
* **getTimestamp():** Get the time of the action.
* **getActionId():** Get the action ID. (0=removed, 1=placed, 2=interaction)
* **getActionString():** Get the action as a string. (Removal, Placement, Interaction)
* **isRolledBack():** If the block is currently rolled back or not.
* **worldName():** The name of the world the block is located in.
---
#### `logPlacement(String user, Location location, Material type, BlockData blockData)`
This will log a block as being placed.
* **user:** Specify the username to log as having placed the block.
* **location:** Specify the location of the block you're logging.
* **type:** Specify the Material of the block you're logging.
* **blockData:** Specify the BlockData of the block you're logging. Can be set to "null".
---
#### `logRemoval(String user, Location location, Material type, BlockData blockData)`
This will log a block as being removed/broken, and will log the block's inventory (if applicable).
* **user:** Specify the username to log as having removed the block.
* **location:** Specify the location of the block you're logging.
* **type:** Specify the Material of the block you're logging.
* **blockData:** Specify the BlockData of the block you're logging. Can be set to "null".
---
#### `logContainerTransaction(String user, Location location)`
This will log any transactions made to a block's inventory immediately after calling the method.
* **user:** Specify the username to log as having added/removed the items.
* **location:** Specify the location of the block inventory you're logging.
---
#### `logInteraction(String user, Location location)`
This will log a block as having been interacted with.
* **user:** Specify the username to log as having caused the interaction.
* **location:** Specify the location of the interaction you're logging.
---
#### `hasPlaced(String user, Block block, int time, int offset)`
This will return true if a user has already placed a block at the location within the specified time limit.
* **user:** The username you're checking to see if they've placed a block already.
* **block:** The block you're checking.
* **time:** How far back to check. "5" would only check through the last 5 seconds of logged blocks.
* **offset:** A time offset. "2" would ignore the last 2 seconds of most recently ignored data. (0 = no offset)
---
#### `hasRemoved(String user, Block block, int time, int offset)`
This will return true if a user has already removed a block at the location within the specified time limit.
* **user:** The username you're checking to see if they've removed a block already.
* **block:** The block you're checking.
* **time:** How far back to check. "5" would only check through the last 5 seconds of logged blocks.
* **offset:** A time offset. "2" would ignore the last 2 seconds of most recently ignored data. (0 = no offset)
---
#### `performPurge(int time)`
This will perform a purge on the CoreProtect database.
* **time:** Purge any data earlier than this. "120" would purge any data older than 120 seconds (2 minutes).
---
### Examples
- Get the last 60 seconds of block data for the user "Notch".
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect != null){ // Ensure we have access to the API
List<String[]> lookup = CoreProtect.performLookup(60, Arrays.asList("Notch"), null, null, null, null, 0, null);
if (lookup != null){
for (String[] result : lookup){
ParseResult parseResult = CoreProtect.parseResult(result);
int x = parseResult.getX();
int y = parseResult.getY();
int z = parseResult.getZ();
//...
}
}
}
```
---
- Get the last 60 seconds of block data for the user "Notch", excluding dirt and grass blocks.
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect != null){ // Ensure we have access to the API
List<Object> exclude = Arrays.asList(Material.DIRT, Material.GRASS);
List<String[]> lookup = CoreProtect.performLookup(60, Arrays.asList("Notch"), null, null, exclude, null, 0, null);
if (lookup != null){
for (String[] value : lookup){
ParseResult result = CoreProtect.parseResult(value);
int x = result.getX();
int y = result.getY();
int z = result.getZ();
//...
}
}
}
```
---
- Get the last 60 seconds of block data within 5 blocks of a location.
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect != null){ // Ensure we have access to the API
List<String[]> lookup = CoreProtect.performLookup(60, null, null, null, null, null, 5, location);
if (lookup != null){
for (String[] value : lookup){
ParseResult result = CoreProtect.parseResult(value);
int x = result.getX();
int y = result.getY();
int z = result.getZ();
//...
}
}
}
```
---
- Rollbacks / restores use the same code structure as the above examples. For example:
```java
class BasicThread implements Runnable {
@Override
public void run() {
try {
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect != null){ // Ensure we have access to the API
List<String[]> lookup = CoreProtect.performRollback(60, Arrays.asList("Notch"), null, null, null, null, 0, null);
if (lookup != null){
for (String[] value : lookup){
ParseResult result = CoreProtect.parseResult(value);
int x = result.getX();
int y = result.getY();
int z = result.getZ();
//...
}
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
thread.start();
```
---
- Check if the user "Notch" has already placed a block at a location within the last 60 seconds.
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect != null){ // Ensure we have access to the API
boolean hasPlaced = CoreProtect.hasPlaced("Notch", block, 60, 0);
// Search queue for pending changes
if (!hasPlaced){
List<String[]> lookup = CoreProtect.queueLookup(block);
for (String[] result : lookup){
ParseResult parseResult = CoreProtect.parseResult(value);
if (parseResult.getActionId()==1 && parseResult.getPlayer().equals("Notch")){
hasPlaced = true;
break;
}
}
}
}
```
---
- Get the last 60 seconds of block data for a specific block.
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect != null){ // Ensure we have access to the API
List<String[]> lookup = CoreProtect.blockLookup(block, 60);
if (lookup != null){
for (String[] result : lookup){
ParseResult parseResult = CoreProtect.parseResult(value);
int x = parseResult.getX();
int y = parseResult.getY();
int z = parseResult.getZ();
//...
}
}
}
```
---
- Get the last 1 day of session data for the user "Notch".
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect != null){ // Ensure we have access to the API
List<String[]> lookup = CoreProtect.sessionLookup("Notch", (24 * 60 * 60));
if (lookup != null){
for (String[] result : lookup){
ParseResult parseResult = CoreProtect.parseResult(value);
int x = parseResult.getX();
int y = parseResult.getY();
int z = parseResult.getZ();
int action = parseResult.getActionId(); // 0 = logout, 1 = login
//...
}
}
}
```
---
- Log the placement of a block at a location by the user "Notch".
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect != null){ // Ensure we have access to the API
boolean success = CoreProtect.logPlacement("Notch", block.getLocation(), block.getType(), block.getData());
}
```
---
- Log adding/remove items in a chest (or some other block inventory).
```java
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect != null){ // Ensure we have access to the API
boolean success = CoreProtect.logContainerTransaction("Notch", inventory.getLocation());
// modify your container contents immediately after (e.g. [i]inventory.addItem(itemStack);[/i])
}
```
---
- Perform a multi-threaded placement check to see if the user "Notch" has already placed a block at a location within the last 60 seconds. This ignores the most recent 1 second of logged data, to account for the fact that that new block data may have already been logged, depending on your code.
```java
final Block block = null; //Should be an actual block
class BasicThread implements Runnable {
@Override
public void run() {
try {
CoreProtectAPI CoreProtect = getCoreProtect();
if (CoreProtect != null){ // Ensure we have access to the API
boolean hasPlaced = CoreProtect.hasPlaced("Notch", block, 60, 1);
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
thread.start();
```
---
+8 -7
View File
@@ -138,7 +138,8 @@ ___
* Example: `t:2w,5d,7h,2m,10s`
* Example: `t:5d2h`
* Example: `t:2.50h` *(2 and a half hours)*
* Example: `t:1h-2h` *(between one to two hours)*
* Example: `t:2.50h` *(two and a half hours)*
---
@@ -171,12 +172,12 @@ ___
| `a:container` | items taken from or put in chests |
| `a:+container` | items put in chests |
| `a:-container` | items taken from chests |
| `a:inventory` | items dropped, picked up, deposited, or withdrawn by players |
| `a:+inventory` | items picked up or withdrawn by players |
| `a:-inventory` | items dropped or deposited by players |
| `a:item` | merges `a:container` and `a:inventory` |
| `a:+item` | merges `a:+container` and `a:+inventory` |
| `a:-item` | merges `a:-container` and `a:-inventory` |
| `a:inventory` | items added or removed from player inventories |
| `a:+inventory` | items added to player inventories |
| `a:-inventory` | items removed from player inventories |
| `a:item` | items dropped, thrown, picked up, deposited, or withdrawn by players |
| `a:+item` | items picked up or withdrawn by players |
| `a:-item` | items dropped, thrown, or deposited by players |
| `a:kill` | mobs/animals killed |
| `a:session` | player logins/logouts |
| `a:+session` | player logins |
+123
View File
@@ -0,0 +1,123 @@
# Languages
Language codes can be entered in `config.yml` for automatic online translation.
---
## CoreProtect Language Codes
| Language | Code |
| --- | --- |
| Afrikaans | `af` |
| Albanian | `sq` |
| Amharic | `am` |
| Arabic | `ar` |
| Armenian | `hy` |
| Azerbaijani | `az` |
| Basque | `eu` |
| Belarusian | `be` |
| Bengali | `bn` |
| Bosnian | `bs` |
| Bulgarian | `bg` |
| Catalan | `ca` |
| Cebuano | `ceb` |
| Chinese (Simplified) | `zh-CN` or `zh` |
| Chinese (Traditional) | `zh-TW` |
| Corsican | `co` |
| Croatian | `hr` |
| Czech | `cs` |
| Danish | `da` |
| Dutch | `nl` |
| English | `en` |
| Esperanto | `eo` |
| Estonian | `et` |
| Finnish | `fi` |
| French | `fr` |
| Frisian | `fy` |
| Galician | `gl` |
| Georgian | `ka` |
| German | `de` |
| Greek | `el` |
| Gujarati | `gu` |
| Haitian Creole | `ht` |
| Hausa | `ha` |
| Hawaiian | `haw` |
| Hebrew | `he` or `iw` |
| Hindi | `hi` |
| Hmong | `hmn` |
| Hungarian | `hu` |
| Icelandic | `is` |
| Igbo | `ig` |
| Indonesian | `id` |
| Irish | `ga` |
| Italian | `it` |
| Japanese | `ja` |
| Javanese | `jv` |
| Kannada | `kn` |
| Kazakh | `kk` |
| Khmer | `km` |
| Kinyarwanda | `rw` |
| Korean | `ko` |
| Kurdish | `ku` |
| Kyrgyz | `ky` |
| Lao | `lo` |
| Latin | `la` |
| Latvian | `lv` |
| Lithuanian | `lt` |
| Luxembourgish | `lb` |
| Macedonian | `mk` |
| Malagasy | `mg` |
| Malay | `ms` |
| Malayalam | `ml` |
| Maltese | `mt` |
| Maori | `mi` |
| Marathi | `mr` |
| Mongolian | `mn` |
| Myanmar (Burmese) | `my` |
| Nepali | `ne` |
| Norwegian | `no` |
| Nyanja (Chichewa) | `ny` |
| Odia (Oriya) | `or` |
| Pashto | `ps` |
| Persian | `fa` |
| Polish | `pl` |
| Portuguese (Portugal, Brazil) | `pt` |
| Punjabi | `pa` |
| Romanian | `ro` |
| Russian | `ru` |
| Samoan | `sm` |
| Scots Gaelic | `gd` |
| Serbian | `sr` |
| Sesotho | `st` |
| Shona | `sn` |
| Sindhi | `sd` |
| Sinhala (Sinhalese) | `si` |
| Slovak | `sk` |
| Slovenian | `sl` |
| Somali | `so` |
| Spanish | `es` |
| Sundanese | `su` |
| Swahili | `sw` |
| Swedish | `sv` |
| Tagalog (Filipino) | `tl` |
| Tajik | `tg` |
| Tamil | `ta` |
| Tatar | `tt` |
| Telugu | `te` |
| Thai | `th` |
| Turkish | `tr` |
| Turkmen | `tk` |
| Ukrainian | `uk` |
| Urdu | `ur` |
| Uyghur | `ug` |
| Uzbek | `uz` |
| Vietnamese | `vi` |
| Welsh | `cy` |
| Xhosa | `xh` |
| Yiddish | `yi` |
| Yoruba | `yo` |
| Zulu | `zu` |
*Source: [cloud.google.com/translate](https://cloud.google.com/translate/docs/languages)*
---
+7 -2
View File
@@ -14,10 +14,15 @@ Use WorldEdit selections as a radius, and log your WorldEdit changes.
&nbsp;
* **CoreProtect-Anti-Xray**
Displays how many ores a player has destroyed in a specific time span.
Displays how many ores a player has destroyed in a specific time span.
[https://dev.bukkit.org/bukkit-plugins/coreprotect-anti-xray/](https://dev.bukkit.org/bukkit-plugins/coreprotect-anti-xray/)
&nbsp;
* **CoreProtect TNT**
The CoreProtect TNT extension adds logging for TNT and creeper explosion sources.
[https://www.spigotmc.org/resources/coreprotect-tnt-log-tnt-creeper-explode-source.69609/](https://www.spigotmc.org/resources/coreprotect-tnt-log-tnt-creeper-explode-source.69609/)
&nbsp;
## Tools
* **CoreProtect Lookup Web Interface**
@@ -36,4 +41,4 @@ Watson is a client side Minecraft mod that displays CoreProtect logs in 3D.
Have you created a plugin that's compatible with CoreProtect?
Let us know to have it added to this list!
---
---
+6 -2
View File
@@ -9,8 +9,11 @@ API_TEST: "API-Test erfolgreich."
CACHE_ERROR: "WARNUNG: Fehler beim Validieren {0} Zwischenspeicher."
CACHE_RELOAD: "Erzwingen des Nachladens von {kartierung|welt} Caches aus der Datenbank."
CHECK_CONFIG: "Bitte überprüfen Sie config.yml"
COMMAND_CONSOLE: "Bitte führen Sie den Befehl von der Konsole aus."
COMMAND_NOT_FOUND: "Befehl \"{0}\" nicht gefunden."
COMMAND_THROTTLED: "Bitte warten Sie einen Moment und versuchen Sie es erneut."
CONSUMER_ERROR: "Verbraucherwarteschlange wird bereits verarbeitet {angehalten|fortgesetzt}."
CONSUMER_TOGGLED: "Die Verarbeitung der Verbraucherwarteschlange wurde durchgeführt {angehalten|fortgesetzt}."
CONTAINER_HEADER: "Containertransaktionen"
DATABASE_BUSY: "Datenbank beschäftigt. Bitte versuchen Sie es später erneut."
DATABASE_INDEX_ERROR: "Datenbankindizes können nicht validiert werden."
@@ -108,12 +111,12 @@ LOOKUP_INTERACTION: "{0} {angeklickt|getötet} {1}."
LOOKUP_ITEM: "{0} {abgeholt|abgeworfen} {1} {2}."
LOOKUP_LOGIN: "{0} eingeloggt {rein|raus}."
LOOKUP_PAGE: "Seite {0}"
LOOKUP_PROJECTILE: "{0} {geworfen|geschossen} {1} {2}."
LOOKUP_ROWS_FOUND: "{0} {Reihe|Reihen} gefunden."
LOOKUP_SEARCHING: "Suche nachschlagen. Warten Sie mal..."
LOOKUP_STORAGE: "{0} {hinterlegt|abgehoben} {1} {2}."
LOOKUP_TIME: "{0} vor"
LOOKUP_USERNAME: "{0} Eingeloggt als {1}."
LOOKUP_VIEW_PAGE: "Um eine Seite anzuzeigen, geben Sie \"{0}\"."
MAXIMUM_RADIUS: "Das Maximum {Nachschlagen|Rollback|Wiederherstellen} Radius ist {0}."
MISSING_ACTION_USER: "Um diese Aktion zu verwenden, geben Sie bitte einen Benutzer an."
MISSING_LOOKUP_TIME: "Bitte geben Sie die Zeit an, um {Nachschlagen|Rollback|Wiederherstellen}."
@@ -139,8 +142,8 @@ PATCH_UPGRADING: "Datenbank-Upgrade im Gange. Warten Sie mal..."
PLEASE_SELECT: "Bitte auswählen: \"{0}\" oder \"{1}\"."
PREVIEW_CANCELLED: "Vorschau abgebrochen."
PREVIEW_CANCELLING: "Vorschau abbrechen..."
PREVIEW_CONTAINER: "Sie können keine Containertransaktionen in der Vorschau anzeigen."
PREVIEW_IN_GAME: "Sie können Rollbacks nur im Spiel in der Vorschau anzeigen."
PREVIEW_TRANSACTION: "Sie können keine Vorschau anzeigen {Behälter|Inventar} Transaktionen."
PURGE_ABORTED: "Bereinigung fehlgeschlagen. Die Datenbank ist möglicherweise beschädigt."
PURGE_ERROR: "Kann nicht verarbeitet werden {0} Daten!"
PURGE_FAILED: "Bereinigung fehlgeschlagen. Bitte versuchen Sie es später erneut."
@@ -189,6 +192,7 @@ UPDATE_HEADER: "{0} Aktualisieren"
UPDATE_NOTICE: "Beachten: {0} ist nun verfügbar."
UPGRADE_IN_PROGRESS: "Upgrade läuft. Bitte versuchen Sie es später erneut."
USER_NOT_FOUND: "Benutzer \"{0}\" nicht gefunden."
USER_OFFLINE: "Der Benutzer \"{0}\" ist nicht online."
USING_MYSQL: "Verwenden von MySQL zur Datenspeicherung."
USING_SQLITE: "Verwenden von SQLite zur Datenspeicherung."
VALID_DONATION_KEY: "Gültiger Spendenschlüssel."
+6 -2
View File
@@ -9,8 +9,11 @@ API_TEST: "API test successful."
CACHE_ERROR: "WARNING: Error while validating {0} cache."
CACHE_RELOAD: "Forcing reload of {mapping|world} caches from database."
CHECK_CONFIG: "Please check config.yml"
COMMAND_CONSOLE: "Please run the command from the console."
COMMAND_NOT_FOUND: "Command \"{0}\" not found."
COMMAND_THROTTLED: "Please wait a moment and try again."
CONSUMER_ERROR: "Consumer queue processing already {paused|resumed}."
CONSUMER_TOGGLED: "Consumer queue processing has been {paused|resumed}."
CONTAINER_HEADER: "Container Transactions"
DATABASE_BUSY: "Database busy. Please try again later."
DATABASE_INDEX_ERROR: "Unable to validate database indexes."
@@ -108,12 +111,12 @@ LOOKUP_INTERACTION: "{0} {clicked|killed} {1}."
LOOKUP_ITEM: "{0} {picked up|dropped} {1} {2}."
LOOKUP_LOGIN: "{0} logged {in|out}."
LOOKUP_PAGE: "Page {0}"
LOOKUP_PROJECTILE: "{0} {threw|shot} {1} {2}."
LOOKUP_ROWS_FOUND: "{0} {row|rows} found."
LOOKUP_SEARCHING: "Lookup searching. Please wait..."
LOOKUP_STORAGE: "{0} {deposited|withdrew} {1} {2}."
LOOKUP_TIME: "{0} ago"
LOOKUP_USERNAME: "{0} logged in as {1}."
LOOKUP_VIEW_PAGE: "To view a page, type \"{0}\"."
MAXIMUM_RADIUS: "The maximum {lookup|rollback|restore} radius is {0}."
MISSING_ACTION_USER: "To use that action, please specify a user."
MISSING_LOOKUP_TIME: "Please specify the amount of time to {lookup|rollback|restore}."
@@ -139,8 +142,8 @@ PATCH_UPGRADING: "Database upgrade in progress. Please wait..."
PLEASE_SELECT: "Please select: \"{0}\" or \"{1}\"."
PREVIEW_CANCELLED: "Preview cancelled."
PREVIEW_CANCELLING: "Cancelling preview..."
PREVIEW_CONTAINER: "You can't preview container transactions."
PREVIEW_IN_GAME: "You can only preview rollbacks in-game."
PREVIEW_TRANSACTION: "You can't preview {container|inventory} transactions."
PURGE_ABORTED: "Purge failed. Database may be corrupt."
PURGE_ERROR: "Unable to process {0} data!"
PURGE_FAILED: "Purge failed. Please try again later."
@@ -189,6 +192,7 @@ UPDATE_HEADER: "{0} Update"
UPDATE_NOTICE: "Notice: {0} is now available."
UPGRADE_IN_PROGRESS: "Upgrade in progress. Please try again later."
USER_NOT_FOUND: "User \"{0}\" not found."
USER_OFFLINE: "The user \"{0}\" is not online."
USING_MYSQL: "Using MySQL for data storage."
USING_SQLITE: "Using SQLite for data storage."
VALID_DONATION_KEY: "Valid donation key."
+8 -4
View File
@@ -9,8 +9,11 @@ API_TEST: "Prueba de API exitosa."
CACHE_ERROR: "ADVERTENCIA: Error al validar {0} cache."
CACHE_RELOAD: "Forzando la recarga de {mapeo|mundo} cachés de la base de datos."
CHECK_CONFIG: "Por favor revise config.yml"
COMMAND_CONSOLE: "Ejecute el comando desde la consola."
COMMAND_NOT_FOUND: "Comando \"{0}\" extraviado."
COMMAND_THROTTLED: "Espere un momento y vuelva a intentarlo."
CONSUMER_ERROR: "Procesamiento de colas de consumidores ya {en pausa|reanudado}."
CONSUMER_TOGGLED: "El procesamiento de la cola del consumidor ha sido {en pausa|reanudado}."
CONTAINER_HEADER: "Transacciones de contenedores"
DATABASE_BUSY: "Base de datos ocupado. Por favor, inténtelo de nuevo más tarde."
DATABASE_INDEX_ERROR: "No se pueden validar los índices de la base de datos."
@@ -108,12 +111,12 @@ LOOKUP_INTERACTION: "{0} {clickeado|muerto} {1}."
LOOKUP_ITEM: "{0} {recogido|caído} {1} {2}."
LOOKUP_LOGIN: "{0} registrado {adentro|afuera}."
LOOKUP_PAGE: "Página {0}"
LOOKUP_PROJECTILE: "{0} {tiró|disparó} {1} {2}."
LOOKUP_ROWS_FOUND: "{0} {fila|filas} encontró."
LOOKUP_SEARCHING: "Búsqueda de búsqueda. Espere por favor..."
LOOKUP_STORAGE: "{0} {depositado|retirado} {1} {2}."
LOOKUP_TIME: "{0} atrás"
LOOKUP_USERNAME: "{0} Conectado como {1}."
LOOKUP_VIEW_PAGE: "Para ver una página, escriba \"{0}\"."
MAXIMUM_RADIUS: "El maximo {buscar|deshacer|restaurar} el radio es {0}."
MISSING_ACTION_USER: "Para utilizar esa acción, especifique un usuario."
MISSING_LOOKUP_TIME: "Por favor, especifique el tiempo para {buscar|deshacer|restaurar}."
@@ -123,7 +126,7 @@ MISSING_ROLLBACK_RADIUS: "No especificó un {deshacer|restaurar} radio."
MISSING_ROLLBACK_USER: "No especificó un {deshacer|restaurar} usuario."
MYSQL_UNAVAILABLE: "Incapaz de conectarse a MySQL servidor."
NO_DATA: "No se encontraron datos en {0}."
NO_DATA_LOCATION: "No {datos|transacciones|interacciones|mensajes} encontró."
NO_DATA_LOCATION: "No se encontraron {datos|transacciones|interacciones|mensajes}."
NO_PERMISSION: "No tienes permiso para hacer eso."
NO_RESULTS: "No se han encontrado resultados."
NO_RESULTS_PAGE: "No {resultados|datos} encontrado para esa página."
@@ -139,8 +142,8 @@ PATCH_UPGRADING: "Actualización de la base de datos en curso. Espere por favor.
PLEASE_SELECT: "Seleccione: \"{0}\" o \"{1}\"."
PREVIEW_CANCELLED: "Vista previa cancelada."
PREVIEW_CANCELLING: "Cancelando vista previa..."
PREVIEW_CONTAINER: "No puede obtener una vista previa de las transacciones de contenedor."
PREVIEW_IN_GAME: "Solo puedes obtener una vista previa de las reversiones en el juego."
PREVIEW_TRANSACTION: "No puedes previsualizar {contenedor|inventario} actas."
PURGE_ABORTED: "La purga falló. La base de datos puede estar dañada."
PURGE_ERROR: "No se puede procesar {0} ¡datos!"
PURGE_FAILED: "La purga falló. Por favor, inténtelo de nuevo más tarde."
@@ -171,7 +174,7 @@ ROLLBACK_STARTED: "{Retroceder|Restaurar|Vista previa} comenzó en \"{0}\"."
ROLLBACK_TIME: "Intervalo de tiempo: {0}."
ROLLBACK_WORLD_ACTION: "Prohibido para {mundo|acción} \"{0}\"."
SIGN_HEADER: "Firmar mensajes"
STATUS_CONSUMER: "Consumidor: {0} {artículo|artículos} en fila."
STATUS_CONSUMER: "Consumidor: {0} {artículo|artículos} en la cola."
STATUS_DATABASE: "Base de datos: Usando {0}."
STATUS_INTEGRATION: "{0}: Integración {habilitado|deshabilitado}."
STATUS_LICENSE: "Licencia: {0}"
@@ -189,6 +192,7 @@ UPDATE_HEADER: "{0} Actualizar"
UPDATE_NOTICE: "Darse cuenta: {0} Ya está disponible."
UPGRADE_IN_PROGRESS: "Actualización en curso. Por favor, inténtelo de nuevo más tarde."
USER_NOT_FOUND: "Usuario \"{0}\" extraviado."
USER_OFFLINE: "El usuario \"{0}\" no está en línea."
USING_MYSQL: "Utilizando MySQL para el almacenamiento de datos."
USING_SQLITE: "Utilizando SQLite para el almacenamiento de datos."
VALID_DONATION_KEY: "Clave de donación válida."
+6 -2
View File
@@ -9,8 +9,11 @@ API_TEST: "Test API réussi."
CACHE_ERROR: "ATTENTION: Erreur lors de la validation {0} cache."
CACHE_RELOAD: "Forcer le rechargement de {cartographie|monde} cache de la base de données."
CHECK_CONFIG: "Veuillez vérifier config.yml"
COMMAND_CONSOLE: "Veuillez exécuter la commande depuis la console."
COMMAND_NOT_FOUND: "Commande \"{0}\" pas trouvé."
COMMAND_THROTTLED: "Veuillez patienter un instant et réessayer."
CONSUMER_ERROR: "Traitement de la file d'attente des consommateurs déjà {mis en pause|repris}."
CONSUMER_TOGGLED: "Le traitement de la file d'attente des consommateurs a été {mis en pause|repris}."
CONTAINER_HEADER: "Transactions de conteneurs"
DATABASE_BUSY: "Base de données occupée. Veuillez réessayer plus tard."
DATABASE_INDEX_ERROR: "Impossible de valider les index de la base de données."
@@ -108,12 +111,12 @@ LOOKUP_INTERACTION: "{0} {cliqué|tué} {1}."
LOOKUP_ITEM: "{0} {ramassé|lâché} {1} {2}."
LOOKUP_LOGIN: "{0} connecté {entrée|sortie}."
LOOKUP_PAGE: "Page {0}"
LOOKUP_PROJECTILE: "{0} {jeté|tiré} {1} {2}."
LOOKUP_ROWS_FOUND: "{0} {ligne|lignes} trouvé."
LOOKUP_SEARCHING: "Recherche de recherche. S'il vous plaît, attendez..."
LOOKUP_STORAGE: "{0} {déposé|retiré} {1} {2}."
LOOKUP_TIME: "{0} depuis"
LOOKUP_USERNAME: "{0} connecté en tant que {1}."
LOOKUP_VIEW_PAGE: "Pour afficher une page, tapez \"{0}\"."
MAXIMUM_RADIUS: "Le maximum {recherche|restauration|restauration} le rayon est {0}."
MISSING_ACTION_USER: "Pour utiliser cette action, veuillez spécifier un utilisateur."
MISSING_LOOKUP_TIME: "Veuillez préciser l'heure à laquelle {recherche|restauration|restauration}."
@@ -139,8 +142,8 @@ PATCH_UPGRADING: "Mise à niveau de la base de données en cours. S'il vous pla
PLEASE_SELECT: "Veuillez sélectionner: \"{0}\" ou alors \"{1}\"."
PREVIEW_CANCELLED: "Aperçu annulé."
PREVIEW_CANCELLING: "Annulation de l'aperçu..."
PREVIEW_CONTAINER: "Vous ne pouvez pas prévisualiser les transactions de conteneur."
PREVIEW_IN_GAME: "Vous ne pouvez prévisualiser les rollbacks que dans le jeu."
PREVIEW_TRANSACTION: "Vous ne pouvez pas prévisualiser {conteneur|inventaire} transactions."
PURGE_ABORTED: "Échec de la purge. La base de données est peut-être corrompue."
PURGE_ERROR: "Impossible de traiter {0} Les données!"
PURGE_FAILED: "Échec de la purge. Veuillez réessayer plus tard."
@@ -189,6 +192,7 @@ UPDATE_HEADER: "{0} Mettre à jour"
UPDATE_NOTICE: "Remarquer: {0} est maintenant disponible."
UPGRADE_IN_PROGRESS: "Mise à niveau en cours. Veuillez réessayer plus tard."
USER_NOT_FOUND: "Utilisateur \"{0}\" pas trouvé."
USER_OFFLINE: "L'utilisateur \"{0}\" n'est pas en ligne."
USING_MYSQL: "Utilisant MySQL pour le stockage des données."
USING_SQLITE: "Utilisant SQLite pour le stockage des données."
VALID_DONATION_KEY: "Clé de don valide."
+6 -2
View File
@@ -9,8 +9,11 @@ API_TEST: "APIテストが成功しました。"
CACHE_ERROR: "警告:検証中にエラーが発生しました {0} キャッシュ。"
CACHE_RELOAD: "のリロードを強制する {マッピング|世界} データベースからのキャッシュ。"
CHECK_CONFIG: "config.ymlを確認してください"
COMMAND_CONSOLE: "コンソールからコマンドを実行してください。"
COMMAND_NOT_FOUND: "指示 \"{0}\" 見つかりません。"
COMMAND_THROTTLED: "しばらく待ってから、もう一度お試しください。"
CONSUMER_ERROR: "すでにコンシューマキュー処理 {一時停止|再開}。"
CONSUMER_TOGGLED: "消費者キューの処理は {一時停止|再開}。"
CONTAINER_HEADER: "コンテナトランザクション"
DATABASE_BUSY: "データベースがビジーです。後でもう一度やり直してください。"
DATABASE_INDEX_ERROR: "データベースインデックスを検証できません。"
@@ -108,12 +111,12 @@ LOOKUP_INTERACTION: "{0} {クリック|殺された} {1}。"
LOOKUP_ITEM: "{0} {拾った|落とした} {1} {2}。"
LOOKUP_LOGIN: "{0} ログに記録されます {in|out}。"
LOOKUP_PAGE: "ページ {0}"
LOOKUP_PROJECTILE: "{0} {投げた|ショット} {1} {2}。"
LOOKUP_ROWS_FOUND: "{0} {行|行} 見つかった。"
LOOKUP_SEARCHING: "ルックアップ検索。お待ちください..."
LOOKUP_STORAGE: "{0} {預け入れ|撤回} {1} {2}。"
LOOKUP_TIME: "{0} 前に"
LOOKUP_USERNAME: "{0} としてログイン {1}。"
LOOKUP_VIEW_PAGE: "ページを表示するには、「{0}\" 。"
MAXIMUM_RADIUS: "最大 {ルックアップ|ロールバック|復元} 半径は {0}。"
MISSING_ACTION_USER: "そのアクションを使用するには、ユーザーを指定してください。"
MISSING_LOOKUP_TIME: "時間を指定してください {ルックアップ|ロールバック|復元}。"
@@ -139,8 +142,8 @@ PATCH_UPGRADING: "データベースのアップグレードが進行中です
PLEASE_SELECT: "選んでください: \"{0}\" また \"{1}\" 。"
PREVIEW_CANCELLED: "プレビューがキャンセルされました。"
PREVIEW_CANCELLING: "プレビューをキャンセルしています..."
PREVIEW_CONTAINER: "コンテナトランザクションをプレビューすることはできません。"
PREVIEW_IN_GAME: "ゲーム内でのみロールバックをプレビューできます。"
PREVIEW_TRANSACTION: "プレビューできません {コンテナ|在庫} トランザクション。"
PURGE_ABORTED: "パージに失敗しました。データベースが破損している可能性があります。"
PURGE_ERROR: "処理できません {0} データ!"
PURGE_FAILED: "パージに失敗しました。後でもう一度やり直してください。"
@@ -189,6 +192,7 @@ UPDATE_HEADER: "{0} アップデート"
UPDATE_NOTICE: "知らせ:{0} 現在利用できます。"
UPGRADE_IN_PROGRESS: "アップグレードが進行中です。後でもう一度やり直してください。"
USER_NOT_FOUND: "ユーザー \"{0}\" 見つかりません。"
USER_OFFLINE: "ユーザー \"{0}\" はオンラインではありません。"
USING_MYSQL: "使用する MySQL データストレージ用。"
USING_SQLITE: "使用する SQLite データストレージ用。"
VALID_DONATION_KEY: "有効な寄付キー。"
+6 -2
View File
@@ -9,8 +9,11 @@ API_TEST: "Test interfejsu API pomyślny."
CACHE_ERROR: "OSTRZEŻENIE: Błąd podczas walidacji {0} Pamięć podręczna."
CACHE_RELOAD: "Wymuszanie przeładowania {mapowanie|świat} pamięci podręczne z bazy danych."
CHECK_CONFIG: "Sprawdź plik config.yml"
COMMAND_CONSOLE: "Uruchom polecenie z konsoli."
COMMAND_NOT_FOUND: "Komenda \"{0}\" nie znaleziono."
COMMAND_THROTTLED: "Poczekaj chwilę i spróbuj ponownie."
CONSUMER_ERROR: "Przetwarzanie kolejki klientów już {wstrzymane|wznowione}."
CONSUMER_TOGGLED: "Przetwarzanie kolejki klientów zostało {wstrzymane|wznowione}."
CONTAINER_HEADER: "Transakcje kontenerowe"
DATABASE_BUSY: "Baza danych zajęta. Spróbuj ponownie później."
DATABASE_INDEX_ERROR: "Nie można zweryfikować indeksów bazy danych."
@@ -108,12 +111,12 @@ LOOKUP_INTERACTION: "{0} {kliknięty|zabity} {1}."
LOOKUP_ITEM: "{0} {odebrany|upuszczony} {1} {2}."
LOOKUP_LOGIN: "{0} zalogowany {w|na zewnątrz}."
LOOKUP_PAGE: "Strona {0}"
LOOKUP_PROJECTILE: "{0} {rzucił|strzał} {1} {2}."
LOOKUP_ROWS_FOUND: "{0} {wiersz|wiersze} znaleziony."
LOOKUP_SEARCHING: "Wyszukiwanie wyszukiwania. Proszę czekać..."
LOOKUP_STORAGE: "{0} {zdeponowane|wycofane} {1} {2}."
LOOKUP_TIME: "{0} temu"
LOOKUP_USERNAME: "{0} zalogowany jako {1}."
LOOKUP_VIEW_PAGE: "Aby wyświetlić stronę, wpisz „{0}”."
MAXIMUM_RADIUS: "Maksymalny {wyszukiwanie|wycofywanie|przywracanie} promień to {0}."
MISSING_ACTION_USER: "Aby skorzystać z tej akcji, określ użytkownika."
MISSING_LOOKUP_TIME: "Proszę określić czas na {wyszukiwanie|przywracanie|przywracanie}."
@@ -139,8 +142,8 @@ PATCH_UPGRADING: "Trwa aktualizacja bazy danych. Proszę czekać..."
PLEASE_SELECT: "Proszę wybrać: \"{0}\" lub \"{1}”."
PREVIEW_CANCELLED: "Podgląd anulowany."
PREVIEW_CANCELLING: "Anulowanie podglądu..."
PREVIEW_CONTAINER: "Nie możesz wyświetlić podglądu transakcji kontenerowych."
PREVIEW_IN_GAME: "Możesz tylko podglądać wycofania w grze."
PREVIEW_TRANSACTION: "Nie możesz wyświetlić podglądu {kontener|inwentarz} transakcje."
PURGE_ABORTED: "Czyszczenie nie powiodło się. Baza danych może być uszkodzona."
PURGE_ERROR: "Nie można przetworzyć {0} dane!"
PURGE_FAILED: "Czyszczenie nie powiodło się. Spróbuj ponownie później."
@@ -189,6 +192,7 @@ UPDATE_HEADER: "{0} Aktualizacja"
UPDATE_NOTICE: "Ogłoszenie: {0} jest teraz dostępne."
UPGRADE_IN_PROGRESS: "Trwa aktualizacja. Spróbuj ponownie później."
USER_NOT_FOUND: "Użytkownik \"{0}\" nie znaleziono."
USER_OFFLINE: "Użytkownik \"{0}\" nie jest online."
USING_MYSQL: "Za pomocą MySQL do przechowywania danych."
USING_SQLITE: "Za pomocą SQLite do przechowywania danych."
VALID_DONATION_KEY: "Ważny klucz darowizny."
+7 -3
View File
@@ -9,8 +9,11 @@ API_TEST: "Тест API прошёл успешно!"
CACHE_ERROR: "ВНИМАНИЕ: Ошибка при проверке кеша {0}."
CACHE_RELOAD: "Принудительная перезагрузка кеша {отображения|мира} из базы данных."
CHECK_CONFIG: "Пожалуйста, проверьте config.yml"
COMMAND_CONSOLE: "Пожалуйста, запустите команду из консоли."
COMMAND_NOT_FOUND: "Команда «{0}» не найдена."
COMMAND_THROTTLED: "Подождите немного и попробуйте еще раз."
CONSUMER_ERROR: "Обработка потребительской очереди уже {приостановлено|возобновлено}."
CONSUMER_TOGGLED: "Обработка очереди потребителей была {приостановлено|возобновлено}."
CONTAINER_HEADER: "Контейнерные транзакции"
DATABASE_BUSY: "База данных занята. Пожалуйста, повторите попытку позже."
DATABASE_INDEX_ERROR: "Невозможно проверить индексы базы данных."
@@ -108,12 +111,12 @@ LOOKUP_INTERACTION: "{0} {нажал|убил} {1}."
LOOKUP_ITEM: "{0} {подобрал|выкинул} {1} {2}."
LOOKUP_LOGIN: "{0} {вошёл|вышел}."
LOOKUP_PAGE: "Страница {0}"
LOOKUP_PROJECTILE: "{0} {бросил|выстрелил} {1} {2}."
LOOKUP_ROWS_FOUND: "{0} {строка|строк} найдено."
LOOKUP_SEARCHING: "Ведётся поиск. Пожалуйста подождите..."
LOOKUP_STORAGE: "{0} {положил|забрал} {1} {2}."
LOOKUP_TIME: "{0} назад"
LOOKUP_USERNAME: "{0} зарегистрирован как {1}."
LOOKUP_VIEW_PAGE: "Чтобы просмотреть страницу, введите «{0}»."
MAXIMUM_RADIUS: "Максимальный радиус для {поиска|отката|восстановления} - {0}."
MISSING_ACTION_USER: "Чтобы использовать это действие, укажите пользователя."
MISSING_LOOKUP_TIME: "Пожалуйста, укажите количество времени, чтобы использовать {поиск|откат|восстановление}."
@@ -139,8 +142,8 @@ PATCH_UPGRADING: "Выполняется обновление базы данн
PLEASE_SELECT: "Пожалуйта выберете: «{0}» или «{1}»."
PREVIEW_CANCELLED: "Предварительный просмотр отменен."
PREVIEW_CANCELLING: "Отмена предварительного просмотра..."
PREVIEW_CONTAINER: "Вы не можете предварительно просмотреть контейнерные транзакции."
PREVIEW_IN_GAME: "Предварительный просмотр откатов доступен только в игре."
PREVIEW_TRANSACTION: "Вы не можете просмотреть {контейнер|инвентарь} транзакции."
PURGE_ABORTED: "Очистка не удалась. База данных может быть повреждена."
PURGE_ERROR: "Невозможно обработать данные {0}!"
PURGE_FAILED: "Очистка не удалась. Пожалуйста, повторите попытку позже."
@@ -189,9 +192,10 @@ UPDATE_HEADER: "{0} Обновление"
UPDATE_NOTICE: "Примечание: теперь доступен {0}."
UPGRADE_IN_PROGRESS: "Выполняется обновление. Пожалуйста, повторите попытку позже."
USER_NOT_FOUND: "Пользователь «{0}» не найден."
USER_OFFLINE: "Пользователь \"{0}\" нет в сети."
USING_MYSQL: "Для хранения данных используется MySQL."
USING_SQLITE: "Для хранения данных используется SQLite."
VALID_DONATION_KEY: "Действующий ключ пожертвования."
VERSION_NOTICE: "Версия {0} уже доступна!"
VERSION_REQUIRED: "{0} {1} или выше требуется."
WORLD_NOT_FOUND: "Мир «{0}» не найден."
WORLD_NOT_FOUND: "Мир «{0}» не найден."
+6 -2
View File
@@ -9,8 +9,11 @@ API_TEST: "Тест API успішний."
CACHE_ERROR: "УВАГА: Помилка під час перевірки {0} кеш."
CACHE_RELOAD: "Примусове перезавантаження {картографування|світу} кеші з бази даних."
CHECK_CONFIG: "Перевірте config.yml"
COMMAND_CONSOLE: "Будь ласка, запустіть команду з консолі."
COMMAND_NOT_FOUND: "Команда \"{0}\" не знайдено."
COMMAND_THROTTLED: "Зачекайте хвилину і повторіть спробу."
CONSUMER_ERROR: "Вже обробка черги споживачів {призупинено|відновлено}."
CONSUMER_TOGGLED: "Обробка черги споживачів була {призупинено|відновлено}."
CONTAINER_HEADER: "Контейнерні операції"
DATABASE_BUSY: "База даних зайнята. Будь-ласка спробуйте пізніше."
DATABASE_INDEX_ERROR: "Неможливо перевірити індекси бази даних."
@@ -108,12 +111,12 @@ LOOKUP_INTERACTION: "{0} {натиснув|убитий} {1}."
LOOKUP_ITEM: "{0} {взяв|скинув} {1} {2}."
LOOKUP_LOGIN: "{0} зареєстрований {в|з ~ ~}."
LOOKUP_PAGE: "Сторінка {0}"
LOOKUP_PROJECTILE: "{0} {кинув|постріл} {1} {2}."
LOOKUP_ROWS_FOUND: "{0} {рядок|рядки} знайдено."
LOOKUP_SEARCHING: "Пошук під час пошуку. Будь ласка, зачекайте..."
LOOKUP_STORAGE: "{0} {здано на зберігання|вилучено} {1} {2}."
LOOKUP_TIME: "{0} тому"
LOOKUP_USERNAME: "{0} Ви увійшли як {1}."
LOOKUP_VIEW_PAGE: "Щоб переглянути сторінку, введіть \"{0}\"."
MAXIMUM_RADIUS: "Максимум {пошук|відкат|відновлення} радіус дорівнює {0}."
MISSING_ACTION_USER: "Щоб використати цю дію, вкажіть користувача."
MISSING_LOOKUP_TIME: "Будь ласка, вкажіть час до {пошук|відкат|відновлення}."
@@ -139,8 +142,8 @@ PATCH_UPGRADING: "Триває оновлення бази даних. Будь
PLEASE_SELECT: "Виберіть будь ласка: \"{0}\" або \"{1}\"."
PREVIEW_CANCELLED: "Попередній перегляд скасовано."
PREVIEW_CANCELLING: "Скасування попереднього перегляду..."
PREVIEW_CONTAINER: "Ви не можете переглядати транзакційні контейнери."
PREVIEW_IN_GAME: "Попередній перегляд можна лише в грі."
PREVIEW_TRANSACTION: "Ви не можете попередньо переглянути {тару|інвентар} трансакцій."
PURGE_ABORTED: "Помилка очищення. Можливо, база даних пошкоджена."
PURGE_ERROR: "Не вдається обробити {0} дані!"
PURGE_FAILED: "Помилка очищення. Будь-ласка спробуйте пізніше."
@@ -189,6 +192,7 @@ UPDATE_HEADER: "{0} Оновлення"
UPDATE_NOTICE: "Примітка: {0} тепер доступний."
UPGRADE_IN_PROGRESS: "Оновлення триває. Будь-ласка спробуйте пізніше."
USER_NOT_FOUND: "Користувач \"{0}\" не знайдено."
USER_OFFLINE: "Користувач \"{0}\" не в мережі."
USING_MYSQL: "Використання MySQL для зберігання даних."
USING_SQLITE: "Використання SQLite для зберігання даних."
VALID_DONATION_KEY: "Дійсний ключ пожертви."
+6 -2
View File
@@ -9,8 +9,11 @@ API_TEST: "Kiểm tra API thành công."
CACHE_ERROR: "CẢNH BÁO: Lỗi khi xác thực {0} bộ nhớ đệm."
CACHE_RELOAD: "Buộc tải lại {lập bản đồ|thế giới} bộ nhớ đệm từ cơ sở dữ liệu."
CHECK_CONFIG: "Vui lòng kiểm tra config.yml"
COMMAND_CONSOLE: "Vui lòng chạy lệnh từ bảng điều khiển."
COMMAND_NOT_FOUND: "Yêu cầu \"{0}\" không tìm thấy."
COMMAND_THROTTLED: "Vui lòng đợi trong giây lát và thử lại."
CONSUMER_ERROR: "Đã xử lý hàng đợi của người tiêu dùng {bị tạm dừng|tiếp tục}."
CONSUMER_TOGGLED: "Xử lý hàng đợi của người tiêu dùng đã được {bị tạm dừng|tiếp tục}."
CONTAINER_HEADER: "Giao dịch vùng chứa"
DATABASE_BUSY: "Cơ sở dữ liệu bận rộn. Vui lòng thử lại sau."
DATABASE_INDEX_ERROR: "Không thể xác thực các chỉ mục cơ sở dữ liệu."
@@ -108,12 +111,12 @@ LOOKUP_INTERACTION: "{0} {đã nhấp vào|giết} {1}."
LOOKUP_ITEM: "{0} {nhặt lên|đánh rơi} {1} {2}."
LOOKUP_LOGIN: "{0} ghi nhật ký {vào|ra}."
LOOKUP_PAGE: "Trang {0}"
LOOKUP_PROJECTILE: "{0} {ném|bắn} {1} {2}."
LOOKUP_ROWS_FOUND: "{0} {hàng|hàng} tìm."
LOOKUP_SEARCHING: "Tra cứu tìm kiếm. Vui lòng chờ..."
LOOKUP_STORAGE: "{0} {ký gửi|rút tiền} {1} {2}."
LOOKUP_TIME: "{0} trước kia"
LOOKUP_USERNAME: "{0} đăng nhập với tư cách {1}."
LOOKUP_VIEW_PAGE: "Để xem một trang, hãy nhập \"{0}\"."
MAXIMUM_RADIUS: "Giá trị lớn nhất {tra cứu|khôi phục|khôi phục} bán kính là {0}."
MISSING_ACTION_USER: "Để sử dụng hành động đó, vui lòng chỉ định người dùng."
MISSING_LOOKUP_TIME: "Vui lòng xác định thời gian để {tra cứu|khôi phục|khôi phục}."
@@ -139,8 +142,8 @@ PATCH_UPGRADING: "Đang nâng cấp cơ sở dữ liệu. Vui lòng chờ..."
PLEASE_SELECT: "Xin hãy lựa chọn: \"{0}\" hoặc \"{1}\"."
PREVIEW_CANCELLED: "Đã hủy bản xem trước."
PREVIEW_CANCELLING: "Đang hủy bản xem trước..."
PREVIEW_CONTAINER: "Bạn không thể xem trước các giao dịch vùng chứa."
PREVIEW_IN_GAME: "Bạn chỉ có thể xem trước các lần quay lại trong trò chơi."
PREVIEW_TRANSACTION: "Bạn không thể xem trước {container|hàng tồn kho} các giao dịch."
PURGE_ABORTED: "Thanh trừng không thành công. Cơ sở dữ liệu có thể bị hỏng."
PURGE_ERROR: "Không thể xử lý {0} dữ liệu!"
PURGE_FAILED: "Thanh trừng không thành công. Vui lòng thử lại sau."
@@ -189,6 +192,7 @@ UPDATE_HEADER: "{0} Cập nhật"
UPDATE_NOTICE: "Lưu ý: {0} hiện đã có sẵn."
UPGRADE_IN_PROGRESS: "Đang nâng cấp. Vui lòng thử lại sau."
USER_NOT_FOUND: "Người sử dụng \"{0}\" không tìm thấy."
USER_OFFLINE: "Người dùng \"{0}\" không trực tuyến."
USING_MYSQL: "Sử dụng MySQL để lưu trữ dữ liệu."
USING_SQLITE: "Sử dụng SQLite để lưu trữ dữ liệu."
VALID_DONATION_KEY: "Chìa khóa quyên góp hợp lệ."
+8 -4
View File
@@ -10,8 +10,11 @@ API_TEST: "API 测试成功。"
CACHE_ERROR: "警告: 验证缓存 {0} 时出错。"
CACHE_RELOAD: "正在强制从数据库中重新加载{映射|世界}的缓存。"
CHECK_CONFIG: "请检查 config.yml 文件"
COMMAND_CONSOLE: "请从控制台运行命令。"
COMMAND_NOT_FOUND: "找不到命令 \"{0}\""
COMMAND_THROTTLED: "请稍等片刻,然后重试。"
CONSUMER_ERROR: "消费者队列处理已经 {暂停|继续}."
CONSUMER_TOGGLED: "消费者队列处理已 {暂停|继续}."
CONTAINER_HEADER: "容器物品变更记录"
DATABASE_BUSY: "数据库繁忙,请稍后重试。"
DATABASE_INDEX_ERROR: "无法验证数据库索引。"
@@ -39,7 +42,7 @@ HELP_EXCLUDE_2: "例子: [e:stone], [e:Notch], [e:stone,Notch]"
HELP_HEADER: "{0} 帮助"
HELP_INCLUDE_1: "包括方块/实体。"
HELP_INCLUDE_2: "例子: [i:stone], [i:zombie], [i:stone,wood,bedrock]"
HELP_INSPECT_1: "启用检查器后,你可以: "
HELP_INSPECT_1: "启用检查器后,你可以:"
HELP_INSPECT_2: "左键单击以查看方块放置记录。"
HELP_INSPECT_3: "右键单击以查看相邻方块破坏记录。"
HELP_INSPECT_4: "放置一个方块以查看放置位置的破坏记录。"
@@ -109,12 +112,12 @@ LOOKUP_INTERACTION: "{0} {点击|击杀} {1}."
LOOKUP_ITEM: "{0} {拾起|丢弃} {1} {2}."
LOOKUP_LOGIN: "{0} {登入|离开}."
LOOKUP_PAGE: "第 {0} 页"
LOOKUP_PROJECTILE: "{0} {扔|射} {1} {2}."
LOOKUP_ROWS_FOUND: "已找到 {0}{行|行}。"
LOOKUP_SEARCHING: "正在搜索,请稍等..."
LOOKUP_STORAGE: "{0} {放入|取出} {1} {2}."
LOOKUP_TIME: "{0} 前"
LOOKUP_USERNAME: "{0} 已登入为 {1}."
LOOKUP_VIEW_PAGE: "查看指定操作记录,请输入\"{0}\"。"
MAXIMUM_RADIUS: "最大{查找|回滚|恢复}半径是 {0}."
MISSING_ACTION_USER: "要使用该标识符,请指定玩家名。"
MISSING_LOOKUP_TIME: "请指定{查找|回滚|恢复}时间."
@@ -140,8 +143,8 @@ PATCH_UPGRADING: "正在进行数据库升级,请稍等..."
PLEASE_SELECT: "请选择: \"{0}\"或\"{1}\"。"
PREVIEW_CANCELLED: "预览已取消。"
PREVIEW_CANCELLING: "正在取消预览..."
PREVIEW_CONTAINER: "你无法预览容器的存入取出操作。"
PREVIEW_IN_GAME: "你只能在游戏中预览回滚操作。"
PREVIEW_TRANSACTION: "您无法预览 {集装箱|库存} 交易。"
PURGE_ABORTED: "清除失败,数据库可能已损坏。"
PURGE_ERROR: "无法处理 {0} 数据!"
PURGE_FAILED: "数据清除失败,请稍后再试。"
@@ -190,9 +193,10 @@ UPDATE_HEADER: "{0} 更新"
UPDATE_NOTICE: "注意: {0} 现在可用。"
UPGRADE_IN_PROGRESS: "正在进行升级,请稍后再试。"
USER_NOT_FOUND: "玩家\"{0}\"未找到。"
USER_OFFLINE: "用户 \"{0}\"不在线。"
USING_MYSQL: "使用 MySQL 用于数据存储。"
USING_SQLITE: "使用 SQLite 用于数据存储。"
VALID_DONATION_KEY: "有效的捐赠密钥。"
VERSION_NOTICE: "版本 {0} 现在可用。"
VERSION_REQUIRED: "{0} 需要使用 {1} 或更高版本。"
WORLD_NOT_FOUND: "找不到世界 \"{0}\"。"
WORLD_NOT_FOUND: "找不到世界 \"{0}\"。"
+9 -5
View File
@@ -10,8 +10,11 @@ API_TEST: "API 測試成功。"
CACHE_ERROR: "警告: 驗證快取 {0} 時出現錯誤。"
CACHE_RELOAD: "正在強制從資料庫中重新載入{鏡像|世界}快取。"
CHECK_CONFIG: "請檢查 config.yml 檔案。"
COMMAND_CONSOLE: "請從控制台運行命令。"
COMMAND_NOT_FOUND: "未知的指令 \"{0}\"。"
COMMAND_THROTTLED: "請稍後再試。"
CONSUMER_ERROR: "消費者隊列處理已經 {暫停|繼續}."
CONSUMER_TOGGLED: "消費者隊列處理已 {暫停|繼續}."
CONTAINER_HEADER: "儲存容器變更記錄。"
DATABASE_BUSY: "資料庫繁忙,請稍後再試。"
DATABASE_INDEX_ERROR: "無法驗證資料庫索引。"
@@ -39,7 +42,7 @@ HELP_EXCLUDE_2: "範例: [e:stone], [e:Notch], [e:stone,Notch]"
HELP_HEADER: "{0} 說明"
HELP_INCLUDE_1: "包括指定的方塊/實體"
HELP_INCLUDE_2: "範例: [i:stone], [i:zombie], [i:stone,wood,bedrock]"
HELP_INSPECT_1: "當檢查器啟用後,你可以執行以下操作: "
HELP_INSPECT_1: "當檢查器啟用後,你可以執行以下操作:"
HELP_INSPECT_2: "對你欲查詢的方塊點擊左鍵,可以查看方塊放置記錄。"
HELP_INSPECT_3: "對你欲查詢的方塊點擊右鍵,可以查看相鄰方塊破壞記錄。"
HELP_INSPECT_4: "對你欲查詢的位置放置方塊,可以查看放置位置破壞記錄。"
@@ -109,12 +112,12 @@ LOOKUP_INTERACTION: "{0} {點擊|殺死} {1}。"
LOOKUP_ITEM: "{0} {撿起|拋棄} {1} {2}。"
LOOKUP_LOGIN: "{0} 已登{入|出}。"
LOOKUP_PAGE: "第 {0} 頁"
LOOKUP_PROJECTILE: "{0} {扔|射} {1} {2}."
LOOKUP_ROWS_FOUND: "已找到 {0} {行|行}。"
LOOKUP_SEARCHING: "正在搜尋,請稍候……"
LOOKUP_STORAGE: "{0} {存|取} {1} {2}。"
LOOKUP_TIME: "{0} 前"
LOOKUP_USERNAME: "{0} 以 {1} 的身分登入。"
LOOKUP_VIEW_PAGE: "若要查看指定頁面,請輸入 \"{0}\"。"
MAXIMUM_RADIUS: "最大 {查詢|回滾|恢復} 的範圍為 {0}。"
MISSING_ACTION_USER: "若要使用此操作,請指定玩家。"
MISSING_LOOKUP_TIME: "請指定{查詢|回滾|恢復}的時間範圍。"
@@ -140,8 +143,8 @@ PATCH_UPGRADING: "正在進行資料庫升級,請稍候……"
PLEASE_SELECT: "請選擇: \"{0}\" 或是 \"{1}\"。"
PREVIEW_CANCELLED: "預覽已取消。"
PREVIEW_CANCELLING: "正在取消預覽……"
PREVIEW_CONTAINER: "你無法預覽容器內的物品資料。"
PREVIEW_IN_GAME: "你只能在遊戲中預覽回滾。"
PREVIEW_TRANSACTION: "您無法預覽 {集裝箱|庫存} 交易。"
PURGE_ABORTED: "清除失敗,你的資料可能已損毀。"
PURGE_ERROR: "無法處理 {0} 條資料 !"
PURGE_FAILED: "清除失敗,請稍後再試。"
@@ -190,9 +193,10 @@ UPDATE_HEADER: "{0} 更新"
UPDATE_NOTICE: "通知: {0} 現已推出。"
UPGRADE_IN_PROGRESS: "正在進行更新,請稍後再試。"
USER_NOT_FOUND: "找不到玩家 \"{0}\"。"
USER_OFFLINE: "用戶 \"{0}\"不在線。"
USING_MYSQL: "使用 MySQL 進行資料儲存。"
USING_SQLITE: "使用 SQLite 進行資料儲存。"
VALID_DONATION_KEY: "有效的贈品金鑰"
VERSION_NOTICE: "版本 {0} 現已推出。"
VERSION_REQUIRED: "{0} 需要使用 {1} 或更高版本。 "
WORLD_NOT_FOUND: "世界: \"{0}\" 不存在。"
VERSION_REQUIRED: "{0} 需要使用 {1} 或更高版本。"
WORLD_NOT_FOUND: "世界: \"{0}\" 不存在。"
+1 -1
View File
@@ -4,4 +4,4 @@ theme: readthedocs
repo_url: https://github.com/PlayPro/CoreProtect
docs_dir: 'docs'
extra_css:
- css/extra.css
- css/extra.css
+4 -4
View File
@@ -2,7 +2,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>net.coreprotect</groupId>
<artifactId>CoreProtect</artifactId>
<version>20.4</version>
<version>21.0</version>
<properties>
<project.branch></project.branch>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@@ -25,8 +25,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
<plugin>
@@ -94,7 +94,7 @@
<dependency>
<groupId>io.papermc.paper</groupId>
<artifactId>paper-api</artifactId>
<version>1.17-R0.1-SNAPSHOT</version>
<version>1.18.1-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
@@ -4,6 +4,7 @@ import java.io.File;
import org.bstats.bukkit.MetricsLite;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
@@ -17,6 +18,8 @@ import net.coreprotect.database.Database;
import net.coreprotect.language.Language;
import net.coreprotect.language.Phrase;
import net.coreprotect.listener.ListenerHandler;
import net.coreprotect.listener.player.PlayerQuitListener;
import net.coreprotect.paper.PaperAdapter;
import net.coreprotect.thread.CacheHandler;
import net.coreprotect.thread.NetworkHandler;
import net.coreprotect.utility.Chat;
@@ -158,6 +161,13 @@ public final class CoreProtect extends JavaPlugin {
private static void safeShutdown(CoreProtect plugin) {
try {
/* if server is stopping, log disconnections of online players */
if (PaperAdapter.ADAPTER.isStopping(plugin.getServer())) {
for (Player player : plugin.getServer().getOnlinePlayers()) {
PlayerQuitListener.queuePlayerQuit(player);
}
}
ConfigHandler.serverRunning = false;
long shutdownTime = System.currentTimeMillis();
long alertTime = shutdownTime + (10 * 1000);
@@ -3,8 +3,10 @@ package net.coreprotect;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Location;
@@ -16,12 +18,14 @@ import org.bukkit.block.data.BlockData;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import net.coreprotect.api.BlockAPI;
import net.coreprotect.api.QueueLookup;
import net.coreprotect.api.SessionLookup;
import net.coreprotect.config.Config;
import net.coreprotect.consumer.Queue;
import net.coreprotect.database.Database;
import net.coreprotect.database.Lookup;
import net.coreprotect.database.Rollback;
import net.coreprotect.database.lookup.BlockLookupAPI;
import net.coreprotect.language.Phrase;
import net.coreprotect.listener.player.InventoryChangeListener;
import net.coreprotect.utility.Chat;
@@ -42,8 +46,18 @@ public class CoreProtectAPI extends Queue {
public String getActionString() {
int actionID = Integer.parseInt(parse[7]);
String result = "unknown";
if (parse.length < 13 && Integer.parseInt(parse[6]) == SessionLookup.ID) {
switch (actionID) {
case 0:
return "logout";
case 1:
return "login";
default:
return "unknown";
}
}
String result = "unknown";
if (actionID == 0) {
result = "break";
}
@@ -79,6 +93,10 @@ public class CoreProtectAPI extends Queue {
}
public Material getType() {
if (parse.length < 13) {
return null;
}
int actionID = this.getActionId();
int type = Integer.parseInt(parse[5]);
String typeName;
@@ -95,8 +113,12 @@ public class CoreProtectAPI extends Queue {
}
public BlockData getBlockData() {
if (parse.length < 13) {
return null;
}
String blockData = parse[12];
if (blockData.length() == 0) {
if (blockData == null || blockData.length() == 0) {
return getType().createBlockData();
}
return Bukkit.getServer().createBlockData(blockData);
@@ -115,25 +137,29 @@ public class CoreProtectAPI extends Queue {
}
public boolean isRolledBack() {
return Integer.parseInt(parse[8]) == 1;
if (parse.length < 13) {
return false;
}
return (Integer.parseInt(parse[8]) == 1 || Integer.parseInt(parse[8]) == 3);
}
public String worldName() {
return Util.getWorldName(Integer.parseInt(parse[9]));
return Util.getWorldName(Integer.parseInt(parse.length < 13 ? parse[5] : parse[9]));
}
}
private static List<Object> parseList(List<Object> list) {
List<Object> result = new ArrayList<>();
private static Map<Object, Boolean> parseList(List<Object> list) {
Map<Object, Boolean> result = new HashMap<>();
if (list != null) {
for (Object value : list) {
if (value instanceof Material || value instanceof EntityType) {
result.add(value);
result.put(value, false);
}
else if (value instanceof Integer) {
Material material = Util.getType((Integer) value);
result.add(material);
result.put(material, false);
}
}
}
@@ -142,16 +168,24 @@ public class CoreProtectAPI extends Queue {
}
public int APIVersion() {
return 8;
return 9;
}
public List<String[]> blockLookup(Block block, int time) {
if (Config.getGlobal().API_ENABLED) {
return BlockLookupAPI.performLookup(block, time);
return BlockAPI.performLookup(block, time);
}
return null;
}
public List<String[]> queueLookup(Block block) {
return QueueLookup.performLookup(block);
}
public List<String[]> sessionLookup(String user, int time) {
return SessionLookup.performLookup(user, time);
}
public boolean hasPlaced(String user, Block block, int time, int offset) {
// Determine if a user has placed a block at this location in the last # of seconds.
boolean match = false;
@@ -232,7 +266,7 @@ public class CoreProtectAPI extends Queue {
if (Config.getGlobal().API_ENABLED) {
if (user != null && location != null) {
if (user.length() > 0) {
Queue.queuePlayerInteraction(user, location.getBlock().getState());
Queue.queuePlayerInteraction(user, location.getBlock().getState(), location.getBlock().getType());
return true;
}
}
@@ -385,7 +419,7 @@ public class CoreProtectAPI extends Queue {
return null;
}
private List<String[]> processData(int time, int radius, Location location, List<Object> restrictBlocks, List<Object> excludeBlocks, List<String> restrictUsers, List<String> excludeUsers, List<Integer> actionList, int action, int lookup, int offset, int rowCount, boolean useLimit) {
private List<String[]> processData(int time, int radius, Location location, Map<Object, Boolean> restrictBlocksMap, Map<Object, Boolean> excludeBlocks, List<String> restrictUsers, List<String> excludeUsers, List<Integer> actionList, int action, int lookup, int offset, int rowCount, boolean useLimit) {
// You need to either specify time/radius or time/user
List<String[]> result = new ArrayList<>();
List<String> uuids = new ArrayList<>();
@@ -402,6 +436,7 @@ public class CoreProtectAPI extends Queue {
actionList = new ArrayList<>();
}
List<Object> restrictBlocks = new ArrayList<>(restrictBlocksMap.keySet());
if (actionList.size() == 0 && restrictBlocks.size() > 0) {
boolean addedMaterial = false;
boolean addedEntity = false;
@@ -431,7 +466,8 @@ public class CoreProtectAPI extends Queue {
}
long timestamp = System.currentTimeMillis() / 1000L;
long timePeriod = timestamp - time;
long startTime = timestamp - time;
long endTime = 0;
if (radius < 1) {
radius = -1;
@@ -473,16 +509,16 @@ public class CoreProtectAPI extends Queue {
}
if (useLimit) {
result = Lookup.performPartialLookup(statement, null, uuids, restrictUsers, restrictBlocks, excludeBlocks, excludeUsers, actionList, location, argRadius, timePeriod, offset, rowCount, restrictWorld, true);
result = Lookup.performPartialLookup(statement, null, uuids, restrictUsers, restrictBlocks, excludeBlocks, excludeUsers, actionList, location, argRadius, null, startTime, endTime, offset, rowCount, restrictWorld, true);
}
else {
result = Lookup.performLookup(statement, null, uuids, restrictUsers, restrictBlocks, excludeBlocks, excludeUsers, actionList, location, argRadius, timePeriod, restrictWorld, true);
result = Lookup.performLookup(statement, null, uuids, restrictUsers, restrictBlocks, excludeBlocks, excludeUsers, actionList, location, argRadius, startTime, endTime, restrictWorld, true);
}
}
else {
if (!Bukkit.isPrimaryThread()) {
boolean verbose = false;
result = Rollback.performRollbackRestore(statement, null, uuids, restrictUsers, null, restrictBlocks, excludeBlocks, excludeUsers, actionList, location, argRadius, timePeriod, restrictWorld, false, verbose, action, 0);
result = Rollback.performRollbackRestore(statement, null, uuids, restrictUsers, null, restrictBlocks, excludeBlocks, excludeUsers, actionList, location, argRadius, startTime, endTime, restrictWorld, false, verbose, action, 0);
}
}
@@ -497,7 +533,7 @@ public class CoreProtectAPI extends Queue {
}
@Deprecated
private List<String[]> processData(String user, int time, int radius, Location location, List<Object> restrictBlocks, List<Object> excludeBlocks, int action, int lookup, int offset, int rowCount, boolean useLimit) {
private List<String[]> processData(String user, int time, int radius, Location location, Map<Object, Boolean> restrictBlocks, Map<Object, Boolean> excludeBlocks, int action, int lookup, int offset, int rowCount, boolean useLimit) {
ArrayList<String> restrictUsers = new ArrayList<>();
if (user != null) {
restrictUsers.add(user);
@@ -1,4 +1,4 @@
package net.coreprotect.database.lookup;
package net.coreprotect.api;
import java.sql.Connection;
import java.sql.ResultSet;
@@ -13,7 +13,7 @@ import net.coreprotect.database.Database;
import net.coreprotect.database.statement.UserStatement;
import net.coreprotect.utility.Util;
public class BlockLookupAPI {
public class BlockAPI {
public static List<String[]> performLookup(Block block, int offset) {
List<String[]> result = new ArrayList<>();
@@ -38,7 +38,7 @@ public class BlockLookupAPI {
}
Statement statement = connection.createStatement();
String query = "SELECT time,user,action,type,data,blockdata,rolled_back FROM " + ConfigHandler.prefix + "block WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND time > '" + checkTime + "' ORDER BY rowid DESC";
String query = "SELECT time,user,action,type,data,blockdata,rolled_back FROM " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND time > '" + checkTime + "' ORDER BY rowid DESC";
ResultSet results = statement.executeQuery(query);
while (results.next()) {
@@ -0,0 +1,85 @@
package net.coreprotect.api;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import net.coreprotect.config.Config;
import net.coreprotect.consumer.Consumer;
import net.coreprotect.consumer.Queue;
import net.coreprotect.consumer.process.Process;
import net.coreprotect.utility.Util;
public class QueueLookup extends Queue {
private QueueLookup() {
throw new IllegalStateException("API class");
}
public static List<String[]> performLookup(Block block) {
List<String[]> result = new ArrayList<>();
if (!Config.getGlobal().API_ENABLED) {
return result;
}
try {
int consumerCount = 0;
int currentConsumerSize = Process.getCurrentConsumerSize();
if (currentConsumerSize == 0) {
consumerCount = Consumer.getConsumerSize(0) + Consumer.getConsumerSize(1);
}
else {
int consumerId = (Consumer.currentConsumer == 1) ? 1 : 0;
consumerCount = Consumer.getConsumerSize(consumerId) + currentConsumerSize;
}
if (consumerCount == 0) {
return result;
}
int currentConsumer = Consumer.currentConsumer;
ArrayList<Object[]> consumerData = Consumer.consumer.get(currentConsumer);
Map<Integer, String[]> users = Consumer.consumerUsers.get(currentConsumer);
Map<Integer, Object> consumerObject = Consumer.consumerObjects.get(currentConsumer);
Location oldLocation = block.getLocation();
for (Object[] data : consumerData) {
int id = (int) data[0];
int action = (int) data[1];
if (action != Process.BLOCK_BREAK && action != Process.BLOCK_PLACE) {
continue;
}
String[] userData = users.get(id);
Object objectData = consumerObject.get(id);
if (userData != null && objectData != null && (objectData instanceof BlockState) && ((BlockState) objectData).getLocation().equals(oldLocation)) {
Material blockType = (Material) data[2];
int legacyData = (int) data[3];
String blockData = (String) data[7];
String user = userData[0];
BlockState blockState = (BlockState) objectData;
Location location = blockState.getLocation();
int wid = Util.getWorldId(location.getWorld().getName());
int resultType = Util.getBlockId(blockType);
int time = (int) (System.currentTimeMillis() / 1000L);
String[] lookupData = new String[] { String.valueOf(time), user, String.valueOf(location.getBlockX()), String.valueOf(location.getBlockY()), String.valueOf(location.getBlockZ()), String.valueOf(resultType), String.valueOf(legacyData), String.valueOf(action), "0", String.valueOf(wid), blockData };
String[] lineData = Util.toStringArray(lookupData);
result.add(lineData);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
@@ -0,0 +1,76 @@
package net.coreprotect.api;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import net.coreprotect.config.Config;
import net.coreprotect.config.ConfigHandler;
import net.coreprotect.database.Database;
import net.coreprotect.database.statement.UserStatement;
public class SessionLookup {
public static final int ID = 0;
private SessionLookup() {
throw new IllegalStateException("API class");
}
public static List<String[]> performLookup(String user, int offset) {
List<String[]> result = new ArrayList<>();
if (!Config.getGlobal().API_ENABLED) {
return result;
}
try (Connection connection = Database.getConnection(false, 1000)) {
if (connection == null || user == null) {
return result;
}
String type = String.valueOf(ID);
int time = (int) (System.currentTimeMillis() / 1000L);
int checkTime = 0;
if (offset > 0) {
checkTime = time - offset;
}
if (ConfigHandler.playerIdCache.get(user.toLowerCase(Locale.ROOT)) == null) {
UserStatement.loadId(connection, user, null);
}
int userId = ConfigHandler.playerIdCache.get(user.toLowerCase(Locale.ROOT));
try (Statement statement = connection.createStatement()) {
String query = "SELECT time,user,wid,x,y,z,action FROM " + ConfigHandler.prefix + "session WHERE user = '" + userId + "' AND time > '" + checkTime + "' ORDER BY rowid DESC";
ResultSet results = statement.executeQuery(query);
while (results.next()) {
String resultTime = results.getString("time");
int resultUserId = results.getInt("user");
String resultWorldId = results.getString("wid");
String resultX = results.getString("x");
String resultY = results.getString("y");
String resultZ = results.getString("z");
String resultAction = results.getString("action");
if (ConfigHandler.playerIdCacheReversed.get(resultUserId) == null) {
UserStatement.loadName(connection, resultUserId);
}
String resultUser = ConfigHandler.playerIdCacheReversed.get(resultUserId);
String[] lookupData = new String[] { resultTime, resultUser, resultX, resultY, resultZ, resultWorldId, type, resultAction };
result.add(lookupData);
}
results.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
@@ -10,10 +10,12 @@ import org.bukkit.block.Sign;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Directional;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.MerchantRecipe;
import org.bukkit.inventory.meta.ItemMeta;
import net.coreprotect.config.ConfigHandler;
@@ -42,9 +44,11 @@ public class BukkitAdapter implements BukkitInterface {
BukkitAdapter.ADAPTER = new Bukkit_v1_16();
break;
case BUKKIT_V1_17:
BukkitAdapter.ADAPTER = new Bukkit_v1_17();
break;
case BUKKIT_V1_18:
default:
BukkitAdapter.ADAPTER = new Bukkit_v1_17();
BukkitAdapter.ADAPTER = new Bukkit_v1_18();
break;
}
}
@@ -118,6 +122,11 @@ public class BukkitAdapter implements BukkitInterface {
return Material.ITEM_FRAME;
}
@Override
public Material getFrameType(EntityType type) {
return type == EntityType.ITEM_FRAME ? Material.ITEM_FRAME : null;
}
@Override
public Class<?> getFrameClass(Material material) {
return ItemFrame.class;
@@ -138,4 +147,9 @@ public class BukkitAdapter implements BukkitInterface {
return Util.isAir(material);
}
@Override
public ItemStack adjustIngredient(MerchantRecipe recipe, ItemStack itemStack) {
return null;
}
}
@@ -9,17 +9,23 @@ import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.MerchantRecipe;
import org.bukkit.inventory.meta.ItemMeta;
public interface BukkitInterface {
public ItemStack adjustIngredient(MerchantRecipe recipe, ItemStack itemStack);
public Material getBucketContents(Material material);
public Material getFrameType(Entity entity);
public Material getFrameType(EntityType type);
public Class<?> getFrameClass(Material material);
public String parseLegacyName(String name);
@@ -31,7 +31,7 @@ public class Bukkit_v1_16 extends Bukkit_v1_15 implements BukkitInterface {
BlockGroup.FIRE = new HashSet<>(Arrays.asList(Material.FIRE, Material.SOUL_FIRE));
BlockGroup.LANTERNS = new HashSet<>(Arrays.asList(Material.LANTERN, Material.SOUL_LANTERN));
BlockGroup.SOUL_BLOCKS = new HashSet<>(Arrays.asList(Material.SOUL_SAND, Material.SOUL_SOIL));
BlockGroup.INTERACT_BLOCKS = new HashSet<>(Arrays.asList(Material.SPRUCE_FENCE_GATE, Material.BIRCH_FENCE_GATE, Material.JUNGLE_FENCE_GATE, Material.DARK_OAK_FENCE_GATE, Material.ACACIA_FENCE_GATE, Material.DISPENSER, Material.NOTE_BLOCK, Material.CHEST, Material.FURNACE, Material.LEVER, Material.REPEATER, Material.ACACIA_TRAPDOOR, Material.BIRCH_TRAPDOOR, Material.DARK_OAK_TRAPDOOR, Material.JUNGLE_TRAPDOOR, Material.SPRUCE_TRAPDOOR, Material.OAK_TRAPDOOR, Material.OAK_FENCE_GATE, Material.BREWING_STAND, Material.ANVIL, Material.CHIPPED_ANVIL, Material.DAMAGED_ANVIL, Material.ENDER_CHEST, Material.TRAPPED_CHEST, Material.COMPARATOR, Material.HOPPER, Material.DROPPER, Material.SHULKER_BOX, Material.BLACK_SHULKER_BOX, Material.BLUE_SHULKER_BOX, Material.BROWN_SHULKER_BOX, Material.CYAN_SHULKER_BOX, Material.GRAY_SHULKER_BOX, Material.GREEN_SHULKER_BOX, Material.LIGHT_BLUE_SHULKER_BOX, Material.LIME_SHULKER_BOX, Material.MAGENTA_SHULKER_BOX, Material.ORANGE_SHULKER_BOX, Material.PINK_SHULKER_BOX, Material.PURPLE_SHULKER_BOX, Material.RED_SHULKER_BOX, Material.LIGHT_GRAY_SHULKER_BOX, Material.WHITE_SHULKER_BOX, Material.YELLOW_SHULKER_BOX, Material.BARREL, Material.BLAST_FURNACE, Material.GRINDSTONE, Material.LOOM, Material.SMOKER, Material.CARTOGRAPHY_TABLE, Material.CRIMSON_FENCE_GATE, Material.WARPED_FENCE_GATE, Material.CRIMSON_TRAPDOOR, Material.WARPED_TRAPDOOR));
BlockGroup.INTERACT_BLOCKS = new HashSet<>(Arrays.asList(Material.SPRUCE_FENCE_GATE, Material.BIRCH_FENCE_GATE, Material.JUNGLE_FENCE_GATE, Material.DARK_OAK_FENCE_GATE, Material.ACACIA_FENCE_GATE, Material.DISPENSER, Material.NOTE_BLOCK, Material.CHEST, Material.FURNACE, Material.LEVER, Material.REPEATER, Material.ACACIA_TRAPDOOR, Material.BIRCH_TRAPDOOR, Material.DARK_OAK_TRAPDOOR, Material.JUNGLE_TRAPDOOR, Material.SPRUCE_TRAPDOOR, Material.OAK_TRAPDOOR, Material.OAK_FENCE_GATE, Material.BREWING_STAND, Material.ANVIL, Material.CHIPPED_ANVIL, Material.DAMAGED_ANVIL, Material.ENDER_CHEST, Material.TRAPPED_CHEST, Material.COMPARATOR, Material.HOPPER, Material.DROPPER, Material.SHULKER_BOX, Material.BLACK_SHULKER_BOX, Material.BLUE_SHULKER_BOX, Material.BROWN_SHULKER_BOX, Material.CYAN_SHULKER_BOX, Material.GRAY_SHULKER_BOX, Material.GREEN_SHULKER_BOX, Material.LIGHT_BLUE_SHULKER_BOX, Material.LIME_SHULKER_BOX, Material.MAGENTA_SHULKER_BOX, Material.ORANGE_SHULKER_BOX, Material.PINK_SHULKER_BOX, Material.PURPLE_SHULKER_BOX, Material.RED_SHULKER_BOX, Material.LIGHT_GRAY_SHULKER_BOX, Material.WHITE_SHULKER_BOX, Material.YELLOW_SHULKER_BOX, Material.BARREL, Material.BLAST_FURNACE, Material.GRINDSTONE, Material.LOOM, Material.SMOKER, Material.CRAFTING_TABLE, Material.CARTOGRAPHY_TABLE, Material.ENCHANTING_TABLE, Material.SMITHING_TABLE, Material.STONECUTTER, Material.CRIMSON_FENCE_GATE, Material.WARPED_FENCE_GATE, Material.CRIMSON_TRAPDOOR, Material.WARPED_TRAPDOOR));
BlockGroup.SAFE_INTERACT_BLOCKS = new HashSet<>(Arrays.asList(Material.LEVER, Material.ACACIA_TRAPDOOR, Material.BIRCH_TRAPDOOR, Material.DARK_OAK_TRAPDOOR, Material.JUNGLE_TRAPDOOR, Material.SPRUCE_TRAPDOOR, Material.OAK_TRAPDOOR, Material.OAK_FENCE_GATE, Material.SPRUCE_FENCE_GATE, Material.BIRCH_FENCE_GATE, Material.JUNGLE_FENCE_GATE, Material.DARK_OAK_FENCE_GATE, Material.ACACIA_FENCE_GATE, Material.CRIMSON_FENCE_GATE, Material.WARPED_FENCE_GATE, Material.CRIMSON_TRAPDOOR, Material.WARPED_TRAPDOOR));
BlockGroup.UPDATE_STATE = new HashSet<>(Arrays.asList(Material.TORCH, Material.WALL_TORCH, Material.REDSTONE_WIRE, Material.RAIL, Material.POWERED_RAIL, Material.DETECTOR_RAIL, Material.FURNACE, Material.BLAST_FURNACE, Material.SMOKER, Material.LEVER, Material.REDSTONE_TORCH, Material.REDSTONE_WALL_TORCH, Material.GLOWSTONE, Material.JACK_O_LANTERN, Material.REPEATER, Material.REDSTONE_LAMP, Material.BEACON, Material.COMPARATOR, Material.DAYLIGHT_DETECTOR, Material.REDSTONE_BLOCK, Material.HOPPER, Material.CHEST, Material.TRAPPED_CHEST, Material.ACTIVATOR_RAIL, Material.SOUL_TORCH, Material.SOUL_WALL_TORCH, Material.SHROOMLIGHT, Material.RESPAWN_ANCHOR, Material.CRYING_OBSIDIAN, Material.TARGET));
BlockGroup.NON_ATTACHABLE = new HashSet<>(Arrays.asList(Material.AIR, Material.CAVE_AIR, Material.BARRIER, Material.CORNFLOWER, Material.LILY_OF_THE_VALLEY, Material.WITHER_ROSE, Material.SWEET_BERRY_BUSH, Material.OAK_SAPLING, Material.SPRUCE_SAPLING, Material.BIRCH_SAPLING, Material.JUNGLE_SAPLING, Material.ACACIA_SAPLING, Material.DARK_OAK_SAPLING, Material.WATER, Material.LAVA, Material.POWERED_RAIL, Material.DETECTOR_RAIL, Material.GRASS, Material.FERN, Material.DEAD_BUSH, Material.DANDELION, Material.POPPY, Material.BLUE_ORCHID, Material.ALLIUM, Material.AZURE_BLUET, Material.RED_TULIP, Material.ORANGE_TULIP, Material.WHITE_TULIP, Material.PINK_TULIP, Material.OXEYE_DAISY, Material.BROWN_MUSHROOM, Material.RED_MUSHROOM, Material.TORCH, Material.WALL_TORCH, Material.REDSTONE_WIRE, Material.LADDER, Material.RAIL, Material.LEVER, Material.REDSTONE_TORCH, Material.REDSTONE_WALL_TORCH, Material.SNOW, Material.SUGAR_CANE, Material.NETHER_PORTAL, Material.REPEATER, Material.KELP, Material.CHORUS_FLOWER, Material.CHORUS_PLANT, Material.SOUL_TORCH, Material.SOUL_WALL_TORCH));
@@ -15,6 +15,7 @@ import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.type.PointedDripstone;
import org.bukkit.entity.Axolotl;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.GlowItemFrame;
import org.bukkit.entity.Goat;
import org.bukkit.entity.ItemFrame;
@@ -122,7 +123,7 @@ public class Bukkit_v1_17 extends Bukkit_v1_16 implements BukkitInterface {
if (subMeta.hasItems()) {
list = new ArrayList<>();
for (ItemStack itemStack : subMeta.getItems()) {
Map<String, Object> itemMap = Util.serializeItemStack(itemStack, slot);
Map<String, Object> itemMap = Util.serializeItemStack(itemStack, null, slot);
if (itemMap.size() > 0) {
list.add(itemMap);
}
@@ -199,6 +200,18 @@ public class Bukkit_v1_17 extends Bukkit_v1_16 implements BukkitInterface {
return (entity instanceof GlowItemFrame) ? Material.GLOW_ITEM_FRAME : Material.ITEM_FRAME;
}
@Override
public Material getFrameType(EntityType type) {
switch (type) {
case ITEM_FRAME:
return Material.ITEM_FRAME;
case GLOW_ITEM_FRAME:
return Material.GLOW_ITEM_FRAME;
default:
return null;
}
}
@Override
public Class<?> getFrameClass(Material material) {
return (material == Material.GLOW_ITEM_FRAME) ? GlowItemFrame.class : ItemFrame.class;
@@ -0,0 +1,31 @@
package net.coreprotect.bukkit;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.MerchantRecipe;
public class Bukkit_v1_18 extends Bukkit_v1_17 implements BukkitInterface {
private Boolean hasAdjust = null;
@Override
public ItemStack adjustIngredient(MerchantRecipe recipe, ItemStack itemStack) {
try {
if (hasAdjust == null) {
hasAdjust = true;
MerchantRecipe.class.getMethod("adjust", ItemStack.class); // Bukkit 1.18.1+
}
else if (Boolean.FALSE.equals(hasAdjust)) {
return null;
}
ItemStack adjustedStack = itemStack.clone();
recipe.adjust(adjustedStack);
return adjustedStack;
}
catch (Exception e) {
hasAdjust = false;
return null;
}
}
}
@@ -17,9 +17,10 @@ public class ApplyCommand {
try {
if (ConfigHandler.lastRollback.get(user.getName()) != null) {
List<Object> list = ConfigHandler.lastRollback.get(user.getName());
long time = (Long) list.get(0);
args = (String[]) list.get(1);
Location location = (Location) list.get(2);
long startTime = (Long) list.get(0);
long endTime = (Long) list.get(1);
args = (String[]) list.get(2);
Location location = (Location) list.get(3);
boolean valid = false;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("#preview")) {
@@ -32,7 +33,7 @@ public class ApplyCommand {
}
else {
ConfigHandler.lastRollback.remove(user.getName());
RollbackRestoreCommand.runCommand(user, command, permission, args, location, time);
RollbackRestoreCommand.runCommand(user, command, permission, args, location, startTime, endTime);
}
}
else {
@@ -17,9 +17,10 @@ public class CancelCommand {
try {
if (ConfigHandler.lastRollback.get(user.getName()) != null) {
List<Object> list = ConfigHandler.lastRollback.get(user.getName());
long time = (Long) list.get(0);
args = (String[]) list.get(1);
Location location = (Location) list.get(2);
long startTime = (Long) list.get(0);
long endTime = (Long) list.get(1);
args = (String[]) list.get(2);
Location location = (Location) list.get(3);
boolean valid = false;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("#preview")) {
@@ -32,7 +33,7 @@ public class CancelCommand {
}
else {
ConfigHandler.lastRollback.remove(user.getName());
RollbackRestoreCommand.runCommand(user, command, permission, args, location, time);
RollbackRestoreCommand.runCommand(user, command, permission, args, location, startTime, endTime);
}
}
else {
@@ -3,8 +3,10 @@ package net.coreprotect.command;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -70,13 +72,13 @@ public class CommandHandler implements CommandExecutor {
if (argument.startsWith("#")) {
argument = argument.replaceFirst("#", "");
}
if (argument.equals("broke") || argument.equals("break") || argument.equals("remove") || argument.equals("destroy") || argument.equals("block-break") || argument.equals("block-remove") || argument.equals("-block") || argument.equals("block-")) {
if (argument.equals("broke") || argument.equals("break") || argument.equals("remove") || argument.equals("destroy") || argument.equals("block-break") || argument.equals("block-remove") || argument.equals("-block") || argument.equals("-blocks") || argument.equals("block-")) {
result.add(0);
}
else if (argument.equals("placed") || argument.equals("place") || argument.equals("block-place") || argument.equals("+block") || argument.equals("block+")) {
else if (argument.equals("placed") || argument.equals("place") || argument.equals("block-place") || argument.equals("+block") || argument.equals("+blocks") || argument.equals("block+")) {
result.add(1);
}
else if (argument.equals("block") || argument.equals("block-change") || argument.equals("change")) {
else if (argument.equals("block") || argument.equals("blocks") || argument.equals("block-change") || argument.equals("change") || argument.equals("changes")) {
result.add(0);
result.add(1);
}
@@ -97,17 +99,17 @@ public class CommandHandler implements CommandExecutor {
result.add(4);
result.add(1);
}
else if (argument.equals("chat")) {
else if (argument.equals("chat") || argument.equals("chats")) {
result.add(6);
}
else if (argument.equals("command") || argument.equals("commands")) {
result.add(7);
}
else if (argument.equals("login") || argument.equals("+session") || argument.equals("session+") || argument.equals("+connection") || argument.equals("connection+")) {
else if (argument.equals("logins") || argument.equals("login") || argument.equals("+session") || argument.equals("+sessions") || argument.equals("session+") || argument.equals("+connection") || argument.equals("connection+")) {
result.add(8);
result.add(1);
}
else if (argument.equals("logout") || argument.equals("-session") || argument.equals("session-") || argument.equals("-connection") || argument.equals("connection-")) {
else if (argument.equals("logout") || argument.equals("logouts") || argument.equals("-session") || argument.equals("-sessions") || argument.equals("session-") || argument.equals("-connection") || argument.equals("connection-")) {
result.add(8);
result.add(0);
}
@@ -117,31 +119,31 @@ public class CommandHandler implements CommandExecutor {
else if (argument.equals("username") || argument.equals("usernames") || argument.equals("user") || argument.equals("users") || argument.equals("name") || argument.equals("names") || argument.equals("uuid") || argument.equals("uuids") || argument.equals("username-change") || argument.equals("username-changes") || argument.equals("name-change") || argument.equals("name-changes")) {
result.add(9);
}
else if (argument.equals("sign")) {
else if (argument.equals("sign") || argument.equals("signs")) {
result.add(10);
}
else if (argument.equals("item") || argument.equals("items")) {
result.add(4);
result.add(11);
else if (argument.equals("inv") || argument.equals("inventory") || argument.equals("inventories")) {
result.add(4); // container
result.add(11); // item
}
else if (argument.equals("-item") || argument.equals("item-") || argument.equals("-items") || argument.equals("items-")) {
result.add(4);
result.add(11);
result.add(0);
}
else if (argument.equals("+item") || argument.equals("item+") || argument.equals("+items") || argument.equals("items+")) {
else if (argument.equals("-inv") || argument.equals("inv-") || argument.equals("-inventory") || argument.equals("inventory-") || argument.equals("-inventories")) {
result.add(4);
result.add(11);
result.add(1);
}
else if (argument.equals("inv") || argument.equals("inventory") || argument.equals("inventories")) {
result.add(11);
}
else if (argument.equals("-inv") || argument.equals("inv-") || argument.equals("-inventory") || argument.equals("inventory-") || argument.equals("-inventories") || argument.equals("drop") || argument.equals("drops") || argument.equals("deposit") || argument.equals("deposits") || argument.equals("deposited")) {
else if (argument.equals("+inv") || argument.equals("inv+") || argument.equals("+inventory") || argument.equals("inventory+") || argument.equals("+inventories")) {
result.add(4);
result.add(11);
result.add(0);
}
else if (argument.equals("+inv") || argument.equals("inv+") || argument.equals("+inventory") || argument.equals("inventory+") || argument.equals("+inventories") || argument.equals("pickup") || argument.equals("pickups") || argument.equals("withdraw") || argument.equals("withdraws") || argument.equals("withdrew")) {
else if (argument.equals("item") || argument.equals("items")) {
result.add(11);
}
else if (argument.equals("-item") || argument.equals("item-") || argument.equals("-items") || argument.equals("items-") || argument.equals("drop") || argument.equals("drops") || argument.equals("deposit") || argument.equals("deposits") || argument.equals("deposited")) {
result.add(11);
result.add(0);
}
else if (argument.equals("+item") || argument.equals("item+") || argument.equals("+items") || argument.equals("items+") || argument.equals("pickup") || argument.equals("pickups") || argument.equals("withdraw") || argument.equals("withdraws") || argument.equals("withdrew")) {
result.add(11);
result.add(1);
}
@@ -255,9 +257,9 @@ public class CommandHandler implements CommandExecutor {
return result;
}
protected static List<Object> parseExcluded(CommandSender player, String[] inputArguments, List<Integer> argAction) {
protected static Map<Object, Boolean> parseExcluded(CommandSender player, String[] inputArguments, List<Integer> argAction) {
String[] argumentArray = inputArguments.clone();
List<Object> excluded = new ArrayList<>();
Map<Object, Boolean> excluded = new HashMap<>();
int count = 0;
int next = 0;
for (String argument : argumentArray) {
@@ -276,20 +278,22 @@ public class CommandHandler implements CommandExecutor {
String[] i2 = argument.split(",");
for (String i3 : i2) {
if (i3.equals("#natural")) {
excluded.addAll(naturalBlocks);
for (Material block : naturalBlocks) {
excluded.put(block, false);
}
}
else {
Material i3_material = Util.getType(i3);
if (i3_material != null && (i3_material.isBlock() || argAction.contains(4))) {
excluded.add(i3_material);
excluded.put(i3_material, false);
}
else {
EntityType i3_entity = Util.getEntityType(i3);
if (i3_entity != null) {
excluded.add(i3_entity);
excluded.put(i3_entity, false);
}
else if (i3_material != null) {
excluded.add(i3_material);
excluded.put(i3_material, false);
}
}
}
@@ -303,20 +307,22 @@ public class CommandHandler implements CommandExecutor {
}
else {
if (argument.equals("#natural")) {
excluded.addAll(naturalBlocks);
for (Material block : naturalBlocks) {
excluded.put(block, false);
}
}
else {
Material iMaterial = Util.getType(argument);
if (iMaterial != null && (iMaterial.isBlock() || argAction.contains(4))) {
excluded.add(iMaterial);
excluded.put(iMaterial, false);
}
else {
EntityType iEntity = Util.getEntityType(argument);
if (iEntity != null) {
excluded.add(iEntity);
excluded.put(iEntity, false);
}
else if (iMaterial != null) {
excluded.add(iMaterial);
excluded.put(iMaterial, false);
}
}
}
@@ -691,11 +697,13 @@ public class CommandHandler implements CommandExecutor {
return restricted;
}
protected static long parseTime(String[] inputArguments) {
protected static long[] parseTime(String[] inputArguments) {
String[] argumentArray = inputArguments.clone();
long time = 0;
long timeStart = 0;
long timeEnd = 0;
int count = 0;
int next = 0;
boolean range = false;
double w = 0;
double d = 0;
double h = 0;
@@ -720,41 +728,59 @@ public class CommandHandler implements CommandExecutor {
argument = argument.replaceAll("d", "d:");
argument = argument.replaceAll("h", "h:");
argument = argument.replaceAll("s", "s:");
range = argument.contains("-");
int argCount = 0;
String[] i2 = argument.split(":");
for (String i3 : i2) {
if (i3.endsWith("w")) {
if (range && argCount > 0 && timeStart == 0 && i3.startsWith("-")) {
timeStart = (long) (((w * 7 * 24 * 60 * 60) + (d * 24 * 60 * 60) + (h * 60 * 60) + (m * 60) + s));
w = 0;
d = 0;
h = 0;
m = 0;
s = 0;
}
if (i3.endsWith("w") && w == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
w = Double.parseDouble(i4);
}
}
else if (i3.endsWith("d")) {
else if (i3.endsWith("d") && d == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
d = Double.parseDouble(i4);
}
}
else if (i3.endsWith("h")) {
else if (i3.endsWith("h") && h == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
h = Double.parseDouble(i4);
}
}
else if (i3.endsWith("m")) {
else if (i3.endsWith("m") && m == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
m = Double.parseDouble(i4);
}
}
else if (i3.endsWith("s")) {
else if (i3.endsWith("s") && s == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
s = Double.parseDouble(i4);
}
}
argCount++;
}
if (timeStart > 0) {
timeEnd = (long) (((w * 7 * 24 * 60 * 60) + (d * 24 * 60 * 60) + (h * 60 * 60) + (m * 60) + s));
}
else {
timeStart = (long) (((w * 7 * 24 * 60 * 60) + (d * 24 * 60 * 60) + (h * 60 * 60) + (m * 60) + s));
}
double rs = ((w * 7 * 24 * 60 * 60) + (d * 24 * 60 * 60) + (h * 60 * 60) + (m * 60) + s);
time = (long) rs;
next = 0;
}
else {
@@ -764,7 +790,12 @@ public class CommandHandler implements CommandExecutor {
count++;
}
return time;
if (timeEnd >= timeStart) {
return new long[] { timeEnd, timeStart };
}
else {
return new long[] { timeStart, timeEnd };
}
}
private static String timeString(BigDecimal input) {
@@ -776,6 +807,7 @@ public class CommandHandler implements CommandExecutor {
String time = "";
int count = 0;
int next = 0;
boolean range = false;
BigDecimal w = new BigDecimal(0);
BigDecimal d = new BigDecimal(0);
BigDecimal h = new BigDecimal(0);
@@ -800,43 +832,82 @@ public class CommandHandler implements CommandExecutor {
argument = argument.replaceAll("d", "d:");
argument = argument.replaceAll("h", "h:");
argument = argument.replaceAll("s", "s:");
range = argument.contains("-");
int argCount = 0;
String[] i2 = argument.split(":");
for (String i3 : i2) {
if (i3.endsWith("w")) {
if (range && argCount > 0 && !time.contains("-") && i3.startsWith("-")) {
w = new BigDecimal(0);
d = new BigDecimal(0);
h = new BigDecimal(0);
m = new BigDecimal(0);
s = new BigDecimal(0);
time = time + " -";
}
if (i3.endsWith("w") && w.intValue() == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
w = new BigDecimal(i4);
time = time + " " + Phrase.build(Phrase.TIME_WEEKS, timeString(w), (w.doubleValue() == 1 ? Selector.FIRST : Selector.SECOND));
if (range) {
time = time + " " + timeString(w) + "w";
}
else {
time = time + " " + Phrase.build(Phrase.TIME_WEEKS, timeString(w), (w.doubleValue() == 1 ? Selector.FIRST : Selector.SECOND));
}
}
}
else if (i3.endsWith("d")) {
else if (i3.endsWith("d") && d.intValue() == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
d = new BigDecimal(i4);
time = time + " " + Phrase.build(Phrase.TIME_DAYS, timeString(d), (d.doubleValue() == 1 ? Selector.FIRST : Selector.SECOND));
if (range) {
time = time + " " + timeString(d) + "d";
}
else {
time = time + " " + Phrase.build(Phrase.TIME_DAYS, timeString(d), (d.doubleValue() == 1 ? Selector.FIRST : Selector.SECOND));
}
}
}
else if (i3.endsWith("h")) {
else if (i3.endsWith("h") && h.intValue() == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
h = new BigDecimal(i4);
time = time + " " + Phrase.build(Phrase.TIME_HOURS, timeString(h), (h.doubleValue() == 1 ? Selector.FIRST : Selector.SECOND));
if (range) {
time = time + " " + timeString(h) + "h";
}
else {
time = time + " " + Phrase.build(Phrase.TIME_HOURS, timeString(h), (h.doubleValue() == 1 ? Selector.FIRST : Selector.SECOND));
}
}
}
else if (i3.endsWith("m")) {
else if (i3.endsWith("m") && m.intValue() == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
m = new BigDecimal(i4);
time = time + " " + Phrase.build(Phrase.TIME_MINUTES, timeString(m), (m.doubleValue() == 1 ? Selector.FIRST : Selector.SECOND));
if (range) {
time = time + " " + timeString(m) + "m";
}
else {
time = time + " " + Phrase.build(Phrase.TIME_MINUTES, timeString(m), (m.doubleValue() == 1 ? Selector.FIRST : Selector.SECOND));
}
}
}
else if (i3.endsWith("s")) {
else if (i3.endsWith("s") && s.intValue() == 0) {
String i4 = i3.replaceAll("[^0-9.]", "");
if (i4.length() > 0 && i4.replaceAll("[^0-9]", "").length() > 0 && i4.indexOf('.') == i4.lastIndexOf('.')) {
s = new BigDecimal(i4);
time = time + " " + Phrase.build(Phrase.TIME_SECONDS, timeString(s), (s.doubleValue() == 1 ? Selector.FIRST : Selector.SECOND));
if (range) {
time = time + " " + timeString(s) + "s";
}
else {
time = time + " " + Phrase.build(Phrase.TIME_SECONDS, timeString(s), (s.doubleValue() == 1 ? Selector.FIRST : Selector.SECOND));
}
}
}
argCount++;
}
next = 0;
}
@@ -1098,7 +1169,7 @@ public class CommandHandler implements CommandExecutor {
else if (user.hasPermission("coreprotect.restore") && (corecommand.equals("restore") || corecommand.equals("rs") || corecommand.equals("re") || corecommand.equals("undo") || corecommand.equals("apply") || corecommand.equals("cancel"))) {
permission = true;
}
else if (user.hasPermission("coreprotect.inspect") && (corecommand.equals("i") || corecommand.equals("inspect"))) {
else if (user.hasPermission("coreprotect.inspect") && (corecommand.equals("i") || corecommand.equals("inspect") || corecommand.equals("inspector"))) {
permission = true;
}
else if (user.hasPermission("coreprotect.help") && corecommand.equals("help")) {
@@ -1107,7 +1178,7 @@ public class CommandHandler implements CommandExecutor {
else if (user.hasPermission("coreprotect.purge") && corecommand.equals("purge")) {
permission = true;
}
else if (user.hasPermission("coreprotect.lookup") && (corecommand.equals("l") || corecommand.equals("lookup") || corecommand.equals("near"))) {
else if (user.hasPermission("coreprotect.lookup") && (corecommand.equals("l") || corecommand.equals("lookup") || corecommand.equals("page") || corecommand.equals("near"))) {
permission = true;
}
else if (user.hasPermission("coreprotect.lookup.near") && corecommand.equals("near")) {
@@ -1122,10 +1193,13 @@ public class CommandHandler implements CommandExecutor {
else if (user.hasPermission("coreprotect.status") && (corecommand.equals("status") || corecommand.equals("stats") || corecommand.equals("version"))) {
permission = true;
}
else if (user.hasPermission("coreprotect.consumer") && corecommand.equals("consumer")) {
permission = true;
}
}
if (corecommand.equals("rollback") || corecommand.equals("restore") || corecommand.equals("rb") || corecommand.equals("rs") || corecommand.equals("ro") || corecommand.equals("re")) {
RollbackRestoreCommand.runCommand(user, command, permission, argumentArray, null, 0);
RollbackRestoreCommand.runCommand(user, command, permission, argumentArray, null, 0, 0);
}
else if (corecommand.equals("apply")) {
ApplyCommand.runCommand(user, command, permission, argumentArray);
@@ -1145,7 +1219,7 @@ public class CommandHandler implements CommandExecutor {
else if (corecommand.equals("inspect") || corecommand.equals("i")) {
InspectCommand.runCommand(user, permission, argumentArray);
}
else if (corecommand.equals("lookup") || corecommand.equals("l")) {
else if (corecommand.equals("lookup") || corecommand.equals("l") || corecommand.equals("page")) {
LookupCommand.runCommand(user, command, permission, argumentArray);
}
else if (corecommand.equals("near")) {
@@ -1160,6 +1234,9 @@ public class CommandHandler implements CommandExecutor {
else if (corecommand.equals("reload")) {
ReloadCommand.runCommand(user, permission, argumentArray);
}
else if (corecommand.equals("consumer")) {
ConsumerCommand.runCommand(user, permission, argumentArray);
}
else {
Chat.sendMessage(user, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.COMMAND_NOT_FOUND, Color.WHITE, "/co " + corecommand));
}
@@ -0,0 +1,69 @@
package net.coreprotect.command;
import java.util.Locale;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import net.coreprotect.config.ConfigHandler;
import net.coreprotect.language.Phrase;
import net.coreprotect.language.Selector;
import net.coreprotect.utility.Chat;
import net.coreprotect.utility.Color;
public class ConsumerCommand {
private ConsumerCommand() {
throw new IllegalStateException("Command class");
}
protected static void runCommand(final CommandSender player, boolean permission, String[] args) {
if (!permission) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
if (!(player instanceof ConsoleCommandSender)) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.COMMAND_CONSOLE));
return;
}
if (ConfigHandler.converterRunning) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.UPGRADE_IN_PROGRESS));
return;
}
if (ConfigHandler.purgeRunning) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PURGE_IN_PROGRESS));
return;
}
if (args.length == 2) {
String action = args[1].toLowerCase(Locale.ROOT);
boolean pauseCommand = (action.equals("pause") || action.equals("disable") || action.equals("stop"));
boolean resumeCommand = (action.equals("resume") || action.equals("enable") || action.equals("start"));
if (pauseCommand || resumeCommand) {
if (ConfigHandler.pauseConsumer) {
if (pauseCommand) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.CONSUMER_ERROR, Selector.FIRST)); // already paused
}
else {
ConfigHandler.pauseConsumer = false;
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.CONSUMER_TOGGLED, Selector.SECOND)); // now started
}
}
else {
if (resumeCommand) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.CONSUMER_ERROR, Selector.SECOND)); // already running
}
else {
ConfigHandler.pauseConsumer = true;
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.CONSUMER_TOGGLED, Selector.FIRST)); // now paused
}
}
return;
}
}
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_PARAMETERS, Color.WHITE, "/co consumer <pause|resume>"));
}
}
@@ -6,6 +6,7 @@ import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Location;
@@ -24,6 +25,7 @@ import net.coreprotect.config.Config;
import net.coreprotect.config.ConfigHandler;
import net.coreprotect.database.Database;
import net.coreprotect.database.Lookup;
import net.coreprotect.database.logger.ItemLogger;
import net.coreprotect.database.lookup.BlockLookup;
import net.coreprotect.database.lookup.ChestTransactionLookup;
import net.coreprotect.database.lookup.InteractionLookup;
@@ -48,10 +50,12 @@ public class LookupCommand {
int argNoisy = CommandHandler.parseNoisy(args);
List<Integer> argAction = CommandHandler.parseAction(args);
List<Object> argBlocks = CommandHandler.parseRestricted(player, args, argAction);
List<Object> argExclude = CommandHandler.parseExcluded(player, args, argAction);
Map<Object, Boolean> argExclude = CommandHandler.parseExcluded(player, args, argAction);
List<String> argExcludeUsers = CommandHandler.parseExcludedUsers(player, args);
String ts = CommandHandler.parseTimeString(args);
long rbseconds = CommandHandler.parseTime(args);
long[] argTime = CommandHandler.parseTime(args);
long startTime = argTime[0];
long endTime = argTime[1];
int argWid = CommandHandler.parseWorld(args, true, true);
int parseRows = CommandHandler.parseRows(args);
boolean count = CommandHandler.parseCount(args);
@@ -63,6 +67,11 @@ public class LookupCommand {
return;
}
if (args[0].toLowerCase(Locale.ROOT).equals("page") && (args.length != 2 || !args[1].equals(args[1].replaceAll("[^0-9]", "")))) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_PARAMETERS, Color.WHITE, "/co page <page>"));
return;
}
int argExcluded = argExclude.size();
int argRestricted = argBlocks.size();
@@ -86,7 +95,7 @@ public class LookupCommand {
}
/* check for invalid block/entity combinations (exclude) */
for (Object arg : argExclude) {
for (Object arg : argExclude.keySet()) {
if (arg instanceof Material) {
hasBlock = true;
}
@@ -204,7 +213,7 @@ public class LookupCommand {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
if (argAction.contains(4) && !player.hasPermission("coreprotect.lookup.container")) {
if (argAction.contains(4) && !argAction.contains(11) && !player.hasPermission("coreprotect.lookup.container")) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
@@ -228,7 +237,11 @@ public class LookupCommand {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
if (argAction.contains(11) && (!player.hasPermission("coreprotect.lookup.inventory") || !player.hasPermission("coreprotect.lookup.item"))) {
if (argAction.contains(11) && !argAction.contains(4) && !player.hasPermission("coreprotect.lookup.item")) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
if (argAction.contains(4) && argAction.contains(11) && !player.hasPermission("coreprotect.lookup.inventory")) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
return;
}
@@ -248,11 +261,18 @@ public class LookupCommand {
}
}
if (rbseconds <= 0 && !pageLookup && type == 4 && (argBlocks.size() > 0 || argUsers.size() > 0)) {
if (startTime <= 0 && !pageLookup && type == 4 && (argBlocks.size() > 0 || argUsers.size() > 0)) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_LOOKUP_TIME, Selector.FIRST));
return;
}
if (argAction.contains(4) && argAction.contains(11)) { // a:inventory
argExclude.put(Material.FIRE, false);
argExclude.put(Material.WATER, false);
argExclude.put(Material.FARMLAND, false);
argExcludeUsers.add("#hopper");
}
if (type == 1) {
boolean defaultRe = true;
int p = 0;
@@ -479,7 +499,7 @@ public class LookupCommand {
boolean defaultRe = true;
int pa = 1;
int re = 4;
if (argAction.contains(6) || argAction.contains(7) || argAction.contains(9)) {
if (argAction.contains(6) || argAction.contains(7) || argAction.contains(9) || (argAction.contains(4) && argAction.contains(11))) {
re = 7;
}
if (parseRows > 0) {
@@ -554,7 +574,8 @@ public class LookupCommand {
c++;
}
long cs = -1;
long timeStart = -1;
long timeEnd = 0;
int x = 0;
int y = 0;
int z = 0;
@@ -567,14 +588,14 @@ public class LookupCommand {
y = Integer.parseInt(data[1]);
z = Integer.parseInt(data[2]);
wid = Integer.parseInt(data[3]);
cs = Long.parseLong(data[4]);
// arg_radius = Integer.parseInt(data[5]);
argNoisy = Integer.parseInt(data[5]);
argExcluded = Integer.parseInt(data[6]);
argRestricted = Integer.parseInt(data[7]);
argWid = Integer.parseInt(data[8]);
timeStart = Long.parseLong(data[4]);
timeEnd = Long.parseLong(data[5]);
argNoisy = Integer.parseInt(data[6]);
argExcluded = Integer.parseInt(data[7]);
argRestricted = Integer.parseInt(data[8]);
argWid = Integer.parseInt(data[9]);
if (defaultRe) {
re = Integer.parseInt(data[9]);
re = Integer.parseInt(data[10]);
}
rollbackusers = ConfigHandler.lookupUlist.get(player.getName());
@@ -584,7 +605,8 @@ public class LookupCommand {
argAction = ConfigHandler.lookupAlist.get(player.getName());
argRadius = ConfigHandler.lookupRadius.get(player.getName());
ts = ConfigHandler.lookupTime.get(player.getName());
rbseconds = 1;
startTime = 1;
endTime = 0;
}
else {
if (lo != null) {
@@ -599,7 +621,7 @@ public class LookupCommand {
}
if (rollbackusers.contains("#container")) {
if (argAction.contains(6) || argAction.contains(7) || argAction.contains(8) || argAction.contains(9) || argAction.contains(10)) {
if (argAction.contains(6) || argAction.contains(7) || argAction.contains(8) || argAction.contains(9) || argAction.contains(10) || argAction.contains(11)) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_USERNAME, "#container"));
return;
}
@@ -641,19 +663,27 @@ public class LookupCommand {
final List<String> rollbackusers2 = rollbackusers;
long unixtimestamp = (System.currentTimeMillis() / 1000L);
if (cs == -1) {
if (rbseconds <= 0) {
cs = 0;
if (timeStart == -1) {
if (startTime <= 0) {
timeStart = 0;
}
else {
cs = unixtimestamp - rbseconds;
timeStart = unixtimestamp - startTime;
}
if (endTime <= 0) {
timeEnd = 0;
}
else {
timeEnd = unixtimestamp - endTime;
}
}
final long stime = cs;
final long finalTimeStart = timeStart;
final long finalTimeEnd = timeEnd;
final Integer[] radius = argRadius;
try {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.LOOKUP_SEARCHING));
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Color.ITALIC + Phrase.build(Phrase.LOOKUP_SEARCHING));
final CommandSender player2 = player;
final int finalX = x;
final int finalY = y;
@@ -666,7 +696,7 @@ public class LookupCommand {
final int restricted = argRestricted;
// final List<String> uuid_list = arg_uuids;
final List<Object> blist = argBlocks;
final List<Object> elist = argExclude;
final Map<Object, Boolean> elist = argExclude;
final List<String> euserlist = argExcludeUsers;
final int page = pa;
final int displayResults = re;
@@ -684,7 +714,7 @@ public class LookupCommand {
List<String> uuidList = new ArrayList<>();
Location location = finalLocation;
boolean exists = false;
String bc = finalX + "." + finalY + "." + finalZ + "." + finalWid + "." + stime + "." + noisy + "." + excluded + "." + restricted + "." + finalArgWid + "." + displayResults;
String bc = finalX + "." + finalY + "." + finalZ + "." + finalWid + "." + finalTimeStart + "." + finalTimeEnd + "." + noisy + "." + excluded + "." + restricted + "." + finalArgWid + "." + displayResults;
ConfigHandler.lookupCommand.put(player2.getName(), bc);
ConfigHandler.lookupPage.put(player2.getName(), page);
ConfigHandler.lookupTime.put(player2.getName(), rtime);
@@ -755,28 +785,34 @@ public class LookupCommand {
location = new Location(Bukkit.getServer().getWorld(Util.getWorldName(finalWid)), finalX, finalY, finalZ);
}
Long[] rowData = new Long[] { 0L, 0L, 0L, 0L };
long rowMax = (long) page * displayResults;
long pageStart = rowMax - displayResults;
int rows = 0;
long rows = 0L;
boolean checkRows = true;
if (typeLookup == 5 && page > 1) {
rows = ConfigHandler.lookupRows.get(player2.getName());
rowData = ConfigHandler.lookupRows.get(player2.getName());
rows = rowData[3];
if (pageStart < rows) {
checkRows = false;
}
}
if (checkRows) {
rows = Lookup.countLookupRows(statement, player2, uuidList, userList, blist, elist, euserlist, finalArgAction, location, radius, stime, restrict_world, true);
ConfigHandler.lookupRows.put(player2.getName(), rows);
rows = Lookup.countLookupRows(statement, player2, uuidList, userList, blist, elist, euserlist, finalArgAction, location, radius, rowData, finalTimeStart, finalTimeEnd, restrict_world, true);
rowData[3] = rows;
ConfigHandler.lookupRows.put(player2.getName(), rowData);
}
if (finalCount) {
String row_format = NumberFormat.getInstance().format(rows);
Chat.sendMessage(player2, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.LOOKUP_ROWS_FOUND, row_format, (rows == 1 ? Selector.FIRST : Selector.SECOND)));
}
else if (pageStart < rows) {
List<String[]> lookupList = Lookup.performPartialLookup(statement, player2, uuidList, userList, blist, elist, euserlist, finalArgAction, location, radius, stime, (int) pageStart, displayResults, restrict_world, true);
Chat.sendMessage(player2, Color.WHITE + "----- " + Color.DARK_AQUA + Phrase.build(Phrase.LOOKUP_HEADER, "CoreProtect") + Color.WHITE + " -----");
List<String[]> lookupList = Lookup.performPartialLookup(statement, player2, uuidList, userList, blist, elist, euserlist, finalArgAction, location, radius, rowData, finalTimeStart, finalTimeEnd, (int) pageStart, displayResults, restrict_world, true);
Chat.sendMessage(player2, Color.WHITE + "----- " + Color.DARK_AQUA + Phrase.build(Phrase.LOOKUP_HEADER, "CoreProtect" + Color.WHITE + " | " + Color.DARK_AQUA) + Color.WHITE + " -----");
if (finalArgAction.contains(6) || finalArgAction.contains(7)) { // Chat/command
for (String[] data : lookupList) {
String time = data[0];
@@ -796,10 +832,17 @@ public class LookupCommand {
int z = Integer.parseInt(data[5]);
int action = Integer.parseInt(data[6]);
String timeago = Util.getTimeSince(Integer.parseInt(time), unixtimestamp, true);
double time_length = Util.getTimeSince(Integer.parseInt(time), unixtimestamp, false).replaceAll("[^0-9]", "").length() * 1.50;
int padding = (int) (time_length + 12.50);
String leftPadding = Strings.padStart("", padding, ' ');
Chat.sendComponent(player2, timeago + " " + Color.WHITE + "- " + Color.DARK_AQUA + Phrase.build(Phrase.LOOKUP_LOGIN, Color.DARK_AQUA + dplayer + Color.WHITE, (action != 0 ? Selector.FIRST : Selector.SECOND)));
int timeLength = 50 + (Util.getTimeSince(Integer.parseInt(time), unixtimestamp, false).replaceAll("[^0-9]", "").length() * 6);
String leftPadding = Color.BOLD + Strings.padStart("", 10, ' ');
if (timeLength % 4 == 0) {
leftPadding = Strings.padStart("", timeLength / 4, ' ');
}
else {
leftPadding = leftPadding + Color.WHITE + Strings.padStart("", (timeLength - 50) / 4, ' ');
}
String tag = (action != 0 ? Color.GREEN + "+" : Color.RED + "-");
Chat.sendComponent(player2, timeago + " " + tag + " " + Color.DARK_AQUA + Phrase.build(Phrase.LOOKUP_LOGIN, Color.DARK_AQUA + dplayer + Color.WHITE, (action != 0 ? Selector.FIRST : Selector.SECOND)));
Chat.sendComponent(player2, Color.WHITE + leftPadding + Color.GREY + "^ " + Util.getCoordinates(command.getName(), wid, x, y, z, true, true) + "");
}
}
@@ -822,18 +865,67 @@ public class LookupCommand {
int z = Integer.parseInt(data[5]);
String message = data[6];
String timeago = Util.getTimeSince(Integer.parseInt(time), unixtimestamp, true);
double time_length = Util.getTimeSince(Integer.parseInt(time), unixtimestamp, false).replaceAll("[^0-9]", "").length() * 1.50;
int padding = (int) (time_length + 12.50);
String leftPadding = Strings.padStart("", padding, ' ');
int timeLength = 50 + (Util.getTimeSince(Integer.parseInt(time), unixtimestamp, false).replaceAll("[^0-9]", "").length() * 6);
String leftPadding = Color.BOLD + Strings.padStart("", 10, ' ');
if (timeLength % 4 == 0) {
leftPadding = Strings.padStart("", timeLength / 4, ' ');
}
else {
leftPadding = leftPadding + Color.WHITE + Strings.padStart("", (timeLength - 50) / 4, ' ');
}
Chat.sendComponent(player2, timeago + " " + Color.WHITE + "- " + Color.DARK_AQUA + dplayer + ": " + Color.WHITE, message);
Chat.sendComponent(player2, Color.WHITE + leftPadding + Color.GREY + "^ " + Util.getCoordinates(command.getName(), wid, x, y, z, true, true) + "");
}
}
else if (finalArgAction.contains(4) && finalArgAction.contains(11)) { // inventory transactions
for (String[] data : lookupList) {
String time = data[0];
String dplayer = data[1];
String dtype = data[5];
int ddata = Integer.parseInt(data[6]);
int daction = Integer.parseInt(data[7]);
int amount = Integer.parseInt(data[10]);
String rbd = ((Integer.parseInt(data[8]) == 2 || Integer.parseInt(data[8]) == 3) ? Color.STRIKETHROUGH : "");
String timeago = Util.getTimeSince(Integer.parseInt(time), unixtimestamp, true);
Material blockType = Util.itemFilter(Util.getType(Integer.parseInt(dtype)), (Integer.parseInt(data[13]) == 0));
String dname = Util.nameFilter(blockType.name().toLowerCase(Locale.ROOT), ddata);
String selector = Selector.FIRST;
String tag = Color.WHITE + "-";
if (daction == 2 || daction == 3) { // LOOKUP_ITEM
selector = (daction != 2 ? Selector.FIRST : Selector.SECOND);
tag = (daction != 2 ? Color.GREEN + "+" : Color.RED + "-");
}
else if (daction == 4 || daction == 5) { // LOOKUP_STORAGE
selector = (daction == 4 ? Selector.FIRST : Selector.SECOND);
tag = (daction == 4 ? Color.GREEN + "+" : Color.RED + "-");
}
else if (daction == 6 || daction == 7) { // LOOKUP_PROJECTILE
selector = Selector.SECOND;
tag = Color.RED + "-";
}
else if (daction == ItemLogger.ITEM_BREAK || daction == ItemLogger.ITEM_DESTROY || daction == ItemLogger.ITEM_CREATE) {
selector = (daction == ItemLogger.ITEM_CREATE ? Selector.FIRST : Selector.SECOND);
tag = (daction == ItemLogger.ITEM_CREATE ? Color.GREEN + "+" : Color.RED + "-");
}
else if (daction == ItemLogger.ITEM_SELL || daction == ItemLogger.ITEM_BUY) { // LOOKUP_TRADE
selector = (daction == ItemLogger.ITEM_BUY ? Selector.FIRST : Selector.SECOND);
tag = (daction == ItemLogger.ITEM_BUY ? Color.GREEN + "+" : Color.RED + "-");
}
else { // LOOKUP_CONTAINER
selector = (daction == 0 ? Selector.FIRST : Selector.SECOND);
tag = (daction == 0 ? Color.GREEN + "+" : Color.RED + "-");
}
Chat.sendComponent(player2, timeago + " " + tag + " " + Phrase.build(Phrase.LOOKUP_CONTAINER, Color.DARK_AQUA + rbd + dplayer + Color.WHITE + rbd, "x" + amount, Color.DARK_AQUA + rbd + dname + Color.WHITE, selector));
}
}
else {
for (String[] data : lookupList) {
int drb = Integer.parseInt(data[8]);
String rbd = "";
if (drb == 1) {
if (drb == 1 || drb == 3) {
rbd = Color.STRIKETHROUGH;
}
@@ -850,9 +942,14 @@ public class LookupCommand {
String tag = Color.WHITE + "-";
String timeago = Util.getTimeSince(Integer.parseInt(time), unixtimestamp, true);
double timeLength = Util.getTimeSince(Integer.parseInt(time), unixtimestamp, false).replaceAll("[^0-9]", "").length() * 1.50;
int padding = (int) (timeLength + 12.50);
String leftPadding = Strings.padStart("", padding, ' ');
int timeLength = 50 + (Util.getTimeSince(Integer.parseInt(time), unixtimestamp, false).replaceAll("[^0-9]", "").length() * 6);
String leftPadding = Color.BOLD + Strings.padStart("", 10, ' ');
if (timeLength % 4 == 0) {
leftPadding = Strings.padStart("", timeLength / 4, ' ');
}
else {
leftPadding = leftPadding + Color.WHITE + Strings.padStart("", (timeLength - 50) / 4, ' ');
}
String dname = "";
boolean isPlayer = false;
@@ -892,16 +989,25 @@ public class LookupCommand {
if (daction == 2 || daction == 3) {
phrase = Phrase.LOOKUP_ITEM; // {picked up|dropped}
selector = (daction != 2 ? Selector.FIRST : Selector.SECOND);
action = "a:inventory";
tag = (daction != 2 ? Color.GREEN + "+" : Color.RED + "-");
action = "a:item";
}
else if (daction == 4 || daction == 5) {
phrase = Phrase.LOOKUP_STORAGE; // {deposited|withdrew}
selector = (daction != 4 ? Selector.FIRST : Selector.SECOND);
action = "a:inventory";
tag = (daction != 4 ? Color.RED + "-" : Color.GREEN + "+");
action = "a:item";
}
else if (daction == 6 || daction == 7) {
phrase = Phrase.LOOKUP_PROJECTILE; // {threw|shot}
selector = (daction != 7 ? Selector.FIRST : Selector.SECOND);
tag = Color.RED + "-";
action = "a:item";
}
else {
phrase = Phrase.LOOKUP_CONTAINER; // {added|removed}
selector = (daction != 0 ? Selector.FIRST : Selector.SECOND);
tag = (daction != 0 ? Color.GREEN + "+" : Color.RED + "-");
action = "a:container";
}
@@ -911,28 +1017,28 @@ public class LookupCommand {
if (daction == 2 || daction == 3) {
phrase = Phrase.LOOKUP_INTERACTION; // {clicked|killed}
selector = (daction != 3 ? Selector.FIRST : Selector.SECOND);
tag = (daction != 3 ? Color.WHITE + "-" : Color.RED + "-");
action = (daction == 2 ? "a:click" : "a:kill");
}
else {
phrase = Phrase.LOOKUP_BLOCK; // {placed|broke}
selector = (daction != 0 ? Selector.FIRST : Selector.SECOND);
tag = (daction != 0 ? Color.GREEN + "+" : Color.RED + "-");
}
// tag = ChatColors.RED + "-";
Chat.sendComponent(player2, timeago + " " + tag + " " + Phrase.build(phrase, Color.DARK_AQUA + rbd + dplayer + Color.WHITE + rbd, Color.DARK_AQUA + rbd + dname + Color.WHITE, selector));
}
boolean itemLookup = finalArgAction.contains(4) && finalArgAction.contains(11);
action = (finalArgAction.size() == 0 || itemLookup ? " (" + action + ")" : "");
action = (finalArgAction.size() == 0 ? " (" + action + ")" : "");
Chat.sendComponent(player2, Color.WHITE + leftPadding + Color.GREY + "^ " + Util.getCoordinates(command.getName(), wid, x, y, z, true, true) + Color.GREY + Color.ITALIC + action);
}
}
if (rows > displayResults) {
int total_pages = (int) Math.ceil(rows / (displayResults + 0.0));
if (finalArgAction.contains(6) || finalArgAction.contains(7) || finalArgAction.contains(9)) {
if (finalArgAction.contains(6) || finalArgAction.contains(7) || finalArgAction.contains(9) || (finalArgAction.contains(4) && finalArgAction.contains(11))) {
Chat.sendMessage(player2, "-----");
}
Chat.sendComponent(player2, Util.getPageNavigation(command.getName(), page, total_pages) + "| " + Phrase.build(Phrase.LOOKUP_VIEW_PAGE, Color.WHITE, "/co l <page>"));
Chat.sendComponent(player2, Util.getPageNavigation(command.getName(), page, total_pages));
}
}
else if (rows > 0) {
@@ -31,10 +31,12 @@ public class PurgeCommand extends Consumer {
int resultc = args.length;
Location location = CommandHandler.parseLocation(player, args);
final Integer[] argRadius = CommandHandler.parseRadius(args, player, location);
final long seconds = CommandHandler.parseTime(args);
final long[] argTime = CommandHandler.parseTime(args);
final int argWid = CommandHandler.parseWorld(args, false, false);
final List<Integer> argAction = CommandHandler.parseAction(args);
final List<Integer> supportedActions = Arrays.asList();
long startTime = argTime[1] > 0 ? argTime[0] : 0;
long endTime = argTime[1] > 0 ? argTime[1] : argTime[0];
if (ConfigHandler.converterRunning) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.UPGRADE_IN_PROGRESS));
@@ -52,7 +54,7 @@ public class PurgeCommand extends Consumer {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_PARAMETERS, "/co purge t:<time>"));
return;
}
if (seconds <= 0) {
if (endTime <= 0) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_PARAMETERS, "/co purge t:<time>"));
return;
}
@@ -72,11 +74,11 @@ public class PurgeCommand extends Consumer {
return;
}
}
if (player instanceof Player && seconds < 2592000) {
if (player instanceof Player && endTime < 2592000) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PURGE_MINIMUM_TIME, "30", Selector.FIRST)); // 30 days
return;
}
else if (seconds < 86400) {
else if (endTime < 86400) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PURGE_MINIMUM_TIME, "24", Selector.SECOND)); // 24 hours
return;
}
@@ -96,7 +98,8 @@ public class PurgeCommand extends Consumer {
public void run() {
try {
long timestamp = (System.currentTimeMillis() / 1000L);
long ptime = timestamp - seconds;
long timeStart = startTime > 0 ? (timestamp - startTime) : 0;
long timeEnd = timestamp - endTime;
long removed = 0;
Connection connection = null;
@@ -196,10 +199,10 @@ public class PurgeCommand extends Consumer {
String timeLimit = "";
if (purgeTables.contains(table)) {
if (argWid > 0 && worldTables.contains(table)) {
timeLimit = " WHERE (wid = '" + argWid + "' AND time >= '" + ptime + "') OR wid != '" + argWid + "'";
timeLimit = " WHERE (wid = '" + argWid + "' AND (time >= '" + timeEnd + "' OR time < '" + timeStart + "')) OR wid != '" + argWid + "'";
}
else if (argWid == 0) {
timeLimit = " WHERE time >= '" + ptime + "'";
timeLimit = " WHERE (time >= '" + timeEnd + "' OR time < '" + timeStart + "')";
}
}
query = "INSERT INTO " + purgePrefix + table + " SELECT " + columns + " FROM " + ConfigHandler.prefix + table + timeLimit;
@@ -262,7 +265,7 @@ public class PurgeCommand extends Consumer {
}
if (purge) {
query = "DELETE FROM " + purgePrefix + table + " WHERE time < '" + ptime + "'" + worldRestriction;
query = "DELETE FROM " + purgePrefix + table + " WHERE time < '" + timeEnd + "' AND time >= '" + timeStart + "'" + worldRestriction;
preparedStmt = connection.prepareStatement(query);
preparedStmt.execute();
preparedStmt.close();
@@ -321,7 +324,7 @@ public class PurgeCommand extends Consumer {
}
if (purge) {
query = "DELETE FROM " + ConfigHandler.prefix + table + " WHERE time < '" + ptime + "'" + worldRestriction;
query = "DELETE FROM " + ConfigHandler.prefix + table + " WHERE time < '" + timeEnd + "' AND time >= '" + timeStart + "'" + worldRestriction;
preparedStmt = connection.prepareStatement(query);
preparedStmt.execute();
removed = removed + preparedStmt.getUpdateCount();
@@ -5,6 +5,7 @@ import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Location;
@@ -31,7 +32,7 @@ import net.coreprotect.utility.Color;
import net.coreprotect.utility.Util;
public class RollbackRestoreCommand {
protected static void runCommand(CommandSender player, Command command, boolean permission, String[] args, Location argLocation, long forceSeconds) {
protected static void runCommand(CommandSender player, Command command, boolean permission, String[] args, Location argLocation, long forceStart, long forceEnd) {
Location lo = (argLocation != null ? argLocation : CommandHandler.parseLocation(player, args));
List<String> argUuids = new ArrayList<>();
List<String> argUsers = CommandHandler.parseUsers(args);
@@ -39,10 +40,12 @@ public class RollbackRestoreCommand {
int argNoisy = CommandHandler.parseNoisy(args);
List<Integer> argAction = CommandHandler.parseAction(args);
List<Object> argBlocks = CommandHandler.parseRestricted(player, args, argAction);
List<Object> argExclude = CommandHandler.parseExcluded(player, args, argAction);
Map<Object, Boolean> argExclude = CommandHandler.parseExcluded(player, args, argAction);
List<String> argExcludeUsers = CommandHandler.parseExcludedUsers(player, args);
String ts = CommandHandler.parseTimeString(args);
long rbSeconds = CommandHandler.parseTime(args);
long[] argTime = CommandHandler.parseTime(args);
long startTime = argTime[0];
long endTime = argTime[1];
int argWid = CommandHandler.parseWorld(args, true, true);
boolean count = CommandHandler.parseCount(args);
boolean worldedit = CommandHandler.parseWorldEdit(args);
@@ -74,7 +77,7 @@ public class RollbackRestoreCommand {
}
/* check for invalid block/entity combinations (exclude) */
for (Object arg : argExclude) {
for (Object arg : argExclude.keySet()) {
if (arg instanceof Material) {
hasBlock = true;
}
@@ -139,7 +142,7 @@ public class RollbackRestoreCommand {
return;
}
}
if (preview > 1 && forceSeconds <= 0) {
if (preview > 1 && forceStart <= 0) {
preview = 1;
}
@@ -151,7 +154,7 @@ public class RollbackRestoreCommand {
final int finalAction = a;
int DEFAULT_RADIUS = Config.getGlobal().DEFAULT_RADIUS;
if ((player instanceof Player || player instanceof BlockCommandSender) && argRadius == null && DEFAULT_RADIUS > 0 && !forceglobal) {
if ((player instanceof Player || player instanceof BlockCommandSender) && argRadius == null && DEFAULT_RADIUS > 0 && !forceglobal && !argAction.contains(11)) {
Location location = lo;
int xmin = location.getBlockX() - DEFAULT_RADIUS;
int xmax = location.getBlockX() + DEFAULT_RADIUS;
@@ -178,6 +181,21 @@ public class RollbackRestoreCommand {
return;
}
if (argAction.contains(4) && argAction.contains(11)) { // a:inventory
if (argUsers.size() == 0) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.MISSING_ACTION_USER));
return;
}
argExclude.put(Material.FIRE, false);
argExclude.put(Material.WATER, false);
argExclude.put(Material.FARMLAND, false);
argExcludeUsers.add("#hopper");
}
else if (!argAction.contains(4) && Config.getGlobal().EXCLUDE_TNT && !argExclude.containsKey(Material.TNT) && !argBlocks.contains(Material.TNT)) {
argExclude.put(Material.TNT, true);
}
if (g == 1 && (argUsers.size() > 0 || (argUsers.size() == 0 && argRadius != null))) {
Integer MAX_RADIUS = Config.getGlobal().MAX_RADIUS;
if (argRadius != null) {
@@ -195,11 +213,11 @@ public class RollbackRestoreCommand {
return;
}
else if (preview > 0) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PREVIEW_CONTAINER));
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PREVIEW_TRANSACTION, !argAction.contains(11) ? Selector.FIRST : Selector.SECOND));
return;
}
}
if (argAction.contains(8) || argAction.contains(11) || (!argAction.contains(0) && !argAction.contains(1) && !argAction.contains(3) && !argAction.contains(4))) {
if (argAction.contains(8) || (argAction.contains(11) && !argAction.contains(4)) || (!argAction.contains(0) && !argAction.contains(1) && !argAction.contains(3) && !argAction.contains(4))) {
if (finalAction == 0) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.ACTION_NOT_SUPPORTED));
}
@@ -213,16 +231,26 @@ public class RollbackRestoreCommand {
if (argUsers.size() == 0) {
argUsers.add("#global");
}
List<String> rollbackusers = argUsers;
int c = 0;
for (String ruser : rollbackusers) {
List<Player> players = Bukkit.getServer().matchPlayer(ruser);
List<Player> players = Bukkit.getServer().matchPlayer(ruser); // here
for (Player p : players) {
if (p.getName().equalsIgnoreCase(ruser)) {
rollbackusers.set(c, p.getName());
ruser = p.getName();
rollbackusers.set(c, ruser);
}
}
c++;
if (argAction.contains(4) && argAction.contains(11)) {
Player onlineUser = Bukkit.getServer().getPlayer(ruser);
if (onlineUser == null || !onlineUser.isOnline()) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.USER_OFFLINE, ruser));
return;
}
}
}
int wid = 0;
@@ -230,6 +258,11 @@ public class RollbackRestoreCommand {
int y = 0;
int z = 0;
if (rollbackusers.contains("#container")) {
if (argAction.contains(11)) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.INVALID_USERNAME, "#container"));
return;
}
boolean valid = false;
if (ConfigHandler.lookupType.get(player.getName()) != null) {
int lookupType = ConfigHandler.lookupType.get(player.getName());
@@ -244,7 +277,7 @@ public class RollbackRestoreCommand {
}
if (valid) {
if (preview > 0) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PREVIEW_CONTAINER));
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PREVIEW_TRANSACTION, Selector.FIRST));
return;
}
else {
@@ -283,13 +316,16 @@ public class RollbackRestoreCommand {
}
final List<String> rollbackusers2 = rollbackusers;
if (rbSeconds > 0) {
if (startTime > 0) {
long unixtimestamp = (System.currentTimeMillis() / 1000L);
long seconds = unixtimestamp - rbSeconds;
if (forceSeconds > 0) {
seconds = forceSeconds;
long timeStart = unixtimestamp - startTime;
long timeEnd = endTime > 0 ? (unixtimestamp - endTime) : 0;
if (forceStart > 0) {
timeStart = forceStart;
timeEnd = forceEnd;
}
final long stime = seconds;
final long finalTimeStart = timeStart;
final long finalTimeEnd = timeEnd;
final Integer[] radius = argRadius;
try {
final CommandSender player2 = player;
@@ -297,7 +333,7 @@ public class RollbackRestoreCommand {
final String rtime = ts;
final List<String> uuidList = argUuids;
final List<Object> blist = argBlocks;
final List<Object> elist = argExclude;
final Map<Object, Boolean> elist = argExclude;
final List<String> euserlist = argExcludeUsers;
final Location locationFinal = lo;
final int finalArgWid = argWid;
@@ -389,17 +425,18 @@ public class RollbackRestoreCommand {
}
if (finalArgAction.contains(5)) {
ContainerRollback.performContainerRollbackRestore(statement, player2, uuidList, rollbackusers2, rtime, blist, elist, euserlist, finalArgAction, location, radius, stime, restrictWorld, false, verbose, action);
ContainerRollback.performContainerRollbackRestore(statement, player2, uuidList, rollbackusers2, rtime, blist, elist, euserlist, finalArgAction, location, radius, finalTimeStart, finalTimeEnd, restrictWorld, false, verbose, action);
}
else {
Rollback.performRollbackRestore(statement, player2, uuidList, rollbackusers2, rtime, blist, elist, euserlist, finalArgAction, location, radius, stime, restrictWorld, false, verbose, action, finalPreview);
if (finalPreview < 2) {
List<Object> list = new ArrayList<>();
list.add(stime);
list.add(finalArgs);
list.add(locationFinal);
ConfigHandler.lastRollback.put(player2.getName(), list);
}
Rollback.performRollbackRestore(statement, player2, uuidList, rollbackusers2, rtime, blist, elist, euserlist, finalArgAction, location, radius, finalTimeStart, finalTimeEnd, restrictWorld, false, verbose, action, finalPreview);
}
if (finalPreview < 2) {
List<Object> list = new ArrayList<>();
list.add(finalTimeStart);
list.add(finalTimeEnd);
list.add(finalArgs);
list.add(locationFinal);
ConfigHandler.lastRollback.put(player2.getName(), list);
}
}
else {
@@ -24,7 +24,7 @@ public class TabHandler implements TabCompleter {
// private static String[] COMMANDS = new String[] { "help", "inspect", "rollback", "restore", "lookup", "purge", "reload", "status", "near", "undo" }; // max 10!
private static String[] HELP = new String[] { "inspect", "rollback", "restore", "lookup", "purge", "teleport", "status", "params", "users", "time", "radius", "action", "include", "exclude" };
private static String[] PARAMS = new String[] { "user:", "time:", "radius:", "action:", "include:", "exclude:", "#container" };
private static String[] ACTIONS = new String[] { "block", "+block", "-block", "click", "kill", "container", "chat", "command", "+inventory", "-inventory", "inventory", "item", "+item", "-item", "sign", "session", "+session", "-session", "username" };
private static String[] ACTIONS = new String[] { "block", "+block", "-block", "click", "kill", "+container", "-container", "container", "chat", "command", "+inventory", "-inventory", "inventory", "item", "+item", "-item", "sign", "session", "+session", "-session", "username" };
private static String[] NUMBERS = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
private static String[] TIMES = new String[] { "w", "d", "h", "m", "s" };
private static ArrayList<String> materials = null;
@@ -17,9 +17,10 @@ public class UndoCommand {
try {
if (ConfigHandler.lastRollback.get(user.getName()) != null) {
List<Object> list = ConfigHandler.lastRollback.get(user.getName());
long time = (Long) list.get(0);
args = (String[]) list.get(1);
Location location = (Location) list.get(2);
long startTime = (Long) list.get(0);
long endTime = (Long) list.get(1);
args = (String[]) list.get(2);
Location location = (Location) list.get(3);
for (String arg : args) {
if (arg.equals("#preview")) {
CancelCommand.runCommand(user, command, permission, args);
@@ -38,7 +39,7 @@ public class UndoCommand {
}
if (valid) {
ConfigHandler.lastRollback.remove(user.getName());
RollbackRestoreCommand.runCommand(user, command, permission, args, location, time);
RollbackRestoreCommand.runCommand(user, command, permission, args, location, startTime, endTime);
}
}
else {
@@ -41,9 +41,12 @@ public class Config extends Language {
public String MYSQL_USERNAME;
public String MYSQL_PASSWORD;
public String LANGUAGE;
public boolean ENABLE_AWE;
public boolean HOVER_EVENTS;
public boolean DATABASE_LOCK;
public boolean LOG_CANCELLED_CHAT;
public boolean HOPPER_FILTER_META;
public boolean EXCLUDE_TNT;
public boolean MYSQL;
public boolean CHECK_UPDATES;
public boolean API_ENABLED;
@@ -178,9 +181,12 @@ public class Config extends Language {
}
private void readValues() {
this.ENABLE_AWE = this.getBoolean("enable-awe", false);
this.HOVER_EVENTS = this.getBoolean("hover-events", true);
this.DATABASE_LOCK = this.getBoolean("database-lock", true);
this.LOG_CANCELLED_CHAT = this.getBoolean("log-cancelled-chat", true);
this.HOPPER_FILTER_META = this.getBoolean("hopper-filter-meta", false);
this.EXCLUDE_TNT = this.getBoolean("exclude-tnt", false);
this.DONATION_KEY = this.getString("donation-key");
this.MYSQL = this.getBoolean("use-mysql");
this.PREFIX = this.getString("table-prefix");
@@ -14,6 +14,7 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
@@ -181,7 +182,7 @@ public class ConfigFile extends Config {
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).equalsIgnoreCase(oldLine)) {
if (newLine.length() > 0) {
if (newLine != null && newLine.length() > 0) {
lines.set(i, newLine);
}
else {
@@ -204,6 +205,27 @@ public class ConfigFile extends Config {
}
}
public static void sortFile(String fileName) {
try {
Path path = Paths.get(ConfigHandler.path + fileName);
List<String> lines = Files.readAllLines(path);
List<String> sort = lines.subList(2, lines.size());
Collections.sort(sort);
lines = lines.subList(0, 2);
lines.addAll(sort);
if (lines.size() > 0) {
String lastLine = lines.get(lines.size() - 1); // append the final line to prevent a line separator from being added
Files.write(path, (lines.remove(lines.size() - 1).isEmpty() ? lines : lines), StandardCharsets.UTF_8);
Files.write(path, lastLine.getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND);
lines.clear();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void resetCache(String cacheName, String fileName) throws IOException {
File file = new File(CoreProtect.getInstance().getDataFolder(), cacheName);
if (file.length() > 0) {
@@ -42,7 +42,7 @@ public class ConfigHandler extends Queue {
public static final int EDITION_VERSION = 2;
public static final String EDITION_BRANCH = Util.getBranch();
public static final String EDITION_NAME = Util.getPluginName();
public static final String JAVA_VERSION = "1.8";
public static final String JAVA_VERSION = "11.0";
public static final String SPIGOT_VERSION = "1.14";
public static String path = "plugins/CoreProtect/";
public static String sqlite = "database.db";
@@ -58,6 +58,7 @@ public class ConfigHandler extends Queue {
public static volatile boolean serverRunning = false;
public static volatile boolean converterRunning = false;
public static volatile boolean purgeRunning = false;
public static volatile boolean pauseConsumer = false;
public static volatile boolean worldeditEnabled = false;
public static volatile boolean databaseReachable = true;
public static volatile int worldId = 0;
@@ -87,8 +88,15 @@ public class ConfigHandler extends Queue {
public static Map<String, Integer> loggingItem = syncMap();
public static ConcurrentHashMap<String, List<Object>> transactingChest = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, List<ItemStack[]>> oldContainer = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, List<ItemStack>> itemsDrop = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, List<ItemStack>> itemsPickup = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, List<ItemStack>> itemsDrop = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, List<ItemStack>> itemsThrown = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, List<ItemStack>> itemsShot = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, List<ItemStack>> itemsBreak = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, List<ItemStack>> itemsDestroy = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, List<ItemStack>> itemsCreate = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, List<ItemStack>> itemsSell = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, List<ItemStack>> itemsBuy = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, Object[]> hopperAbort = new ConcurrentHashMap<>();
public static Map<String, List<ItemStack[]>> forceContainer = syncMap();
public static Map<String, Integer> lookupType = syncMap();
@@ -97,13 +105,13 @@ public class ConfigHandler extends Queue {
public static Map<String, Integer> lookupPage = syncMap();
public static Map<String, String> lookupCommand = syncMap();
public static Map<String, List<Object>> lookupBlist = syncMap();
public static Map<String, List<Object>> lookupElist = syncMap();
public static Map<String, Map<Object, Boolean>> lookupElist = syncMap();
public static Map<String, List<String>> lookupEUserlist = syncMap();
public static Map<String, List<String>> lookupUlist = syncMap();
public static Map<String, List<Integer>> lookupAlist = syncMap();
public static Map<String, Integer[]> lookupRadius = syncMap();
public static Map<String, String> lookupTime = syncMap();
public static Map<String, Integer> lookupRows = syncMap();
public static Map<String, Long[]> lookupRows = syncMap();
public static Map<String, String> uuidCache = syncMap();
public static Map<String, String> uuidCacheReversed = syncMap();
public static Map<String, Integer> playerIdCache = syncMap();
@@ -111,6 +119,7 @@ public class ConfigHandler extends Queue {
public static Map<String, List<Object>> lastRollback = syncMap();
public static Map<String, Boolean> activeRollbacks = syncMap();
public static Map<UUID, Object[]> entityBlockMapper = syncMap();
public static ConcurrentHashMap<Long, Long> populatedChunks = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, String> language = new ConcurrentHashMap<>();
public static List<String> databaseTables = new ArrayList<>();
@@ -200,6 +209,8 @@ public class ConfigHandler extends Queue {
}
tempFile.delete();
Class.forName("org.sqlite.JDBC");
}
catch (Exception e) {
e.printStackTrace();
@@ -100,7 +100,7 @@ public class Consumer extends Process implements Runnable, Thread.UncaughtExcept
private static void pauseConsumer(int process_id) {
try {
while ((ConfigHandler.serverRunning || ConfigHandler.converterRunning) && (Consumer.isPaused || ConfigHandler.purgeRunning || Consumer.consumer_id.get(process_id)[1] == 1)) {
while ((ConfigHandler.serverRunning || ConfigHandler.converterRunning) && (Consumer.isPaused || ConfigHandler.pauseConsumer || ConfigHandler.purgeRunning || Consumer.consumer_id.get(process_id)[1] == 1)) {
pausedSuccess = true;
Thread.sleep(100);
}
@@ -11,6 +11,8 @@ import org.bukkit.block.BlockState;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.block.data.Bisected;
import org.bukkit.block.data.Bisected.Half;
import org.bukkit.block.data.type.Bed;
import org.bukkit.block.data.type.Bed.Part;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
@@ -21,6 +23,7 @@ import net.coreprotect.config.Config;
import net.coreprotect.config.ConfigHandler;
import net.coreprotect.consumer.process.Process;
import net.coreprotect.listener.block.BlockUtil;
import net.coreprotect.model.BlockGroup;
import net.coreprotect.utility.Util;
public class Queue {
@@ -57,7 +60,7 @@ public class Queue {
Consumer.consumer.get(currentConsumer).add(data);
}
private static void queueStandardData(int consumerId, int currentConsumer, String[] user, Object object) {
private static synchronized void queueStandardData(int consumerId, int currentConsumer, String[] user, Object object) {
Consumer.consumerUsers.get(currentConsumer).put(consumerId, user);
Consumer.consumerObjects.get(currentConsumer).put(consumerId, object);
Consumer.consumer_id.put(currentConsumer, new Integer[] { Consumer.consumer_id.get(currentConsumer)[0], 0 });
@@ -99,19 +102,29 @@ public class Queue {
CreatureSpawner mobSpawner = (CreatureSpawner) block;
extraData = Util.getSpawnerType(mobSpawner.getSpawnedType());
}
else if (type.equals(Material.SUNFLOWER) || type.equals(Material.LILAC) || type.equals(Material.TALL_GRASS) || type.equals(Material.LARGE_FERN) || type.equals(Material.ROSE_BUSH) || type.equals(Material.PEONY)) { // Double plant
else if (type == Material.IRON_DOOR || BlockGroup.DOORS.contains(type) || type.equals(Material.SUNFLOWER) || type.equals(Material.LILAC) || type.equals(Material.TALL_GRASS) || type.equals(Material.LARGE_FERN) || type.equals(Material.ROSE_BUSH) || type.equals(Material.PEONY)) { // Double plant
if (block.getBlockData() instanceof Bisected) {
if (((Bisected) block.getBlockData()).getHalf().equals(Half.TOP) && !user.startsWith("#")) {
if (((Bisected) block.getBlockData()).getHalf().equals(Half.TOP)) {
if (blockNumber == 5) {
return;
}
if (block.getY() > BukkitAdapter.ADAPTER.getMinHeight(block.getWorld())) {
block = block.getWorld().getBlockAt(block.getX(), block.getY() - 1, block.getZ()).getState();
if (type != block.getType()) {
return;
}
blockData = block.getBlockData().getAsString();
}
}
}
}
else if (type.name().endsWith("_BED") && block.getBlockData() instanceof Bed) {
if (((Bed) block.getBlockData()).getPart().equals(Part.HEAD)) {
return;
}
}
int currentConsumer = Consumer.currentConsumer;
int consumerId = Consumer.newConsumerId(currentConsumer);
@@ -136,7 +149,7 @@ public class Queue {
replaceType = blockReplaced.getType();
replaceData = 0;
if ((replaceType.equals(Material.SUNFLOWER) || replaceType.equals(Material.LILAC) || replaceType.equals(Material.TALL_GRASS) || replaceType.equals(Material.LARGE_FERN) || replaceType.equals(Material.ROSE_BUSH) || replaceType.equals(Material.PEONY)) && replaceData >= 8) { // Double plant top half
if ((replaceType == Material.IRON_DOOR || BlockGroup.DOORS.contains(replaceType) || replaceType.equals(Material.SUNFLOWER) || replaceType.equals(Material.LILAC) || replaceType.equals(Material.TALL_GRASS) || replaceType.equals(Material.LARGE_FERN) || replaceType.equals(Material.ROSE_BUSH) || replaceType.equals(Material.PEONY)) && replaceData >= 8) { // Double plant top half
BlockState blockBelow = blockReplaced.getWorld().getBlockAt(blockReplaced.getX(), blockReplaced.getY() - 1, blockReplaced.getZ()).getState();
Material belowType = blockBelow.getType();
Queue.queueBlockBreak(user, blockBelow, belowType, blockBelow.getBlockData().getAsString(), 0);
@@ -216,18 +229,6 @@ public class Queue {
queueStandardData(consumerId, currentConsumer, new String[] { user, null }, location);
}
protected static void queueContainerRollbackUpdate(String user, Location location, List<Object[]> list, int action) {
if (location == null) {
location = new Location(Bukkit.getServer().getWorlds().get(0), 0, 0, 0);
}
int currentConsumer = Consumer.currentConsumer;
int consumerId = Consumer.newConsumerId(currentConsumer);
addConsumer(currentConsumer, new Object[] { consumerId, Process.CONTAINER_ROLLBACK_UPDATE, null, 0, null, 0, action, null });
Consumer.consumerObjectArrayList.get(currentConsumer).put(consumerId, list);
queueStandardData(consumerId, currentConsumer, new String[] { user, null }, location);
}
protected static synchronized void queueContainerTransaction(String user, Location location, Material type, Object inventory, int chestId) {
int currentConsumer = Consumer.currentConsumer;
int consumerId = Consumer.newConsumerId(currentConsumer);
@@ -236,10 +237,10 @@ public class Queue {
queueStandardData(consumerId, currentConsumer, new String[] { user, null }, location);
}
protected static void queueItemTransaction(String user, Location location, int time, int itemId) {
protected static void queueItemTransaction(String user, Location location, int time, int offset, int itemId) {
int currentConsumer = Consumer.currentConsumer;
int consumerId = Consumer.newConsumerId(currentConsumer);
addConsumer(currentConsumer, new Object[] { consumerId, Process.ITEM_TRANSACTION, null, 0, null, time, itemId, null });
addConsumer(currentConsumer, new Object[] { consumerId, Process.ITEM_TRANSACTION, null, offset, null, time, itemId, null });
queueStandardData(consumerId, currentConsumer, new String[] { user, null }, location);
}
@@ -265,20 +266,6 @@ public class Queue {
queueStandardData(consumerId, currentConsumer, new String[] { user, null }, new Object[] { block, type });
}
protected static void queueHangingRemove(String user, BlockState block, int delay) {
int currentConsumer = Consumer.currentConsumer;
int consumerId = Consumer.newConsumerId(currentConsumer);
addConsumer(currentConsumer, new Object[] { consumerId, Process.HANGING_REMOVE, null, 0, null, 0, delay, null });
queueStandardData(consumerId, currentConsumer, new String[] { user, null }, block);
}
protected static void queueHangingSpawn(String user, BlockState block, Material type, int data, int delay) {
int currentConsumer = Consumer.currentConsumer;
int consumerId = Consumer.newConsumerId(currentConsumer);
addConsumer(currentConsumer, new Object[] { consumerId, Process.HANGING_SPAWN, type, data, null, 0, delay, null });
queueStandardData(consumerId, currentConsumer, new String[] { user, null }, block);
}
protected static void queueMaterialInsert(int id, String name) {
int currentConsumer = Consumer.currentConsumer;
int consumerId = Consumer.newConsumerId(currentConsumer);
@@ -293,7 +280,7 @@ public class Queue {
queueStandardData(consumerId, currentConsumer, new String[] { null, null }, data);
}
protected static void queueNaturalBlockBreak(String user, BlockState block, Block relative, Material type, int data) {
protected static void queueNaturalBlockBreak(String user, BlockState block, Block relative, Material type, String blockData, int data) {
List<BlockState> blockStates = new ArrayList<>();
if (relative != null) {
blockStates.add(relative.getState());
@@ -301,7 +288,7 @@ public class Queue {
int currentConsumer = Consumer.currentConsumer;
int consumerId = Consumer.newConsumerId(currentConsumer);
addConsumer(currentConsumer, new Object[] { consumerId, Process.NATURAL_BLOCK_BREAK, type, data, null, 0, 0, null });
addConsumer(currentConsumer, new Object[] { consumerId, Process.NATURAL_BLOCK_BREAK, type, data, null, 0, 0, blockData });
Consumer.consumerBlockList.get(currentConsumer).put(consumerId, blockStates);
queueStandardData(consumerId, currentConsumer, new String[] { user, null }, block);
}
@@ -322,10 +309,10 @@ public class Queue {
queueStandardData(consumerId, currentConsumer, new String[] { player.getName(), null }, new Object[] { timestamp, player.getLocation().clone() });
}
protected static void queuePlayerInteraction(String user, BlockState block) {
protected static void queuePlayerInteraction(String user, BlockState block, Material type) {
int currentConsumer = Consumer.currentConsumer;
int consumerId = Consumer.newConsumerId(currentConsumer);
addConsumer(currentConsumer, new Object[] { consumerId, Process.PLAYER_INTERACTION, null, 0, null, 0, 0, null });
addConsumer(currentConsumer, new Object[] { consumerId, Process.PLAYER_INTERACTION, type, 0, null, 0, 0, null });
queueStandardData(consumerId, currentConsumer, new String[] { user, null }, block);
}
@@ -352,13 +339,14 @@ public class Queue {
queueStandardData(consumerId, currentConsumer, new String[] { player.getName(), null }, player.getLocation().clone());
}
protected static void queueRollbackUpdate(String user, Location location, List<Object[]> list, int action) {
protected static void queueRollbackUpdate(String user, Location location, List<Object[]> list, int table, int action) {
if (location == null) {
location = new Location(Bukkit.getServer().getWorlds().get(0), 0, 0, 0);
}
int currentConsumer = Consumer.currentConsumer;
int consumerId = Consumer.newConsumerId(currentConsumer);
addConsumer(currentConsumer, new Object[] { consumerId, Process.ROLLBACK_UPDATE, null, 0, null, 0, action, null });
addConsumer(currentConsumer, new Object[] { consumerId, table, null, 0, null, 0, action, null });
Consumer.consumerObjectArrayList.get(currentConsumer).put(consumerId, list);
queueStandardData(consumerId, currentConsumer, new String[] { user, null }, location);
}
@@ -3,16 +3,12 @@ package net.coreprotect.consumer.process;
import java.sql.PreparedStatement;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.block.Skull;
import org.bukkit.block.data.Bisected;
import org.bukkit.block.data.type.Door;
import net.coreprotect.database.logger.BlockBreakLogger;
import net.coreprotect.database.logger.SkullBreakLogger;
import net.coreprotect.model.BlockGroup;
import net.coreprotect.utility.Util;
class BlockBreakProcess {
@@ -25,17 +21,7 @@ class BlockBreakProcess {
SkullBreakLogger.log(preparedStmt, preparedStmtSkulls, batchCount, user, block);
}
else {
BlockBreakLogger.log(preparedStmt, batchCount, user, block.getLocation(), Util.getBlockId(blockType), blockDataId, meta, block.getBlockData().getAsString());
if (forceData == 5) { // Fix for doors
if ((blockType == Material.IRON_DOOR || BlockGroup.DOORS.contains(blockType)) && (replaceType != Material.IRON_DOOR && !BlockGroup.DOORS.contains(replaceType))) {
Door door = (Door) block.getBlockData();
door.setHalf(Bisected.Half.TOP);
blockData = door.getAsString();
Location location = block.getLocation();
location.setY(location.getY() + 1);
BlockBreakLogger.log(preparedStmt, batchCount, user, location, Util.getBlockId(blockType), 0, null, blockData);
}
}
BlockBreakLogger.log(preparedStmt, batchCount, user, block.getLocation(), Util.getBlockId(blockType), blockDataId, meta, block.getBlockData().getAsString(), blockData);
}
}
}
@@ -1,15 +0,0 @@
package net.coreprotect.consumer.process;
import org.bukkit.block.BlockState;
import net.coreprotect.utility.entity.HangingUtil;
class HangingRemoveProcess {
static void process(Object object, int delay) {
if (object instanceof BlockState) {
BlockState block = (BlockState) object;
HangingUtil.removeHanging(block, delay);
}
}
}
@@ -1,16 +0,0 @@
package net.coreprotect.consumer.process;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import net.coreprotect.utility.entity.HangingUtil;
class HangingSpawnProcess {
static void process(Object object, Material type, int data, int delay) {
if (object instanceof BlockState) {
BlockState block = (BlockState) object;
HangingUtil.spawnHanging(block, type, data, delay);
}
}
}
@@ -11,26 +11,33 @@ import net.coreprotect.database.logger.ItemLogger;
class ItemTransactionProcess extends Queue {
static void process(PreparedStatement preparedStmt, int batchCount, int processId, int id, int forceData, int time, String user, Object object) {
static void process(PreparedStatement preparedStmt, int batchCount, int processId, int id, int forceData, int time, int offset, String user, Object object) {
if (object instanceof Location) {
Location location = (Location) object;
String loggingItemId = user.toLowerCase(Locale.ROOT) + "." + location.getBlockX() + "." + location.getBlockY() + "." + location.getBlockZ();
if (ConfigHandler.loggingItem.get(loggingItemId) != null) {
int current_chest = ConfigHandler.loggingItem.get(loggingItemId);
if (ConfigHandler.itemsDrop.get(loggingItemId) == null && ConfigHandler.itemsPickup.get(loggingItemId) == null) {
if (ConfigHandler.itemsPickup.get(loggingItemId) == null && ConfigHandler.itemsDrop.get(loggingItemId) == null && ConfigHandler.itemsThrown.get(loggingItemId) == null && ConfigHandler.itemsShot.get(loggingItemId) == null && ConfigHandler.itemsBreak.get(loggingItemId) == null && ConfigHandler.itemsDestroy.get(loggingItemId) == null && ConfigHandler.itemsCreate.get(loggingItemId) == null && ConfigHandler.itemsSell.get(loggingItemId) == null && ConfigHandler.itemsBuy.get(loggingItemId) == null) {
return;
}
if (current_chest == forceData) {
int currentTime = (int) (System.currentTimeMillis() / 1000L);
if (currentTime > time) {
ItemLogger.log(preparedStmt, batchCount, location, user);
ConfigHandler.itemsDrop.remove(loggingItemId);
ItemLogger.log(preparedStmt, batchCount, location, offset, user);
ConfigHandler.itemsPickup.remove(loggingItemId);
ConfigHandler.itemsDrop.remove(loggingItemId);
ConfigHandler.itemsThrown.remove(loggingItemId);
ConfigHandler.itemsShot.remove(loggingItemId);
ConfigHandler.itemsBreak.remove(loggingItemId);
ConfigHandler.itemsDestroy.remove(loggingItemId);
ConfigHandler.itemsCreate.remove(loggingItemId);
ConfigHandler.itemsSell.remove(loggingItemId);
ConfigHandler.itemsBuy.remove(loggingItemId);
ConfigHandler.loggingItem.remove(loggingItemId);
}
else {
Queue.queueItemTransaction(user, location, time, forceData);
Queue.queueItemTransaction(user, location, time, offset, forceData);
}
}
}
@@ -15,7 +15,7 @@ import net.coreprotect.utility.Util;
class NaturalBlockBreakProcess {
static void process(Statement statement, PreparedStatement preparedStmt, int batchCount, int processId, int id, String user, Object object, Material blockType, int blockData) {
static void process(Statement statement, PreparedStatement preparedStmt, int batchCount, int processId, int id, String user, Object object, Material blockType, int blockData, String overrideData) {
if (object instanceof BlockState) {
BlockState block = (BlockState) object;
Map<Integer, List<BlockState>> blockLists = Consumer.consumerBlockList.get(processId);
@@ -28,7 +28,7 @@ class NaturalBlockBreakProcess {
}
}
blockLists.remove(id);
BlockBreakLogger.log(preparedStmt, batchCount, user, block.getLocation(), Util.getBlockId(blockType), blockData, null, block.getBlockData().getAsString());
BlockBreakLogger.log(preparedStmt, batchCount, user, block.getLocation(), Util.getBlockId(blockType), blockData, null, block.getBlockData().getAsString(), overrideData);
}
}
}
@@ -2,16 +2,17 @@ package net.coreprotect.consumer.process;
import java.sql.PreparedStatement;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import net.coreprotect.database.logger.PlayerInteractLogger;
class PlayerInteractionProcess {
static void process(PreparedStatement preparedStmt, int batchCount, String user, Object object) {
static void process(PreparedStatement preparedStmt, int batchCount, String user, Object object, Material type) {
if (object instanceof BlockState) {
BlockState block = (BlockState) object;
PlayerInteractLogger.log(preparedStmt, batchCount, user, block);
PlayerInteractLogger.log(preparedStmt, batchCount, user, block, type);
}
}
}
@@ -35,8 +35,6 @@ public class Process {
public static final int PLAYER_LOGOUT = 15;
public static final int ENTITY_KILL = 16;
public static final int ENTITY_SPAWN = 17;
public static final int HANGING_REMOVE = 18;
public static final int HANGING_SPAWN = 19;
public static final int NATURAL_BLOCK_BREAK = 20;
public static final int MATERIAL_INSERT = 21;
public static final int ART_INSERT = 22;
@@ -44,6 +42,9 @@ public class Process {
public static final int PLAYER_KILL = 24;
public static final int BLOCKDATA_INSERT = 25;
public static final int ITEM_TRANSACTION = 26;
public static final int INVENTORY_ROLLBACK_UPDATE = 27;
public static final int INVENTORY_CONTAINER_ROLLBACK_UPDATE = 28;
public static final int BLOCK_INVENTORY_ROLLBACK_UPDATE = 29;
public static int lastLockUpdate = 0;
private static volatile int currentConsumerSize = 0;
@@ -143,13 +144,13 @@ public class Process {
ContainerBreakProcess.process(preparedStmtContainers, i, processId, id, blockType, user, object);
break;
case Process.PLAYER_INTERACTION:
PlayerInteractionProcess.process(preparedStmtBlocks, i, user, object);
PlayerInteractionProcess.process(preparedStmtBlocks, i, user, object, blockType);
break;
case Process.CONTAINER_TRANSACTION:
ContainerTransactionProcess.process(preparedStmtContainers, preparedStmtItems, i, processId, id, blockType, forceData, user, object);
break;
case Process.ITEM_TRANSACTION:
ItemTransactionProcess.process(preparedStmtItems, i, processId, id, forceData, replaceData, user, object);
ItemTransactionProcess.process(preparedStmtItems, i, processId, id, forceData, replaceData, blockData, user, object);
break;
case Process.STRUCTURE_GROWTH:
StructureGrowthProcess.process(statement, preparedStmtBlocks, i, processId, id, user, object, forceData);
@@ -160,6 +161,15 @@ public class Process {
case Process.CONTAINER_ROLLBACK_UPDATE:
RollbackUpdateProcess.process(statement, processId, id, forceData, 1);
break;
case Process.INVENTORY_ROLLBACK_UPDATE:
RollbackUpdateProcess.process(statement, processId, id, forceData, 2);
break;
case Process.INVENTORY_CONTAINER_ROLLBACK_UPDATE:
RollbackUpdateProcess.process(statement, processId, id, forceData, 3);
break;
case Process.BLOCK_INVENTORY_ROLLBACK_UPDATE:
RollbackUpdateProcess.process(statement, processId, id, forceData, 4);
break;
case Process.WORLD_INSERT:
WorldInsertProcess.process(preparedStmtWorlds, i, statement, object, forceData);
break;
@@ -187,14 +197,8 @@ public class Process {
case Process.ENTITY_SPAWN:
EntitySpawnProcess.process(statement, object, forceData);
break;
case Process.HANGING_REMOVE:
HangingRemoveProcess.process(object, forceData);
break;
case Process.HANGING_SPAWN:
HangingSpawnProcess.process(object, blockType, blockData, forceData);
break;
case Process.NATURAL_BLOCK_BREAK:
NaturalBlockBreakProcess.process(statement, preparedStmtBlocks, i, processId, id, user, object, blockType, blockData);
NaturalBlockBreakProcess.process(statement, preparedStmtBlocks, i, processId, id, user, object, blockType, blockData, (String) data[7]);
break;
case Process.MATERIAL_INSERT:
MaterialInsertProcess.process(preparedStmtMaterials, statement, i, object, forceData);
@@ -6,6 +6,7 @@ import java.util.Map;
import net.coreprotect.consumer.Consumer;
import net.coreprotect.database.Database;
import net.coreprotect.utility.Util;
class RollbackUpdateProcess {
@@ -16,8 +17,8 @@ class RollbackUpdateProcess {
for (Object[] listRow : list) {
long rowid = (Long) listRow[0];
int rolledBack = (Integer) listRow[9];
if (rolledBack == action) {
Database.performUpdate(statement, rowid, action, table);
if (Util.rolledBack(rolledBack, (table == 2 || table == 3 || table == 4)) == action) { // 1 = restore, 0 = rollback
Database.performUpdate(statement, rowid, rolledBack, table);
}
}
updateLists.remove(id);
@@ -28,7 +28,7 @@ class StructureGrowthProcess {
int count = 0;
for (BlockState blockState : blockStates) {
if (count < replaceBlockCount) {
BlockBreakLogger.log(preparedStmt, batchCount, user, blockState.getLocation(), Util.getBlockId(blockState.getType()), 0, null, blockState.getBlockData().getAsString());
BlockBreakLogger.log(preparedStmt, batchCount, user, blockState.getLocation(), Util.getBlockId(blockState.getType()), 0, null, blockState.getBlockData().getAsString(), null);
}
else {
BlockPlaceLogger.log(preparedStmt, batchCount, user, blockState, 0, 0, null, -1, false, null, null, null);
@@ -1,22 +1,27 @@
package net.coreprotect.database;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.LivingEntity;
import org.bukkit.inventory.ItemStack;
import net.coreprotect.CoreProtect;
import net.coreprotect.config.ConfigHandler;
import net.coreprotect.consumer.Queue;
import net.coreprotect.consumer.process.Process;
import net.coreprotect.language.Phrase;
import net.coreprotect.model.BlockGroup;
import net.coreprotect.utility.Chat;
@@ -24,11 +29,11 @@ import net.coreprotect.utility.Util;
public class ContainerRollback extends Queue {
public static void performContainerRollbackRestore(Statement statement, CommandSender user, List<String> checkUuids, List<String> checkUsers, String timeString, List<Object> restrictList, List<Object> excludeList, List<String> excludeUserList, List<Integer> actionList, final Location location, Integer[] radius, long checkTime, boolean restrictWorld, boolean lookup, boolean verbose, final int rollbackType) {
public static void performContainerRollbackRestore(Statement statement, CommandSender user, List<String> checkUuids, List<String> checkUsers, String timeString, List<Object> restrictList, Map<Object, Boolean> excludeList, List<String> excludeUserList, List<Integer> actionList, final Location location, Integer[] radius, long startTime, long endTime, boolean restrictWorld, boolean lookup, boolean verbose, final int rollbackType) {
try {
long startTime = System.currentTimeMillis();
long timeStart = System.currentTimeMillis();
final List<Object[]> lookupList = Lookup.performLookupRaw(statement, user, checkUuids, checkUsers, restrictList, excludeList, excludeUserList, actionList, location, radius, checkTime, -1, -1, restrictWorld, lookup);
final List<Object[]> lookupList = Lookup.performLookupRaw(statement, user, checkUuids, checkUsers, restrictList, excludeList, excludeUserList, actionList, location, radius, null, startTime, endTime, -1, -1, restrictWorld, lookup);
if (rollbackType == 1) {
Collections.reverse(lookupList);
}
@@ -38,7 +43,7 @@ public class ContainerRollback extends Queue {
userString = user.getName();
}
Queue.queueContainerRollbackUpdate(userString, location, lookupList, rollbackType); // Perform update transaction in consumer
Queue.queueRollbackUpdate(userString, location, lookupList, Process.CONTAINER_ROLLBACK_UPDATE, rollbackType); // Perform update transaction in consumer
final String finalUserString = userString;
ConfigHandler.rollbackHash.put(userString, new int[] { 0, 0, 0, 0 });
@@ -58,17 +63,23 @@ public class ContainerRollback extends Queue {
}
Object container = null;
Material type = block.getType();
List<ItemFrame> matchingFrames = new ArrayList<>();
if (BlockGroup.CONTAINERS.contains(type)) {
container = Util.getContainerInventory(block.getState(), false);
}
else {
for (Entity entity : block.getChunk().getEntities()) {
if (entity instanceof ArmorStand) {
if (entity.getLocation().getBlockX() == location.getBlockX() && entity.getLocation().getBlockY() == location.getBlockY() && entity.getLocation().getBlockZ() == location.getBlockZ()) {
if (entity.getLocation().getBlockX() == location.getBlockX() && entity.getLocation().getBlockY() == location.getBlockY() && entity.getLocation().getBlockZ() == location.getBlockZ()) {
if (entity instanceof ArmorStand) {
type = Material.ARMOR_STAND;
container = Util.getEntityEquipment((LivingEntity) entity);
}
else if (entity instanceof ItemFrame) {
type = Material.ITEM_FRAME;
container = entity;
matchingFrames.add((ItemFrame) entity);
}
}
}
}
@@ -86,7 +97,7 @@ public class ContainerRollback extends Queue {
int rowTypeRaw = (Integer) lookupRow[6];
int rowData = (Integer) lookupRow[7];
int rowAction = (Integer) lookupRow[8];
int rowRolledBack = (Integer) lookupRow[9];
int rowRolledBack = Util.rolledBack((Integer) lookupRow[9], false);
// int rowWid = (Integer)lookupRow[10];
int rowAmount = (Integer) lookupRow[11];
byte[] rowMetadata = (byte[]) lookupRow[12];
@@ -107,12 +118,27 @@ public class ContainerRollback extends Queue {
ItemStack itemstack = new ItemStack(rowType, rowAmount, (short) rowData);
Object[] populatedStack = Rollback.populateItemStack(itemstack, rowMetadata);
int slot = (Integer) populatedStack[0];
itemstack = (ItemStack) populatedStack[1];
String faceData = (String) populatedStack[1];
itemstack = (ItemStack) populatedStack[2];
if (type == Material.ITEM_FRAME && faceData.length() > 0) {
BlockFace blockFace = BlockFace.valueOf(faceData);
ItemFrame itemFrame = (ItemFrame) container;
if (blockFace != itemFrame.getFacing()) {
for (ItemFrame frame : matchingFrames) {
if (blockFace == frame.getFacing()) {
container = frame;
break;
}
}
}
}
Rollback.modifyContainerItems(type, container, slot, itemstack, action);
}
}
}
matchingFrames.clear();
ConfigHandler.rollbackHash.put(finalUserString, new int[] { itemCount, modifyCount, entityCount, 1 });
}
@@ -139,8 +165,8 @@ public class ContainerRollback extends Queue {
rollbackHashData = ConfigHandler.rollbackHash.get(finalUserString);
int blockCount = rollbackHashData[1];
long endTime = System.currentTimeMillis();
double totalSeconds = (endTime - startTime) / 1000.0;
long timeFinish = System.currentTimeMillis();
double totalSeconds = (timeFinish - timeStart) / 1000.0;
if (user != null) {
int file = -1;
@@ -187,16 +187,15 @@ public class Database extends Queue {
}
}
public static void performUpdate(Statement statement, long id, int action, int table) {
public static void performUpdate(Statement statement, long id, int rb, int table) {
try {
int rolledBack = 1;
if (action == 1) {
rolledBack = 0;
}
if (table == 1) {
int rolledBack = Util.toggleRolledBack(rb, (table == 2 || table == 3 || table == 4)); // co_item, co_container, co_block
if (table == 1 || table == 3) {
statement.executeUpdate("UPDATE " + ConfigHandler.prefix + "container SET rolled_back='" + rolledBack + "' WHERE rowid='" + id + "'");
}
else if (table == 2) {
statement.executeUpdate("UPDATE " + ConfigHandler.prefix + "item SET rolled_back='" + rolledBack + "' WHERE rowid='" + id + "'");
}
else {
statement.executeUpdate("UPDATE " + ConfigHandler.prefix + "block SET rolled_back='" + rolledBack + "' WHERE rowid='" + id + "'");
}
@@ -213,7 +212,7 @@ public class Database extends Queue {
String blockInsert = "INSERT INTO " + ConfigHandler.prefix + "block (time, user, wid, x, y, z, type, data, meta, blockdata, action, rolled_back) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
String skullInsert = "INSERT INTO " + ConfigHandler.prefix + "skull (time, owner) VALUES (?, ?)";
String containerInsert = "INSERT INTO " + ConfigHandler.prefix + "container (time, user, wid, x, y, z, type, data, amount, metadata, action, rolled_back) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
String itemInsert = "INSERT INTO " + ConfigHandler.prefix + "item (time, user, wid, x, y, z, type, data, amount, action) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
String itemInsert = "INSERT INTO " + ConfigHandler.prefix + "item (time, user, wid, x, y, z, type, data, amount, action, rolled_back) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
String worldInsert = "INSERT INTO " + ConfigHandler.prefix + "world (id, world) VALUES (?, ?)";
String chatInsert = "INSERT INTO " + ConfigHandler.prefix + "chat (time, user, wid, x, y, z, message) VALUES (?, ?, ?, ?, ?, ?, ?)";
String commandInsert = "INSERT INTO " + ConfigHandler.prefix + "command (time, user, wid, x, y, z, message) VALUES (?, ?, ?, ?, ?, ?, ?)";
@@ -295,6 +294,10 @@ public class Database extends Queue {
private static void initializeTables(String prefix, Statement statement) {
try {
if (!Config.getGlobal().MYSQL) {
statement.executeUpdate("PRAGMA journal_mode=WAL;");
}
boolean lockInitialized = false;
String query = "SELECT rowid as id FROM " + prefix + "database_lock WHERE rowid='1' LIMIT 1";
ResultSet rs = statement.executeQuery(query);
@@ -335,7 +338,7 @@ public class Database extends Queue {
index = ", INDEX(wid,x,z,time), INDEX(user,time), INDEX(type,time)";
statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + prefix + "container(rowid int(10) NOT NULL AUTO_INCREMENT,PRIMARY KEY(rowid), time int(10), user int(8), wid int(4), x int(8), y int(3), z int(8), type int(6), data int(6), amount int(4), metadata blob, action int(2), rolled_back tinyint(1)" + index + ") ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4");
index = ", INDEX(wid,x,z,time), INDEX(user,time), INDEX(type,time)";
statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + prefix + "item(rowid int(10) NOT NULL AUTO_INCREMENT,PRIMARY KEY(rowid), time int(10), user int(8), wid int(4), x int(8), y int(3), z int(8), type int(6), data blob, amount int(4), action tinyint(1)" + index + ") ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4");
statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + prefix + "item(rowid int(10) NOT NULL AUTO_INCREMENT,PRIMARY KEY(rowid), time int(10), user int(8), wid int(4), x int(8), y int(3), z int(8), type int(6), data blob, amount int(4), action tinyint(1), rolled_back tinyint(1)" + index + ") ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4");
statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + prefix + "database_lock(rowid int(8) NOT NULL AUTO_INCREMENT,PRIMARY KEY(rowid),status tinyint(1),time int(10)) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4");
statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + prefix + "entity(rowid int(8) NOT NULL AUTO_INCREMENT,PRIMARY KEY(rowid), time int(10), data blob) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4");
index = ", INDEX(id)";
@@ -414,7 +417,7 @@ public class Database extends Queue {
statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + prefix + "container (time INTEGER, user INTEGER, wid INTEGER, x INTEGER, y INTEGER, z INTEGER, type INTEGER, data INTEGER, amount INTEGER, metadata BLOB, action INTEGER, rolled_back INTEGER);");
}
if (!tableData.contains(prefix + "item")) {
statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + prefix + "item (time INTEGER, user INTEGER, wid INTEGER, x INTEGER, y INTEGER, z INTEGER, type INTEGER, data BLOB, amount INTEGER, action INTEGER);");
statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + prefix + "item (time INTEGER, user INTEGER, wid INTEGER, x INTEGER, y INTEGER, z INTEGER, type INTEGER, data BLOB, amount INTEGER, action INTEGER, rolled_back INTEGER);");
}
if (!tableData.contains(prefix + "database_lock")) {
statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + prefix + "database_lock (status INTEGER, time INTEGER);");
@@ -6,6 +6,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.bukkit.Location;
import org.bukkit.Material;
@@ -56,7 +57,7 @@ public class Lookup extends Queue {
else if (i == 13 && map[i] instanceof Byte[]) {
results[newId] = Util.byteDataToString((byte[]) map[i], (int) map[6]);
}
else if (i > 0) {
else if (i > 0) { // skip rowid
if (map[i] instanceof Integer) {
results[newId] = map[i].toString();
}
@@ -75,8 +76,8 @@ public class Lookup extends Queue {
return newList;
}
public static int countLookupRows(Statement statement, CommandSender user, List<String> checkUuids, List<String> checkUsers, List<Object> restrictList, List<Object> excludeList, List<String> excludeUserList, List<Integer> actionList, Location location, Integer[] radius, long checkTime, boolean restrictWorld, boolean lookup) {
int rows = 0;
public static long countLookupRows(Statement statement, CommandSender user, List<String> checkUuids, List<String> checkUsers, List<Object> restrictList, Map<Object, Boolean> excludeList, List<String> excludeUserList, List<Integer> actionList, Location location, Integer[] radius, Long[] rowData, long startTime, long endTime, boolean restrictWorld, boolean lookup) {
Long rows = 0L;
try {
while (Consumer.isPaused) {
@@ -84,9 +85,12 @@ public class Lookup extends Queue {
}
Consumer.isPaused = true;
ResultSet results = rawLookupResultSet(statement, user, checkUuids, checkUsers, restrictList, excludeList, excludeUserList, actionList, location, radius, checkTime, -1, -1, restrictWorld, lookup, true);
ResultSet results = rawLookupResultSet(statement, user, checkUuids, checkUsers, restrictList, excludeList, excludeUserList, actionList, location, radius, null, startTime, endTime, -1, -1, restrictWorld, lookup, true);
while (results.next()) {
rows += results.getInt("count");
int resultTable = results.getInt("tbl");
long count = results.getLong("count");
rowData[resultTable] = count;
rows += count;
}
results.close();
}
@@ -99,11 +103,11 @@ public class Lookup extends Queue {
return rows;
}
public static List<String[]> performLookup(Statement statement, CommandSender user, List<String> checkUuids, List<String> checkUsers, List<Object> restrictList, List<Object> excludeList, List<String> excludeUserList, List<Integer> actionList, Location location, Integer[] radius, long checkTime, boolean restrictWorld, boolean lookup) {
public static List<String[]> performLookup(Statement statement, CommandSender user, List<String> checkUuids, List<String> checkUsers, List<Object> restrictList, Map<Object, Boolean> excludeList, List<String> excludeUserList, List<Integer> actionList, Location location, Integer[] radius, long startTime, long endTime, boolean restrictWorld, boolean lookup) {
List<String[]> newList = new ArrayList<>();
try {
List<Object[]> lookupList = performLookupRaw(statement, user, checkUuids, checkUsers, restrictList, excludeList, excludeUserList, actionList, location, radius, checkTime, -1, -1, restrictWorld, lookup);
List<Object[]> lookupList = performLookupRaw(statement, user, checkUuids, checkUsers, restrictList, excludeList, excludeUserList, actionList, location, radius, null, startTime, endTime, -1, -1, restrictWorld, lookup);
newList = convertRawLookup(statement, lookupList);
}
catch (Exception e) {
@@ -113,7 +117,7 @@ public class Lookup extends Queue {
return newList;
}
static List<Object[]> performLookupRaw(Statement statement, CommandSender user, List<String> checkUuids, List<String> checkUsers, List<Object> restrictList, List<Object> excludeList, List<String> excludeUserList, List<Integer> actionList, Location location, Integer[] radius, long checkTime, int limitOffset, int limitCount, boolean restrictWorld, boolean lookup) {
static List<Object[]> performLookupRaw(Statement statement, CommandSender user, List<String> checkUuids, List<String> checkUsers, List<Object> restrictList, Map<Object, Boolean> excludeList, List<String> excludeUserList, List<Integer> actionList, Location location, Integer[] radius, Long[] rowData, long startTime, long endTime, int limitOffset, int limitCount, boolean restrictWorld, boolean lookup) {
List<Object[]> list = new ArrayList<>();
List<Integer> invalidRollbackActions = new ArrayList<>();
invalidRollbackActions.add(2);
@@ -122,6 +126,10 @@ public class Lookup extends Queue {
invalidRollbackActions.add(3);
}
if (actionList.contains(4) && actionList.contains(11)) {
invalidRollbackActions.clear();
}
try {
while (Consumer.isPaused) {
Thread.sleep(1);
@@ -129,7 +137,7 @@ public class Lookup extends Queue {
Consumer.isPaused = true;
ResultSet results = rawLookupResultSet(statement, user, checkUuids, checkUsers, restrictList, excludeList, excludeUserList, actionList, location, radius, checkTime, limitOffset, limitCount, restrictWorld, lookup, false);
ResultSet results = rawLookupResultSet(statement, user, checkUuids, checkUsers, restrictList, excludeList, excludeUserList, actionList, location, radius, rowData, startTime, endTime, limitOffset, limitCount, restrictWorld, lookup, false);
while (results.next()) {
if (actionList.contains(6) || actionList.contains(7)) {
@@ -208,6 +216,7 @@ public class Lookup extends Queue {
else {
int resultData = 0;
int resultAmount = -1;
int resultTable = 0;
byte[] resultMeta = null;
byte[] resultBlockData = null;
long resultId = results.getLong("id");
@@ -221,10 +230,13 @@ public class Lookup extends Queue {
int resultZ = results.getInt("z");
int resultWorldId = results.getInt("wid");
boolean hasTbl = false;
if ((lookup && actionList.size() == 0) || actionList.contains(4) || actionList.contains(5) || actionList.contains(11)) {
resultData = results.getInt("data");
resultAmount = results.getInt("amount");
resultMeta = results.getBytes("metadata");
resultTable = results.getInt("tbl");
hasTbl = true;
}
else {
resultData = results.getInt("data");
@@ -233,7 +245,6 @@ public class Lookup extends Queue {
}
boolean valid = true;
if (!lookup) {
if (invalidRollbackActions.contains(resultAction)) {
valid = false;
@@ -241,8 +252,14 @@ public class Lookup extends Queue {
}
if (valid) {
Object[] dataArray = new Object[] { resultId, resultTime, resultUserId, resultX, resultY, resultZ, resultType, resultData, resultAction, resultRolledBack, resultWorldId, resultAmount, resultMeta, resultBlockData };
list.add(dataArray);
if (hasTbl) {
Object[] dataArray = new Object[] { resultId, resultTime, resultUserId, resultX, resultY, resultZ, resultType, resultData, resultAction, resultRolledBack, resultWorldId, resultAmount, resultMeta, resultBlockData, resultTable };
list.add(dataArray);
}
else {
Object[] dataArray = new Object[] { resultId, resultTime, resultUserId, resultX, resultY, resultZ, resultType, resultData, resultAction, resultRolledBack, resultWorldId, resultAmount, resultMeta, resultBlockData };
list.add(dataArray);
}
}
}
}
@@ -256,11 +273,11 @@ public class Lookup extends Queue {
return list;
}
public static List<String[]> performPartialLookup(Statement statement, CommandSender user, List<String> checkUuids, List<String> checkUsers, List<Object> restrictList, List<Object> excludeList, List<String> excludeUserList, List<Integer> actionList, Location location, Integer[] radius, long checkTime, int limitOffset, int limitCount, boolean restrictWorld, boolean lookup) {
public static List<String[]> performPartialLookup(Statement statement, CommandSender user, List<String> checkUuids, List<String> checkUsers, List<Object> restrictList, Map<Object, Boolean> excludeList, List<String> excludeUserList, List<Integer> actionList, Location location, Integer[] radius, Long[] rowData, long startTime, long endTime, int limitOffset, int limitCount, boolean restrictWorld, boolean lookup) {
List<String[]> newList = new ArrayList<>();
try {
List<Object[]> lookupList = performLookupRaw(statement, user, checkUuids, checkUsers, restrictList, excludeList, excludeUserList, actionList, location, radius, checkTime, limitOffset, limitCount, restrictWorld, lookup);
List<Object[]> lookupList = performLookupRaw(statement, user, checkUuids, checkUsers, restrictList, excludeList, excludeUserList, actionList, location, radius, rowData, startTime, endTime, limitOffset, limitCount, restrictWorld, lookup);
newList = convertRawLookup(statement, lookupList);
}
catch (Exception e) {
@@ -270,7 +287,7 @@ public class Lookup extends Queue {
return newList;
}
private static ResultSet rawLookupResultSet(Statement statement, CommandSender user, List<String> checkUuids, List<String> checkUsers, List<Object> restrictList, List<Object> excludeList, List<String> excludeUserList, List<Integer> actionList, Location location, Integer[] radius, long checkTime, int limitOffset, int limitCount, boolean restrictWorld, boolean lookup, boolean count) {
private static ResultSet rawLookupResultSet(Statement statement, CommandSender user, List<String> checkUuids, List<String> checkUsers, List<Object> restrictList, Map<Object, Boolean> excludeList, List<String> excludeUserList, List<Integer> actionList, Location location, Integer[] radius, Long[] rowData, long startTime, long endTime, int limitOffset, int limitCount, boolean restrictWorld, boolean lookup, boolean count) {
ResultSet results = null;
try {
@@ -279,12 +296,14 @@ public class Lookup extends Queue {
restrictWorld = true;
}
boolean inventoryQuery = (actionList.contains(4) && actionList.contains(11));
boolean validAction = false;
String queryBlock = "";
String queryEntity = "";
String queryLimit = "";
String queryTable = "block";
String action = "";
String actionExclude = "";
String includeBlock = "";
String includeEntity = "";
String excludeBlock = "";
@@ -292,6 +311,7 @@ public class Lookup extends Queue {
String users = "";
String uuids = "";
String excludeUsers = "";
String unionLimit = "";
String index = "";
String query = "";
@@ -372,7 +392,7 @@ public class Lookup extends Queue {
StringBuilder excludeListMaterial = new StringBuilder();
StringBuilder excludeListEntity = new StringBuilder();
for (Object restrictTarget : excludeList) {
for (Object restrictTarget : excludeList.keySet()) {
String targetName = "";
if (restrictTarget instanceof Material) {
@@ -425,6 +445,17 @@ public class Lookup extends Queue {
excludeUsers = excludeUserText.toString();
}
// Specify actions to exclude from a:item
if ((lookup && actionList.size() == 0) || (actionList.contains(11) && actionList.size() == 1)) {
StringBuilder actionText = new StringBuilder();
actionText = actionText.append(ItemLogger.ITEM_BREAK);
actionText.append(",").append(ItemLogger.ITEM_DESTROY);
actionText.append(",").append(ItemLogger.ITEM_CREATE);
actionText.append(",").append(ItemLogger.ITEM_SELL);
actionText.append(",").append(ItemLogger.ITEM_BUY);
actionExclude = actionText.toString();
}
if (!actionList.isEmpty()) {
StringBuilder actionText = new StringBuilder();
for (Integer actionTarget : actionList) {
@@ -449,18 +480,27 @@ public class Lookup extends Queue {
// If selecting from co_item & co_container, add in actions for both transaction types
if (actionList.contains(11) && actionList.contains(4)) {
if (actionTarget == ItemLogger.ITEM_REMOVE) {
actionText.append(",").append(ItemLogger.ITEM_DROP);
actionText.append(",").append(ItemLogger.ITEM_ADD_ENDER);
}
if (actionTarget == ItemLogger.ITEM_ADD) {
actionText.append(",").append(ItemLogger.ITEM_PICKUP);
actionText.append(",").append(ItemLogger.ITEM_REMOVE_ENDER);
actionText.append(",").append(ItemLogger.ITEM_CREATE);
actionText.append(",").append(ItemLogger.ITEM_BUY);
}
if (actionTarget == ItemLogger.ITEM_ADD) {
actionText.append(",").append(ItemLogger.ITEM_DROP);
actionText.append(",").append(ItemLogger.ITEM_ADD_ENDER);
actionText.append(",").append(ItemLogger.ITEM_THROW);
actionText.append(",").append(ItemLogger.ITEM_SHOOT);
actionText.append(",").append(ItemLogger.ITEM_BREAK);
actionText.append(",").append(ItemLogger.ITEM_DESTROY);
actionText.append(",").append(ItemLogger.ITEM_SELL);
}
}
// If just looking up drops/pickups, include ender chest transactions
else if (actionList.contains(11) && !actionList.contains(4)) {
if (actionTarget == ItemLogger.ITEM_DROP) {
actionText.append(",").append(ItemLogger.ITEM_ADD_ENDER);
actionText.append(",").append(ItemLogger.ITEM_THROW);
actionText.append(",").append(ItemLogger.ITEM_SHOOT);
}
if (actionTarget == ItemLogger.ITEM_PICKUP) {
actionText.append(",").append(ItemLogger.ITEM_REMOVE_ENDER);
@@ -511,7 +551,7 @@ public class Lookup extends Queue {
if (validAction) {
queryBlock = queryBlock + " action IN(" + action + ") AND";
}
else if (includeBlock.length() > 0 || includeEntity.length() > 0 || excludeBlock.length() > 0 || excludeEntity.length() > 0) {
else if (inventoryQuery || actionExclude.length() > 0 || includeBlock.length() > 0 || includeEntity.length() > 0 || excludeBlock.length() > 0 || excludeEntity.length() > 0) {
queryBlock = queryBlock + " action NOT IN(-1) AND";
}
@@ -535,8 +575,12 @@ public class Lookup extends Queue {
queryBlock = queryBlock + " user NOT IN(" + excludeUsers + ") AND";
}
if (checkTime > 0) {
queryBlock = queryBlock + " time > '" + checkTime + "' AND";
if (startTime > 0) {
queryBlock = queryBlock + " time > '" + startTime + "' AND";
}
if (endTime > 0) {
queryBlock = queryBlock + " time <= '" + endTime + "' AND";
}
if (actionList.contains(10)) {
@@ -562,6 +606,7 @@ public class Lookup extends Queue {
String baseQuery = ((!includeEntity.isEmpty() || !excludeEntity.isEmpty()) ? queryEntity : queryBlock);
if (limitOffset > -1 && limitCount > -1) {
queryLimit = " LIMIT " + limitOffset + ", " + limitCount + "";
unionLimit = " ORDER BY time DESC, id DESC LIMIT " + (limitOffset + limitCount) + "";
}
String rows = "rowid as id,time,user,wid,x,y,z,action,type,data,meta,blockdata,rolled_back";
@@ -600,8 +645,10 @@ public class Lookup extends Queue {
rows = "COUNT(*) as count";
queryLimit = " LIMIT 0, 3";
queryOrder = "";
unionLimit = "";
}
String unionSelect = "SELECT * FROM (";
if (Config.getGlobal().MYSQL) {
if (radius == null || users.length() > 0 || includeBlock.length() > 0 || includeEntity.length() > 0) {
// index_mysql = "IGNORE INDEX(wid) ";
@@ -617,10 +664,15 @@ public class Lookup extends Queue {
if (users.length() > 0) {
index = "USE INDEX(user) ";
}
if ((radius != null || actionList.contains(5)) || (index.equals("") && restrictWorld)) {
if ((index.equals("") && restrictWorld)) {
index = "USE INDEX(wid) ";
}
if ((radius != null || actionList.size() > 0)) {
index = "";
}
}
unionSelect = "(";
}
else {
if (queryTable.equals("block")) {
@@ -630,23 +682,39 @@ public class Lookup extends Queue {
if (users.length() > 0) {
index = "INDEXED BY block_user_index ";
}
if ((radius != null || actionList.contains(5)) || (index.equals("") && restrictWorld)) {
if ((index.equals("") && restrictWorld)) {
index = "INDEXED BY block_index ";
}
if ((radius != null || actionList.size() > 0)) {
index = "";
}
}
}
boolean itemLookup = (actionList.contains(4) && actionList.contains(11));
if (lookup && actionList.size() == 0) {
boolean itemLookup = inventoryQuery;
if ((lookup && actionList.size() == 0) || (itemLookup && !actionList.contains(0))) {
if (!count) {
rows = "rowid as id,time,user,wid,x,y,z,type,meta as metadata,data,-1 as amount,action,rolled_back";
}
if (inventoryQuery) {
if (validAction) {
baseQuery = baseQuery.replace("action IN(" + action + ")", "action IN(1)");
}
else {
baseQuery = baseQuery.replace("action NOT IN(-1)", "action IN(1)");
}
if (!count) {
rows = "rowid as id,time,user,wid,x,y,z,type,meta as metadata,data,1 as amount,action,rolled_back";
}
}
if (includeBlock.length() > 0 || excludeBlock.length() > 0) {
baseQuery = baseQuery.replace("action NOT IN(-1)", "action NOT IN(3)"); // if block specified for include/exclude, filter out entity data
}
query = "SELECT " + rows + " FROM " + ConfigHandler.prefix + queryTable + " " + index + "WHERE" + baseQuery + " UNION ";
query = unionSelect + "SELECT " + "'0' as tbl," + rows + " FROM " + ConfigHandler.prefix + "block " + index + "WHERE" + baseQuery + unionLimit + ") UNION ALL ";
itemLookup = true;
}
@@ -654,17 +722,26 @@ public class Lookup extends Queue {
if (!count) {
rows = "rowid as id,time,user,wid,x,y,z,type,metadata,data,amount,action,rolled_back";
}
query = query + "SELECT " + rows + " FROM " + ConfigHandler.prefix + "container WHERE" + queryBlock + " UNION ";
query = query + unionSelect + "SELECT " + "'1' as tbl," + rows + " FROM " + ConfigHandler.prefix + "container WHERE" + queryBlock + unionLimit + ") UNION ALL ";
if (!count) {
rows = "rowid as id,time,user,wid,x,y,z,type,data as metadata,0 as data,amount,action,0 as rolled_back";
queryOrder = " ORDER BY time DESC, id DESC";
rows = "rowid as id,time,user,wid,x,y,z,type,data as metadata,0 as data,amount,action,rolled_back";
queryOrder = " ORDER BY time DESC, tbl DESC, id DESC";
}
query = query + "SELECT " + rows + " FROM " + ConfigHandler.prefix + "item WHERE" + queryBlock;
if (actionExclude.length() > 0) {
queryBlock = queryBlock.replace("action NOT IN(-1)", "action NOT IN(" + actionExclude + ")");
}
query = query + unionSelect + "SELECT " + "'2' as tbl," + rows + " FROM " + ConfigHandler.prefix + "item WHERE" + queryBlock + unionLimit + ")";
}
if (query.length() == 0) {
query = "SELECT " + rows + " FROM " + ConfigHandler.prefix + queryTable + " " + index + "WHERE" + baseQuery;
if (actionExclude.length() > 0) {
baseQuery = baseQuery.replace("action NOT IN(-1)", "action NOT IN(" + actionExclude + ")");
}
query = "SELECT " + "'0' as tbl," + rows + " FROM " + ConfigHandler.prefix + queryTable + " " + index + "WHERE" + baseQuery;
}
query = query + queryOrder + queryLimit + "";
@@ -677,6 +754,21 @@ public class Lookup extends Queue {
return results;
}
/*
private static long calculateTableOffset(long col2, long col3, long limitOffset, int limitCount) {
return (limitOffset - (col2 + col3)) < 0L ? 0L : (limitOffset - (col2 + col3));
}
private static long calculateTableLimit(long col1, long col2, long col3, long limitOffset, int limitCount) {
long offset = calculateTableOffset(col2, col3, limitOffset, limitCount);
long limit = (col2 + col3) + limitCount;
limit = (limit > (limitOffset + limitCount)) ? (limitOffset + limitCount) : limit;
limit = (limit > (col1 - offset)) ? (col1 - offset) : limit;
return limit;
}
*/
public static String whoPlaced(Statement statement, BlockState block) {
String result = "";
@@ -690,7 +782,7 @@ public class Lookup extends Queue {
int z = block.getZ();
int time = (int) (System.currentTimeMillis() / 1000L);
int worldId = Util.getWorldId(block.getWorld().getName());
String query = "SELECT user,type FROM " + ConfigHandler.prefix + "block WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND rolled_back = '0' AND action='1' ORDER BY rowid DESC LIMIT 0, 1";
String query = "SELECT user,type FROM " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND rolled_back IN(0,2) AND action='1' ORDER BY rowid DESC LIMIT 0, 1";
ResultSet results = statement.executeQuery(query);
while (results.next()) {
File diff suppressed because it is too large. Load diff
@@ -8,6 +8,7 @@ import org.bukkit.Location;
import org.bukkit.Material;
import net.coreprotect.CoreProtect;
import net.coreprotect.bukkit.BukkitAdapter;
import net.coreprotect.config.ConfigHandler;
import net.coreprotect.database.statement.BlockStatement;
import net.coreprotect.database.statement.UserStatement;
@@ -21,7 +22,7 @@ public class BlockBreakLogger {
throw new IllegalStateException("Database class");
}
public static void log(PreparedStatement preparedStmt, int batchCount, String user, Location location, int type, int data, List<Object> meta, String blockData) {
public static void log(PreparedStatement preparedStmt, int batchCount, String user, Location location, int type, int data, List<Object> meta, String blockData, String overrideData) {
try {
if (ConfigHandler.blacklist.get(user.toLowerCase(Locale.ROOT)) != null || location == null) {
return;
@@ -42,6 +43,9 @@ public class BlockBreakLogger {
if (checkType == Material.LECTERN) {
blockData = blockData.replaceFirst("has_book=true", "has_book=false");
}
else if (checkType == Material.PAINTING || BukkitAdapter.ADAPTER.isItemFrame(checkType)) {
blockData = overrideData;
}
CoreProtectPreLogEvent event = new CoreProtectPreLogEvent(user);
CoreProtect.getInstance().getServer().getPluginManager().callEvent(event);
@@ -5,12 +5,7 @@ import java.util.List;
import java.util.Locale;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.type.Bed;
import org.bukkit.block.data.type.Door;
import org.bukkit.block.data.type.Door.Hinge;
import net.coreprotect.CoreProtect;
import net.coreprotect.bukkit.BukkitAdapter;
@@ -18,7 +13,6 @@ import net.coreprotect.config.ConfigHandler;
import net.coreprotect.database.statement.BlockStatement;
import net.coreprotect.database.statement.UserStatement;
import net.coreprotect.event.CoreProtectPreLogEvent;
import net.coreprotect.model.BlockGroup;
import net.coreprotect.thread.CacheHandler;
import net.coreprotect.utility.Util;
@@ -33,6 +27,7 @@ public class BlockPlaceLogger {
if (user == null || ConfigHandler.blacklist.get(user.toLowerCase(Locale.ROOT)) != null) {
return;
}
Material type = block.getType();
if (blockData == null && (forceType == null || (!forceType.equals(Material.WATER)) && (!forceType.equals(Material.LAVA)))) {
blockData = block.getBlockData().getAsString();
@@ -59,106 +54,48 @@ public class BlockPlaceLogger {
return;
}
int x = block.getX();
int y = block.getY();
int z = block.getZ();
long chunkKey = (x >> 4) & 0xffffffffL | ((z >> 4) & 0xffffffffL) << 32;
if (ConfigHandler.populatedChunks.get(chunkKey) != null) {
boolean isWater = user.equals("#water");
boolean isLava = user.equals("#lava");
boolean isVine = user.equals("#vine");
if (isWater || isLava || isVine) {
int timeDelay = isWater ? 60 : 240;
long timeSincePopulation = ((System.currentTimeMillis() / 1000L) - ConfigHandler.populatedChunks.getOrDefault(chunkKey, 0L));
if (timeSincePopulation <= timeDelay) {
return;
}
if (timeSincePopulation > 240) {
ConfigHandler.populatedChunks.remove(chunkKey);
}
}
else if (type == Material.WATER || type == Material.LAVA) {
ConfigHandler.populatedChunks.remove(chunkKey);
}
}
CoreProtectPreLogEvent event = new CoreProtectPreLogEvent(user);
CoreProtect.getInstance().getServer().getPluginManager().callEvent(event);
int userId = UserStatement.getId(preparedStmt, event.getUser(), true);
int wid = Util.getWorldId(block.getWorld().getName());
int time = (int) (System.currentTimeMillis() / 1000L);
int x = block.getX();
int y = block.getY();
int z = block.getZ();
int dx = x;
int dy = y;
int dz = z;
Material doubletype = type;
int doubledata = data;
int logdouble = 0;
if (event.getUser().length() > 0) {
CacheHandler.lookupCache.put("" + x + "." + y + "." + z + "." + wid + "", new Object[] { time, event.getUser(), type });
}
String doubleBlockData = null;
if (type.name().endsWith("_BED") || type == Material.IRON_DOOR || BlockGroup.DOORS.contains(type)) { // properly log double blocks (doors/beds)
BlockData blockStateBlockData = block.getBlockData();
if (blockStateBlockData instanceof Bed) {
Bed bed = (Bed) blockStateBlockData;
Bed.Part bedPart = bed.getPart();
BlockFace face = bed.getFacing();
int bedData = 1;
switch (face) {
case WEST:
dx = ((bedPart == Bed.Part.HEAD) ? (x + 1) : (x - 1));
bedData = 2;
break;
case EAST:
dx = ((bedPart == Bed.Part.HEAD) ? (x - 1) : (x + 1));
bedData = 3;
break;
case SOUTH:
dz = ((bedPart == Bed.Part.HEAD) ? (z - 1) : (z + 1));
bedData = 4;
break;
default:
dz = ((bedPart == Bed.Part.HEAD) ? (z + 1) : (z - 1));
break;
}
if (bedPart == Bed.Part.HEAD) {
data = 4 + bedData;
doubledata = bedData;
bed.setPart(Bed.Part.FOOT);
doubleBlockData = bed.getAsString();
}
else {
data = bedData;
doubledata = 4 + bedData;
bed.setPart(Bed.Part.HEAD);
doubleBlockData = bed.getAsString();
}
}
else if (blockStateBlockData instanceof Door) {
Door door = (Door) blockStateBlockData;
BlockFace face = door.getFacing();
Hinge hinge = door.getHinge();
switch (face) {
case EAST:
data = 0;
break;
case SOUTH:
data = 1;
break;
case WEST:
data = 2;
break;
default:
data = 3;
break;
}
if (hinge.equals(Hinge.RIGHT)) {
data = data + 4;
}
if (data < 8) {
dy = y + 1;
doubledata = data + 8;
}
}
logdouble = 1;
}
int internalType = Util.getBlockId(type.name(), true);
int internalDoubleType = Util.getBlockId(doubletype.name(), true);
if (replacedType > 0 && Util.getType(replacedType) != Material.AIR && Util.getType(replacedType) != Material.CAVE_AIR) {
BlockStatement.insert(preparedStmt, batchCount, time, userId, wid, x, y, z, replacedType, replacedData, null, replaceBlockData, 0, 0);
}
BlockStatement.insert(preparedStmt, batchCount, time, userId, wid, x, y, z, internalType, data, meta, blockData, 1, 0);
if (logdouble == 1) {
BlockStatement.insert(preparedStmt, batchCount, time, userId, wid, dx, dy, dz, internalDoubleType, doubledata, null, doubleBlockData, 1, 0);
}
}
catch (Exception e) {
e.printStackTrace();
@@ -19,7 +19,7 @@ public class ContainerBreakLogger {
public static void log(PreparedStatement preparedStmt, int batchCount, String player, Location l, Material type, ItemStack[] oldInventory) {
try {
Util.mergeItems(type, oldInventory);
ContainerLogger.logTransaction(preparedStmt, batchCount, player, type, oldInventory, 0, l);
ContainerLogger.logTransaction(preparedStmt, batchCount, player, type, null, oldInventory, 0, l);
String loggingContainerId = player.toLowerCase(Locale.ROOT) + "." + l.getBlockX() + "." + l.getBlockY() + "." + l.getBlockZ();
// If there was a pending chest transaction, it would have already been processed.
@@ -9,6 +9,7 @@ import java.util.Map;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.ItemFrame;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
@@ -31,12 +32,19 @@ public class ContainerLogger extends Queue {
public static void log(PreparedStatement preparedStmtContainer, PreparedStatement preparedStmtItems, int batchCount, String player, Material type, Object container, Location location) {
try {
ItemStack[] contents = null;
if (type.equals(Material.ARMOR_STAND)) {
String faceData = null;
if (type == Material.ARMOR_STAND) {
EntityEquipment equipment = (EntityEquipment) container;
if (equipment != null) {
contents = Util.getArmorStandContents(equipment);
}
}
else if (type == Material.ITEM_FRAME) {
ItemFrame itemFrame = (ItemFrame) container;
contents = Util.getItemFrameItem(itemFrame);
faceData = itemFrame.getFacing().name();
}
else {
Inventory inventory = (Inventory) container;
if (inventory != null) {
@@ -133,12 +141,12 @@ public class ContainerLogger extends Queue {
Util.mergeItems(type, newInventory);
if (type != Material.ENDER_CHEST) {
logTransaction(preparedStmtContainer, batchCount, player, type, oldInventory, 0, location);
logTransaction(preparedStmtContainer, batchCount, player, type, newInventory, 1, location);
logTransaction(preparedStmtContainer, batchCount, player, type, faceData, oldInventory, 0, location);
logTransaction(preparedStmtContainer, batchCount, player, type, faceData, newInventory, 1, location);
}
else { // pass ender chest transactions to item logger
ItemLogger.logTransaction(preparedStmtItems, batchCount, player, location, oldInventory, ItemLogger.ITEM_REMOVE_ENDER);
ItemLogger.logTransaction(preparedStmtItems, batchCount, player, location, newInventory, ItemLogger.ITEM_ADD_ENDER);
ItemLogger.logTransaction(preparedStmtItems, batchCount, 0, player, location, oldInventory, ItemLogger.ITEM_REMOVE_ENDER);
ItemLogger.logTransaction(preparedStmtItems, batchCount, 0, player, location, newInventory, ItemLogger.ITEM_ADD_ENDER);
}
oldList.remove(0);
@@ -149,7 +157,7 @@ public class ContainerLogger extends Queue {
}
}
protected static void logTransaction(PreparedStatement preparedStmt, int batchCount, String user, Material type, ItemStack[] items, int action, Location location) {
protected static void logTransaction(PreparedStatement preparedStmt, int batchCount, String user, Material type, String faceData, ItemStack[] items, int action, Location location) {
try {
if (ConfigHandler.blacklist.get(user.toLowerCase(Locale.ROOT)) != null) {
return;
@@ -159,7 +167,7 @@ public class ContainerLogger extends Queue {
if (item != null) {
if (item.getAmount() > 0 && !Util.isAir(item.getType())) {
// Object[] metadata = new Object[] { slot, item.getItemMeta() };
List<List<Map<String, Object>>> metadata = ItemMetaHandler.seralize(item, type, slot);
List<List<Map<String, Object>>> metadata = ItemMetaHandler.seralize(item, type, faceData, slot);
if (metadata.size() == 0) {
metadata = null;
}
@@ -25,12 +25,19 @@ public class ItemLogger {
public static final int ITEM_PICKUP = 3;
public static final int ITEM_REMOVE_ENDER = 4;
public static final int ITEM_ADD_ENDER = 5;
public static final int ITEM_THROW = 6;
public static final int ITEM_SHOOT = 7;
public static final int ITEM_BREAK = 8;
public static final int ITEM_DESTROY = 9;
public static final int ITEM_CREATE = 10;
public static final int ITEM_SELL = 11;
public static final int ITEM_BUY = 12;
private ItemLogger() {
throw new IllegalStateException("Database class");
}
public static void log(PreparedStatement preparedStmt, int batchCount, Location location, String user) {
public static void log(PreparedStatement preparedStmt, int batchCount, Location location, int offset, String user) {
try {
if (ConfigHandler.blacklist.get(user.toLowerCase(Locale.ROOT)) != null) {
return;
@@ -38,32 +45,81 @@ public class ItemLogger {
String loggingItemId = user.toLowerCase(Locale.ROOT) + "." + location.getBlockX() + "." + location.getBlockY() + "." + location.getBlockZ();
List<ItemStack> dropList = ConfigHandler.itemsDrop.getOrDefault(loggingItemId, new ArrayList<>());
ItemStack[] itemDrops = new ItemStack[dropList.size()];
itemDrops = dropList.toArray(itemDrops);
dropList.clear();
List<ItemStack> pickupList = ConfigHandler.itemsPickup.getOrDefault(loggingItemId, new ArrayList<>());
ItemStack[] itemPickups = new ItemStack[pickupList.size()];
itemPickups = pickupList.toArray(itemPickups);
pickupList.clear();
Util.mergeItems(null, itemDrops);
List<ItemStack> dropList = ConfigHandler.itemsDrop.getOrDefault(loggingItemId, new ArrayList<>());
ItemStack[] itemDrops = new ItemStack[dropList.size()];
itemDrops = dropList.toArray(itemDrops);
dropList.clear();
List<ItemStack> thrownList = ConfigHandler.itemsThrown.getOrDefault(loggingItemId, new ArrayList<>());
ItemStack[] itemThrows = new ItemStack[thrownList.size()];
itemThrows = thrownList.toArray(itemThrows);
thrownList.clear();
List<ItemStack> shotList = ConfigHandler.itemsShot.getOrDefault(loggingItemId, new ArrayList<>());
ItemStack[] itemShots = new ItemStack[shotList.size()];
itemShots = shotList.toArray(itemShots);
shotList.clear();
List<ItemStack> breakList = ConfigHandler.itemsBreak.getOrDefault(loggingItemId, new ArrayList<>());
ItemStack[] itemBreaks = new ItemStack[breakList.size()];
itemBreaks = breakList.toArray(itemBreaks);
breakList.clear();
List<ItemStack> destroyList = ConfigHandler.itemsDestroy.getOrDefault(loggingItemId, new ArrayList<>());
ItemStack[] itemDestroys = new ItemStack[destroyList.size()];
itemDestroys = destroyList.toArray(itemDestroys);
destroyList.clear();
List<ItemStack> createList = ConfigHandler.itemsCreate.getOrDefault(loggingItemId, new ArrayList<>());
ItemStack[] itemCreates = new ItemStack[createList.size()];
itemCreates = createList.toArray(itemCreates);
createList.clear();
List<ItemStack> sellList = ConfigHandler.itemsSell.getOrDefault(loggingItemId, new ArrayList<>());
ItemStack[] itemSells = new ItemStack[sellList.size()];
itemSells = sellList.toArray(itemSells);
sellList.clear();
List<ItemStack> buyList = ConfigHandler.itemsBuy.getOrDefault(loggingItemId, new ArrayList<>());
ItemStack[] itemBuys = new ItemStack[buyList.size()];
itemBuys = buyList.toArray(itemBuys);
buyList.clear();
Util.mergeItems(null, itemPickups);
logTransaction(preparedStmt, batchCount, user, location, itemDrops, ITEM_DROP);
logTransaction(preparedStmt, batchCount, user, location, itemPickups, ITEM_PICKUP);
Util.mergeItems(null, itemDrops);
Util.mergeItems(null, itemThrows);
Util.mergeItems(null, itemShots);
Util.mergeItems(null, itemBreaks);
Util.mergeItems(null, itemDestroys);
Util.mergeItems(null, itemCreates);
Util.mergeItems(null, itemSells);
Util.mergeItems(null, itemBuys);
logTransaction(preparedStmt, batchCount, offset, user, location, itemPickups, ITEM_PICKUP);
logTransaction(preparedStmt, batchCount, offset, user, location, itemDrops, ITEM_DROP);
logTransaction(preparedStmt, batchCount, offset, user, location, itemThrows, ITEM_THROW);
logTransaction(preparedStmt, batchCount, offset, user, location, itemShots, ITEM_SHOOT);
logTransaction(preparedStmt, batchCount, offset, user, location, itemBreaks, ITEM_BREAK);
logTransaction(preparedStmt, batchCount, offset, user, location, itemDestroys, ITEM_DESTROY);
logTransaction(preparedStmt, batchCount, offset, user, location, itemCreates, ITEM_CREATE);
logTransaction(preparedStmt, batchCount, offset, user, location, itemSells, ITEM_SELL);
logTransaction(preparedStmt, batchCount, offset, user, location, itemBuys, ITEM_BUY);
}
catch (Exception e) {
e.printStackTrace();
}
}
protected static void logTransaction(PreparedStatement preparedStmt, int batchCount, String user, Location location, ItemStack[] items, int action) {
protected static void logTransaction(PreparedStatement preparedStmt, int batchCount, int offset, String user, Location location, ItemStack[] items, int action) {
try {
for (ItemStack item : items) {
if (item != null && item.getAmount() > 0 && !Util.isAir(item.getType())) {
// Object[] metadata = new Object[] { slot, item.getItemMeta() };
List<List<Map<String, Object>>> data = ItemMetaHandler.seralize(item, null, 0);
List<List<Map<String, Object>>> data = ItemMetaHandler.seralize(item, null, null, 0);
if (data.size() == 0) {
data = null;
}
@@ -73,7 +129,7 @@ public class ItemLogger {
int userId = UserStatement.getId(preparedStmt, event.getUser(), true);
int wid = Util.getWorldId(location.getWorld().getName());
int time = (int) (System.currentTimeMillis() / 1000L);
int time = (int) (System.currentTimeMillis() / 1000L) - offset;
int x = location.getBlockX();
int y = location.getBlockY();
int z = location.getBlockZ();
@@ -19,9 +19,9 @@ public class PlayerInteractLogger {
throw new IllegalStateException("Database class");
}
public static void log(PreparedStatement preparedStmt, int batchCount, String user, BlockState block) {
public static void log(PreparedStatement preparedStmt, int batchCount, String user, BlockState block, Material blockType) {
try {
int type = Util.getBlockId(block.getType().name(), true);
int type = Util.getBlockId(blockType.name(), true);
if (ConfigHandler.blacklist.get(user.toLowerCase(Locale.ROOT)) != null || Util.getType(type).equals(Material.AIR) || Util.getType(type).equals(Material.CAVE_AIR)) {
return;
}
@@ -36,7 +36,7 @@ public class SkullBreakLogger {
keys.close();
}
BlockBreakLogger.log(preparedStmt, batchCount, user, block.getLocation(), type, skullKey, null, block.getBlockData().getAsString());
BlockBreakLogger.log(preparedStmt, batchCount, user, block.getLocation(), type, skullKey, null, block.getBlockData().getAsString(), null);
}
catch (Exception e) {
e.printStackTrace();
@@ -56,7 +56,7 @@ public class BlockLookup {
String blockName = block.getType().name().toLowerCase(Locale.ROOT);
String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "block WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action IN(0,1) AND time >= '" + checkTime + "' LIMIT 0, 1";
String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action IN(0,1) AND time >= '" + checkTime + "' LIMIT 0, 1";
ResultSet results = statement.executeQuery(query);
while (results.next()) {
count = results.getInt("count");
@@ -64,7 +64,7 @@ public class BlockLookup {
results.close();
int totalPages = (int) Math.ceil(count / (limit + 0.0));
query = "SELECT time,user,action,type,data,rolled_back FROM " + ConfigHandler.prefix + "block WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action IN(0,1) AND time >= '" + checkTime + "' ORDER BY rowid DESC LIMIT " + page_start + ", " + limit + "";
query = "SELECT time,user,action,type,data,rolled_back FROM " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action IN(0,1) AND time >= '" + checkTime + "' ORDER BY rowid DESC LIMIT " + page_start + ", " + limit + "";
results = statement.executeQuery(query);
StringBuilder resultTextBuilder = new StringBuilder();
@@ -91,17 +91,20 @@ public class BlockLookup {
Phrase phrase = Phrase.LOOKUP_BLOCK;
String selector = Selector.FIRST;
String tag = Color.WHITE + "-";
if (resultAction == 2 || resultAction == 3) {
phrase = Phrase.LOOKUP_INTERACTION; // {clicked|killed}
selector = (resultAction != 3 ? Selector.FIRST : Selector.SECOND);
tag = (resultAction != 3 ? Color.WHITE + "-" : Color.RED + "-");
}
else {
phrase = Phrase.LOOKUP_BLOCK; // {placed|broke}
selector = (resultAction != 0 ? Selector.FIRST : Selector.SECOND);
tag = (resultAction != 0 ? Color.GREEN + "+" : Color.RED + "-");
}
String rbFormat = "";
if (resultRolledBack == 1) {
if (resultRolledBack == 1 || resultRolledBack == 3) {
rbFormat = Color.STRIKETHROUGH;
}
@@ -126,7 +129,7 @@ public class BlockLookup {
target = target.split(":")[1];
}
resultTextBuilder.append(timeAgo + " " + Color.WHITE + "- ").append(Phrase.build(phrase, Color.DARK_AQUA + rbFormat + resultUser + Color.WHITE + rbFormat, Color.DARK_AQUA + rbFormat + target + Color.WHITE, selector)).append("\n");
resultTextBuilder.append(timeAgo + " " + tag + " ").append(Phrase.build(phrase, Color.DARK_AQUA + rbFormat + resultUser + Color.WHITE + rbFormat, Color.DARK_AQUA + rbFormat + target + Color.WHITE, selector)).append("\n");
}
resultText = resultTextBuilder.toString();
@@ -135,7 +138,7 @@ public class BlockLookup {
if (found) {
if (count > limit) {
String pageInfo = Color.WHITE + "-----\n";
pageInfo = pageInfo + Util.getPageNavigation(command, page, totalPages) + "| " + Phrase.build(Phrase.LOOKUP_VIEW_PAGE, Color.WHITE, "/co l <page>") + "\n";
pageInfo = pageInfo + Util.getPageNavigation(command, page, totalPages) + "\n";
resultText = resultText + pageInfo;
}
}
@@ -53,9 +53,9 @@ public class ChestTransactionLookup {
int rowMax = page * limit;
int pageStart = rowMax - limit;
String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "container WHERE wid = '" + worldId + "' AND (x = '" + x + "' OR x = '" + x2 + "') AND (z = '" + z + "' OR z = '" + z2 + "') AND y = '" + y + "' LIMIT 0, 1";
String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "container " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + x + "' OR x = '" + x2 + "') AND (z = '" + z + "' OR z = '" + z2 + "') AND y = '" + y + "' LIMIT 0, 1";
if (exact) {
query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "container WHERE wid = '" + worldId + "' AND (x = '" + l.getBlockX() + "') AND (z = '" + l.getBlockZ() + "') AND y = '" + y + "' LIMIT 0, 1";
query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "container " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + l.getBlockX() + "') AND (z = '" + l.getBlockZ() + "') AND y = '" + y + "' LIMIT 0, 1";
}
ResultSet results = statement.executeQuery(query);
@@ -66,9 +66,9 @@ public class ChestTransactionLookup {
int totalPages = (int) Math.ceil(count / (limit + 0.0));
query = "SELECT time,user,action,type,data,amount,rolled_back FROM " + ConfigHandler.prefix + "container WHERE wid = '" + worldId + "' AND (x = '" + x + "' OR x = '" + x2 + "') AND (z = '" + z + "' OR z = '" + z2 + "') AND y = '" + y + "' ORDER BY rowid DESC LIMIT " + pageStart + ", " + limit + "";
query = "SELECT time,user,action,type,data,amount,rolled_back FROM " + ConfigHandler.prefix + "container " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + x + "' OR x = '" + x2 + "') AND (z = '" + z + "' OR z = '" + z2 + "') AND y = '" + y + "' ORDER BY rowid DESC LIMIT " + pageStart + ", " + limit + "";
if (exact) {
query = "SELECT time,user,action,type,data,amount,rolled_back FROM " + ConfigHandler.prefix + "container WHERE wid = '" + worldId + "' AND (x = '" + l.getBlockX() + "') AND (z = '" + l.getBlockZ() + "') AND y = '" + y + "' ORDER BY rowid DESC LIMIT " + pageStart + ", " + limit + "";
query = "SELECT time,user,action,type,data,amount,rolled_back FROM " + ConfigHandler.prefix + "container " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + l.getBlockX() + "') AND (z = '" + l.getBlockZ() + "') AND y = '" + y + "' ORDER BY rowid DESC LIMIT " + pageStart + ", " + limit + "";
}
results = statement.executeQuery(query);
@@ -95,8 +95,9 @@ public class ChestTransactionLookup {
found = true;
String selector = (resultAction != 0 ? Selector.FIRST : Selector.SECOND);
String tag = (resultAction != 0 ? Color.GREEN + "+" : Color.RED + "-");
String rbFormat = "";
if (resultRolledBack == 1) {
if (resultRolledBack == 1 || resultRolledBack == 3) {
rbFormat = Color.STRIKETHROUGH;
}
@@ -115,7 +116,7 @@ public class ChestTransactionLookup {
target = target.split(":")[1];
}
resultBuilder.append(timeAgo + " " + Color.WHITE + "- ").append(Phrase.build(Phrase.LOOKUP_CONTAINER, Color.DARK_AQUA + rbFormat + resultUser + Color.WHITE + rbFormat, "x" + resultAmount, Color.DARK_AQUA + rbFormat + target + Color.WHITE, selector)).append("\n");
resultBuilder.append(timeAgo + " " + tag + " ").append(Phrase.build(Phrase.LOOKUP_CONTAINER, Color.DARK_AQUA + rbFormat + resultUser + Color.WHITE + rbFormat, "x" + resultAmount, Color.DARK_AQUA + rbFormat + target + Color.WHITE, selector)).append("\n");
}
result = resultBuilder.toString();
results.close();
@@ -123,7 +124,7 @@ public class ChestTransactionLookup {
if (found) {
if (count > limit) {
String pageInfo = Color.WHITE + "-----\n";
pageInfo = pageInfo + Util.getPageNavigation(command, page, totalPages) + "| " + Phrase.build(Phrase.LOOKUP_VIEW_PAGE, Color.WHITE, "/co l <page>") + "\n";
pageInfo = pageInfo + Util.getPageNavigation(command, page, totalPages) + "\n";
result = result + pageInfo;
}
}
@@ -54,7 +54,7 @@ public class InteractionLookup {
checkTime = time - offset;
}
String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "block WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action='2' AND time >= '" + checkTime + "' LIMIT 0, 1";
String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action='2' AND time >= '" + checkTime + "' LIMIT 0, 1";
ResultSet results = statement.executeQuery(query);
while (results.next()) {
@@ -63,7 +63,7 @@ public class InteractionLookup {
results.close();
int totalPages = (int) Math.ceil(count / (limit + 0.0));
query = "SELECT time,user,action,type,data,rolled_back FROM " + ConfigHandler.prefix + "block WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action='2' AND time >= '" + checkTime + "' ORDER BY rowid DESC LIMIT " + pageStart + ", " + limit + "";
query = "SELECT time,user,action,type,data,rolled_back FROM " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action='2' AND time >= '" + checkTime + "' ORDER BY rowid DESC LIMIT " + pageStart + ", " + limit + "";
results = statement.executeQuery(query);
StringBuilder resultBuilder = new StringBuilder();
@@ -88,7 +88,7 @@ public class InteractionLookup {
found = true;
String rbFormat = "";
if (resultRolledBack == 1) {
if (resultRolledBack == 1 || resultRolledBack == 3) {
rbFormat = Color.STRIKETHROUGH;
}
@@ -115,7 +115,7 @@ public class InteractionLookup {
if (found) {
if (count > limit) {
String pageInfo = Color.WHITE + "-----\n";
pageInfo = pageInfo + Util.getPageNavigation(command, page, totalPages) + "| " + Phrase.build(Phrase.LOOKUP_VIEW_PAGE, Color.WHITE, "/co l <page>") + "\n";
pageInfo = pageInfo + Util.getPageNavigation(command, page, totalPages) + "\n";
result = result + pageInfo;
}
}
@@ -50,7 +50,7 @@ public class SignMessageLookup {
int rowMax = page * limit;
int pageStart = rowMax - limit;
String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "sign WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action = '1' AND (LENGTH(line_1) > 0 OR LENGTH(line_2) > 0 OR LENGTH(line_3) > 0 OR LENGTH(line_4) > 0) LIMIT 0, 1";
String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "sign " + Util.getWidIndex("sign") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action = '1' AND (LENGTH(line_1) > 0 OR LENGTH(line_2) > 0 OR LENGTH(line_3) > 0 OR LENGTH(line_4) > 0) LIMIT 0, 1";
ResultSet results = statement.executeQuery(query);
while (results.next()) {
@@ -60,7 +60,7 @@ public class SignMessageLookup {
int totalPages = (int) Math.ceil(count / (limit + 0.0));
query = "SELECT time,user,line_1,line_2,line_3,line_4 FROM " + ConfigHandler.prefix + "sign WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action = '1' AND (LENGTH(line_1) > 0 OR LENGTH(line_2) > 0 OR LENGTH(line_3) > 0 OR LENGTH(line_4) > 0) ORDER BY rowid DESC LIMIT " + pageStart + ", " + limit + "";
query = "SELECT time,user,line_1,line_2,line_3,line_4 FROM " + ConfigHandler.prefix + "sign " + Util.getWidIndex("sign") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action = '1' AND (LENGTH(line_1) > 0 OR LENGTH(line_2) > 0 OR LENGTH(line_3) > 0 OR LENGTH(line_4) > 0) ORDER BY rowid DESC LIMIT " + pageStart + ", " + limit + "";
results = statement.executeQuery(query);
while (results.next()) {
@@ -115,7 +115,7 @@ public class SignMessageLookup {
if (found) {
if (count > limit) {
result.add(Color.WHITE + "-----");
result.add(Util.getPageNavigation(command, page, totalPages) + "| " + Phrase.build(Phrase.LOOKUP_VIEW_PAGE, Color.WHITE, "/co l <page>"));
result.add(Util.getPageNavigation(command, page, totalPages));
}
}
else {
@@ -23,6 +23,7 @@ public class ItemStatement {
preparedStmt.setObject(8, byteData);
preparedStmt.setInt(9, amount);
preparedStmt.setInt(10, action);
preparedStmt.setInt(11, 0); // rolled_back
preparedStmt.addBatch();
if (batchCount > 0 && batchCount % 1000 == 0) {
@@ -38,8 +38,11 @@ public class Language {
phrases.put(Phrase.CACHE_ERROR, "WARNING: Error while validating {0} cache.");
phrases.put(Phrase.CACHE_RELOAD, "Forcing reload of {mapping|world} caches from database.");
phrases.put(Phrase.CHECK_CONFIG, "Please check config.yml");
phrases.put(Phrase.COMMAND_CONSOLE, "Please run the command from the console.");
phrases.put(Phrase.COMMAND_NOT_FOUND, "Command \"{0}\" not found.");
phrases.put(Phrase.COMMAND_THROTTLED, "Please wait a moment and try again.");
phrases.put(Phrase.CONSUMER_ERROR, "Consumer queue processing already {paused|resumed}.");
phrases.put(Phrase.CONSUMER_TOGGLED, "Consumer queue processing has been {paused|resumed}.");
phrases.put(Phrase.CONTAINER_HEADER, "Container Transactions");
phrases.put(Phrase.DATABASE_BUSY, "Database busy. Please try again later.");
phrases.put(Phrase.DATABASE_INDEX_ERROR, "Unable to validate database indexes.");
@@ -137,12 +140,12 @@ public class Language {
phrases.put(Phrase.LOOKUP_ITEM, "{0} {picked up|dropped} {1} {2}.");
phrases.put(Phrase.LOOKUP_LOGIN, "{0} logged {in|out}.");
phrases.put(Phrase.LOOKUP_PAGE, "Page {0}");
phrases.put(Phrase.LOOKUP_PROJECTILE, "{0} {threw|shot} {1} {2}.");
phrases.put(Phrase.LOOKUP_ROWS_FOUND, "{0} {row|rows} found.");
phrases.put(Phrase.LOOKUP_SEARCHING, "Lookup searching. Please wait...");
phrases.put(Phrase.LOOKUP_STORAGE, "{0} {deposited|withdrew} {1} {2}.");
phrases.put(Phrase.LOOKUP_TIME, "{0} ago");
phrases.put(Phrase.LOOKUP_USERNAME, "{0} logged in as {1}.");
phrases.put(Phrase.LOOKUP_VIEW_PAGE, "To view a page, type \"{0}\".");
phrases.put(Phrase.MAXIMUM_RADIUS, "The maximum {lookup|rollback|restore} radius is {0}.");
phrases.put(Phrase.MISSING_ACTION_USER, "To use that action, please specify a user.");
phrases.put(Phrase.MISSING_LOOKUP_TIME, "Please specify the amount of time to {lookup|rollback|restore}.");
@@ -168,8 +171,8 @@ public class Language {
phrases.put(Phrase.PLEASE_SELECT, "Please select: \"{0}\" or \"{1}\".");
phrases.put(Phrase.PREVIEW_CANCELLED, "Preview cancelled.");
phrases.put(Phrase.PREVIEW_CANCELLING, "Cancelling preview...");
phrases.put(Phrase.PREVIEW_CONTAINER, "You can't preview container transactions.");
phrases.put(Phrase.PREVIEW_IN_GAME, "You can only preview rollbacks in-game.");
phrases.put(Phrase.PREVIEW_TRANSACTION, "You can't preview {container|inventory} transactions.");
phrases.put(Phrase.PURGE_ABORTED, "Purge failed. Database may be corrupt.");
phrases.put(Phrase.PURGE_ERROR, "Unable to process {0} data!");
phrases.put(Phrase.PURGE_FAILED, "Purge failed. Please try again later.");
@@ -218,6 +221,7 @@ public class Language {
phrases.put(Phrase.UPDATE_NOTICE, "Notice: {0} is now available.");
phrases.put(Phrase.UPGRADE_IN_PROGRESS, "Upgrade in progress. Please try again later.");
phrases.put(Phrase.USER_NOT_FOUND, "User \"{0}\" not found.");
phrases.put(Phrase.USER_OFFLINE, "The user \"{0}\" is not online.");
phrases.put(Phrase.USING_MYSQL, "Using MySQL for data storage.");
phrases.put(Phrase.USING_SQLITE, "Using SQLite for data storage.");
phrases.put(Phrase.VALID_DONATION_KEY, "Valid donation key.");
@@ -19,8 +19,11 @@ public enum Phrase {
CACHE_ERROR,
CACHE_RELOAD,
CHECK_CONFIG,
COMMAND_CONSOLE,
COMMAND_NOT_FOUND,
COMMAND_THROTTLED,
CONSUMER_ERROR,
CONSUMER_TOGGLED,
CONTAINER_HEADER,
DATABASE_BUSY,
DATABASE_INDEX_ERROR,
@@ -118,12 +121,12 @@ public enum Phrase {
LOOKUP_ITEM,
LOOKUP_LOGIN,
LOOKUP_PAGE,
LOOKUP_PROJECTILE,
LOOKUP_ROWS_FOUND,
LOOKUP_SEARCHING,
LOOKUP_STORAGE,
LOOKUP_TIME,
LOOKUP_USERNAME,
LOOKUP_VIEW_PAGE,
MAXIMUM_RADIUS,
MISSING_ACTION_USER,
MISSING_LOOKUP_TIME,
@@ -149,8 +152,8 @@ public enum Phrase {
PLEASE_SELECT,
PREVIEW_CANCELLED,
PREVIEW_CANCELLING,
PREVIEW_CONTAINER,
PREVIEW_IN_GAME,
PREVIEW_TRANSACTION,
PURGE_ABORTED,
PURGE_ERROR,
PURGE_FAILED,
@@ -199,6 +202,7 @@ public enum Phrase {
UPDATE_NOTICE,
UPGRADE_IN_PROGRESS,
USER_NOT_FOUND,
USER_OFFLINE,
USING_MYSQL,
USING_SQLITE,
VALID_DONATION_KEY,
@@ -28,8 +28,10 @@ import net.coreprotect.listener.entity.HangingBreakByEntityListener;
import net.coreprotect.listener.entity.HangingBreakListener;
import net.coreprotect.listener.entity.HangingPlaceListener;
import net.coreprotect.listener.player.ArmorStandManipulateListener;
import net.coreprotect.listener.player.CraftItemListener;
import net.coreprotect.listener.player.FoodLevelChangeListener;
import net.coreprotect.listener.player.InventoryChangeListener;
import net.coreprotect.listener.player.InventoryClickListener;
import net.coreprotect.listener.player.PlayerBucketEmptyListener;
import net.coreprotect.listener.player.PlayerBucketFillListener;
import net.coreprotect.listener.player.PlayerChatListener;
@@ -38,10 +40,13 @@ import net.coreprotect.listener.player.PlayerDeathListener;
import net.coreprotect.listener.player.PlayerDropItemListener;
import net.coreprotect.listener.player.PlayerInteractEntityListener;
import net.coreprotect.listener.player.PlayerInteractListener;
import net.coreprotect.listener.player.PlayerItemBreakListener;
import net.coreprotect.listener.player.PlayerJoinListener;
import net.coreprotect.listener.player.PlayerQuitListener;
import net.coreprotect.listener.player.PlayerTakeLecternBookListener;
import net.coreprotect.listener.player.ProjectileLaunchListener;
import net.coreprotect.listener.player.SignChangeListener;
import net.coreprotect.listener.world.ChunkPopulateListener;
import net.coreprotect.listener.world.LeavesDecayListener;
import net.coreprotect.listener.world.PortalCreateListener;
import net.coreprotect.listener.world.StructureGrowListener;
@@ -82,25 +87,31 @@ public final class ListenerHandler {
pluginManager.registerEvents(new HangingBreakByEntityListener(), plugin);
// Player Listeners
pluginManager.registerEvents(new InventoryChangeListener(), plugin);
pluginManager.registerEvents(new ArmorStandManipulateListener(), plugin);
pluginManager.registerEvents(new CraftItemListener(), plugin);
pluginManager.registerEvents(new FoodLevelChangeListener(), plugin);
pluginManager.registerEvents(new InventoryChangeListener(), plugin);
pluginManager.registerEvents(new InventoryClickListener(), plugin);
pluginManager.registerEvents(new PlayerBucketEmptyListener(), plugin);
pluginManager.registerEvents(new PlayerBucketFillListener(), plugin);
pluginManager.registerEvents(new PlayerCommandListener(), plugin);
pluginManager.registerEvents(new PlayerDeathListener(), plugin);
pluginManager.registerEvents(new PlayerDropItemListener(), plugin);
pluginManager.registerEvents(new FoodLevelChangeListener(), plugin);
pluginManager.registerEvents(new PlayerPickupArrowListener(), plugin);
pluginManager.registerEvents(new PlayerInteractEntityListener(), plugin);
pluginManager.registerEvents(new PlayerInteractListener(), plugin);
pluginManager.registerEvents(new PlayerItemBreakListener(), plugin);
pluginManager.registerEvents(new PlayerJoinListener(), plugin);
pluginManager.registerEvents(new PlayerQuitListener(), plugin);
pluginManager.registerEvents(new SignChangeListener(), plugin);
pluginManager.registerEvents(new PlayerInteractListener(), plugin);
pluginManager.registerEvents(new PlayerTakeLecternBookListener(), plugin);
pluginManager.registerEvents(new ProjectileLaunchListener(), plugin);
// World Listeners
pluginManager.registerEvents(new StructureGrowListener(), plugin);
pluginManager.registerEvents(new ChunkPopulateListener(), plugin);
pluginManager.registerEvents(new LeavesDecayListener(), plugin);
pluginManager.registerEvents(new PortalCreateListener(), plugin);
pluginManager.registerEvents(new StructureGrowListener(), plugin);
// Paper Listeners / Fallbacks
try {
@@ -0,0 +1,55 @@
package net.coreprotect.listener;
import org.bukkit.Material;
import org.bukkit.entity.AbstractArrow;
import org.bukkit.entity.Arrow;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerPickupArrowEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionData;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionType;
import net.coreprotect.consumer.Queue;
import net.coreprotect.listener.entity.EntityPickupItemListener;
public final class PlayerPickupArrowListener extends Queue implements Listener {
public static ItemStack getArrowType(AbstractArrow arrow) {
ItemStack itemStack = null;
switch (arrow.getType()) {
case SPECTRAL_ARROW:
itemStack = new ItemStack(Material.SPECTRAL_ARROW);
break;
default:
itemStack = new ItemStack(Material.ARROW);
break;
}
if (arrow instanceof Arrow) {
Arrow arrowEntity = (Arrow) arrow;
PotionData data = arrowEntity.getBasePotionData();
if (data.getType() != PotionType.UNCRAFTABLE) {
itemStack = new ItemStack(Material.TIPPED_ARROW);
PotionMeta meta = (PotionMeta) itemStack.getItemMeta();
meta.setBasePotionData(data);
for (PotionEffect effect : arrowEntity.getCustomEffects()) {
meta.addCustomEffect(effect, false);
}
itemStack.setItemMeta(meta);
}
}
return itemStack;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
protected void onPlayerPickupArrowEvent(PlayerPickupArrowEvent event) {
ItemStack itemStack = getArrowType(event.getArrow());
EntityPickupItemListener.onItemPickup(event.getPlayer(), event.getArrow().getLocation(), itemStack);
}
}
@@ -22,6 +22,7 @@ import org.bukkit.block.data.MultipleFacing;
import org.bukkit.block.data.Rail;
import org.bukkit.block.data.Rail.Shape;
import org.bukkit.block.data.Waterlogged;
import org.bukkit.block.data.type.Bed;
import org.bukkit.block.data.type.Bell;
import org.bukkit.block.data.type.Lantern;
import org.bukkit.enchantments.Enchantment;
@@ -46,8 +47,10 @@ public final class BlockBreakListener extends Queue implements Listener {
if (blockData instanceof Directional && !(blockData instanceof Bisected) && scanMin != BlockUtil.BOTTOM && scanMin != BlockUtil.TOP) {
Directional directional = (Directional) blockData;
BlockFace blockFace = directional.getFacing();
boolean adjacent = scanBlock.getRelative(blockFace.getOppositeFace()).getLocation().equals(block.getLocation());
return adjacent;
if (blockData instanceof Bed) {
blockFace = ((Bed) blockData).getPart() == Bed.Part.FOOT ? blockFace.getOppositeFace() : blockFace;
}
return scanBlock.getRelative(blockFace.getOppositeFace()).getLocation().equals(block.getLocation());
}
else if (blockData instanceof MultipleFacing) {
MultipleFacing multipleFacing = (MultipleFacing) blockData;
@@ -119,10 +122,6 @@ public final class BlockBreakListener extends Queue implements Listener {
if (scanMin < 7) {
Location scanLocation = locationMap[scanMin - 1];
if (scanMin == 4 && (type == Material.IRON_DOOR || BlockGroup.DOORS.contains(type))) { // required for doors
scanLocation = locationMap[5];
scanDown = true;
}
Block scanBlock = world.getBlockAt(scanLocation);
Material scanType = scanBlock.getType();
if (scanMin == 5) {
@@ -27,9 +27,9 @@ import net.coreprotect.consumer.Queue;
import net.coreprotect.database.Database;
import net.coreprotect.model.BlockGroup;
public class BlockExplodeListener extends Queue implements Listener {
public final class BlockExplodeListener extends Queue implements Listener {
protected static void processBlockExplode(String user, World world, List<Block> blockList) {
public static void processBlockExplode(String user, World world, List<Block> blockList) {
HashMap<Location, Block> blockMap = new HashMap<>();
for (Block block : blockList) {
@@ -4,6 +4,7 @@ import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
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.Lightable;
@@ -13,10 +14,13 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockIgniteEvent.IgniteCause;
import org.bukkit.inventory.ItemStack;
import net.coreprotect.bukkit.BukkitAdapter;
import net.coreprotect.config.Config;
import net.coreprotect.consumer.Queue;
import net.coreprotect.database.logger.ItemLogger;
import net.coreprotect.listener.player.ProjectileLaunchListener;
import net.coreprotect.model.BlockGroup;
import net.coreprotect.thread.CacheHandler;
import net.coreprotect.utility.Util;
@@ -74,9 +78,59 @@ public final class BlockIgniteListener extends Queue implements Listener {
}
}
if (blockIgnited == Material.FIRE && event.getCause() == IgniteCause.LAVA && event.getIgnitingBlock() != null) {
boolean burnableBlock = false;
for (BlockFace face : BlockFace.values()) {
Location blockLocation = block.getLocation();
scanLocation.setX(blockLocation.getX());
scanLocation.setY(blockLocation.getY());
scanLocation.setZ(blockLocation.getZ());
switch (face) {
case NORTH:
scanLocation.setZ(scanLocation.getZ() - 1);
break;
case SOUTH:
scanLocation.setZ(scanLocation.getZ() + 1);
break;
case WEST:
scanLocation.setX(scanLocation.getX() - 1);
break;
case EAST:
scanLocation.setX(scanLocation.getX() + 1);
break;
case DOWN:
scanLocation.setY(scanLocation.getY() - 1);
break;
case UP:
scanLocation.setY(scanLocation.getY() + 1);
break;
default:
continue;
}
if (scanLocation.getY() < BukkitAdapter.ADAPTER.getMinHeight(world) || scanLocation.getY() >= world.getMaxHeight()) {
continue;
}
if (scanLocation.getBlock().getType().isBurnable()) {
burnableBlock = true;
break;
}
}
if (!burnableBlock) {
return;
}
}
Queue.queueBlockPlace("#fire", block.getState(), block.getType(), replacedBlock, blockIgnited, -1, 0, forceBlockData.getAsString());
}
else {
if (event.getCause() == IgniteCause.FIREBALL) {
ProjectileLaunchListener.playerLaunchProjectile(event.getPlayer().getLocation(), event.getPlayer().getName(), new ItemStack(Material.FIRE_CHARGE), 1, -1, 1, ItemLogger.ITEM_THROW);
}
Player player = event.getPlayer();
Queue.queueBlockPlace(player.getName(), block.getState(), block.getType(), replacedBlock, blockIgnited, -1, 0, forceBlockData.getAsString());
int unixtimestamp = (int) (System.currentTimeMillis() / 1000L);
@@ -15,7 +15,9 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.inventory.ItemStack;
import net.coreprotect.config.Config;
import net.coreprotect.config.ConfigHandler;
import net.coreprotect.consumer.Queue;
import net.coreprotect.listener.block.BlockUtil;
@@ -25,24 +27,27 @@ public final class CreatureSpawnListener extends Queue implements Listener {
@EventHandler
public void onCreatureSpawn(CreatureSpawnEvent event) {
if (event.isCancelled()) {
if (event.isCancelled() || !event.getEntityType().equals(EntityType.ARMOR_STAND)) {
return;
}
if (event.getEntityType().equals(EntityType.ARMOR_STAND)) {
World world = event.getEntity().getWorld();
Location location = event.getEntity().getLocation();
String key = world.getName() + "-" + location.getBlockX() + "-" + location.getBlockY() + "-" + location.getBlockZ();
Iterator<Entry<UUID, Object[]>> it = ConfigHandler.entityBlockMapper.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<UUID, Object[]> pair = it.next();
UUID uuid = pair.getKey();
Object[] data = pair.getValue();
if ((data[0].equals(key) || data[1].equals(key)) && Util.getEntityMaterial(event.getEntityType()).equals(data[2])) {
Player player = Bukkit.getServer().getPlayer(uuid);
Block gravityLocation = BlockUtil.gravityScan(location, Material.ARMOR_STAND, player.getName());
Queue.queueBlockPlace(player.getName(), gravityLocation.getState(), location.getBlock().getType(), location.getBlock().getState(), (Material) data[2], (int) event.getEntity().getLocation().getYaw(), 1, null);
it.remove();
}
World world = event.getEntity().getWorld();
if (!Config.getConfig(world).BLOCK_PLACE) {
return;
}
Location location = event.getEntity().getLocation();
String key = world.getName() + "-" + location.getBlockX() + "-" + location.getBlockY() + "-" + location.getBlockZ();
Iterator<Entry<UUID, Object[]>> it = ConfigHandler.entityBlockMapper.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<UUID, Object[]> pair = it.next();
UUID uuid = pair.getKey();
Object[] data = pair.getValue();
if ((data[0].equals(key) || data[1].equals(key)) && Util.getEntityMaterial(event.getEntityType()) == ((ItemStack) data[2]).getType()) {
Player player = Bukkit.getServer().getPlayer(uuid);
Block gravityLocation = BlockUtil.gravityScan(location, Material.ARMOR_STAND, player.getName());
Queue.queueBlockPlace(player.getName(), gravityLocation.getState(), location.getBlock().getType(), location.getBlock().getState(), ((ItemStack) data[2]).getType(), (int) event.getEntity().getLocation().getYaw(), 1, null);
it.remove();
}
}
}
@@ -13,11 +13,10 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByBlockEvent;
import net.coreprotect.bukkit.BukkitAdapter;
import net.coreprotect.config.Config;
import net.coreprotect.consumer.Queue;
import net.coreprotect.database.Database;
import net.coreprotect.utility.Util;
import net.coreprotect.listener.player.PlayerInteractEntityListener;
public final class EntityDamageByBlockListener extends Queue implements Listener {
@@ -33,7 +32,7 @@ public final class EntityDamageByBlockListener extends Queue implements Listener
return;
}
if (event.isCancelled() || !Config.getConfig(entity.getWorld()).BLOCK_BREAK) {
if (event.isCancelled()) {
return;
}
@@ -43,22 +42,17 @@ public final class EntityDamageByBlockListener extends Queue implements Listener
user = "#tnt";
}
if (entity instanceof ItemFrame) {
Material frameType = BukkitAdapter.ADAPTER.getFrameType(entity);
ItemFrame frame = (ItemFrame) event.getEntity();
int data = 0;
if (frame.getItem() != null) {
data = Util.getBlockId(frame.getItem().getType());
if (entity instanceof ItemFrame && Config.getConfig(entity.getWorld()).ITEM_TRANSACTIONS) {
ItemFrame frame = (ItemFrame) entity;
if (frame.getItem().getType() != Material.AIR) {
PlayerInteractEntityListener.queueFrameTransaction(user, frame, false);
}
Queue.queueBlockBreak(user, block.getState(), frameType, null, data);
Queue.queueBlockPlace(user, block.getState(), frameType, null, frameType, -1, 0, null);
}
else if (entity instanceof ArmorStand) {
else if (entity instanceof ArmorStand && Config.getConfig(entity.getWorld()).BLOCK_BREAK) {
Database.containerBreakCheck(user, Material.ARMOR_STAND, entity, null, block.getLocation());
Queue.queueBlockBreak(user, block.getState(), Material.ARMOR_STAND, null, (int) entity.getLocation().getYaw());
}
else if (entity instanceof EnderCrystal) {
else if (entity instanceof EnderCrystal && Config.getConfig(entity.getWorld()).BLOCK_BREAK) {
EnderCrystal crystal = (EnderCrystal) event.getEntity();
Queue.queueBlockBreak(user, block.getState(), Material.END_CRYSTAL, null, crystal.isShowingBottom() ? 1 : 0);
}
@@ -3,6 +3,7 @@ package net.coreprotect.listener.entity;
import java.util.Locale;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
@@ -29,16 +30,17 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.projectiles.ProjectileSource;
import net.coreprotect.CoreProtect;
import net.coreprotect.bukkit.BukkitAdapter;
import net.coreprotect.config.Config;
import net.coreprotect.config.ConfigHandler;
import net.coreprotect.consumer.Queue;
import net.coreprotect.database.Database;
import net.coreprotect.listener.player.PlayerInteractEntityListener;
import net.coreprotect.utility.Util;
public final class EntityDamageByEntityListener extends Queue implements Listener {
@EventHandler(priority = EventPriority.MONITOR)
// EntityPickupItemEvent resulting from this event can trigger BEFORE this event if both are set to MONITOR
@EventHandler(priority = EventPriority.HIGHEST)
protected void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
Entity damager = event.getDamager();
@@ -50,10 +52,12 @@ public final class EntityDamageByEntityListener extends Queue implements Listene
final Entity entity = event.getEntity();
Location entityLocation = entity.getLocation();
Block block = entityLocation.getBlock();
boolean logDrops = true;
if (damager instanceof Player) {
Player player = (Player) damager;
user = player.getName();
logDrops = player.getGameMode() != GameMode.CREATIVE;
if (ConfigHandler.inspecting.get(player.getName()) != null) {
if (ConfigHandler.inspecting.get(player.getName())) {
@@ -105,24 +109,18 @@ public final class EntityDamageByEntityListener extends Queue implements Listene
user = "#" + damager.getType().name().toLowerCase(Locale.ROOT);
}
if (!event.isCancelled() && Config.getConfig(entity.getWorld()).BLOCK_BREAK && !inspecting) {
if (entity instanceof ItemFrame) {
ItemFrame frame = (ItemFrame) event.getEntity();
int data = 0;
if (frame.getItem() != null) {
data = Util.getBlockId(frame.getItem().getType());
if (!event.isCancelled() && !inspecting) {
if (entity instanceof ItemFrame && Config.getConfig(entityLocation.getWorld()).ITEM_TRANSACTIONS) {
ItemFrame frame = (ItemFrame) entity;
if (frame.getItem().getType() != Material.AIR) {
PlayerInteractEntityListener.queueFrameTransaction(user, frame, logDrops);
}
Material frameType = BukkitAdapter.ADAPTER.getFrameType(entity);
Queue.queueBlockBreak(user, block.getState(), frameType, null, data);
Queue.queueBlockPlace(user, block.getState(), frameType, null, frameType, data, 1, null);
}
else if (entity instanceof EnderCrystal) {
else if (entity instanceof EnderCrystal && Config.getConfig(entity.getWorld()).BLOCK_BREAK) {
EnderCrystal crystal = (EnderCrystal) event.getEntity();
Queue.queueBlockBreak(user, block.getState(), Material.END_CRYSTAL, null, crystal.isShowingBottom() ? 1 : 0);
}
else if (entity instanceof ArmorStand) {
else if (entity instanceof ArmorStand && Config.getConfig(entity.getWorld()).BLOCK_BREAK) {
// Do this here, as we're unable to read armor stand contents on EntityDeathEvent (in survival mode)
if (Config.getConfig(entityLocation.getWorld()).ITEM_TRANSACTIONS) {
String killer = user;
@@ -5,9 +5,11 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.attribute.Attributable;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeInstance;
@@ -52,6 +54,7 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.MerchantRecipe;
@@ -59,6 +62,7 @@ import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.projectiles.ProjectileSource;
import net.coreprotect.CoreProtect;
import net.coreprotect.bukkit.BukkitAdapter;
import net.coreprotect.config.Config;
import net.coreprotect.consumer.Queue;
@@ -66,6 +70,453 @@ import net.coreprotect.utility.serialize.ItemMetaHandler;
public final class EntityDeathListener extends Queue implements Listener {
public static void parseEntityKills(String message) {
message = message.trim().toLowerCase(Locale.ROOT);
if (!message.contains(" ")) {
return;
}
String[] args = message.split(" ");
if (args.length < 2 || !args[0].replaceFirst("/", "").equals("kill") || !args[1].startsWith("@e")) {
return;
}
List<LivingEntity> entityList = new ArrayList<>();
for (World world : Bukkit.getWorlds()) {
List<LivingEntity> livingEntities = world.getLivingEntities();
for (LivingEntity entity : livingEntities) {
if (entity instanceof Player) {
continue;
}
if (entity.isValid()) {
entityList.add(entity);
}
}
}
Bukkit.getScheduler().runTask(CoreProtect.getInstance(), () -> {
for (LivingEntity entity : entityList) {
if (entity != null && entity.isDead()) {
logEntityDeath(entity, "#command");
}
}
});
}
protected static void logEntityDeath(LivingEntity entity, String e) {
if (!Config.getConfig(entity.getWorld()).ENTITY_KILLS) {
return;
}
EntityDamageEvent damage = entity.getLastDamageCause();
if (damage == null) {
return;
}
boolean isCommand = (damage.getCause() == DamageCause.VOID && entity.getLocation().getBlockY() >= BukkitAdapter.ADAPTER.getMinHeight(entity.getWorld()));
if (e == null) {
e = isCommand ? "#command" : "";
}
boolean skip = true;
if (!Config.getConfig(entity.getWorld()).SKIP_GENERIC_DATA || (!(entity instanceof Zombie) && !(entity instanceof Skeleton))) {
skip = false;
}
if (damage instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent attack = (EntityDamageByEntityEvent) damage;
Entity attacker = attack.getDamager();
if (attacker instanceof Player) {
Player player = (Player) attacker;
e = player.getName();
}
else if (attacker instanceof AbstractArrow) {
AbstractArrow arrow = (AbstractArrow) attacker;
ProjectileSource shooter = arrow.getShooter();
if (shooter instanceof Player) {
Player player = (Player) shooter;
e = player.getName();
}
else if (shooter instanceof LivingEntity) {
EntityType entityType = ((LivingEntity) shooter).getType();
if (entityType != null) { // Check for MyPet plugin
String name = entityType.name().toLowerCase(Locale.ROOT);
e = "#" + name;
}
}
}
else if (attacker instanceof ThrownPotion) {
ThrownPotion potion = (ThrownPotion) attacker;
ProjectileSource shooter = potion.getShooter();
if (shooter instanceof Player) {
Player player = (Player) shooter;
e = player.getName();
}
else if (shooter instanceof LivingEntity) {
EntityType entityType = ((LivingEntity) shooter).getType();
if (entityType != null) { // Check for MyPet plugin
String name = entityType.name().toLowerCase(Locale.ROOT);
e = "#" + name;
}
}
}
else if (attacker.getType().name() != null) {
e = "#" + attacker.getType().name().toLowerCase(Locale.ROOT);
}
}
else {
EntityDamageEvent.DamageCause cause = damage.getCause();
if (cause.equals(EntityDamageEvent.DamageCause.FIRE)) {
e = "#fire";
}
else if (cause.equals(EntityDamageEvent.DamageCause.FIRE_TICK)) {
if (!skip) {
e = "#fire";
}
}
else if (cause.equals(EntityDamageEvent.DamageCause.LAVA)) {
e = "#lava";
}
else if (cause.equals(EntityDamageEvent.DamageCause.BLOCK_EXPLOSION)) {
e = "#explosion";
}
else if (cause.equals(EntityDamageEvent.DamageCause.MAGIC)) {
e = "#magic";
}
}
if (entity instanceof ArmorStand) {
Location entityLocation = entity.getLocation();
if (!Config.getConfig(entityLocation.getWorld()).ITEM_TRANSACTIONS) {
entityLocation.setY(entityLocation.getY() + 0.99);
Block block = entityLocation.getBlock();
Queue.queueBlockBreak(e, block.getState(), Material.ARMOR_STAND, null, (int) entityLocation.getYaw());
}
/*
else if (isCommand) {
entityLocation.setY(entityLocation.getY() + 0.99);
Block block = entityLocation.getBlock();
Database.containerBreakCheck(e, Material.ARMOR_STAND, entity, null, block.getLocation());
Queue.queueBlockBreak(e, block.getState(), Material.ARMOR_STAND, null, (int) entityLocation.getYaw());
}
*/
return;
}
EntityType entity_type = entity.getType();
if (e.length() == 0) {
// assume killed self
if (!skip) {
if (!(entity instanceof Player) && entity_type.name() != null) {
// Player player = (Player)entity;
// e = player.getName();
e = "#" + entity_type.name().toLowerCase(Locale.ROOT);
}
else if (entity instanceof Player) {
e = entity.getName();
}
}
}
if (e.startsWith("#wither")) {
e = "#wither";
}
if (e.startsWith("#enderdragon")) {
e = "#enderdragon";
}
if (e.startsWith("#primedtnt") || e.startsWith("#tnt")) {
e = "#tnt";
}
if (e.startsWith("#lightning")) {
e = "#lightning";
}
if (e.length() > 0) {
List<Object> data = new ArrayList<>();
List<Object> age = new ArrayList<>();
List<Object> tame = new ArrayList<>();
List<Object> attributes = new ArrayList<>();
List<Object> details = new ArrayList<>();
List<Object> info = new ArrayList<>();
EntityType type = entity_type;
// Basic LivingEntity attributes
details.add(entity.getRemoveWhenFarAway());
details.add(entity.getCanPickupItems());
if (entity instanceof Ageable) {
Ageable ageable = (Ageable) entity;
age.add(ageable.getAge());
age.add(ageable.getAgeLock());
age.add(ageable.isAdult());
age.add(ageable.canBreed());
age.add(null);
}
if (entity instanceof Tameable) {
Tameable tameable = (Tameable) entity;
tame.add(tameable.isTamed());
if (tameable.isTamed()) {
if (tameable.getOwner() != null) {
tame.add(tameable.getOwner().getName());
}
}
}
if (entity instanceof Attributable) {
Attributable attributable = entity;
for (Attribute attribute : Attribute.values()) {
AttributeInstance attributeInstance = attributable.getAttribute(attribute);
if (attributeInstance != null) {
List<Object> attributeData = new ArrayList<>();
List<Object> attributeModifiers = new ArrayList<>();
attributeData.add(attributeInstance.getAttribute());
attributeData.add(attributeInstance.getBaseValue());
for (AttributeModifier modifier : attributeInstance.getModifiers()) {
attributeModifiers.add(modifier.serialize());
}
attributeData.add(attributeModifiers);
attributes.add(attributeData);
}
}
}
if (entity instanceof Creeper) {
Creeper creeper = (Creeper) entity;
info.add(creeper.isPowered());
}
else if (entity instanceof Enderman) {
Enderman enderman = (Enderman) entity;
info.add(null);
try {
info.add(enderman.getCarriedBlock().getAsString());
}
catch (Exception endermanException) {
}
}
else if (entity instanceof IronGolem) {
IronGolem irongolem = (IronGolem) entity;
info.add(irongolem.isPlayerCreated());
}
else if (entity instanceof Cat) {
Cat cat = (Cat) entity;
info.add(cat.getCatType());
info.add(cat.getCollarColor());
}
else if (entity instanceof Fox) {
Fox fox = (Fox) entity;
info.add(fox.getFoxType());
info.add(fox.isSitting());
}
else if (entity instanceof Panda) {
Panda panda = (Panda) entity;
info.add(panda.getMainGene());
info.add(panda.getHiddenGene());
}
else if (entity instanceof Pig) {
Pig pig = (Pig) entity;
info.add(pig.hasSaddle());
}
else if (entity instanceof Sheep) {
Sheep sheep = (Sheep) entity;
info.add(sheep.isSheared());
info.add(sheep.getColor());
}
else if (entity instanceof MushroomCow) {
MushroomCow mushroomCow = (MushroomCow) entity;
info.add(mushroomCow.getVariant());
}
else if (entity instanceof Skeleton) {
info.add(null);
}
else if (entity instanceof Slime) {
Slime slime = (Slime) entity;
info.add(slime.getSize());
}
else if (entity instanceof Parrot) {
Parrot parrot = (Parrot) entity;
info.add(parrot.getVariant());
}
else if (entity instanceof TropicalFish) {
TropicalFish tropicalFish = (TropicalFish) entity;
info.add(tropicalFish.getBodyColor());
info.add(tropicalFish.getPattern());
info.add(tropicalFish.getPatternColor());
}
else if (entity instanceof Phantom) {
Phantom phantom = (Phantom) entity;
info.add(phantom.getSize());
}
else if (entity instanceof AbstractVillager) {
AbstractVillager abstractVillager = (AbstractVillager) entity;
List<Object> recipes = new ArrayList<>();
for (MerchantRecipe merchantRecipe : abstractVillager.getRecipes()) {
List<Object> recipe = new ArrayList<>();
List<Object> ingredients = new ArrayList<>();
List<Object> itemMap = new ArrayList<>();
ItemStack item = merchantRecipe.getResult().clone();
List<List<Map<String, Object>>> metadata = ItemMetaHandler.seralize(item, item.getType(), null, 0);
item.setItemMeta(null);
itemMap.add(item.serialize());
itemMap.add(metadata);
recipe.add(itemMap);
recipe.add(merchantRecipe.getUses());
recipe.add(merchantRecipe.getMaxUses());
recipe.add(merchantRecipe.hasExperienceReward());
for (ItemStack ingredient : merchantRecipe.getIngredients()) {
itemMap = new ArrayList<>();
item = ingredient.clone();
metadata = ItemMetaHandler.seralize(item, item.getType(), null, 0);
item.setItemMeta(null);
itemMap.add(item.serialize());
itemMap.add(metadata);
ingredients.add(itemMap);
}
recipe.add(ingredients);
recipe.add(merchantRecipe.getVillagerExperience());
recipe.add(merchantRecipe.getPriceMultiplier());
recipes.add(recipe);
}
if (abstractVillager instanceof Villager) {
Villager villager = (Villager) abstractVillager;
info.add(villager.getProfession());
info.add(villager.getVillagerType());
info.add(recipes);
info.add(villager.getVillagerLevel());
info.add(villager.getVillagerExperience());
}
else {
info.add(null);
info.add(null);
info.add(recipes);
}
}
else if (entity instanceof Raider) {
Raider raider = (Raider) entity;
info.add(raider.isPatrolLeader());
if (entity instanceof Spellcaster) {
Spellcaster spellcaster = (Spellcaster) entity;
info.add(spellcaster.getSpell());
}
}
else if (entity instanceof Wolf) {
Wolf wolf = (Wolf) entity;
info.add(wolf.isSitting());
info.add(wolf.getCollarColor());
}
else if (entity instanceof ZombieVillager) {
ZombieVillager zombieVillager = (ZombieVillager) entity;
info.add(zombieVillager.isBaby());
info.add(zombieVillager.getVillagerProfession());
}
else if (entity instanceof Zombie) {
Zombie zombie = (Zombie) entity;
info.add(zombie.isBaby());
info.add(null);
info.add(null);
}
else if (entity instanceof AbstractHorse) {
AbstractHorse abstractHorse = (AbstractHorse) entity;
info.add(null);
info.add(null);
info.add(abstractHorse.getDomestication());
info.add(abstractHorse.getJumpStrength());
info.add(abstractHorse.getMaxDomestication());
info.add(null);
info.add(null);
if (entity instanceof Horse) {
Horse horse = (Horse) entity;
info.add(null);
ItemStack saddle = horse.getInventory().getSaddle();
if (saddle != null) {
info.add(saddle.serialize());
}
else {
info.add(null);
}
info.add(horse.getColor());
info.add(horse.getStyle());
ItemStack horseArmor = horse.getInventory().getArmor();
if (horseArmor != null) {
ItemStack armor = horseArmor.clone();
ItemMeta itemMeta = armor.getItemMeta();
Color color = null;
if (itemMeta instanceof LeatherArmorMeta) {
LeatherArmorMeta meta = (LeatherArmorMeta) itemMeta;
color = meta.getColor();
meta.setColor(null);
armor.setItemMeta(meta);
}
info.add(armor.serialize());
if (color != null) {
info.add(color.serialize());
}
else {
info.add(null);
}
}
else {
info.add(null);
info.add(null);
}
}
else if (entity instanceof ChestedHorse) {
ChestedHorse chestedHorse = (ChestedHorse) entity;
info.add(chestedHorse.isCarryingChest());
if (entity instanceof Llama) {
Llama llama = (Llama) entity;
ItemStack decor = llama.getInventory().getDecor();
if (decor != null) {
info.add(decor.serialize());
}
else {
info.add(null);
}
info.add(llama.getColor());
}
}
}
else {
BukkitAdapter.ADAPTER.getEntityMeta(entity, info);
}
data.add(age);
data.add(tame);
data.add(info);
data.add(entity.isCustomNameVisible());
data.add(entity.getCustomName());
data.add(attributes);
data.add(details);
if (!(entity instanceof Player)) {
Queue.queueEntityKill(e, entity.getLocation(), data, type);
}
else {
Queue.queuePlayerKill(e, entity.getLocation(), entity.getName());
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityDeath(EntityDeathEvent event) {
LivingEntity entity = event.getEntity();
@@ -73,400 +524,6 @@ public final class EntityDeathListener extends Queue implements Listener {
return;
}
if (Config.getConfig(entity.getWorld()).ENTITY_KILLS) {
EntityDamageEvent damage = entity.getLastDamageCause();
if (damage != null) {
String e = "";
boolean skip = true;
if (!Config.getConfig(entity.getWorld()).SKIP_GENERIC_DATA || (!(entity instanceof Zombie) && !(entity instanceof Skeleton))) {
skip = false;
}
if (damage instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent attack = (EntityDamageByEntityEvent) damage;
Entity attacker = attack.getDamager();
if (attacker instanceof Player) {
Player player = (Player) attacker;
e = player.getName();
}
else if (attacker instanceof AbstractArrow) {
AbstractArrow arrow = (AbstractArrow) attacker;
ProjectileSource shooter = arrow.getShooter();
if (shooter instanceof Player) {
Player player = (Player) shooter;
e = player.getName();
}
else if (shooter instanceof LivingEntity) {
EntityType entityType = ((LivingEntity) shooter).getType();
if (entityType != null) { // Check for MyPet plugin
String name = entityType.name().toLowerCase(Locale.ROOT);
e = "#" + name;
}
}
}
else if (attacker instanceof ThrownPotion) {
ThrownPotion potion = (ThrownPotion) attacker;
ProjectileSource shooter = potion.getShooter();
if (shooter instanceof Player) {
Player player = (Player) shooter;
e = player.getName();
}
else if (shooter instanceof LivingEntity) {
EntityType entityType = ((LivingEntity) shooter).getType();
if (entityType != null) { // Check for MyPet plugin
String name = entityType.name().toLowerCase(Locale.ROOT);
e = "#" + name;
}
}
}
else if (attacker.getType().name() != null) {
e = "#" + attacker.getType().name().toLowerCase(Locale.ROOT);
}
}
else {
EntityDamageEvent.DamageCause cause = damage.getCause();
if (cause.equals(EntityDamageEvent.DamageCause.FIRE)) {
e = "#fire";
}
else if (cause.equals(EntityDamageEvent.DamageCause.FIRE_TICK)) {
if (!skip) {
e = "#fire";
}
}
else if (cause.equals(EntityDamageEvent.DamageCause.LAVA)) {
e = "#lava";
}
else if (cause.equals(EntityDamageEvent.DamageCause.BLOCK_EXPLOSION)) {
e = "#explosion";
}
else if (cause.equals(EntityDamageEvent.DamageCause.MAGIC)) {
e = "#magic";
}
}
if (entity instanceof ArmorStand) {
Location entityLocation = entity.getLocation();
if (!Config.getConfig(entityLocation.getWorld()).ITEM_TRANSACTIONS) {
entityLocation.setY(entityLocation.getY() + 0.99);
Block block = entityLocation.getBlock();
Queue.queueBlockBreak(e, block.getState(), Material.ARMOR_STAND, null, (int) entityLocation.getYaw());
}
return;
}
EntityType entity_type = entity.getType();
if (e.length() == 0) {
// assume killed self
if (!skip) {
if (!(entity instanceof Player) && entity_type.name() != null) {
// Player player = (Player)entity;
// e = player.getName();
e = "#" + entity_type.name().toLowerCase(Locale.ROOT);
}
else if (entity instanceof Player) {
e = entity.getName();
}
}
}
if (e.startsWith("#wither")) {
e = "#wither";
}
if (e.startsWith("#enderdragon")) {
e = "#enderdragon";
}
if (e.startsWith("#primedtnt") || e.startsWith("#tnt")) {
e = "#tnt";
}
if (e.startsWith("#lightning")) {
e = "#lightning";
}
if (e.length() > 0) {
List<Object> data = new ArrayList<>();
List<Object> age = new ArrayList<>();
List<Object> tame = new ArrayList<>();
List<Object> attributes = new ArrayList<>();
List<Object> details = new ArrayList<>();
List<Object> info = new ArrayList<>();
EntityType type = entity_type;
// Basic LivingEntity attributes
details.add(entity.getRemoveWhenFarAway());
details.add(entity.getCanPickupItems());
if (entity instanceof Ageable) {
Ageable ageable = (Ageable) entity;
age.add(ageable.getAge());
age.add(ageable.getAgeLock());
age.add(ageable.isAdult());
age.add(ageable.canBreed());
age.add(null);
}
if (entity instanceof Tameable) {
Tameable tameable = (Tameable) entity;
tame.add(tameable.isTamed());
if (tameable.isTamed()) {
if (tameable.getOwner() != null) {
tame.add(tameable.getOwner().getName());
}
}
}
if (entity instanceof Attributable) {
Attributable attributable = entity;
for (Attribute attribute : Attribute.values()) {
AttributeInstance attributeInstance = attributable.getAttribute(attribute);
if (attributeInstance != null) {
List<Object> attributeData = new ArrayList<>();
List<Object> attributeModifiers = new ArrayList<>();
attributeData.add(attributeInstance.getAttribute());
attributeData.add(attributeInstance.getBaseValue());
for (AttributeModifier modifier : attributeInstance.getModifiers()) {
attributeModifiers.add(modifier.serialize());
}
attributeData.add(attributeModifiers);
attributes.add(attributeData);
}
}
}
if (entity instanceof Creeper) {
Creeper creeper = (Creeper) entity;
info.add(creeper.isPowered());
}
else if (entity instanceof Enderman) {
Enderman enderman = (Enderman) entity;
info.add(null);
try {
info.add(enderman.getCarriedBlock().getAsString());
}
catch (Exception endermanException) {
}
}
else if (entity instanceof IronGolem) {
IronGolem irongolem = (IronGolem) entity;
info.add(irongolem.isPlayerCreated());
}
else if (entity instanceof Cat) {
Cat cat = (Cat) entity;
info.add(cat.getCatType());
info.add(cat.getCollarColor());
}
else if (entity instanceof Fox) {
Fox fox = (Fox) entity;
info.add(fox.getFoxType());
info.add(fox.isSitting());
}
else if (entity instanceof Panda) {
Panda panda = (Panda) entity;
info.add(panda.getMainGene());
info.add(panda.getHiddenGene());
}
else if (entity instanceof Pig) {
Pig pig = (Pig) entity;
info.add(pig.hasSaddle());
}
else if (entity instanceof Sheep) {
Sheep sheep = (Sheep) entity;
info.add(sheep.isSheared());
info.add(sheep.getColor());
}
else if (entity instanceof MushroomCow) {
MushroomCow mushroomCow = (MushroomCow) entity;
info.add(mushroomCow.getVariant());
}
else if (entity instanceof Skeleton) {
info.add(null);
}
else if (entity instanceof Slime) {
Slime slime = (Slime) entity;
info.add(slime.getSize());
}
else if (entity instanceof Parrot) {
Parrot parrot = (Parrot) entity;
info.add(parrot.getVariant());
}
else if (entity instanceof TropicalFish) {
TropicalFish tropicalFish = (TropicalFish) entity;
info.add(tropicalFish.getBodyColor());
info.add(tropicalFish.getPattern());
info.add(tropicalFish.getPatternColor());
}
else if (entity instanceof Phantom) {
Phantom phantom = (Phantom) entity;
info.add(phantom.getSize());
}
else if (entity instanceof AbstractVillager) {
AbstractVillager abstractVillager = (AbstractVillager) entity;
List<Object> recipes = new ArrayList<>();
for (MerchantRecipe merchantRecipe : abstractVillager.getRecipes()) {
List<Object> recipe = new ArrayList<>();
List<Object> ingredients = new ArrayList<>();
List<Object> itemMap = new ArrayList<>();
ItemStack item = merchantRecipe.getResult().clone();
List<List<Map<String, Object>>> metadata = ItemMetaHandler.seralize(item, item.getType(), 0);
item.setItemMeta(null);
itemMap.add(item.serialize());
itemMap.add(metadata);
recipe.add(itemMap);
recipe.add(merchantRecipe.getUses());
recipe.add(merchantRecipe.getMaxUses());
recipe.add(merchantRecipe.hasExperienceReward());
for (ItemStack ingredient : merchantRecipe.getIngredients()) {
itemMap = new ArrayList<>();
item = ingredient.clone();
metadata = ItemMetaHandler.seralize(item, item.getType(), 0);
item.setItemMeta(null);
itemMap.add(item.serialize());
itemMap.add(metadata);
ingredients.add(itemMap);
}
recipe.add(ingredients);
recipe.add(merchantRecipe.getVillagerExperience());
recipe.add(merchantRecipe.getPriceMultiplier());
recipes.add(recipe);
}
if (abstractVillager instanceof Villager) {
Villager villager = (Villager) abstractVillager;
info.add(villager.getProfession());
info.add(villager.getVillagerType());
info.add(recipes);
info.add(villager.getVillagerLevel());
info.add(villager.getVillagerExperience());
}
else {
info.add(null);
info.add(null);
info.add(recipes);
}
}
else if (entity instanceof Raider) {
Raider raider = (Raider) entity;
info.add(raider.isPatrolLeader());
if (entity instanceof Spellcaster) {
Spellcaster spellcaster = (Spellcaster) entity;
info.add(spellcaster.getSpell());
}
}
else if (entity instanceof Wolf) {
Wolf wolf = (Wolf) entity;
info.add(wolf.isSitting());
info.add(wolf.getCollarColor());
}
else if (entity instanceof ZombieVillager) {
ZombieVillager zombieVillager = (ZombieVillager) entity;
info.add(zombieVillager.isBaby());
info.add(zombieVillager.getVillagerProfession());
}
else if (entity instanceof Zombie) {
Zombie zombie = (Zombie) entity;
info.add(zombie.isBaby());
info.add(null);
info.add(null);
}
else if (entity instanceof AbstractHorse) {
AbstractHorse abstractHorse = (AbstractHorse) entity;
info.add(null);
info.add(null);
info.add(abstractHorse.getDomestication());
info.add(abstractHorse.getJumpStrength());
info.add(abstractHorse.getMaxDomestication());
info.add(null);
info.add(null);
if (entity instanceof Horse) {
Horse horse = (Horse) entity;
info.add(null);
ItemStack saddle = horse.getInventory().getSaddle();
if (saddle != null) {
info.add(saddle.serialize());
}
else {
info.add(null);
}
info.add(horse.getColor());
info.add(horse.getStyle());
ItemStack horseArmor = horse.getInventory().getArmor();
if (horseArmor != null) {
ItemStack armor = horseArmor.clone();
ItemMeta itemMeta = armor.getItemMeta();
Color color = null;
if (itemMeta instanceof LeatherArmorMeta) {
LeatherArmorMeta meta = (LeatherArmorMeta) itemMeta;
color = meta.getColor();
meta.setColor(null);
armor.setItemMeta(meta);
}
info.add(armor.serialize());
if (color != null) {
info.add(color.serialize());
}
else {
info.add(null);
}
}
else {
info.add(null);
info.add(null);
}
}
else if (entity instanceof ChestedHorse) {
ChestedHorse chestedHorse = (ChestedHorse) entity;
info.add(chestedHorse.isCarryingChest());
if (entity instanceof Llama) {
Llama llama = (Llama) entity;
ItemStack decor = llama.getInventory().getDecor();
if (decor != null) {
info.add(decor.serialize());
}
else {
info.add(null);
}
info.add(llama.getColor());
}
}
}
else {
BukkitAdapter.ADAPTER.getEntityMeta(entity, info);
}
data.add(age);
data.add(tame);
data.add(info);
data.add(entity.isCustomNameVisible());
data.add(entity.getCustomName());
data.add(attributes);
data.add(details);
if (!(entity instanceof Player)) {
Queue.queueEntityKill(e, entity.getLocation(), data, type);
}
else {
Queue.queuePlayerKill(e, entity.getLocation(), entity.getName());
}
}
}
}
logEntityDeath(entity, null);
}
}
@@ -16,9 +16,10 @@ import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityExplodeEvent;
import net.coreprotect.config.Config;
import net.coreprotect.consumer.Queue;
import net.coreprotect.listener.block.BlockExplodeListener;
public final class EntityExplodeListener extends BlockExplodeListener implements Listener {
public final class EntityExplodeListener extends Queue implements Listener {
@EventHandler(priority = EventPriority.MONITOR)
protected void onEntityExplode(EntityExplodeEvent event) {
@@ -20,21 +20,8 @@ import net.coreprotect.consumer.Queue;
public final class EntityPickupItemListener extends Queue implements Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
protected void onEntityPickupItem(EntityPickupItemEvent event) {
if (event.getEntityType() != EntityType.PLAYER) {
return;
}
Item item = event.getItem();
Location location = item.getLocation();
if (!Config.getConfig(location.getWorld()).ITEM_PICKUPS) {
return;
}
Player player = (Player) event.getEntity();
ItemStack itemStack = item.getItemStack();
if (itemStack == null) {
public static void onItemPickup(Player player, Location location, ItemStack itemStack) {
if (itemStack == null || location == null || !Config.getConfig(location.getWorld()).ITEM_PICKUPS) {
return;
}
@@ -46,7 +33,18 @@ public final class EntityPickupItemListener extends Queue implements Listener {
ConfigHandler.itemsPickup.put(loggingItemId, list);
int time = (int) (System.currentTimeMillis() / 1000L) + 1;
Queue.queueItemTransaction(player.getName(), location.clone(), time, itemId);
Queue.queueItemTransaction(player.getName(), location.clone(), time, 0, itemId);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
protected void onEntityPickupItem(EntityPickupItemEvent event) {
if (event.getEntityType() != EntityType.PLAYER) {
return;
}
Player player = (Player) event.getEntity();
Item item = event.getItem();
onItemPickup(player, item.getLocation(), item.getItemStack());
}
}
@@ -4,6 +4,7 @@ import java.sql.Connection;
import java.sql.Statement;
import java.util.Locale;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
@@ -22,6 +23,7 @@ import net.coreprotect.consumer.Queue;
import net.coreprotect.database.Database;
import net.coreprotect.database.lookup.BlockLookup;
import net.coreprotect.language.Phrase;
import net.coreprotect.listener.player.PlayerInteractEntityListener;
import net.coreprotect.utility.Chat;
import net.coreprotect.utility.Color;
import net.coreprotect.utility.Util;
@@ -33,6 +35,28 @@ public final class HangingBreakByEntityListener extends Queue implements Listene
class BasicThread implements Runnable {
@Override
public void run() {
if (!player.hasPermission("coreprotect.inspect")) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
ConfigHandler.inspecting.put(player.getName(), false);
return;
}
if (ConfigHandler.converterRunning) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.UPGRADE_IN_PROGRESS));
return;
}
if (ConfigHandler.purgeRunning) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PURGE_IN_PROGRESS));
return;
}
if (ConfigHandler.lookupThrottle.get(player.getName()) != null) {
Object[] lookupThrottle = ConfigHandler.lookupThrottle.get(player.getName());
if ((boolean) lookupThrottle[0] || ((System.currentTimeMillis() - (long) lookupThrottle[1])) < 100) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.DATABASE_BUSY));
return;
}
}
ConfigHandler.lookupThrottle.put(player.getName(), new Object[] { true, System.currentTimeMillis() });
try (Connection connection = Database.getConnection(true)) {
if (connection != null) {
Statement statement = connection.createStatement();
@@ -56,6 +80,8 @@ public final class HangingBreakByEntityListener extends Queue implements Listene
catch (Exception e) {
e.printStackTrace();
}
ConfigHandler.lookupThrottle.put(player.getName(), new Object[] { false, System.currentTimeMillis() });
}
}
Runnable runnable = new BasicThread();
@@ -68,6 +94,7 @@ public final class HangingBreakByEntityListener extends Queue implements Listene
Entity entity = event.getEntity();
Entity remover = event.getRemover();
BlockState blockEvent = event.getEntity().getLocation().getBlock().getState();
boolean logDrops = true;
boolean inspecting = false;
if (event.getRemover() instanceof Player) {
@@ -89,30 +116,36 @@ public final class HangingBreakByEntityListener extends Queue implements Listene
if (remover instanceof Player) {
Player player = (Player) remover;
culprit = player.getName();
logDrops = player.getGameMode() != GameMode.CREATIVE;
}
else if (remover.getType() != null) {
culprit = "#" + remover.getType().name().toLowerCase(Locale.ROOT);
}
}
String blockData = null;
Material material;
int itemData = 0;
if (entity instanceof ItemFrame) {
material = BukkitAdapter.ADAPTER.getFrameType(entity);
ItemFrame itemframe = (ItemFrame) entity;
blockData = "FACING=" + itemframe.getFacing().name();
if (itemframe.getItem() != null) {
itemData = Util.getBlockId(itemframe.getItem().getType());
if (!event.isCancelled() && Config.getConfig(entity.getWorld()).ITEM_TRANSACTIONS && !inspecting) {
if (itemframe.getItem().getType() != Material.AIR) {
PlayerInteractEntityListener.queueFrameTransaction(culprit, itemframe, logDrops);
}
}
}
else {
material = Material.PAINTING;
Painting painting = (Painting) entity;
blockData = "FACING=" + painting.getFacing().name();
itemData = Util.getArtId(painting.getArt().toString(), true);
}
if (!event.isCancelled() && Config.getConfig(blockEvent.getWorld()).BLOCK_BREAK && !inspecting) {
Queue.queueBlockBreak(culprit, blockEvent, material, null, itemData);
Queue.queueBlockBreak(culprit, blockEvent, material, blockData, itemData);
}
}
}
@@ -15,6 +15,8 @@ import org.bukkit.event.hanging.HangingBreakEvent;
import net.coreprotect.bukkit.BukkitAdapter;
import net.coreprotect.config.Config;
import net.coreprotect.consumer.Queue;
import net.coreprotect.database.Lookup;
import net.coreprotect.listener.player.PlayerInteractEntityListener;
import net.coreprotect.utility.Util;
public final class HangingBreakListener extends Queue implements Listener {
@@ -29,6 +31,7 @@ public final class HangingBreakListener extends Queue implements Listener {
if (cause.equals(HangingBreakEvent.RemoveCause.EXPLOSION) || cause.equals(HangingBreakEvent.RemoveCause.PHYSICS) || cause.equals(HangingBreakEvent.RemoveCause.OBSTRUCTION)) {
String causeName = "#explosion";
Block attachedBlock = null;
boolean logDrops = false;
if (cause.equals(HangingBreakEvent.RemoveCause.PHYSICS)) {
causeName = "#physics";
@@ -41,26 +44,36 @@ public final class HangingBreakListener extends Queue implements Listener {
Hanging hangingEntity = (Hanging) entity;
BlockFace attached = hangingEntity.getAttachedFace();
attachedBlock = hangingEntity.getLocation().getBlock().getRelative(attached);
String removed = Lookup.whoRemovedCache(attachedBlock.getState());
if (removed.length() > 0) {
causeName = removed;
logDrops = true;
}
}
String blockData = null;
Material material;
int itemData = 0;
if (entity instanceof ItemFrame) {
material = BukkitAdapter.ADAPTER.getFrameType(entity);
ItemFrame itemframe = (ItemFrame) entity;
blockData = "FACING=" + itemframe.getFacing().name();
if (itemframe.getItem() != null) {
itemData = Util.getBlockId(itemframe.getItem().getType());
if (!event.isCancelled() && Config.getConfig(entity.getWorld()).ITEM_TRANSACTIONS) {
if (itemframe.getItem().getType() != Material.AIR) {
PlayerInteractEntityListener.queueFrameTransaction(causeName, itemframe, logDrops);
}
}
}
else {
material = Material.PAINTING;
Painting painting = (Painting) entity;
blockData = "FACING=" + painting.getFacing().name();
itemData = Util.getArtId(painting.getArt().toString(), true);
}
if (!event.isCancelled() && Config.getConfig(blockEvent.getWorld()).NATURAL_BREAK) {
Queue.queueNaturalBlockBreak(causeName, blockEvent.getState(), attachedBlock, material, itemData);
Queue.queueNaturalBlockBreak(causeName, blockEvent.getState(), attachedBlock, material, blockData, itemData);
}
}
}
@@ -26,16 +26,20 @@ public final class HangingPlaceListener extends Queue implements Listener {
if (entity instanceof ItemFrame || entity instanceof Painting) {
Block blockEvent = event.getEntity().getLocation().getBlock();
String blockData = null;
Material material;
int artId;
if (entity instanceof ItemFrame) {
material = BukkitAdapter.ADAPTER.getFrameType(entity);
ItemFrame itemFrame = (ItemFrame) entity;
blockData = "FACING=" + itemFrame.getFacing().name();
artId = 0;
}
else {
material = Material.PAINTING;
Painting painting = (Painting) entity;
blockData = "FACING=" + painting.getFacing().name();
artId = Util.getArtId(painting.getArt().toString(), true);
}
@@ -48,7 +52,7 @@ public final class HangingPlaceListener extends Queue implements Listener {
}
if (!event.isCancelled() && Config.getConfig(blockEvent.getWorld()).BLOCK_PLACE && inspect == 0) {
Queue.queueBlockPlace(player.getName(), blockEvent.getState(), blockEvent.getType(), null, material, artId, 1, null);
Queue.queueBlockPlace(player.getName(), blockEvent.getState(), blockEvent.getType(), null, material, artId, 1, blockData);
}
}
}
@@ -31,6 +31,63 @@ import net.coreprotect.utility.Util;
public final class ArmorStandManipulateListener extends Queue implements Listener {
public static void inspectHangingTransactions(final Location location, final Player finalPlayer) {
class BasicThread implements Runnable {
@Override
public void run() {
if (!finalPlayer.hasPermission("coreprotect.inspect")) {
Chat.sendMessage(finalPlayer, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
ConfigHandler.inspecting.put(finalPlayer.getName(), false);
return;
}
if (ConfigHandler.converterRunning) {
Chat.sendMessage(finalPlayer, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.UPGRADE_IN_PROGRESS));
return;
}
if (ConfigHandler.purgeRunning) {
Chat.sendMessage(finalPlayer, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PURGE_IN_PROGRESS));
return;
}
if (ConfigHandler.lookupThrottle.get(finalPlayer.getName()) != null) {
Object[] lookupThrottle = ConfigHandler.lookupThrottle.get(finalPlayer.getName());
if ((boolean) lookupThrottle[0] || ((System.currentTimeMillis() - (long) lookupThrottle[1])) < 100) {
Chat.sendMessage(finalPlayer, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.DATABASE_BUSY));
return;
}
}
ConfigHandler.lookupThrottle.put(finalPlayer.getName(), new Object[] { true, System.currentTimeMillis() });
try (Connection connection = Database.getConnection(true)) {
if (connection != null) {
Statement statement = connection.createStatement();
String blockData = ChestTransactionLookup.performLookup(null, statement, location, finalPlayer, 1, 7, true);
if (blockData.contains("\n")) {
for (String b : blockData.split("\n")) {
Chat.sendComponent(finalPlayer, b);
}
}
else {
Chat.sendComponent(finalPlayer, blockData);
}
statement.close();
}
else {
Chat.sendMessage(finalPlayer, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.DATABASE_BUSY));
}
}
catch (Exception e) {
e.printStackTrace();
}
ConfigHandler.lookupThrottle.put(finalPlayer.getName(), new Object[] { false, System.currentTimeMillis() });
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
thread.start();
}
@EventHandler(priority = EventPriority.MONITOR)
protected void onPlayerArmorStandManipulateEvent(PlayerArmorStandManipulateEvent event) {
Player player = event.getPlayer();
@@ -40,67 +97,11 @@ public final class ArmorStandManipulateListener extends Queue implements Listene
ItemStack item = event.getArmorStandItem();
ItemStack playerItem = event.getPlayerItem();
if (!Config.getConfig(player.getWorld()).ITEM_TRANSACTIONS) {
return;
}
if (ConfigHandler.inspecting.get(player.getName()) != null) {
if (ConfigHandler.inspecting.get(player.getName())) {
final Player finalPlayer = player;
if (BlockGroup.CONTAINERS.contains(Material.ARMOR_STAND)) {
// logged armor stand items
class BasicThread implements Runnable {
@Override
public void run() {
if (ConfigHandler.converterRunning) {
Chat.sendMessage(finalPlayer, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.UPGRADE_IN_PROGRESS));
return;
}
if (ConfigHandler.purgeRunning) {
Chat.sendMessage(finalPlayer, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.PURGE_IN_PROGRESS));
return;
}
if (ConfigHandler.lookupThrottle.get(finalPlayer.getName()) != null) {
Object[] lookupThrottle = ConfigHandler.lookupThrottle.get(finalPlayer.getName());
if ((boolean) lookupThrottle[0] || ((System.currentTimeMillis() - (long) lookupThrottle[1])) < 100) {
Chat.sendMessage(finalPlayer, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.DATABASE_BUSY));
return;
}
}
ConfigHandler.lookupThrottle.put(finalPlayer.getName(), new Object[] { true, System.currentTimeMillis() });
try (Connection connection = Database.getConnection(true)) {
if (connection != null) {
Statement statement = connection.createStatement();
Location standLocation = armorStand.getLocation();
String blockData = ChestTransactionLookup.performLookup(null, statement, standLocation, finalPlayer, 1, 7, true);
if (blockData.contains("\n")) {
for (String b : blockData.split("\n")) {
Chat.sendComponent(finalPlayer, b);
}
}
else {
Chat.sendComponent(finalPlayer, blockData);
}
statement.close();
}
else {
Chat.sendMessage(finalPlayer, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.DATABASE_BUSY));
}
}
catch (Exception e) {
e.printStackTrace();
}
ConfigHandler.lookupThrottle.put(finalPlayer.getName(), new Object[] { false, System.currentTimeMillis() });
}
}
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
thread.start();
inspectHangingTransactions(armorStand.getLocation(), player);
}
event.setCancelled(true);
@@ -111,6 +112,10 @@ public final class ArmorStandManipulateListener extends Queue implements Listene
return;
}
if (!Config.getConfig(player.getWorld()).ITEM_TRANSACTIONS) {
return;
}
if (item == null && playerItem == null) {
return;
}
@@ -0,0 +1,196 @@
package net.coreprotect.listener.player;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.inventory.InventoryType.SlotType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.MerchantInventory;
import org.bukkit.inventory.MerchantRecipe;
import org.bukkit.inventory.Recipe;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.inventory.ShapelessRecipe;
import net.coreprotect.bukkit.BukkitAdapter;
import net.coreprotect.config.Config;
import net.coreprotect.config.ConfigHandler;
import net.coreprotect.consumer.Queue;
import net.coreprotect.database.logger.ItemLogger;
public final class CraftItemListener extends Queue implements Listener {
protected static void logCraftedItem(Location location, String user, ItemStack itemStack, int action) {
if (!Config.getConfig(location.getWorld()).ITEM_TRANSACTIONS || itemStack == null) {
return;
}
String loggingItemId = user.toLowerCase(Locale.ROOT) + "." + location.getBlockX() + "." + location.getBlockY() + "." + location.getBlockZ();
int itemId = getItemId(loggingItemId);
if (action == ItemLogger.ITEM_BUY) {
List<ItemStack> list = ConfigHandler.itemsBuy.getOrDefault(loggingItemId, new ArrayList<>());
list.add(itemStack);
ConfigHandler.itemsBuy.put(loggingItemId, list);
}
else if (action == ItemLogger.ITEM_SELL) {
List<ItemStack> list = ConfigHandler.itemsSell.getOrDefault(loggingItemId, new ArrayList<>());
list.add(itemStack);
ConfigHandler.itemsSell.put(loggingItemId, list);
}
else if (action == ItemLogger.ITEM_CREATE) {
List<ItemStack> list = ConfigHandler.itemsCreate.getOrDefault(loggingItemId, new ArrayList<>());
list.add(itemStack);
ConfigHandler.itemsCreate.put(loggingItemId, list);
}
else {
List<ItemStack> list = ConfigHandler.itemsDestroy.getOrDefault(loggingItemId, new ArrayList<>());
list.add(itemStack);
ConfigHandler.itemsDestroy.put(loggingItemId, list);
}
int time = (int) (System.currentTimeMillis() / 1000L) + 1;
Queue.queueItemTransaction(user, location.clone(), time, 0, itemId);
}
protected static void playerCraftItem(InventoryClickEvent event, boolean isTrade) {
if (event.getResult() == Result.DENY || event.getSlotType() != SlotType.RESULT) {
return;
}
Player player = (Player) event.getWhoClicked();
if (event.getClick() == ClickType.NUMBER_KEY && player.getInventory().getItem(event.getHotbarButton()) != null) {
return;
}
if ((event.getClick() == ClickType.DROP || event.getClick() == ClickType.CONTROL_DROP) && event.getCursor().getType() != Material.AIR) {
return;
}
Inventory bottomInventory = event.getView().getBottomInventory();
if (bottomInventory.getType() != InventoryType.PLAYER) {
return;
}
Recipe recipe = null;
if (!isTrade && event instanceof CraftItemEvent) {
recipe = ((CraftItemEvent) event).getRecipe();
}
else if (isTrade && event.getInventory() instanceof MerchantInventory) {
recipe = ((MerchantInventory) event.getInventory()).getSelectedRecipe();
}
if (recipe == null) {
return;
}
ItemStack addItem = recipe.getResult().clone();
int amount = addItem.getAmount();
if (amount == 0) {
return;
}
int amountMultiplier = 1;
if (event.getClick() == ClickType.SHIFT_LEFT || event.getClick() == ClickType.SHIFT_RIGHT) {
int newMultiplier = Integer.MIN_VALUE;
for (ItemStack item : event.getInventory().getContents()) {
if (item != null && item.getType() != Material.AIR && !item.equals(recipe.getResult())) {
if (isTrade) {
int merchantAmount = newMultiplier;
MerchantRecipe merchantRecipe = (MerchantRecipe) recipe;
for (ItemStack ingredient : merchantRecipe.getIngredients()) {
if (ingredient.isSimilar(item)) {
ItemStack adjusted = BukkitAdapter.ADAPTER.adjustIngredient(merchantRecipe, ingredient);
if (adjusted == null) {
return;
}
merchantAmount = item.getAmount() / adjusted.getAmount();
break;
}
}
int merchantUsesLeft = merchantRecipe.getMaxUses() - merchantRecipe.getUses();
if (merchantUsesLeft < merchantAmount) {
merchantAmount = merchantUsesLeft;
}
if (newMultiplier == Integer.MIN_VALUE || merchantAmount < newMultiplier) {
newMultiplier = merchantAmount;
}
}
else if (newMultiplier == Integer.MIN_VALUE || item.getAmount() < newMultiplier) {
newMultiplier = item.getAmount();
}
}
}
amountMultiplier = (newMultiplier == Integer.MIN_VALUE ? 1 : newMultiplier);
int addAmount = amount * amountMultiplier;
Inventory virtualInventory = Bukkit.createInventory(null, 36);
virtualInventory.setStorageContents(bottomInventory.getStorageContents());
addItem.setAmount(1);
int addSuccess = 0;
for (int i = 0; i < addAmount; i++) {
if (!virtualInventory.addItem(addItem).isEmpty()) {
break;
}
addSuccess++;
}
if (addSuccess < addAmount) {
addAmount = (int) (Math.ceil(addSuccess / (double) amount) * amount);
amountMultiplier = addAmount / amount;
}
virtualInventory.clear();
addItem.setAmount(addAmount);
}
List<ItemStack> oldItems = new ArrayList<>();
if (recipe instanceof ShapelessRecipe) {
oldItems.addAll(((ShapelessRecipe) recipe).getIngredientList());
}
else if (recipe instanceof ShapedRecipe) {
oldItems.addAll(((ShapedRecipe) recipe).getIngredientMap().values());
}
else if (recipe instanceof MerchantRecipe) {
oldItems.addAll(((MerchantRecipe) recipe).getIngredients());
}
if (addItem.getAmount() > 0) {
for (ItemStack oldItem : oldItems) {
if (oldItem == null || oldItem.getType() == Material.AIR) {
continue;
}
ItemStack removedItem = isTrade ? BukkitAdapter.ADAPTER.adjustIngredient((MerchantRecipe) recipe, oldItem) : oldItem.clone();
if (removedItem == null) {
return;
}
removedItem.setAmount(removedItem.getAmount() * amountMultiplier);
logCraftedItem(event.getInventory().getLocation(), player.getName(), removedItem, isTrade ? ItemLogger.ITEM_SELL : ItemLogger.ITEM_DESTROY);
}
logCraftedItem(event.getInventory().getLocation(), player.getName(), addItem, isTrade ? ItemLogger.ITEM_BUY : ItemLogger.ITEM_CREATE);
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
protected void onCraftItem(CraftItemEvent event) {
playerCraftItem(event, false);
}
}
@@ -59,7 +59,7 @@ public final class InventoryChangeListener extends Queue implements Listener {
BlockState blockState = location.getBlock().getState();
Material type = blockState.getType();
if (BlockGroup.CONTAINERS.contains(type)) {
if (BlockGroup.CONTAINERS.contains(type) && blockState instanceof InventoryHolder) {
InventoryHolder inventoryHolder = (InventoryHolder) blockState;
return onInventoryInteract(user, inventoryHolder.getInventory(), inventoryData, null, location, false);
}
@@ -0,0 +1,17 @@
package net.coreprotect.listener.player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import net.coreprotect.consumer.Queue;
public final class InventoryClickListener extends Queue implements Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
protected void onVillagerTrade(InventoryClickEvent event) {
CraftItemListener.playerCraftItem(event, true);
}
}
@@ -19,6 +19,10 @@ public final class PlayerChatListener extends Queue implements Listener {
}
Player player = event.getPlayer();
if (event.isCancelled() && !Config.getConfig(player.getWorld()).LOG_CANCELLED_CHAT) {
return;
}
if (!message.startsWith("/") && Config.getConfig(player.getWorld()).PLAYER_MESSAGES) {
long timestamp = System.currentTimeMillis() / 1000L;
Queue.queuePlayerChat(player, message, timestamp);
@@ -18,5 +18,21 @@ public final class PlayerCommandListener extends Queue implements Listener {
long timestamp = System.currentTimeMillis() / 1000L;
Queue.queuePlayerCommand(player, event.getMessage(), timestamp);
}
/*
if (Config.getGlobal().ENTITY_KILLS && player.hasPermission("bukkit.command.kill")) {
EntityDeathListener.parseEntityKills(event.getMessage());
}
*/
}
/*
@EventHandler(priority = EventPriority.MONITOR)
public void onServerCommand(ServerCommandEvent event) {
if (Config.getGlobal().ENTITY_KILLS && event.getCommand().toLowerCase(Locale.ROOT).startsWith("kill")) {
EntityDeathListener.parseEntityKills(event.getCommand());
}
}
*/
}
@@ -32,14 +32,14 @@ public final class PlayerDeathListener extends Queue implements Listener {
return;
}
Player player = (Player) entity;
String user = ((Player) entity).getName();
List<ItemStack> items = event.getDrops();
if (items == null || items.size() == 0) {
return;
}
for (ItemStack itemStack : items) {
PlayerDropItemListener.playerDropItem(location, player, itemStack);
PlayerDropItemListener.playerDropItem(location, user, itemStack);
}
}
@@ -6,7 +6,6 @@ import java.util.Locale;
import org.bukkit.Location;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
@@ -19,12 +18,12 @@ import net.coreprotect.consumer.Queue;
public final class PlayerDropItemListener extends Queue implements Listener {
protected static void playerDropItem(Location location, Player player, ItemStack itemStack) {
if (itemStack == null) {
protected static void playerDropItem(Location location, String user, ItemStack itemStack) {
if (!Config.getConfig(location.getWorld()).ITEM_DROPS || itemStack == null) {
return;
}
String loggingItemId = player.getName().toLowerCase(Locale.ROOT) + "." + location.getBlockX() + "." + location.getBlockY() + "." + location.getBlockZ();
String loggingItemId = user.toLowerCase(Locale.ROOT) + "." + location.getBlockX() + "." + location.getBlockY() + "." + location.getBlockZ();
int itemId = getItemId(loggingItemId);
List<ItemStack> list = ConfigHandler.itemsDrop.getOrDefault(loggingItemId, new ArrayList<>());
@@ -32,20 +31,14 @@ public final class PlayerDropItemListener extends Queue implements Listener {
ConfigHandler.itemsDrop.put(loggingItemId, list);
int time = (int) (System.currentTimeMillis() / 1000L) + 1;
Queue.queueItemTransaction(player.getName(), location.clone(), time, itemId);
Queue.queueItemTransaction(user, location.clone(), time, 0, itemId);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
protected void onPlayerDropItem(PlayerDropItemEvent event) {
Item item = event.getItemDrop();
Location location = item.getLocation();
if (!Config.getConfig(location.getWorld()).ITEM_DROPS) {
return;
}
Player player = event.getPlayer();
ItemStack itemStack = item.getItemStack();
playerDropItem(location, player, itemStack);
playerDropItem(item.getLocation(), event.getPlayer().getName(), itemStack);
}
}
@@ -1,8 +1,12 @@
package net.coreprotect.listener.player;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
@@ -11,10 +15,13 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerArmorStandManipulateEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import net.coreprotect.bukkit.BukkitAdapter;
import net.coreprotect.config.Config;
import net.coreprotect.config.ConfigHandler;
import net.coreprotect.consumer.Queue;
import net.coreprotect.model.BlockGroup;
import net.coreprotect.utility.Util;
public final class PlayerInteractEntityListener extends Queue implements Listener {
@@ -27,24 +34,86 @@ public final class PlayerInteractEntityListener extends Queue implements Listene
Player player = event.getPlayer();
final Entity entity = event.getRightClicked(); // change item in ItemFrame, etc
World world = entity.getWorld();
if (entity instanceof ItemFrame && !event.isCancelled() && Config.getConfig(world).BLOCK_PLACE) {
if (entity instanceof ItemFrame) {
ItemFrame frame = (ItemFrame) entity;
if (frame.getItem().getType().equals(Material.AIR) && !player.getInventory().getItemInMainHand().getType().equals(Material.AIR)) {
Material material = BukkitAdapter.ADAPTER.getFrameType(entity);
int hand = Util.getBlockId(player.getInventory().getItemInMainHand().getType());
int data = 0;
Material handType = Material.AIR;
ItemStack mainHand = player.getInventory().getItemInMainHand();
ItemStack offHand = player.getInventory().getItemInOffHand();
if (event.getHand().equals(EquipmentSlot.HAND) && mainHand.getType() != Material.AIR) {
handType = mainHand.getType();
}
else if (event.getHand().equals(EquipmentSlot.OFF_HAND) && offHand.getType() != Material.AIR) {
handType = offHand.getType();
}
else if (event.getHand().equals(EquipmentSlot.OFF_HAND)) {
return;
}
if (frame.getItem() != null) {
data = Util.getBlockId(frame.getItem().getType());
if (ConfigHandler.inspecting.get(player.getName()) != null && ConfigHandler.inspecting.get(player.getName())) {
if (BlockGroup.CONTAINERS.contains(Material.ARMOR_STAND)) {
// logged armor stand items
ArmorStandManipulateListener.inspectHangingTransactions(frame.getLocation(), player);
}
String playerName = player.getName();
Block block = frame.getLocation().getBlock();
Queue.queueBlockBreak(playerName, block.getState(), material, null, data);
Queue.queueBlockPlace(playerName, block.getState(), block.getType(), null, material, hand, 1, null);
event.setCancelled(true);
}
if (event.isCancelled()) {
return;
}
if (frame.getItem().getType() != Material.AIR && event.getHand().equals(EquipmentSlot.HAND) && Config.getConfig(player.getWorld()).PLAYER_INTERACTIONS) {
Queue.queuePlayerInteraction(player.getName(), entity.getLocation().getBlock().getState(), Material.ITEM_FRAME);
}
if (!Config.getConfig(player.getWorld()).ITEM_TRANSACTIONS) {
return;
}
if (frame.getItem().getType().equals(Material.AIR) && !handType.equals(Material.AIR)) {
queueFrameTransaction(player.getName(), frame, false);
}
}
}
public static void queueFrameTransaction(String user, ItemFrame frame, boolean logDrop) {
ItemStack[] contents = Util.getItemFrameItem(frame);
Material type = Material.ITEM_FRAME;
Location frameLocation = frame.getLocation();
int x = frameLocation.getBlockX();
int y = frameLocation.getBlockY();
int z = frameLocation.getBlockZ();
String transactingChestId = frameLocation.getWorld().getUID().toString() + "." + x + "." + y + "." + z;
String loggingChestId = user.toLowerCase(Locale.ROOT) + "." + x + "." + y + "." + z;
int chestId = Queue.getChestId(loggingChestId);
if (chestId > 0) {
if (ConfigHandler.forceContainer.get(loggingChestId) != null) {
int forceSize = ConfigHandler.forceContainer.get(loggingChestId).size();
List<ItemStack[]> list = ConfigHandler.oldContainer.get(loggingChestId);
if (list.size() <= forceSize) {
list.add(Util.getContainerState(contents));
ConfigHandler.oldContainer.put(loggingChestId, list);
}
}
}
else {
List<ItemStack[]> list = new ArrayList<>();
list.add(Util.getContainerState(contents));
ConfigHandler.oldContainer.put(loggingChestId, list);
}
ConfigHandler.transactingChest.computeIfAbsent(transactingChestId, k -> Collections.synchronizedList(new ArrayList<>()));
Queue.queueContainerTransaction(user, frameLocation, type, frame, chestId);
if (logDrop) {
ItemStack dropItem = frame.getItem();
if (dropItem.getType() == Material.AIR) {
return;
}
PlayerDropItemListener.playerDropItem(frame.getLocation(), user, dropItem);
}
}
}
@@ -25,6 +25,8 @@ import org.bukkit.block.data.Bisected.Half;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Lightable;
import org.bukkit.block.data.Waterlogged;
import org.bukkit.block.data.type.Bed;
import org.bukkit.block.data.type.Bed.Part;
import org.bukkit.block.data.type.Cake;
import org.bukkit.entity.EnderCrystal;
import org.bukkit.entity.Entity;
@@ -69,6 +71,12 @@ public final class PlayerInteractListener extends Queue implements Listener {
return;
}
if (!player.hasPermission("coreprotect.inspect")) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_PERMISSION));
ConfigHandler.inspecting.put(player.getName(), false);
return;
}
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
BlockState checkBlock = event.getClickedBlock().getState();
int x = checkBlock.getX();
@@ -82,6 +90,13 @@ public final class PlayerInteractListener extends Queue implements Listener {
checkBlock = world.getBlockAt(checkBlock.getX(), checkBlock.getY() - 1, checkBlock.getZ()).getState();
}
}
/* Check if clicking top half of bed */
if (checkBlockData instanceof Bed) {
Bed bed = (Bed) checkBlockData;
if (bed.getPart().equals(Part.HEAD)) {
checkBlock = event.getClickedBlock().getRelative(bed.getFacing().getOppositeFace()).getState();
}
}
final BlockState blockFinal = checkBlock;
class BasicThread implements Runnable {
@@ -278,8 +293,8 @@ public final class PlayerInteractListener extends Queue implements Listener {
if (ConfigHandler.lookupThrottle.get(player.getName()) != null) {
Object[] lookupThrottle = ConfigHandler.lookupThrottle.get(player.getName());
if ((boolean) lookupThrottle[0] || (System.currentTimeMillis() - (long) lookupThrottle[1]) < 100) {
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.DATABASE_BUSY));
return;
Chat.sendMessage(player, Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.DATABASE_BUSY));
return;
}
}
@@ -384,7 +399,7 @@ public final class PlayerInteractListener extends Queue implements Listener {
Thread thread = new Thread(runnable);
thread.start();
if (!BlockGroup.SAFE_INTERACT_BLOCKS.contains(type)) {
if (!BlockGroup.SAFE_INTERACT_BLOCKS.contains(type) || player.isSneaking()) {
event.setCancelled(true);
}
}
@@ -522,12 +537,12 @@ public final class PlayerInteractListener extends Queue implements Listener {
}
}
}
else if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
else if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK) || event.getAction().equals(Action.RIGHT_CLICK_AIR)) {
Player player = event.getPlayer();
Block block = event.getClickedBlock();
World world = player.getWorld();
if (block != null) {
if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK) && block != null) {
final Material type = block.getType();
if (event.useInteractedBlock() != Event.Result.DENY) {
boolean isCake = false;
@@ -581,7 +596,7 @@ public final class PlayerInteractListener extends Queue implements Listener {
}
}
Queue.queuePlayerInteraction(player.getName(), interactBlock.getState());
Queue.queuePlayerInteraction(player.getName(), interactBlock.getState(), type);
}
}
else if (BlockGroup.LIGHTABLES.contains(type)) { // extinguishing a lit block such as a campfire
@@ -641,74 +656,85 @@ public final class PlayerInteractListener extends Queue implements Listener {
CacheHandler.interactCache.put(coordinates, new Object[] { time, Material.CAKE, block.getState() });
}
}
}
}
if (event.useItemInHand() != Event.Result.DENY && Config.getConfig(world).BLOCK_PLACE) {
List<Material> entityBlockTypes = Arrays.asList(Material.ARMOR_STAND, Material.END_CRYSTAL);
Material handType = null;
ItemStack mainHand = player.getInventory().getItemInMainHand();
ItemStack offHand = player.getInventory().getItemInOffHand();
if (event.useItemInHand() != Event.Result.DENY) {
List<Material> entityBlockTypes = Arrays.asList(Material.ARMOR_STAND, Material.END_CRYSTAL, Material.BOW, Material.CROSSBOW, Material.TRIDENT, Material.EXPERIENCE_BOTTLE, Material.SPLASH_POTION, Material.LINGERING_POTION, Material.ENDER_PEARL, Material.FIREWORK_ROCKET, Material.EGG, Material.SNOWBALL);
ItemStack handItem = null;
ItemStack mainHand = player.getInventory().getItemInMainHand();
ItemStack offHand = player.getInventory().getItemInOffHand();
if (event.getHand().equals(EquipmentSlot.HAND) && mainHand != null && entityBlockTypes.contains(mainHand.getType())) {
handType = mainHand.getType();
if (event.getHand().equals(EquipmentSlot.HAND) && mainHand != null && entityBlockTypes.contains(mainHand.getType())) {
handItem = mainHand;
}
else if (event.getHand().equals(EquipmentSlot.OFF_HAND) && offHand != null && entityBlockTypes.contains(offHand.getType())) {
handItem = offHand;
}
else {
return;
}
if (handItem.getType().equals(Material.END_CRYSTAL)) {
if (block != null && Config.getConfig(world).BLOCK_PLACE && (block.getType().equals(Material.OBSIDIAN) || block.getType().equals(Material.BEDROCK))) {
Location crystalLocation = block.getLocation().clone();
crystalLocation.setY(crystalLocation.getY() + 1);
boolean exists = false;
for (Entity entity : crystalLocation.getChunk().getEntities()) {
if (entity instanceof EnderCrystal && entity.getLocation().getBlockX() == crystalLocation.getBlockX() && entity.getLocation().getBlockY() == crystalLocation.getBlockY() && entity.getLocation().getBlockZ() == crystalLocation.getBlockZ()) {
exists = true;
break;
}
}
else if (event.getHand().equals(EquipmentSlot.OFF_HAND) && offHand != null && entityBlockTypes.contains(offHand.getType())) {
handType = offHand.getType();
if (!exists) {
final Player playerFinal = player;
final Location locationFinal = crystalLocation;
Bukkit.getServer().getScheduler().runTask(CoreProtect.getInstance(), () -> {
try {
boolean blockExists = false;
int showingBottom = 0;
for (Entity entity : locationFinal.getChunk().getEntities()) {
if (entity instanceof EnderCrystal && entity.getLocation().getBlockX() == locationFinal.getBlockX() && entity.getLocation().getBlockY() == locationFinal.getBlockY() && entity.getLocation().getBlockZ() == locationFinal.getBlockZ()) {
EnderCrystal enderCrystal = (EnderCrystal) entity;
showingBottom = enderCrystal.isShowingBottom() ? 1 : 0;
blockExists = true;
break;
}
}
if (blockExists) {
Queue.queueBlockPlace(playerFinal.getName(), locationFinal.getBlock().getState(), locationFinal.getBlock().getType(), locationFinal.getBlock().getState(), Material.END_CRYSTAL, showingBottom, 1, null);
}
}
catch (Exception e) {
e.printStackTrace();
}
});
}
else {
}
}
else {
Location relativeBlockLocation = player.getLocation().clone();
relativeBlockLocation.setY(relativeBlockLocation.getY() + 1);
Location blockLocation = relativeBlockLocation.clone();
blockLocation.setY(blockLocation.getY() + 1);
if (handItem.getType() == Material.ARMOR_STAND || handItem.getType() == Material.FIREWORK_ROCKET) {
if (block == null) {
return;
}
if (handType.equals(Material.END_CRYSTAL)) {
Location crystalLocation = block.getLocation();
if (crystalLocation.getBlock().getType().equals(Material.OBSIDIAN) || crystalLocation.getBlock().getType().equals(Material.BEDROCK)) {
crystalLocation.setY(crystalLocation.getY() + 1);
boolean exists = false;
for (Entity entity : crystalLocation.getChunk().getEntities()) {
if (entity instanceof EnderCrystal && entity.getLocation().getBlockX() == crystalLocation.getBlockX() && entity.getLocation().getBlockY() == crystalLocation.getBlockY() && entity.getLocation().getBlockZ() == crystalLocation.getBlockZ()) {
exists = true;
break;
}
}
if (!exists) {
final Player playerFinal = player;
final Location locationFinal = crystalLocation;
Bukkit.getServer().getScheduler().runTask(CoreProtect.getInstance(), () -> {
try {
boolean blockExists = false;
int showingBottom = 0;
for (Entity entity : locationFinal.getChunk().getEntities()) {
if (entity instanceof EnderCrystal && entity.getLocation().getBlockX() == locationFinal.getBlockX() && entity.getLocation().getBlockY() == locationFinal.getBlockY() && entity.getLocation().getBlockZ() == locationFinal.getBlockZ()) {
EnderCrystal enderCrystal = (EnderCrystal) entity;
showingBottom = enderCrystal.isShowingBottom() ? 1 : 0;
blockExists = true;
break;
}
}
if (blockExists) {
Queue.queueBlockPlace(playerFinal.getName(), locationFinal.getBlock().getState(), locationFinal.getBlock().getType(), locationFinal.getBlock().getState(), Material.END_CRYSTAL, showingBottom, 1, null);
}
}
catch (Exception e) {
e.printStackTrace();
}
});
}
}
}
else {
Block relativeBlock = block.getRelative(event.getBlockFace());
Location relativeBlockLocation = relativeBlock.getLocation();
Location blockLocation = block.getLocation();
String relativeBlockKey = world.getName() + "-" + relativeBlockLocation.getBlockX() + "-" + relativeBlockLocation.getBlockY() + "-" + relativeBlockLocation.getBlockZ();
String blockKey = world.getName() + "-" + blockLocation.getBlockX() + "-" + blockLocation.getBlockY() + "-" + blockLocation.getBlockZ();
Object[] keys = new Object[] { relativeBlockKey, blockKey, handType };
ConfigHandler.entityBlockMapper.put(player.getUniqueId(), keys);
}
Block relativeBlock = block.getRelative(event.getBlockFace());
relativeBlockLocation = relativeBlock.getLocation();
blockLocation = block.getLocation();
}
String relativeBlockKey = world.getName() + "-" + relativeBlockLocation.getBlockX() + "-" + relativeBlockLocation.getBlockY() + "-" + relativeBlockLocation.getBlockZ();
String blockKey = world.getName() + "-" + blockLocation.getBlockX() + "-" + blockLocation.getBlockY() + "-" + blockLocation.getBlockZ();
Object[] keys = new Object[] { relativeBlockKey, blockKey, handItem };
ConfigHandler.entityBlockMapper.put(player.getUniqueId(), keys);
}
}
}
@@ -0,0 +1,42 @@
package net.coreprotect.listener.player;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.bukkit.Location;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerItemBreakEvent;
import org.bukkit.inventory.ItemStack;
import net.coreprotect.config.Config;
import net.coreprotect.config.ConfigHandler;
import net.coreprotect.consumer.Queue;
public final class PlayerItemBreakListener extends Queue implements Listener {
protected static void playerBreakItem(Location location, String user, ItemStack itemStack) {
if (!Config.getConfig(location.getWorld()).ITEM_TRANSACTIONS || itemStack == null) {
return;
}
String loggingItemId = user.toLowerCase(Locale.ROOT) + "." + location.getBlockX() + "." + location.getBlockY() + "." + location.getBlockZ();
int itemId = getItemId(loggingItemId);
List<ItemStack> list = ConfigHandler.itemsBreak.getOrDefault(loggingItemId, new ArrayList<>());
list.add(itemStack.clone());
ConfigHandler.itemsBreak.put(loggingItemId, list);
int time = (int) (System.currentTimeMillis() / 1000L) + 1;
Queue.queueItemTransaction(user, location.clone(), time, 0, itemId);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
protected void onPlayerItemBreak(PlayerItemBreakEvent event) {
ItemStack itemStack = event.getBrokenItem();
playerBreakItem(event.getPlayer().getLocation(), event.getPlayer().getName(), itemStack);
}
}
@@ -11,12 +11,16 @@ import net.coreprotect.consumer.Queue;
public final class PlayerQuitListener extends Queue implements Listener {
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
public static void queuePlayerQuit(Player player) {
if (Config.getConfig(player.getWorld()).PLAYER_SESSIONS) {
int time = (int) (System.currentTimeMillis() / 1000L);
Queue.queuePlayerQuit(player, time);
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerQuit(PlayerQuitEvent event) {
queuePlayerQuit(event.getPlayer());
}
}
@@ -9,7 +9,7 @@ import org.bukkit.event.player.PlayerTakeLecternBookEvent;
import net.coreprotect.config.Config;
import net.coreprotect.consumer.Queue;
public class PlayerTakeLecternBookListener extends Queue implements Listener {
public final class PlayerTakeLecternBookListener extends Queue implements Listener {
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerTakeLecternBook(PlayerTakeLecternBookEvent event) {
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff. Show more