1 Commits

Author SHA1 Message Date
1482b2c4fe Merge branch 'master' into inventory-logging 2021-04-25 01:59:46 +02:00
88 changed files with 7518 additions and 8573 deletions

View File

@ -1,14 +0,0 @@
root = true
[*]
charset = utf-8
insert_final_newline = true
trim_trailing_whitespace = true
[*.java]
indent_style = space
indent_size = 4
[*.yml]
indent_style = space
indent_size = 2

11
.gitattributes vendored
View File

@ -1,11 +0,0 @@
# Set the default behavior, in case people don't have core.autocrlf set.
* text=auto
# Explicitly declare text files you want to always be normalized and converted
# to native line endings on checkout.
*.java text
*.txt text
*.yml text
*.xml text
*.md text
LICENSE text

47
pom.xml
View File

@ -1,10 +1,10 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>de.diddiz</groupId>
<artifactId>logblock</artifactId>
<version>1.20.0.0-SNAPSHOT</version>
<version>1.16.5.2-SNAPSHOT</version>
<packaging>jar</packaging>
<name>LogBlock</name>
@ -29,14 +29,12 @@
<distributionManagement>
<repository>
<id>nexus</id>
<name>Releases</name>
<url>https://www.iani.de/nexus/content/repositories/releases/</url>
<id>md_5-releases</id>
<url>https://repo.md-5.net/content/repositories/releases/</url>
</repository>
<snapshotRepository>
<id>nexus</id>
<name>Snapshot</name>
<url>https://www.iani.de/nexus/content/repositories/snapshots/</url>
<id>md_5-snapshots</id>
<url>https://repo.md-5.net/content/repositories/snapshots/</url>
</snapshotRepository>
</distributionManagement>
@ -44,31 +42,31 @@
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.20.4-R0.1-SNAPSHOT</version>
<version>1.16.1-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sk89q.worldedit</groupId>
<artifactId>worldedit-bukkit</artifactId>
<version>7.3.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-bukkit</artifactId>
<version>7.1.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>5.1.0</version>
<version>3.4.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.7.25</version>
<scope>compile</scope>
</dependency>
</dependencies>
@ -79,7 +77,7 @@
</repository>
<repository>
<id>sk89q-repo</id>
<url>https://maven.enginehub.org/repo/</url>
<url>https://maven.sk89q.com/repo/</url>
</repository>
<repository>
<id>brokkonaut-repo</id>
@ -125,15 +123,16 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.12.1</version>
<version>3.7.0</version>
<configuration>
<release>17</release>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.5.0</version>
<version>3.0.0</version>
<executions>
<execution>
<id>regex-property</id>
@ -153,7 +152,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.5.1</version>
<version>3.1.1</version>
<configuration>
</configuration>
<executions>
@ -168,6 +167,10 @@
<pattern>com.zaxxer.hikari</pattern>
<shadedPattern>de.diddiz.lib.com.zaxxer.hikari</shadedPattern>
</relocation>
<relocation>
<pattern>org.slf4j</pattern>
<shadedPattern>de.diddiz.lib.org.slf4j</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>

View File

@ -7,10 +7,11 @@ import org.bukkit.entity.Projectile;
import org.bukkit.projectiles.BlockProjectileSource;
import org.bukkit.projectiles.ProjectileSource;
import static de.diddiz.LogBlock.util.BukkitUtils.entityName;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import static de.diddiz.util.BukkitUtils.entityName;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.block.Block;
@ -34,41 +35,29 @@ public class Actor {
final String name;
final String UUID;
final Location blockLocation;
final Entity entity;
public Actor(String name, String UUID) {
this.name = name;
this.UUID = UUID == null ? "unknown" : (UUID.length() > 36 ? UUID.substring(0, 36) : UUID);
this.blockLocation = null;
this.entity = null;
}
public Actor(String name, String UUID, Block block) {
this.name = name;
this.UUID = UUID == null ? "unknown" : (UUID.length() > 36 ? UUID.substring(0, 36) : UUID);
this.blockLocation = block == null ? null : block.getLocation();
this.entity = null;
}
public Actor(String name, java.util.UUID UUID) {
this.name = name;
this.UUID = UUID.toString();
this.blockLocation = null;
this.entity = null;
}
public Actor(String name, java.util.UUID UUID, Block block) {
this.name = name;
this.UUID = UUID.toString();
this.blockLocation = block == null ? null : block.getLocation();
this.entity = null;
}
public Actor(String name, java.util.UUID UUID, Entity entity) {
this.name = name;
this.UUID = UUID.toString();
this.blockLocation = null;
this.entity = entity;
}
public Actor(String name) {
@ -79,13 +68,6 @@ public class Actor {
this(name, generateUUID(name), block);
}
public Actor(String name, Entity entity) {
this.name = name;
this.UUID = generateUUID(name);
this.blockLocation = null;
this.entity = entity;
}
public Actor(ResultSet rs) throws SQLException {
this(rs.getString("playername"), rs.getString("UUID"));
}
@ -102,16 +84,9 @@ public class Actor {
return blockLocation;
}
/**
* The acting entity object (if known)
*/
public Entity getEntity() {
return entity;
}
public static Actor actorFromEntity(Entity entity) {
if (entity instanceof Player) {
return new Actor(entityName(entity), entity.getUniqueId(), entity);
return new Actor(entityName(entity), entity.getUniqueId());
}
if (entity instanceof Projectile) {
ProjectileSource shooter = ((Projectile) entity).getShooter();
@ -119,10 +94,9 @@ public class Actor {
return actorFromProjectileSource(shooter);
}
}
return new Actor(entityName(entity), entity);
return new Actor(entityName(entity));
}
@Deprecated
public static Actor actorFromEntity(EntityType entity) {
return new Actor(entity.name());
}
@ -157,9 +131,11 @@ public class Actor {
*/
@Deprecated
public static Actor actorFromString(String actorName) {
Player p = Bukkit.getServer().getPlayerExact(actorName);
if (p != null) {
return actorFromEntity(p);
Collection<? extends Player> players = Bukkit.getServer().getOnlinePlayers();
for (Player p : players) {
if (p.getName().equalsIgnoreCase(actorName)) {
return actorFromEntity(p);
}
}
// No player found online with that name, assuming non-player entity/effect
return new Actor(actorName);

View File

@ -17,9 +17,6 @@ public class AutoClearLog implements Runnable {
public void run() {
final CommandsHandler handler = logblock.getCommandsHandler();
for (final String paramStr : autoClearLog) {
if (!logblock.isCompletelyEnabled()) {
return; // do not try when plugin is disabled
}
try {
final QueryParams params = new QueryParams(logblock, getConsoleSender(), Arrays.asList(paramStr.split(" ")));
params.noForcedLimit = true;

View File

@ -1,18 +1,18 @@
package de.diddiz.LogBlock;
import static de.diddiz.LogBlock.util.ActionColor.CREATE;
import static de.diddiz.LogBlock.util.ActionColor.DESTROY;
import static de.diddiz.LogBlock.util.ActionColor.INTERACT;
import static de.diddiz.LogBlock.util.MessagingUtil.createTextComponentWithColor;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyDate;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyLocation;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyMaterial;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyState;
import static de.diddiz.LogBlock.util.TypeColor.DEFAULT;
import static de.diddiz.util.ActionColor.CREATE;
import static de.diddiz.util.ActionColor.DESTROY;
import static de.diddiz.util.ActionColor.INTERACT;
import static de.diddiz.util.TypeColor.DEFAULT;
import static de.diddiz.util.MessagingUtil.createTextComponentWithColor;
import static de.diddiz.util.MessagingUtil.prettyDate;
import static de.diddiz.util.MessagingUtil.prettyLocation;
import static de.diddiz.util.MessagingUtil.prettyMaterial;
import static de.diddiz.util.MessagingUtil.prettyState;
import de.diddiz.LogBlock.blockstate.BlockStateCodecs;
import de.diddiz.LogBlock.util.BukkitUtils;
import de.diddiz.LogBlock.util.Utils;
import de.diddiz.util.BukkitUtils;
import de.diddiz.util.Utils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
@ -22,11 +22,9 @@ import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Note;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Lightable;
import org.bukkit.block.data.Openable;
import org.bukkit.block.data.Powerable;
import org.bukkit.block.data.Waterlogged;
import org.bukkit.block.data.type.Candle;
import org.bukkit.block.data.type.Comparator;
import org.bukkit.block.data.type.DaylightDetector;
import org.bukkit.block.data.type.Lectern;
@ -62,7 +60,7 @@ public class BlockChange implements LookupCacheElement {
}
public BlockChange(ResultSet rs, QueryParams p) throws SQLException {
id = p.needId ? rs.getLong("id") : 0;
id = p.needId ? rs.getInt("id") : 0;
date = p.needDate ? rs.getTimestamp("date").getTime() : 0;
loc = p.needCoords ? new Location(p.world, rs.getInt("x"), rs.getInt("y"), rs.getInt("z")) : null;
actor = p.needPlayer ? new Actor(rs) : null;
@ -83,27 +81,21 @@ public class BlockChange implements LookupCacheElement {
ca = catemp;
}
private BaseComponent getTypeDetails(BlockData type, byte[] typeState) {
return getTypeDetails(type, typeState, null, null);
}
private BaseComponent getTypeDetails(BlockData type, byte[] typeState, BlockData oldType, byte[] oldTypeState) {
BaseComponent typeDetails = null;
private String getTypeDetails(BlockData type, byte[] typeState) {
String typeDetails = null;
if (BlockStateCodecs.hasCodec(type.getMaterial())) {
try {
typeDetails = BlockStateCodecs.getChangesAsComponent(type.getMaterial(), Utils.deserializeYamlConfiguration(typeState), type.equals(oldType) ? Utils.deserializeYamlConfiguration(oldTypeState) : null);
typeDetails = BlockStateCodecs.toString(type.getMaterial(), Utils.deserializeYamlConfiguration(typeState));
} catch (Exception e) {
LogBlock.getInstance().getLogger().log(Level.SEVERE, "Could not parse BlockState for " + type.getMaterial(), e);
}
}
if (typeDetails == null) {
return new TextComponent("");
return "";
} else {
TextComponent component = new TextComponent(" ");
component.addExtra(typeDetails);
return component;
return " " + typeDetails;
}
}
@ -131,10 +123,10 @@ public class BlockChange implements LookupCacheElement {
}
// Process type details once for later use.
BaseComponent typeDetails = getTypeDetails(type, typeState, replaced, replacedState);
BaseComponent replacedDetails = getTypeDetails(replaced, replacedState);
String typeDetails = getTypeDetails(type, typeState);
String replacedDetails = getTypeDetails(replaced, replacedState);
if (type.getMaterial().equals(replaced.getMaterial()) || (type.getMaterial() == Material.CAKE && BukkitUtils.isCandleCake(replaced.getMaterial()))) {
if (type.getMaterial().equals(replaced.getMaterial())) {
if (BukkitUtils.isEmpty(type.getMaterial())) {
msg.addExtra(createTextComponentWithColor("did an unspecified action", INTERACT.getColor()));
} else if (ca != null) {
@ -160,7 +152,7 @@ public class BlockChange implements LookupCacheElement {
msg.addExtra(createTextComponentWithColor("dried ", DESTROY.getColor()));
msg.addExtra(prettyMaterial(type));
}
} else if (BukkitUtils.isContainerBlock(type.getMaterial())) {
} else if (BukkitUtils.getContainerBlocks().contains(type.getMaterial())) {
msg.addExtra(createTextComponentWithColor("opened ", INTERACT.getColor()));
msg.addExtra(prettyMaterial(type));
} else if (type instanceof Openable && ((Openable) type).isOpen() != ((Openable) replaced).isOpen()) {
@ -203,7 +195,7 @@ public class BlockChange implements LookupCacheElement {
msg.addExtra(createTextComponentWithColor("changed the book on a ", INTERACT.getColor()));
msg.addExtra(prettyMaterial(type));
msg.addExtra(" to");
msg.addExtra(prettyState(typeDetails));
msg.addExtra(prettyState(typeDetails.length() == 0 ? " empty" : typeDetails));
} else if (type instanceof Powerable) {
msg.addExtra(createTextComponentWithColor("stepped on ", INTERACT.getColor()));
msg.addExtra(prettyMaterial(type));
@ -213,19 +205,8 @@ public class BlockChange implements LookupCacheElement {
} else if (type instanceof Sign || type instanceof WallSign) {
msg.addExtra(createTextComponentWithColor("edited a ", CREATE.getColor()));
msg.addExtra(prettyMaterial(type));
msg.addExtra(createTextComponentWithColor(" to", CREATE.getColor()));
msg.addExtra(createTextComponentWithColor(" to ", CREATE.getColor()));
msg.addExtra(prettyState(typeDetails));
} else if (type instanceof Candle && ((Candle) type).getCandles() != ((Candle) replaced).getCandles()) {
msg.addExtra(createTextComponentWithColor("added a candle to ", CREATE.getColor()));
msg.addExtra(prettyMaterial(type));
} else if ((type instanceof Candle || BukkitUtils.isCandleCake(type.getMaterial())) && ((Lightable) type).isLit() != ((Lightable) replaced).isLit()) {
if (((Lightable) type).isLit()) {
msg.addExtra(createTextComponentWithColor("lit a ", CREATE.getColor()));
msg.addExtra(prettyMaterial(type));
} else {
msg.addExtra(createTextComponentWithColor("extinguished a ", CREATE.getColor()));
msg.addExtra(prettyMaterial(type));
}
} else {
msg.addExtra(createTextComponentWithColor("replaced ", CREATE.getColor()));
msg.addExtra(prettyMaterial(replaced));

View File

@ -1,11 +1,11 @@
package de.diddiz.LogBlock;
import static de.diddiz.LogBlock.util.LoggingUtil.checkText;
import static de.diddiz.LogBlock.util.MessagingUtil.brackets;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyDate;
import static de.diddiz.util.LoggingUtil.checkText;
import static de.diddiz.util.MessagingUtil.brackets;
import static de.diddiz.util.MessagingUtil.prettyDate;
import de.diddiz.LogBlock.util.MessagingUtil;
import de.diddiz.LogBlock.util.MessagingUtil.BracketType;
import de.diddiz.util.MessagingUtil;
import de.diddiz.util.MessagingUtil.BracketType;
import java.sql.ResultSet;
import java.sql.SQLException;
import net.md_5.bungee.api.chat.BaseComponent;
@ -26,7 +26,7 @@ public class ChatMessage implements LookupCacheElement {
}
public ChatMessage(ResultSet rs, QueryParams p) throws SQLException {
id = p.needId ? rs.getLong("id") : 0;
id = p.needId ? rs.getInt("id") : 0;
date = p.needDate ? rs.getTimestamp("date").getTime() : 0;
player = p.needPlayer ? new Actor(rs) : null;
playerName = p.needPlayer ? rs.getString("playername") : null;

View File

@ -14,21 +14,20 @@ import static de.diddiz.LogBlock.config.Config.rollbackMaxArea;
import static de.diddiz.LogBlock.config.Config.rollbackMaxTime;
import static de.diddiz.LogBlock.config.Config.toolsByName;
import static de.diddiz.LogBlock.config.Config.toolsByType;
import static de.diddiz.LogBlock.util.BukkitUtils.giveTool;
import static de.diddiz.LogBlock.util.BukkitUtils.safeSpawnHeight;
import static de.diddiz.LogBlock.util.TypeColor.DEFAULT;
import static de.diddiz.LogBlock.util.TypeColor.ERROR;
import static de.diddiz.LogBlock.util.TypeColor.HEADER;
import static de.diddiz.LogBlock.util.Utils.isInt;
import static de.diddiz.LogBlock.util.Utils.listing;
import static de.diddiz.util.BukkitUtils.giveTool;
import static de.diddiz.util.BukkitUtils.saveSpawnHeight;
import static de.diddiz.util.TypeColor.DEFAULT;
import static de.diddiz.util.TypeColor.ERROR;
import static de.diddiz.util.TypeColor.HEADER;
import static de.diddiz.util.Utils.isInt;
import static de.diddiz.util.Utils.listing;
import de.diddiz.LogBlock.QueryParams.BlockChangeType;
import de.diddiz.LogBlock.QueryParams.Order;
import de.diddiz.LogBlock.QueryParams.SummarizationMode;
import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.LogBlock.util.MessagingUtil;
import de.diddiz.LogBlock.util.Utils;
import de.diddiz.util.Utils;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
@ -45,10 +44,8 @@ import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.Command;
@ -71,75 +68,53 @@ public class CommandsHandler implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
try {
if (args.length == 0) {
sender.sendMessage(ChatColor.YELLOW + "------------------[ " + ChatColor.WHITE + "LogBlock" + ChatColor.YELLOW + " ]-------------------");
sender.sendMessage(ChatColor.GOLD + "LogBlock " + ChatColor.WHITE + "v" + logblock.getDescription().getVersion() + ChatColor.GOLD + " by DiddiZ");
TextComponent message = MessagingUtil.createTextComponentWithColor("Type ", net.md_5.bungee.api.ChatColor.GOLD);
TextComponent clickable = MessagingUtil.createTextComponentWithColor("/lb help", net.md_5.bungee.api.ChatColor.WHITE);
clickable.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/lb help"));
message.addExtra(clickable);
message.addExtra(" for help");
sender.spigot().sendMessage(message);
sender.sendMessage(ChatColor.LIGHT_PURPLE + "LogBlock v" + logblock.getDescription().getVersion() + " by DiddiZ");
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Type /lb help for help");
} else {
final String command = args[0].toLowerCase();
if (command.equals("help")) {
sender.sendMessage(ChatColor.YELLOW + "----------------[ " + ChatColor.WHITE + "LogBlock Help" + ChatColor.YELLOW + " ]----------------");
TextComponent message = MessagingUtil.createTextComponentWithColor("For the commands list type ", net.md_5.bungee.api.ChatColor.GOLD);
TextComponent clickable = MessagingUtil.createTextComponentWithColor("/lb commands", net.md_5.bungee.api.ChatColor.WHITE);
clickable.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/lb commands"));
message.addExtra(clickable);
sender.spigot().sendMessage(message);
message = MessagingUtil.createTextComponentWithColor("For the parameters list type ", net.md_5.bungee.api.ChatColor.GOLD);
clickable = MessagingUtil.createTextComponentWithColor("/lb params", net.md_5.bungee.api.ChatColor.WHITE);
clickable.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/lb params"));
message.addExtra(clickable);
sender.spigot().sendMessage(message);
message = MessagingUtil.createTextComponentWithColor("For the list of permissions you got type ", net.md_5.bungee.api.ChatColor.GOLD);
clickable = MessagingUtil.createTextComponentWithColor("/lb permissions", net.md_5.bungee.api.ChatColor.WHITE);
clickable.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/lb permissions"));
message.addExtra(clickable);
sender.spigot().sendMessage(message);
sender.sendMessage(ChatColor.DARK_AQUA + "LogBlock Help:");
sender.sendMessage(ChatColor.GOLD + "For the commands list type '/lb commands'");
sender.sendMessage(ChatColor.GOLD + "For the parameters list type '/lb params'");
sender.sendMessage(ChatColor.GOLD + "For the list of permissions you got type '/lb permissions'");
} else if (command.equals("commands")) {
sender.sendMessage(ChatColor.YELLOW + "--------------[ " + ChatColor.WHITE + "LogBlock Commands" + ChatColor.YELLOW + " ]--------------");
sender.sendMessage(ChatColor.GOLD + "/lb tool " + ChatColor.WHITE + "-- Gives you the lb tool");
sender.sendMessage(ChatColor.GOLD + "/lb tool [on|off] " + ChatColor.WHITE + "-- Enables/Disables tool");
sender.sendMessage(ChatColor.GOLD + "/lb tool [params] " + ChatColor.WHITE + "-- Sets the tool lookup query");
sender.sendMessage(ChatColor.GOLD + "/lb tool default " + ChatColor.WHITE + "-- Sets the tool lookup query to default");
sender.sendMessage(ChatColor.GOLD + "/lb toolblock " + ChatColor.WHITE + "-- Analog to tool");
sender.sendMessage(ChatColor.GOLD + "/lb hide " + ChatColor.WHITE + "-- Hides you from log");
sender.sendMessage(ChatColor.GOLD + "/lb rollback [params] " + ChatColor.WHITE + "-- Rollback");
sender.sendMessage(ChatColor.GOLD + "/lb redo [params] " + ChatColor.WHITE + "-- Redo");
sender.sendMessage(ChatColor.GOLD + "/lb tp [params] " + ChatColor.WHITE + "-- Teleports you to the location of griefing");
sender.sendMessage(ChatColor.GOLD + "/lb writelogfile [params] " + ChatColor.WHITE + "-- Writes a log file");
sender.sendMessage(ChatColor.GOLD + "/lb lookup [params] " + ChatColor.WHITE + "-- Lookup");
sender.sendMessage(ChatColor.GOLD + "/lb prev|next " + ChatColor.WHITE + "-- Browse lookup result pages");
sender.sendMessage(ChatColor.GOLD + "/lb page " + ChatColor.WHITE + "-- Shows a specific lookup result page");
sender.sendMessage(ChatColor.GOLD + "/lb me " + ChatColor.WHITE + "-- Displays your stats");
sender.sendMessage("");
sender.sendMessage(ChatColor.GOLD + "Look at " + ChatColor.WHITE + "github.com/LogBlock/LogBlock/wiki/Commands" + ChatColor.GOLD + " for the full commands reference");
sender.sendMessage(ChatColor.DARK_AQUA + "LogBlock Commands:");
sender.sendMessage(ChatColor.GOLD + "/lb tool -- Gives you the lb tool");
sender.sendMessage(ChatColor.GOLD + "/lb tool [on|off] -- Enables/Disables tool");
sender.sendMessage(ChatColor.GOLD + "/lb tool [params] -- Sets the tool lookup query");
sender.sendMessage(ChatColor.GOLD + "/lb tool default -- Sets the tool lookup query to default");
sender.sendMessage(ChatColor.GOLD + "/lb toolblock -- Analog to tool");
sender.sendMessage(ChatColor.GOLD + "/lb hide -- Hides you from log");
sender.sendMessage(ChatColor.GOLD + "/lb rollback [params] -- Rollback");
sender.sendMessage(ChatColor.GOLD + "/lb redo [params] -- Redo");
sender.sendMessage(ChatColor.GOLD + "/lb tp [params] -- Teleports you to the location of griefing");
sender.sendMessage(ChatColor.GOLD + "/lb writelogfile [params] -- Writes a log file");
sender.sendMessage(ChatColor.GOLD + "/lb lookup [params] -- Lookup");
sender.sendMessage(ChatColor.GOLD + "/lb prev|next -- Browse lookup result pages");
sender.sendMessage(ChatColor.GOLD + "/lb page -- Shows a specific lookup result page");
sender.sendMessage(ChatColor.GOLD + "/lb me -- Displays your stats");
sender.sendMessage(ChatColor.GOLD + "Look at github.com/LogBlock/LogBlock/wiki/Commands for the full commands reference");
} else if (command.equals("params")) {
sender.sendMessage(ChatColor.YELLOW + "----------[ " + ChatColor.WHITE + "LogBlock Query Parameters" + ChatColor.YELLOW + " ]----------");
sender.sendMessage(ChatColor.DARK_AQUA + "LogBlock Query Parameters:");
sender.sendMessage(ChatColor.GOLD + "Use doublequotes to escape a keyword: world \"world\"");
sender.sendMessage(ChatColor.GOLD + "player [name1] <name2> <name3> " + ChatColor.WHITE + "-- List of players");
sender.sendMessage(ChatColor.GOLD + "block [type1] <type2> <type3> " + ChatColor.WHITE + "-- List of block types");
sender.sendMessage(ChatColor.GOLD + "created, destroyed " + ChatColor.WHITE + "-- Show only created/destroyed blocks");
sender.sendMessage(ChatColor.GOLD + "chestaccess " + ChatColor.WHITE + "-- Show only chest accesses");
sender.sendMessage(ChatColor.GOLD + "entities [type1] <type2> <type3> " + ChatColor.WHITE + "-- List of entity types; can not be combined with blocks");
sender.sendMessage(ChatColor.GOLD + "area <radius> " + ChatColor.WHITE + "-- Area around you");
sender.sendMessage(ChatColor.GOLD + "selection, sel " + ChatColor.WHITE + "-- Inside current WorldEdit selection");
sender.sendMessage(ChatColor.GOLD + "world [worldname] " + ChatColor.WHITE + "-- Changes the world");
sender.sendMessage(ChatColor.GOLD + "time [number] [minutes|hours|days] " + ChatColor.WHITE + "-- Limits time");
sender.sendMessage(ChatColor.GOLD + "since <dd.MM.yyyy> <HH:mm:ss> " + ChatColor.WHITE + "-- Limits time to a fixed point");
sender.sendMessage(ChatColor.GOLD + "before <dd.MM.yyyy> <HH:mm:ss> " + ChatColor.WHITE + "-- Affects only blocks before a fixed time");
sender.sendMessage(ChatColor.GOLD + "force " + ChatColor.WHITE + "-- Forces replacing not matching blocks");
sender.sendMessage(ChatColor.GOLD + "limit <row count> " + ChatColor.WHITE + "-- Limits the result to count of rows");
sender.sendMessage(ChatColor.GOLD + "sum [none|blocks|players] " + ChatColor.WHITE + "-- Sums the result");
sender.sendMessage(ChatColor.GOLD + "asc, desc " + ChatColor.WHITE + "-- Changes the order of the displayed log");
sender.sendMessage(ChatColor.GOLD + "coords " + ChatColor.WHITE + "-- Shows coordinates for each block");
sender.sendMessage(ChatColor.GOLD + "nocache " + ChatColor.WHITE + "-- Don't set the lookup cache");
sender.sendMessage(ChatColor.GOLD + "silent " + ChatColor.WHITE + "-- Displays lesser messages");
sender.sendMessage(ChatColor.GOLD + "player [name1] <name2> <name3> -- List of players");
sender.sendMessage(ChatColor.GOLD + "block [type1] <type2> <type3> -- List of block types");
sender.sendMessage(ChatColor.GOLD + "created, destroyed -- Show only created/destroyed blocks");
sender.sendMessage(ChatColor.GOLD + "chestaccess -- Show only chest accesses");
sender.sendMessage(ChatColor.GOLD + "entities [type1] <type2> <type3> -- List of entity types; can not be combined with blocks");
sender.sendMessage(ChatColor.GOLD + "area <radius> -- Area around you");
sender.sendMessage(ChatColor.GOLD + "selection, sel -- Inside current WorldEdit selection");
sender.sendMessage(ChatColor.GOLD + "world [worldname] -- Changes the world");
sender.sendMessage(ChatColor.GOLD + "time [number] [minutes|hours|days] -- Limits time");
sender.sendMessage(ChatColor.GOLD + "since <dd.MM.yyyy> <HH:mm:ss> -- Limits time to a fixed point");
sender.sendMessage(ChatColor.GOLD + "before <dd.MM.yyyy> <HH:mm:ss> -- Affects only blocks before a fixed time");
sender.sendMessage(ChatColor.GOLD + "force -- Forces replacing not matching blocks");
sender.sendMessage(ChatColor.GOLD + "limit <row count> -- Limits the result to count of rows");
sender.sendMessage(ChatColor.GOLD + "sum [none|blocks|players] -- Sums the result");
sender.sendMessage(ChatColor.GOLD + "asc, desc -- Changes the order of the displayed log");
sender.sendMessage(ChatColor.GOLD + "coords -- Shows coordinates for each block");
sender.sendMessage(ChatColor.GOLD + "nocache -- Don't set the lookup cache");
sender.sendMessage(ChatColor.GOLD + "silent -- Displays lesser messages");
} else if (command.equals("permissions")) {
sender.sendMessage(ChatColor.DARK_AQUA + "You've got the following permissions:");
for (final String permission : new String[] { "me", "lookup", "tp", "rollback", "clearlog", "hide", "ignoreRestrictions", "spawnTools" }) {
@ -281,16 +256,13 @@ public class CommandsHandler implements CommandExecutor {
}
} else if (command.equals("page")) {
if (args.length == 2 && isInt(args[1])) {
sender.sendMessage("");
showPage(sender, Integer.valueOf(args[1]));
} else {
sender.sendMessage(ChatColor.RED + "You have to specify a page");
}
} else if (command.equals("next") || command.equals("+")) {
sender.sendMessage("");
showPage(sender, getSession(sender).page + 1);
} else if (command.equals("prev") || command.equals("-")) {
sender.sendMessage("");
showPage(sender, getSession(sender).page - 1);
} else if (args[0].equalsIgnoreCase("savequeue")) {
if (logblock.hasPermission(sender, "logblock.rollback")) {
@ -374,7 +346,7 @@ public class CommandsHandler implements CommandExecutor {
if (pos >= 0 && pos < session.lookupCache.length) {
final Location loc = session.lookupCache[pos].getLocation();
if (loc != null) {
player.teleport(new Location(loc.getWorld(), loc.getX() + 0.5, player.getGameMode() != GameMode.SPECTATOR ? safeSpawnHeight(loc) : loc.getY(), loc.getZ() + 0.5, player.getLocation().getYaw(), 90));
player.teleport(new Location(loc.getWorld(), loc.getX() + 0.5, saveSpawnHeight(loc), loc.getZ() + 0.5, player.getLocation().getYaw(), 90));
player.sendMessage(ChatColor.LIGHT_PURPLE + "Teleported to " + loc.getBlockX() + ":" + loc.getBlockY() + ":" + loc.getBlockZ());
} else {
sender.sendMessage(ChatColor.RED + "There is no location associated with that. Did you forget coords parameter?");
@ -544,7 +516,6 @@ public class CommandsHandler implements CommandExecutor {
}
state = conn.createStatement();
rs = executeQuery(state, params.getQuery());
sender.sendMessage("");
sender.sendMessage(ChatColor.DARK_AQUA + params.getTitle() + ":");
final List<LookupCacheElement> blockchanges = new ArrayList<>();
final LookupCacheElementFactory factory = new LookupCacheElementFactory(params, sender instanceof Player ? 2 / 3f : 1);
@ -700,12 +671,10 @@ public class CommandsHandler implements CommandExecutor {
logblock.getServer().getScheduler().scheduleSyncDelayedTask(logblock, new Runnable() {
@Override
public void run() {
if (player.getGameMode() != GameMode.SPECTATOR) {
final int y2 = safeSpawnHeight(loc);
loc.setY(y2);
sender.sendMessage(ChatColor.GREEN + "You were teleported " + Math.abs(y2 - y) + " blocks " + (y2 - y > 0 ? "above" : "below"));
}
final int y2 = saveSpawnHeight(loc);
loc.setY(y2);
player.teleport(loc);
sender.sendMessage(ChatColor.GREEN + "You were teleported " + Math.abs(y2 - y) + " blocks " + (y2 - y > 0 ? "above" : "below"));
}
});
} else {
@ -968,14 +937,14 @@ public class CommandsHandler implements CommandExecutor {
StringBuilder sb = new StringBuilder();
if (params.bct == BlockChangeType.CHAT) {
sb.append("INSERT INTO `lb-chat` (`id`, `date`, `playerid`, `message`) VALUES (");
sb.append(rs.getLong("id")).append(", FROM_UNIXTIME(");
sb.append(rs.getInt("id")).append(", FROM_UNIXTIME(");
sb.append(rs.getTimestamp("date").getTime() / 1000).append("), ");
sb.append(rs.getInt("playerid")).append(", '");
sb.append(Utils.mysqlTextEscape(rs.getString("message")));
sb.append("');\n");
} else if (params.bct == BlockChangeType.KILLS) {
sb.append("INSERT INTO `").append(tableBase).append("-kills` (`id`, `date`, `killer`, `victim`, `weapon`, `x`, `y`, `z`) VALUES (");
sb.append(rs.getLong("id")).append(", FROM_UNIXTIME(");
sb.append(rs.getInt("id")).append(", FROM_UNIXTIME(");
sb.append(rs.getTimestamp("date").getTime() / 1000).append("), ");
sb.append(rs.getInt("killerid")).append(", ");
sb.append(rs.getInt("victimid")).append(", ");
@ -988,7 +957,7 @@ public class CommandsHandler implements CommandExecutor {
} else {
sb.append("INSERT INTO `").append(tableBase).append("-blocks` (`id`, `date`, `playerid`, `replaced`, `replacedData`, `type`, `typeData`, `x`, `y`, `z`) VALUES (");
sb.append(rs.getLong("id")).append(", FROM_UNIXTIME(");
sb.append(rs.getInt("id")).append(", FROM_UNIXTIME(");
sb.append(rs.getTimestamp("date").getTime() / 1000).append("), ");
sb.append(rs.getInt("playerid")).append(", ");
sb.append(rs.getInt("replaced")).append(", ");
@ -1003,7 +972,7 @@ public class CommandsHandler implements CommandExecutor {
byte[] typeState = rs.getBytes("typeState");
if (replacedState != null || typeState != null) {
sb.append("INSERT INTO `").append(tableBase).append("-state` (`id`, `replacedState`, `typeState`) VALUES (");
sb.append(rs.getLong("id")).append(", ");
sb.append(rs.getInt("id")).append(", ");
sb.append(Utils.mysqlPrepareBytesForInsertAllowNull(replacedState)).append(", ");
sb.append(Utils.mysqlPrepareBytesForInsertAllowNull(typeState));
sb.append(");\n");
@ -1011,7 +980,7 @@ public class CommandsHandler implements CommandExecutor {
byte[] item = rs.getBytes("item");
if (item != null) {
sb.append("INSERT INTO `").append(tableBase).append("-chestdata` (`id`, `item`, `itemremove`, `itemtype`) VALUES (");
sb.append(rs.getLong("id")).append(", ");
sb.append(rs.getInt("id")).append(", ");
sb.append(Utils.mysqlPrepareBytesForInsertAllowNull(item)).append(", ");
sb.append(rs.getInt("itemremove")).append(", ");
sb.append(rs.getInt("itemtype"));

View File

@ -5,9 +5,9 @@ import static de.diddiz.LogBlock.config.Config.hiddenBlocks;
import static de.diddiz.LogBlock.config.Config.hiddenPlayers;
import static de.diddiz.LogBlock.config.Config.isLogged;
import static de.diddiz.LogBlock.config.Config.logPlayerInfo;
import static de.diddiz.LogBlock.util.BukkitUtils.compressInventory;
import static de.diddiz.LogBlock.util.BukkitUtils.itemIDfromProjectileEntity;
import static de.diddiz.LogBlock.util.Utils.mysqlTextEscape;
import static de.diddiz.util.BukkitUtils.compressInventory;
import static de.diddiz.util.BukkitUtils.itemIDfromProjectileEntity;
import static de.diddiz.util.Utils.mysqlTextEscape;
import java.io.File;
import java.io.FileNotFoundException;
@ -35,7 +35,8 @@ import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.BlockState;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Waterlogged;
import org.bukkit.block.data.type.Sign;
import org.bukkit.block.data.type.WallSign;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
@ -47,12 +48,11 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.projectiles.ProjectileSource;
import de.diddiz.LogBlock.EntityChange.EntityChangeType;
import de.diddiz.LogBlock.blockstate.BlockStateCodecSign;
import de.diddiz.LogBlock.blockstate.BlockStateCodecs;
import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.events.BlockChangePreLogEvent;
import de.diddiz.LogBlock.events.EntityChangePreLogEvent;
import de.diddiz.LogBlock.util.BukkitUtils;
import de.diddiz.LogBlock.util.Utils;
import de.diddiz.util.Utils;
public class Consumer extends Thread {
private static final int MAX_SHUTDOWN_TIME_MILLIS = 20000;
@ -64,7 +64,7 @@ public class Consumer extends Thread {
private final LogBlock logblock;
private final Map<Actor, Integer> playerIds = new HashMap<>();
private final Map<Actor, Integer> uncommitedPlayerIds = new HashMap<>();
private final Map<World, Map<UUID, Long>> uncommitedEntityIds = new HashMap<>();
private final Map<World, Map<UUID, Integer>> uncommitedEntityIds = new HashMap<>();
private long addEntryCounter;
private long nextWarnCounter;
@ -330,6 +330,25 @@ public class Consumer extends Thread {
addQueueLast(new KillRow(location, killer == null ? null : killer, victim, weapon == null ? 0 : MaterialConverter.getOrAddMaterialId(weapon.getType())));
}
/**
* Logs an actor placing a sign along with its contents
*
* @param actor
* Actor placing the sign
* @param loc
* Location of the placed sign
* @param type
* BlockData of the sign
* @param lines
* The four lines on the sign.
*/
public void queueSignChange(Actor actor, Location loc, BlockData type, String[] lines) {
if ((!(type instanceof Sign) && !(type instanceof WallSign)) || lines == null || lines.length != 4) {
return;
}
queueBlock(actor, loc, type, type, null, BlockStateCodecSign.serialize(lines), null);
}
public void queueChat(Actor player, String message) {
if (!Config.ignoredChat.isEmpty()) {
String lowerCaseMessage = message.toLowerCase();
@ -521,9 +540,8 @@ public class Consumer extends Thread {
final long time = System.currentTimeMillis();
final Set<Actor> insertedPlayers = new HashSet<>();
int counter = 0;
final File importDir = new File(logblock.getDataFolder(), "import");
importDir.mkdirs();
PrintWriter writer = new PrintWriter(new File(importDir, "queue-" + time + "-0.sql"));
new File("plugins/LogBlock/import/").mkdirs();
PrintWriter writer = new PrintWriter(new File("plugins/LogBlock/import/queue-" + time + "-0.sql"));
while (!isQueueEmpty()) {
final Row r = pollQueueFirst();
if (r == null) {
@ -542,7 +560,7 @@ public class Consumer extends Thread {
counter++;
if (counter % 1000 == 0) {
writer.close();
writer = new PrintWriter(new File(importDir, "queue-" + time + "-" + counter / 1000 + ".sql"));
writer = new PrintWriter(new File("plugins/LogBlock/import/queue-" + time + "-" + counter / 1000 + ".sql"));
}
}
writer.close();
@ -629,13 +647,13 @@ public class Consumer extends Thread {
return uncommitedPlayerIds.containsKey(actor);
}
private long getEntityUUID(Connection conn, World world, UUID uuid) throws SQLException {
Map<UUID, Long> uncommitedEntityIdsHere = uncommitedEntityIds.get(world);
private int getEntityUUID(Connection conn, World world, UUID uuid) throws SQLException {
Map<UUID, Integer> uncommitedEntityIdsHere = uncommitedEntityIds.get(world);
if (uncommitedEntityIdsHere == null) {
uncommitedEntityIdsHere = new HashMap<>();
uncommitedEntityIds.put(world, uncommitedEntityIdsHere);
}
Long existing = uncommitedEntityIdsHere.get(uuid);
Integer existing = uncommitedEntityIdsHere.get(uuid);
if (existing != null) {
return existing;
}
@ -649,7 +667,7 @@ public class Consumer extends Thread {
int q1Result = state.executeUpdate(q1);
ResultSet rs = state.executeQuery(q2);
if (rs.next()) {
uncommitedEntityIdsHere.put(uuid, rs.getLong(1));
uncommitedEntityIdsHere.put(uuid, rs.getInt(1));
}
rs.close();
// if there was not any row in the table the query above does not work, so we need to try this one
@ -657,7 +675,7 @@ public class Consumer extends Thread {
state.executeUpdate("INSERT IGNORE INTO `" + table + "-entityids` (entityuuid) VALUES ('" + mysqlTextEscape(uuidString) + "')");
rs = state.executeQuery(q2);
if (rs.next()) {
uncommitedEntityIdsHere.put(uuid, rs.getLong(1));
uncommitedEntityIdsHere.put(uuid, rs.getInt(1));
} else {
logblock.getLogger().warning("[Consumer] Failed to add entity uuid " + uuidString.toString());
logblock.getLogger().warning("[Consumer-Debug] World: " + world.getName());
@ -675,13 +693,10 @@ public class Consumer extends Thread {
if (typeBefore == null || typeBefore.getMaterial() == Material.CAVE_AIR || typeBefore.getMaterial() == Material.VOID_AIR) {
typeBefore = Bukkit.createBlockData(Material.AIR);
}
if (typeAfter == null && ((typeBefore instanceof Waterlogged && ((Waterlogged) typeBefore).isWaterlogged()) || BukkitUtils.isAlwaysWaterlogged(typeBefore.getMaterial()))) {
typeAfter = Bukkit.createBlockData(Material.WATER);
}
if (typeAfter == null || typeAfter.getMaterial() == Material.CAVE_AIR || typeAfter.getMaterial() == Material.VOID_AIR) {
typeAfter = Bukkit.createBlockData(Material.AIR);
}
if (BlockChangePreLogEvent.getHandlerList().getRegisteredListeners().length > 0) {
if (Config.fireCustomEvents) {
// Create and call the event
BlockChangePreLogEvent event = new BlockChangePreLogEvent(actor, loc, typeBefore, typeAfter, stateBefore, stateAfter, ca);
logblock.getServer().getPluginManager().callEvent(event);
@ -711,31 +726,10 @@ public class Consumer extends Thread {
addQueueLast(new BlockRow(loc, actor, replacedMaterialId, replacedStateId, Utils.serializeYamlConfiguration(stateBefore), typeMaterialId, typeStateId, Utils.serializeYamlConfiguration(stateAfter), ca));
}
public void queueEntityModification(Actor actor, Entity entity, EntityChangeType changeType, YamlConfiguration data) {
if (actor == null || changeType == null || entity == null || hiddenPlayers.contains(actor.getName().toLowerCase()) || !isLogged(entity.getWorld())) {
public void queueEntityModification(Actor actor, UUID entityId, EntityType entityType, Location loc, EntityChangeType changeType, YamlConfiguration data) {
if (actor == null || loc == null || changeType == null || entityId == null || entityType == null || hiddenPlayers.contains(actor.getName().toLowerCase()) || !isLogged(loc.getWorld())) {
return;
}
UUID entityId = entity.getUniqueId();
EntityType entityType = entity.getType();
Location loc = entity.getLocation();
if (EntityChangePreLogEvent.getHandlerList().getRegisteredListeners().length > 0) {
// Create and call the event
EntityChangePreLogEvent event = new EntityChangePreLogEvent(actor, loc, entity, changeType, data);
logblock.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
// Update variables
actor = event.getOwnerActor();
loc = event.getLocation();
}
// Do this last so LogBlock still has final say in what is being added
if (actor == null || loc == null || hiddenPlayers.contains(actor.getName().toLowerCase()) || !isLogged(loc.getWorld())) {
return;
}
addQueueLast(new EntityRow(loc, actor, entityType, entityId, changeType, Utils.serializeYamlConfiguration(data)));
}
@ -860,22 +854,22 @@ public class Consumer extends Thread {
smt.setInt(8, safeY(loc));
smt.setInt(9, loc.getBlockZ());
batchHelper.addUncommitedBlockActorId(loc, sourceActor);
batchHelper.addBatch(smt, new LongCallback() {
batchHelper.addBatch(smt, new IntCallback() {
@Override
public void call(long id) throws SQLException {
public void call(int id) throws SQLException {
PreparedStatement ps;
if (typeState != null || replacedState != null) {
ps = batchHelper.getOrPrepareStatement(conn, getWorldConfig(loc.getWorld()).insertBlockStateStatementString, Statement.NO_GENERATED_KEYS);
ps.setBytes(1, replacedState);
ps.setBytes(2, typeState);
ps.setLong(3, id);
ps.setInt(3, id);
batchHelper.addBatch(ps, null);
}
if (ca != null) {
ps = batchHelper.getOrPrepareStatement(conn, getWorldConfig(loc.getWorld()).insertBlockChestDataStatementString, Statement.NO_GENERATED_KEYS);
ps.setBytes(1, finalSerializedItemStack);
ps.setInt(2, ca.remove ? 1 : 0);
ps.setLong(3, id);
ps.setInt(3, id);
ps.setInt(4, ca.itemType);
batchHelper.addBatch(ps, null);
}
@ -1087,7 +1081,7 @@ public class Consumer extends Thread {
PreparedStatement smt = batchHelper.getOrPrepareStatement(conn, statementString, Statement.NO_GENERATED_KEYS);
smt.setLong(1, date);
smt.setInt(2, sourceActor);
smt.setLong(3, getEntityUUID(conn, loc.getWorld(), entityUUID));
smt.setInt(3, getEntityUUID(conn, loc.getWorld(), entityUUID));
smt.setInt(4, EntityTypeConverter.getOrAddEntityTypeId(type));
smt.setInt(5, loc.getBlockX());
smt.setInt(6, safeY(loc));
@ -1100,11 +1094,11 @@ public class Consumer extends Thread {
private class EntityUUIDChange implements Row {
private final World world;
private final long entityId;
private final int entityId;
private final UUID entityUUID;
final String updateEntityUUIDString;
public EntityUUIDChange(World world, long entityId, UUID entityUUID) {
public EntityUUIDChange(World world, int entityId, UUID entityUUID) {
this.world = world;
this.entityId = entityId;
this.entityUUID = entityUUID;
@ -1129,18 +1123,18 @@ public class Consumer extends Thread {
public void process(Connection conn, BatchHelper batchHelper) throws SQLException {
PreparedStatement smt = batchHelper.getOrPrepareStatement(conn, updateEntityUUIDString, Statement.NO_GENERATED_KEYS);
smt.setString(1, entityUUID.toString());
smt.setLong(2, entityId);
smt.setInt(2, entityId);
smt.executeUpdate();
}
}
private int safeY(Location loc) {
int safeY = loc.getBlockY();
if (safeY < Short.MIN_VALUE) {
safeY = Short.MIN_VALUE;
if (safeY < 0) {
safeY = 0;
}
if (safeY > Short.MAX_VALUE) {
safeY = Short.MAX_VALUE;
if (safeY > 65535) {
safeY = 65535;
}
return safeY;
}
@ -1148,7 +1142,7 @@ public class Consumer extends Thread {
private class BatchHelper {
private HashMap<String, PreparedStatement> preparedStatements = new HashMap<>();
private HashSet<PreparedStatement> preparedStatementsWithGeneratedKeys = new HashSet<>();
private LinkedHashMap<PreparedStatement, ArrayList<LongCallback>> generatedKeyHandler = new LinkedHashMap<>();
private LinkedHashMap<PreparedStatement, ArrayList<IntCallback>> generatedKeyHandler = new LinkedHashMap<>();
private HashMap<Location, Integer> uncommitedBlockActors = new HashMap<>();
public void reset() {
@ -1168,21 +1162,21 @@ public class Consumer extends Thread {
public void processStatements(Connection conn) throws SQLException {
while (!generatedKeyHandler.isEmpty()) {
Entry<PreparedStatement, ArrayList<LongCallback>> entry = generatedKeyHandler.entrySet().iterator().next();
Entry<PreparedStatement, ArrayList<IntCallback>> entry = generatedKeyHandler.entrySet().iterator().next();
PreparedStatement smt = entry.getKey();
ArrayList<LongCallback> callbackList = entry.getValue();
ArrayList<IntCallback> callbackList = entry.getValue();
generatedKeyHandler.remove(smt);
smt.executeBatch();
if (preparedStatementsWithGeneratedKeys.contains(smt)) {
ResultSet keys = smt.getGeneratedKeys();
long[] results = new long[callbackList.size()];
int[] results = new int[callbackList.size()];
int pos = 0;
while (keys.next() && pos < results.length) {
results[pos++] = keys.getLong(1);
results[pos++] = keys.getInt(1);
}
keys.close();
for (int i = 0; i < results.length; i++) {
LongCallback callback = callbackList.get(i);
IntCallback callback = callbackList.get(i);
if (callback != null) {
callback.call(results[i]);
}
@ -1204,9 +1198,9 @@ public class Consumer extends Thread {
return smt;
}
public void addBatch(PreparedStatement smt, LongCallback generatedKeysCallback) throws SQLException {
public void addBatch(PreparedStatement smt, IntCallback generatedKeysCallback) throws SQLException {
smt.addBatch();
ArrayList<LongCallback> callbackList = generatedKeyHandler.get(smt);
ArrayList<IntCallback> callbackList = generatedKeyHandler.get(smt);
if (callbackList == null) {
callbackList = new ArrayList<>();
generatedKeyHandler.put(smt, callbackList);
@ -1215,7 +1209,7 @@ public class Consumer extends Thread {
}
}
protected interface LongCallback {
public void call(long value) throws SQLException;
protected interface IntCallback {
public void call(int value) throws SQLException;
}
}

View File

@ -1,8 +1,7 @@
package de.diddiz.LogBlock;
import static de.diddiz.LogBlock.util.Utils.newline;
import de.diddiz.util.Utils.ExtensionFilenameFilter;
import de.diddiz.LogBlock.util.Utils.ExtensionFilenameFilter;
import java.io.*;
import java.sql.Connection;
import java.sql.SQLException;
@ -12,6 +11,8 @@ import java.util.Comparator;
import java.util.logging.Level;
import java.util.regex.Pattern;
import static de.diddiz.util.Utils.newline;
public class DumpedLogImporter implements Runnable {
private final LogBlock logblock;

View File

@ -1,15 +1,15 @@
package de.diddiz.LogBlock;
import static de.diddiz.LogBlock.util.ActionColor.CREATE;
import static de.diddiz.LogBlock.util.ActionColor.DESTROY;
import static de.diddiz.LogBlock.util.ActionColor.INTERACT;
import static de.diddiz.LogBlock.util.MessagingUtil.createTextComponentWithColor;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyDate;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyEntityType;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyLocation;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyMaterial;
import static de.diddiz.util.ActionColor.CREATE;
import static de.diddiz.util.ActionColor.DESTROY;
import static de.diddiz.util.ActionColor.INTERACT;
import static de.diddiz.util.MessagingUtil.createTextComponentWithColor;
import static de.diddiz.util.MessagingUtil.prettyDate;
import static de.diddiz.util.MessagingUtil.prettyEntityType;
import static de.diddiz.util.MessagingUtil.prettyLocation;
import static de.diddiz.util.MessagingUtil.prettyMaterial;
import de.diddiz.LogBlock.util.Utils;
import de.diddiz.util.Utils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
@ -60,7 +60,7 @@ public class EntityChange implements LookupCacheElement {
}
public EntityChange(ResultSet rs, QueryParams p) throws SQLException {
id = p.needId ? rs.getLong("id") : 0;
id = p.needId ? rs.getInt("id") : 0;
date = p.needDate ? rs.getTimestamp("date").getTime() : 0;
loc = p.needCoords ? new Location(p.world, rs.getInt("x"), rs.getInt("y"), rs.getInt("z")) : null;
actor = p.needPlayer ? new Actor(rs) : null;

View File

@ -1,12 +1,11 @@
package de.diddiz.LogBlock;
import static de.diddiz.LogBlock.util.ActionColor.DESTROY;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyDate;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyLocation;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyMaterial;
import de.diddiz.LogBlock.util.BukkitUtils;
import de.diddiz.LogBlock.util.MessagingUtil;
import static de.diddiz.util.ActionColor.DESTROY;
import static de.diddiz.util.MessagingUtil.prettyDate;
import static de.diddiz.util.MessagingUtil.prettyLocation;
import static de.diddiz.util.MessagingUtil.prettyMaterial;
import de.diddiz.util.BukkitUtils;
import de.diddiz.util.MessagingUtil;
import java.sql.ResultSet;
import java.sql.SQLException;
import net.md_5.bungee.api.chat.BaseComponent;
@ -30,7 +29,7 @@ public class Kill implements LookupCacheElement {
}
public Kill(ResultSet rs, QueryParams p) throws SQLException {
id = p.needId ? rs.getLong("id") : 0;
id = p.needId ? rs.getInt("id") : 0;
date = p.needDate ? rs.getTimestamp("date").getTime() : 0;
loc = p.needCoords ? new Location(p.world, rs.getInt("x"), rs.getInt("y"), rs.getInt("z")) : null;
killerName = p.needKiller ? rs.getString("killer") : null;

View File

@ -1,13 +1,12 @@
package de.diddiz.LogBlock;
import de.diddiz.LogBlock.addons.worldguard.WorldGuardLoggingFlagsAddon;
import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.listeners.*;
import de.diddiz.LogBlock.questioner.Questioner;
import de.diddiz.LogBlock.util.BukkitUtils;
import de.diddiz.LogBlock.util.MySQLConnectionPool;
import de.diddiz.LogBlock.worldedit.WorldEditHelper;
import de.diddiz.LogBlock.worldedit.WorldEditLoggingHook;
import de.diddiz.util.BukkitUtils;
import de.diddiz.util.MySQLConnectionPool;
import de.diddiz.worldedit.WorldEditHelper;
import de.diddiz.worldedit.WorldEditLoggingHook;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
@ -39,8 +38,6 @@ public class LogBlock extends JavaPlugin {
private PlayerInfoLogging playerInfoLogging;
private ScaffoldingLogging scaffoldingLogging;
private Questioner questioner;
private WorldGuardLoggingFlagsAddon worldGuardLoggingFlagsAddon;
private boolean isConfigLoaded;
private volatile boolean isCompletelyEnabled;
public static LogBlock getInstance() {
@ -60,33 +57,20 @@ public class LogBlock extends JavaPlugin {
}
@Override
public void onLoad() {
public void onEnable() {
logblock = this;
BukkitUtils.isDoublePlant(Material.AIR); // Force static code to run
final PluginManager pm = getPluginManager();
consumer = new Consumer(this);
try {
Config.load(this);
isConfigLoaded = true;
} catch (final Exception ex) {
getLogger().log(Level.SEVERE, "Could not load LogBlock config! " + ex.getMessage(), ex);
}
if (Config.worldGuardLoggingFlags) {
if (getServer().getPluginManager().getPlugin("WorldGuard") == null) {
getLogger().log(Level.SEVERE, "Invalid config! addons.worldguardLoggingFlags is set to true, but WorldGuard is not loaded.");
} else {
worldGuardLoggingFlagsAddon = new WorldGuardLoggingFlagsAddon(this);
worldGuardLoggingFlagsAddon.onPluginLoad();
}
}
}
@Override
public void onEnable() {
final PluginManager pm = getPluginManager();
if (!isConfigLoaded) {
getLogger().log(Level.SEVERE, "Could not load LogBlock config! " + ex.getMessage());
pm.disablePlugin(this);
return;
}
consumer = new Consumer(this);
try {
getLogger().info("Connecting to " + user + "@" + url + "...");
try {
@ -101,19 +85,11 @@ public class LogBlock extends JavaPlugin {
return;
}
final Statement st = conn.createStatement();
try {
final ResultSet rs = st.executeQuery("SHOW CHARACTER SET where charset='utf8mb4';");
if (rs.next()) {
Config.mb4 = true;
// Allegedly JDBC driver since 2010 hasn't needed this. I did.
try {
st.executeUpdate("SET NAMES utf8mb4;");
} catch (Exception ex) {
getLogger().severe("could not set names to utf8mb4: " + ex.getMessage());
}
}
} catch (Exception ex) {
getLogger().severe("could not verify character set: " + ex.getMessage());
final ResultSet rs = st.executeQuery("SHOW CHARACTER SET where charset='utf8mb4';");
if (rs.next()) {
Config.mb4 = true;
// Allegedly JDBC driver since 2010 hasn't needed this. I did.
st.executeQuery("SET NAMES utf8mb4;");
}
conn.close();
Updater updater = new Updater(this);
@ -150,9 +126,6 @@ public class LogBlock extends JavaPlugin {
}
}
questioner = new Questioner(this);
if (worldGuardLoggingFlagsAddon != null) {
worldGuardLoggingFlagsAddon.onPluginEnable();
}
isCompletelyEnabled = true;
getServer().getScheduler().runTaskAsynchronously(this, new Updater.PlayerCountChecker(this));
}
@ -188,9 +161,6 @@ public class LogBlock extends JavaPlugin {
if (isLogging(Logging.SCAFFOLDING)) {
pm.registerEvents(scaffoldingLogging = new ScaffoldingLogging(this), this);
}
if (isLogging(Logging.CAULDRONINTERACT)) {
pm.registerEvents(new CauldronLogging(this), this);
}
if (isLogging(Logging.CREEPEREXPLOSION) || isLogging(Logging.TNTEXPLOSION) || isLogging(Logging.GHASTFIREBALLEXPLOSION) || isLogging(Logging.ENDERDRAGON) || isLogging(Logging.MISCEXPLOSION)) {
pm.registerEvents(new ExplosionLogging(this), this);
}
@ -219,13 +189,10 @@ public class LogBlock extends JavaPlugin {
if (isLogging(Logging.WITHER)) {
pm.registerEvents(new WitherLogging(this), this);
}
if (isLogging(Logging.NATURALSTRUCTUREGROW)) {
if (isLogging(Logging.NATURALSTRUCTUREGROW) || isLogging(Logging.BONEMEALSTRUCTUREGROW)) {
pm.registerEvents(new StructureGrowLogging(this), this);
}
if (isLogging(Logging.BONEMEALSTRUCTUREGROW)) {
pm.registerEvents(new BlockFertilizeLogging(this), this);
}
if (isLogging(Logging.GRASSGROWTH) || isLogging(Logging.MYCELIUMSPREAD) || isLogging(Logging.VINEGROWTH) || isLogging(Logging.MUSHROOMSPREAD) || isLogging(Logging.BAMBOOGROWTH) || isLogging(Logging.DRIPSTONEGROWTH) || isLogging(Logging.SCULKSPREAD)) {
if (isLogging(Logging.GRASSGROWTH) || isLogging(Logging.MYCELIUMSPREAD) || isLogging(Logging.VINEGROWTH) || isLogging(Logging.MUSHROOMSPREAD)) {
pm.registerEvents(new BlockSpreadLogging(this), this);
}
if (isLogging(Logging.DRAGONEGGTELEPORT)) {
@ -234,9 +201,6 @@ public class LogBlock extends JavaPlugin {
if (isLogging(Logging.LECTERNBOOKCHANGE)) {
pm.registerEvents(new LecternLogging(this), this);
}
if (isLogging(Logging.OXIDIZATION)) {
pm.registerEvents(new OxidizationLogging(this), this);
}
if (Config.isLoggingAnyEntities()) {
if (!WorldEditHelper.hasFullWorldEdit()) {
getLogger().severe("No compatible WorldEdit found, entity logging will not work!");

View File

@ -27,14 +27,12 @@ public enum Logging {
COMPARATORINTERACT,
PRESUREPLATEINTERACT,
TRIPWIREINTERACT,
CAULDRONINTERACT(true),
CREATURECROPTRAMPLE,
CROPTRAMPLE,
NATURALSTRUCTUREGROW,
GRASSGROWTH,
MYCELIUMSPREAD,
VINEGROWTH,
DRIPSTONEGROWTH,
MUSHROOMSPREAD,
BAMBOOGROWTH,
WITHER(true),
@ -48,10 +46,7 @@ public enum Logging {
DAYLIGHTDETECTORINTERACT,
LECTERNBOOKCHANGE(true),
SCAFFOLDING(true),
OXIDIZATION,
SCULKSPREAD(true),
SHULKER_BOX_CONTENT,
RESPAWNANCHOREXPLOSION(true),
PLAYER_COMMANDS,
COMMANDBLOCK_COMMANDS,
CONSOLE_COMMANDS;

View File

@ -1,11 +1,11 @@
package de.diddiz.LogBlock;
import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.util.BukkitUtils;
import de.diddiz.LogBlock.util.CuboidRegion;
import de.diddiz.LogBlock.util.SqlUtil;
import de.diddiz.LogBlock.util.Utils;
import de.diddiz.LogBlock.worldedit.WorldEditHelper;
import de.diddiz.util.BukkitUtils;
import de.diddiz.util.CuboidRegion;
import de.diddiz.util.SqlUtil;
import de.diddiz.util.Utils;
import de.diddiz.worldedit.WorldEditHelper;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
@ -20,8 +20,8 @@ import java.util.regex.Pattern;
import static de.diddiz.LogBlock.Session.getSession;
import static de.diddiz.LogBlock.config.Config.*;
import static de.diddiz.LogBlock.util.BukkitUtils.friendlyWorldname;
import static de.diddiz.LogBlock.util.Utils.*;
import static de.diddiz.util.BukkitUtils.friendlyWorldname;
import static de.diddiz.util.Utils.*;
public final class QueryParams implements Cloneable {
private static final HashMap<String, Integer> keywords = new HashMap<>();
@ -691,20 +691,16 @@ public final class QueryParams implements Cloneable {
if (values.length < 1) {
throw new IllegalArgumentException("No or wrong count of arguments for '" + param + "'");
}
for (String playerName : values) {
for (final String playerName : values) {
if (playerName.length() > 0) {
if (playerName.startsWith("!")) {
playerName = playerName.substring(1);
if (playerName.contains("!")) {
excludePlayersMode = true;
if (playerName.isEmpty()) {
continue;
}
}
if (playerName.contains("\"")) {
players.add(playerName.replace("\"", ""));
players.add(playerName.replaceAll("[^a-zA-Z0-9_]", ""));
} else {
final Player matches = logblock.getServer().getPlayerExact(playerName);
players.add(matches != null ? matches.getName() : playerName.replace("\\\"", ""));
players.add(matches != null ? matches.getName() : playerName.replaceAll("[^a-zA-Z0-9_]", ""));
}
}
}
@ -857,9 +853,6 @@ public final class QueryParams implements Cloneable {
if (values[0].startsWith("p")) {
sum = SummarizationMode.PLAYERS;
} else if (values[0].startsWith("b") || values[0].startsWith("e")) {
if (values[0].startsWith("e")) {
bct = BlockChangeType.ENTITIES;
}
sum = SummarizationMode.TYPES;
} else if (values[0].startsWith("n")) {
sum = SummarizationMode.NONE;

View File

@ -1,9 +1,8 @@
package de.diddiz.LogBlock;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyMaterial;
import static de.diddiz.util.MessagingUtil.prettyMaterial;
import de.diddiz.LogBlock.QueryParams.SummarizationMode;
import de.diddiz.LogBlock.util.MessagingUtil;
import de.diddiz.util.MessagingUtil;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;

View File

@ -1,9 +1,7 @@
package de.diddiz.LogBlock;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyMaterial;
import de.diddiz.LogBlock.QueryParams.SummarizationMode;
import de.diddiz.LogBlock.util.MessagingUtil;
import de.diddiz.util.MessagingUtil;
import org.bukkit.Location;
import java.sql.ResultSet;
@ -12,6 +10,8 @@ import java.util.Objects;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import static de.diddiz.util.MessagingUtil.prettyMaterial;
public class SummedEntityChanges implements LookupCacheElement {
private final int type;
private final int created, destroyed;

View File

@ -1,6 +1,6 @@
package de.diddiz.LogBlock;
import de.diddiz.LogBlock.util.MessagingUtil;
import de.diddiz.util.MessagingUtil;
import java.sql.ResultSet;
import java.sql.SQLException;
import net.md_5.bungee.api.chat.BaseComponent;

View File

@ -3,13 +3,12 @@ package de.diddiz.LogBlock;
import de.diddiz.LogBlock.blockstate.BlockStateCodecSign;
import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.LogBlock.util.ComparableVersion;
import de.diddiz.LogBlock.util.UUIDFetcher;
import de.diddiz.LogBlock.util.Utils;
import de.diddiz.util.UUIDFetcher;
import de.diddiz.util.Utils;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.sign.Side;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.ItemStack;
@ -26,7 +25,8 @@ import java.util.logging.Level;
import static de.diddiz.LogBlock.config.Config.getLoggedWorlds;
import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.LogBlock.util.BukkitUtils.friendlyWorldname;
import static de.diddiz.util.BukkitUtils.friendlyWorldname;
import de.diddiz.util.ComparableVersion;
class Updater {
private final LogBlock logblock;
@ -440,7 +440,7 @@ class Updater {
ResultSet entries = st.executeQuery("SELECT id, date, playerid, replaced, type, data, x, y, z FROM `" + wcfg.table + "` ORDER BY id ASC LIMIT " + BLOCKS_CONVERT_BATCH_SIZE);
while (entries.next()) {
hadRow = true;
long id = entries.getLong("id");
int id = entries.getInt("id");
Timestamp date = entries.getTimestamp("date");
int playerid = entries.getInt("playerid");
int replaced = entries.getInt("replaced");
@ -463,7 +463,7 @@ class Updater {
int newSetId = MaterialConverter.getOrAddMaterialId(setBlockData);
int newSetData = MaterialConverter.getOrAddBlockStateId(setBlockData);
insertStatement.setLong(1, id);
insertStatement.setInt(1, id);
insertStatement.setTimestamp(2, date);
insertStatement.setInt(3, playerid);
insertStatement.setInt(4, newReplacedId);
@ -477,7 +477,7 @@ class Updater {
} catch (Exception e) {
logblock.getLogger().info("Exception in entry " + id + " (" + replaced + ":" + data + "->" + type + ":" + data + "): " + e.getMessage());
}
deleteStatement.setLong(1, id);
deleteStatement.setInt(1, id);
deleteStatement.addBatch();
done++;
@ -523,7 +523,7 @@ class Updater {
boolean anyRow = false;
while (rs.next()) {
anyRow = true;
long id = rs.getLong("id");
int id = rs.getInt("id");
int itemtype = rs.getInt("itemtype");
int itemdata = rs.getInt("itemdata");
int amount = rs.getInt("itemamount");
@ -533,13 +533,13 @@ class Updater {
}
@SuppressWarnings("deprecation")
ItemStack stack = weaponMaterial.getMaxDurability() > 0 ? new ItemStack(weaponMaterial, Math.abs(amount), (short) itemdata) : new ItemStack(weaponMaterial, Math.abs(amount));
insertChestData.setLong(1, id);
insertChestData.setInt(1, id);
insertChestData.setBytes(2, Utils.saveItemStack(stack));
insertChestData.setInt(3, amount >= 0 ? 0 : 1);
insertChestData.setInt(4, MaterialConverter.getOrAddMaterialId(weaponMaterial));
insertChestData.addBatch();
deleteChest.setLong(1, id);
deleteChest.setInt(1, id);
deleteChest.addBatch();
done++;
}
@ -586,7 +586,7 @@ class Updater {
boolean anyRow = false;
while (rs.next()) {
anyRow = true;
long id = rs.getLong("id");
int id = rs.getInt("id");
int weapon = rs.getInt("weapon");
Material weaponMaterial = materialUpdater.getMaterial(weapon, 0);
if (weaponMaterial == null) {
@ -596,7 +596,7 @@ class Updater {
if (newWeapon != weapon) {
anyUpdate = true;
updateWeaponStatement.setInt(1, newWeapon);
updateWeaponStatement.setLong(2, id);
updateWeaponStatement.setInt(2, id);
updateWeaponStatement.addBatch();
}
done++;
@ -638,8 +638,8 @@ class Updater {
if (configVersion.compareTo(new ComparableVersion("1.13.1")) < 0) {
logblock.getLogger().info("Updating tables to 1.13.1 ...");
BlockStateCodecSign signCodec = new BlockStateCodecSign();
try (Connection conn = logblock.getConnection()) {
try {
final Connection conn = logblock.getConnection();
conn.setAutoCommit(false);
final Statement st = conn.createStatement();
for (final WorldConfig wcfg : getLoggedWorlds()) {
@ -668,7 +668,7 @@ class Updater {
boolean anyRow = false;
while (rs.next()) {
anyRow = true;
long id = rs.getLong("id");
int id = rs.getInt("id");
String signText = rs.getString("signtext");
int replaced = rs.getInt("replaced");
boolean nullBlock = rs.wasNull();
@ -676,20 +676,20 @@ class Updater {
if (!nullBlock && signText != null) {
String[] lines = signText.split("\0", 4);
byte[] bytes = Utils.serializeYamlConfiguration(signCodec.serialize(null, Side.FRONT, lines));
byte[] bytes = Utils.serializeYamlConfiguration(BlockStateCodecSign.serialize(lines));
Material replacedMaterial = MaterialConverter.getBlockData(replaced, -1).getMaterial();
Material typeMaterial = MaterialConverter.getBlockData(type, -1).getMaterial();
boolean wasSign = replacedMaterial == Material.OAK_SIGN || replacedMaterial == Material.OAK_WALL_SIGN;
boolean isSign = typeMaterial == Material.OAK_SIGN || typeMaterial == Material.OAK_WALL_SIGN;
insertSignState.setLong(1, id);
insertSignState.setInt(1, id);
insertSignState.setBytes(2, wasSign ? bytes : null);
insertSignState.setBytes(3, isSign ? bytes : null);
insertSignState.addBatch();
}
deleteSign.setLong(1, id);
deleteSign.setInt(1, id);
deleteSign.addBatch();
done++;
}
@ -720,6 +720,7 @@ class Updater {
}
st.close();
conn.close();
} catch (final SQLException ex) {
logblock.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
return false;
@ -729,7 +730,6 @@ class Updater {
}
if (configVersion.compareTo(new ComparableVersion("1.16.0")) < 0) {
logblock.getLogger().info("Updating tables to 1.16.0 ...");
try (Connection conn = logblock.getConnection()) {
conn.setAutoCommit(true);
final Statement st = conn.createStatement();
@ -742,29 +742,14 @@ class Updater {
}
config.set("version", "1.16.0");
}
if (configVersion.compareTo(new ComparableVersion("1.17.0")) < 0) {
logblock.getLogger().info("Updating tables to 1.17.0 ...");
logblock.getLogger().warning("The updating process might take several minutes if you have a huge log table! Please do not shutdown your server until it is completed.");
try (Connection conn = logblock.getConnection()) {
conn.setAutoCommit(true);
final Statement st = conn.createStatement();
for (final WorldConfig wcfg : getLoggedWorlds()) {
st.executeUpdate("ALTER TABLE `" + wcfg.table + "-blocks` CHANGE `y` `y` SMALLINT(5) NOT NULL");
}
st.close();
} catch (final SQLException ex) {
logblock.getLogger().log(Level.SEVERE, "[Updater] Warning: Could not alter table", ex);
}
logblock.getLogger().info("Update to 1.17.0 completed.");
config.set("version", "1.17.0");
}
if (configVersion.compareTo(new ComparableVersion(Config.CURRENT_CONFIG_VERSION)) < 0) {
config.set("version", Config.CURRENT_CONFIG_VERSION);
}
// this can always be checked
try (Connection conn = logblock.getConnection()) {
try {
final Connection conn = logblock.getConnection();
conn.setAutoCommit(true);
final Statement st = conn.createStatement();
checkCharset("lb-players", "name", st, true);
@ -775,51 +760,6 @@ class Updater {
createIndexIfDoesNotExist("lb-blockstates", "name", "UNIQUE KEY `name` (`name`(150))", st, true);
st.close();
} catch (final SQLException ex) {
logblock.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
return false;
}
try (Connection conn = logblock.getConnection()) {
conn.setAutoCommit(true);
final Statement st = conn.createStatement();
PreparedStatement stSelectColumnType = conn.prepareStatement("SELECT `TABLE_NAME`, `COLUMN_TYPE` FROM information_schema.`COLUMNS` WHERE `TABLE_SCHEMA` = ? AND `COLUMN_NAME` = ?");
stSelectColumnType.setString(1, Config.mysqlDatabase);
stSelectColumnType.setString(2, "y");
HashMap<String, String> tablesAndYColumnType = new HashMap<>();
try (ResultSet rs = stSelectColumnType.executeQuery()) {
while (rs.next()) {
String table = rs.getString("TABLE_NAME").toLowerCase();
String type = rs.getString("COLUMN_TYPE").toLowerCase();
tablesAndYColumnType.put(table, type);
}
}
for (final WorldConfig wcfg : getLoggedWorlds()) {
String type = tablesAndYColumnType.get((wcfg.table + "-blocks").toLowerCase());
if (type != null) {
if (type.contains("tinyint") || type.contains("unsigned")) {
logblock.getLogger().info("Fixing y column type for table " + wcfg.table + "-blocks ...");
logblock.getLogger().warning("The updating process might take several minutes if you have a huge log table! Please do not shutdown your server until it is completed.");
st.executeUpdate("ALTER TABLE `" + wcfg.table + "-blocks` CHANGE `y` `y` SMALLINT(5) NOT NULL");
}
}
type = tablesAndYColumnType.get((wcfg.table + "-entities").toLowerCase());
if (type != null) {
if (type.contains("tinyint") || type.contains("unsigned")) {
logblock.getLogger().info("Fixing y column type for table " + wcfg.table + "-entities ...");
logblock.getLogger().warning("The updating process might take several minutes if you have a huge log table! Please do not shutdown your server until it is completed.");
st.executeUpdate("ALTER TABLE `" + wcfg.table + "-entities` CHANGE `y` `y` SMALLINT(5) NOT NULL");
}
}
type = tablesAndYColumnType.get((wcfg.table + "-kills").toLowerCase());
if (type != null) {
if (type.contains("tinyint") || type.contains("unsigned")) {
logblock.getLogger().info("Fixing y column type for table " + wcfg.table + "-kills ...");
logblock.getLogger().warning("The updating process might take several minutes if you have a huge log table! Please do not shutdown your server until it is completed.");
st.executeUpdate("ALTER TABLE `" + wcfg.table + "-kills` CHANGE `y` `y` SMALLINT(5) NOT NULL");
}
}
}
st.close();
conn.close();
} catch (final SQLException ex) {
logblock.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
@ -869,150 +809,49 @@ class Updater {
}
final Statement state = conn.createStatement();
conn.setAutoCommit(true);
createTable(state, "lb-players",
"playerid INT UNSIGNED NOT NULL AUTO_INCREMENT, \n" +
"UUID varchar(36) NOT NULL, \n" +
"playername varchar(32) NOT NULL, \n" +
"firstlogin DATETIME NOT NULL, \n" +
"lastlogin DATETIME NOT NULL, \n" +
"onlinetime INT UNSIGNED NOT NULL, \n" +
"ip varchar(255) NOT NULL, \n" +
"PRIMARY KEY (playerid)\n",
//"INDEX (UUID), " +
//"INDEX (playername)",
"DEFAULT CHARSET " + charset
);
createTable(state, "lb-players", "(playerid INT UNSIGNED NOT NULL AUTO_INCREMENT, UUID varchar(36) NOT NULL, playername varchar(32) NOT NULL, firstlogin DATETIME NOT NULL, lastlogin DATETIME NOT NULL, onlinetime INT UNSIGNED NOT NULL, ip varchar(255) NOT NULL, PRIMARY KEY (playerid), INDEX (UUID), INDEX (playername)) DEFAULT CHARSET " + charset);
// Players table must not be empty or inserts won't work - bug #492
final ResultSet rs = state.executeQuery("SELECT NULL FROM \"lb-players\" LIMIT 1;");
final ResultSet rs = state.executeQuery("SELECT NULL FROM `lb-players` LIMIT 1;");
if (!rs.next()) {
state.execute("INSERT INTO \"lb-players\" (UUID, playername) VALUES ('log_dummy_record','dummy_record') ON CONFLICT DO NOTHING");
state.execute("INSERT IGNORE INTO `lb-players` (UUID,playername) VALUES ('log_dummy_record','dummy_record')");
}
if (isLogging(Logging.CHAT) || isLogging(Logging.PLAYER_COMMANDS) || isLogging(Logging.CONSOLE_COMMANDS) || isLogging(Logging.COMMANDBLOCK_COMMANDS)) {
try {
createTable(state, "lb-chat",
"id INT UNSIGNED NOT NULL AUTO_INCREMENT, " +
"date DATETIME NOT NULL, " +
"playerid INT UNSIGNED NOT NULL, " +
"message VARCHAR(256) NOT NULL, " +
"PRIMARY KEY (id), ",
// "KEY playerid (playerid), " +
// "FULLTEXT message (message)",
"DEFAULT CHARSET " + charset);
createTable(state, "lb-chat", "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, playerid INT UNSIGNED NOT NULL, message VARCHAR(256) NOT NULL, PRIMARY KEY (id), KEY playerid (playerid), FULLTEXT message (message)) DEFAULT CHARSET " + charset);
} catch (SQLException e) {
createTable(state, "lb-chat",
"id INT UNSIGNED NOT NULL AUTO_INCREMENT," +
"date DATETIME NOT NULL," +
"playerid INT UNSIGNED NOT NULL," +
"message VARCHAR(256) NOT NULL," +
"PRIMARY KEY (id)," +
"KEY playerid (playerid)",
"DEFAULT CHARSET " + charset);
createTable(state, "lb-chat", "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, playerid INT UNSIGNED NOT NULL, message VARCHAR(256) NOT NULL, PRIMARY KEY (id), KEY playerid (playerid)) DEFAULT CHARSET " + charset);
}
}
createTable(state, "lb-materials",
"id INT UNSIGNED NOT NULL, " +
"name VARCHAR(255) NOT NULL, " +
"PRIMARY KEY (id)",
"DEFAULT CHARSET " + charset);
createTable(state, "lb-blockstates",
"id INT UNSIGNED NOT NULL, " +
"name VARCHAR(255) NOT NULL, " +
"PRIMARY KEY (id)",
"DEFAULT CHARSET " + charset);
createTable(state, "lb-entitytypes",
"id INT UNSIGNED NOT NULL, " +
"name VARCHAR(255) NOT NULL, " +
"PRIMARY KEY (id)",
"DEFAULT CHARSET " + charset);
createTable(state, "lb-materials", "(id INT UNSIGNED NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY (id)) DEFAULT CHARSET " + charset);
createTable(state, "lb-blockstates", "(id INT UNSIGNED NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY (id)) DEFAULT CHARSET " + charset);
createTable(state, "lb-entitytypes", "(id INT UNSIGNED NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY (id)) DEFAULT CHARSET " + charset);
for (final WorldConfig wcfg : getLoggedWorlds()) {
createTable(state, wcfg.table + "-blocks",
"id INT UNSIGNED NOT NULL AUTO_INCREMENT, " +
"date DATETIME NOT NULL, " +
"playerid INT UNSIGNED NOT NULL, " +
"replaced SMALLINT UNSIGNED NOT NULL, " +
"replacedData SMALLINT NOT NULL, " +
"type SMALLINT UNSIGNED NOT NULL, " +
"typeData SMALLINT NOT NULL, " +
"x MEDIUMINT NOT NULL, " +
"y SMALLINT NOT NULL, " +
"z MEDIUMINT NOT NULL, " +
"PRIMARY KEY (id), " +
"KEY coords (x, z, y), " +
"KEY date (date), " +
"KEY playerid (playerid)",
"");
createTable(state, wcfg.table + "-chestdata",
"id INT UNSIGNED NOT NULL, " +
"item MEDIUMBLOB, " +
"itemremove TINYINT, " +
"itemtype SMALLINT NOT NULL DEFAULT '0', " +
"PRIMARY KEY (id)",
"");
createTable(state, wcfg.table + "-state",
"id INT UNSIGNED NOT NULL, " +
"replacedState MEDIUMBLOB NULL, " +
"typeState MEDIUMBLOB NULL, " +
"PRIMARY KEY (id)",
"");
createTable(state, wcfg.table + "-blocks", "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, playerid INT UNSIGNED NOT NULL, replaced SMALLINT UNSIGNED NOT NULL, replacedData SMALLINT NOT NULL, type SMALLINT UNSIGNED NOT NULL, typeData SMALLINT NOT NULL, x MEDIUMINT NOT NULL, y SMALLINT UNSIGNED NOT NULL, z MEDIUMINT NOT NULL, PRIMARY KEY (id), KEY coords (x, z, y), KEY date (date), KEY playerid (playerid))");
createTable(state, wcfg.table + "-chestdata", "(id INT UNSIGNED NOT NULL, item MEDIUMBLOB, itemremove TINYINT, itemtype SMALLINT NOT NULL DEFAULT '0', PRIMARY KEY (id))");
createTable(state, wcfg.table + "-state", "(id INT UNSIGNED NOT NULL, replacedState MEDIUMBLOB NULL, typeState MEDIUMBLOB NULL, PRIMARY KEY (id))");
if (wcfg.isLogging(Logging.KILL)) {
createTable(state, wcfg.table + "-kills",
"id INT UNSIGNED NOT NULL AUTO_INCREMENT, " +
"date DATETIME NOT NULL, " +
"killer INT UNSIGNED, " +
"victim INT UNSIGNED NOT NULL, " +
"weapon SMALLINT UNSIGNED NOT NULL, " +
"x MEDIUMINT NOT NULL, " +
"y SMALLINT NOT NULL, " +
"z MEDIUMINT NOT NULL, " +
"PRIMARY KEY (id)",
"");
createTable(state, wcfg.table + "-kills", "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, killer INT UNSIGNED, victim INT UNSIGNED NOT NULL, weapon SMALLINT UNSIGNED NOT NULL, x MEDIUMINT NOT NULL, y SMALLINT NOT NULL, z MEDIUMINT NOT NULL, PRIMARY KEY (id))");
}
createTable(state, wcfg.table + "-entityids",
"entityid INT UNSIGNED NOT NULL AUTO_INCREMENT, " +
"entityuuid VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, " +
"PRIMARY KEY (entityid), " +
"UNIQUE KEY (entityuuid)",
"");
createTable(state, wcfg.table + "-entities",
"id INT UNSIGNED NOT NULL AUTO_INCREMENT, " +
"date DATETIME NOT NULL, " +
"playerid INT UNSIGNED NOT NULL, " +
"entityid INT UNSIGNED NOT NULL, " +
"entitytypeid INT UNSIGNED NOT NULL, " +
"x MEDIUMINT NOT NULL, " +
"y SMALLINT NOT NULL, " +
"z MEDIUMINT NOT NULL, " +
"action TINYINT UNSIGNED NOT NULL, " +
"data MEDIUMBLOB NULL, " +
"PRIMARY KEY (id), " +
"KEY coords (x, z, y), " +
"KEY date (date), " +
"KEY playerid (playerid), " +
"KEY entityid (entityid)",
"");
createTable(state, wcfg.table + "-entityids", "(entityid INT UNSIGNED NOT NULL AUTO_INCREMENT, entityuuid VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, PRIMARY KEY (entityid), UNIQUE KEY (entityuuid))");
createTable(state, wcfg.table + "-entities", "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, playerid INT UNSIGNED NOT NULL, entityid INT UNSIGNED NOT NULL, entitytypeid INT UNSIGNED NOT NULL, x MEDIUMINT NOT NULL, y SMALLINT NOT NULL, z MEDIUMINT NOT NULL, action TINYINT UNSIGNED NOT NULL, data MEDIUMBLOB NULL, PRIMARY KEY (id), KEY coords (x, z, y), KEY date (date), KEY playerid (playerid), KEY entityid (entityid))");
}
state.close();
conn.close();
}
private void createTable(Statement state, String table, String columns, String additional) throws SQLException {
logblock.getLogger().log(Level.INFO, "Creating table " + table + ".");
String sql = "CREATE TABLE IF NOT EXISTS \"" + table + "\" (" +
(
columns
.replace("INT UNSIGNED NOT NULL AUTO_INCREMENT", "SERIAL NOT NULL")
.replace("INT UNSIGNED", "INT")
.replace("DATETIME", "TIMESTAMP")
)
+ ") " /* + additional */ ;
logblock.getLogger().info("sql=" + sql);
state.execute(sql);
//try (ResultSet tableResultNew = state.executeQuery("SHOW TABLES LIKE '" + table + "'")) {
// if (!tableResultNew.next()) {
// throw new SQLException("Table " + table + " not found and failed to create");
// }
//}
private void createTable(Statement state, String table, String query) throws SQLException {
try (ResultSet tableResult = state.executeQuery("SHOW TABLES LIKE '" + table + "'")) {
if (!tableResult.next()) {
logblock.getLogger().log(Level.INFO, "Creating table " + table + ".");
state.execute("CREATE TABLE `" + table + "` " + query);
try (ResultSet tableResultNew = state.executeQuery("SHOW TABLES LIKE '" + table + "'")) {
if (!tableResultNew.next()) {
throw new SQLException("Table " + table + " not found and failed to create");
}
}
}
}
}
/**
@ -1046,16 +885,6 @@ class Updater {
renameMaterial("minecraft:cactus_green", Material.GREEN_DYE);
}
if (comparablePreviousMinecraftVersion.compareTo("1.17") < 0 && comparableCurrentMinecraftVersion.compareTo("1.17") >= 0) {
logblock.getLogger().info("[Updater] Upgrading Materials to 1.17");
renameMaterial("minecraft:grass_path", Material.DIRT_PATH);
}
if (comparablePreviousMinecraftVersion.compareTo("1.20.4") < 0 && comparableCurrentMinecraftVersion.compareTo("1.20.4") >= 0) {
logblock.getLogger().info("[Updater] Upgrading Materials to 1.20.4");
renameMaterial("minecraft:grass", Material.SHORT_GRASS);
}
config.set("previousMinecraftVersion", currentMinecraftVersion);
logblock.saveConfig();
}

View File

@ -28,9 +28,10 @@ import org.bukkit.inventory.ItemStack;
import de.diddiz.LogBlock.QueryParams.Order;
import de.diddiz.LogBlock.blockstate.BlockStateCodecs;
import de.diddiz.LogBlock.util.BukkitUtils;
import de.diddiz.LogBlock.util.Utils;
import de.diddiz.LogBlock.worldedit.WorldEditHelper;
import de.diddiz.util.BukkitUtils;
import de.diddiz.util.Utils;
import de.diddiz.worldedit.WorldEditHelper;
import java.io.File;
import java.io.PrintWriter;
import java.sql.ResultSet;
@ -48,7 +49,7 @@ import net.md_5.bungee.api.chat.TextComponent;
import static de.diddiz.LogBlock.config.Config.dontRollback;
import static de.diddiz.LogBlock.config.Config.replaceAnyway;
import static de.diddiz.LogBlock.util.BukkitUtils.*;
import static de.diddiz.util.BukkitUtils.*;
public class WorldEditor implements Runnable {
private final LogBlock logblock;
@ -182,15 +183,11 @@ public class WorldEditor implements Runnable {
logblock.getServer().getScheduler().cancelTask(taskID);
if (errorList.size() > 0) {
try {
final File errorDir = new File(logblock.getDataFolder(), "error");
errorDir.mkdirs();
final File file = new File(errorDir, "WorldEditor-" + new SimpleDateFormat("yy-MM-dd-HH-mm-ss").format(System.currentTimeMillis()) + ".log");
final File file = new File("plugins/LogBlock/error/WorldEditor-" + new SimpleDateFormat("yy-MM-dd-HH-mm-ss").format(System.currentTimeMillis()) + ".log");
file.getParentFile().mkdirs();
final PrintWriter writer = new PrintWriter(file);
for (final WorldEditorException err : errorList) {
for (final LookupCacheElement err : errorList) {
writer.println(BaseComponent.toPlainText(err.getLogMessage()));
err.printStackTrace(writer);
writer.println();
writer.println();
}
writer.close();
} catch (final Exception ex) {

View File

@ -6,7 +6,7 @@ import java.sql.SQLException;
import org.bukkit.inventory.ItemStack;
import de.diddiz.LogBlock.QueryParams.BlockChangeType;
import de.diddiz.LogBlock.util.Utils;
import de.diddiz.util.Utils;
public class WorldEditorEditFactory {
private final WorldEditor editor;

View File

@ -1,80 +0,0 @@
package de.diddiz.LogBlock.addons.worldguard;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.registry.FlagConflictException;
import com.sk89q.worldguard.protection.flags.registry.FlagRegistry;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.events.BlockChangePreLogEvent;
import de.diddiz.LogBlock.events.EntityChangePreLogEvent;
import java.util.logging.Level;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
public class WorldGuardLoggingFlagsAddon {
private final StateFlag LOGBLOCK_LOG_BLOCKS = new StateFlag("logblock-log-blocks", true);
private final StateFlag LOGBLOCK_LOG_ENTITIES = new StateFlag("logblock-log-entities", true);
private LogBlock plugin;
private WorldGuardPlugin worldGuard;
public WorldGuardLoggingFlagsAddon(LogBlock plugin) {
this.plugin = plugin;
}
public void onPluginLoad() {
registerFlags();
}
public void onPluginEnable() {
worldGuard = (WorldGuardPlugin) plugin.getServer().getPluginManager().getPlugin("WorldGuard");
plugin.getServer().getPluginManager().registerEvents(new LoggingListener(), plugin);
}
private void registerFlags() {
try {
FlagRegistry registry = WorldGuard.getInstance().getFlagRegistry();
registry.register(LOGBLOCK_LOG_BLOCKS);
registry.register(LOGBLOCK_LOG_ENTITIES);
} catch (FlagConflictException e) {
plugin.getLogger().log(Level.SEVERE, "Could not initialize Flags", e);
}
}
private class LoggingListener implements Listener {
@EventHandler(ignoreCancelled = true)
public void onBlockChangePreLog(BlockChangePreLogEvent event) {
RegionAssociable regionAssociable = null;
Location location = event.getLocation();
Entity actorEntity = event.getOwnerActor().getEntity();
if (actorEntity instanceof Player) {
regionAssociable = worldGuard.wrapPlayer((Player) actorEntity);
}
ApplicableRegionSet set = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(location));
if (!set.testState(regionAssociable, LOGBLOCK_LOG_BLOCKS)) {
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onEntityChangePreLog(EntityChangePreLogEvent event) {
RegionAssociable regionAssociable = null;
Location location = event.getLocation();
Entity actorEntity = event.getOwnerActor().getEntity();
if (actorEntity instanceof Player) {
regionAssociable = worldGuard.wrapPlayer((Player) actorEntity);
}
ApplicableRegionSet set = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(location));
if (!set.testState(regionAssociable, LOGBLOCK_LOG_ENTITIES)) {
event.setCancelled(true);
}
}
}
}

View File

@ -1,6 +1,5 @@
package de.diddiz.LogBlock.blockstate;
import net.md_5.bungee.api.chat.BaseComponent;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.configuration.file.YamlConfiguration;
@ -12,5 +11,5 @@ public interface BlockStateCodec {
void deserialize(BlockState state, YamlConfiguration conf);
BaseComponent getChangesAsComponent(YamlConfiguration conf, YamlConfiguration oldState);
String toString(YamlConfiguration conf);
}

View File

@ -1,7 +1,7 @@
package de.diddiz.LogBlock.blockstate;
import java.util.List;
import net.md_5.bungee.api.chat.BaseComponent;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.block.Banner;
@ -64,7 +64,7 @@ public class BlockStateCodecBanner implements BlockStateCodec {
}
@Override
public BaseComponent getChangesAsComponent(YamlConfiguration conf, YamlConfiguration oldState) {
public String toString(YamlConfiguration conf) {
return null;
}
}

View File

@ -1,7 +1,5 @@
package de.diddiz.LogBlock.blockstate;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.block.Lectern;
@ -45,10 +43,12 @@ public class BlockStateCodecLectern implements BlockStateCodec {
}
@Override
public BaseComponent getChangesAsComponent(YamlConfiguration conf, YamlConfiguration oldState) {
public String toString(YamlConfiguration conf) {
if (conf != null) {
return new TextComponent("[book]");
StringBuilder sb = new StringBuilder();
sb.append("[").append("book").append("]");
return sb.toString();
}
return new TextComponent("empty");
return null;
}
}

View File

@ -4,9 +4,7 @@ import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.LogBlock.util.BukkitUtils;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import de.diddiz.util.BukkitUtils;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.block.ShulkerBox;
@ -16,7 +14,7 @@ import org.bukkit.inventory.ItemStack;
public class BlockStateCodecShulkerBox implements BlockStateCodec {
@Override
public Material[] getApplicableMaterials() {
return BukkitUtils.getShulkerBoxBlocks().toArray(Material[]::new);
return BukkitUtils.getShulkerBoxBlocks().toArray(new Material[BukkitUtils.getShulkerBoxBlocks().size()]);
}
@Override
@ -62,7 +60,7 @@ public class BlockStateCodecShulkerBox implements BlockStateCodec {
}
@Override
public BaseComponent getChangesAsComponent(YamlConfiguration conf, YamlConfiguration oldState) {
public String toString(YamlConfiguration conf) {
if (conf != null) {
StringBuilder sb = new StringBuilder();
sb.append("[");
@ -80,7 +78,7 @@ public class BlockStateCodecShulkerBox implements BlockStateCodec {
}
}
sb.append("]");
return anySlot ? new TextComponent(sb.toString()) : null;
return anySlot ? sb.toString() : null;
}
return null;
}

View File

@ -1,88 +1,57 @@
package de.diddiz.LogBlock.blockstate;
import de.diddiz.LogBlock.util.BukkitUtils;
import java.awt.Color;
import de.diddiz.util.BukkitUtils;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.block.Sign;
import org.bukkit.block.sign.Side;
import org.bukkit.block.sign.SignSide;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
public class BlockStateCodecSign implements BlockStateCodec {
@Override
public Material[] getApplicableMaterials() {
return BukkitUtils.getAllSignMaterials().toArray(Material[]::new);
return BukkitUtils.getAllSignsArray();
}
@Override
public YamlConfiguration serialize(BlockState state) {
YamlConfiguration conf = null;
if (state instanceof Sign sign) {
boolean waxed = sign.isWaxed();
if (waxed) {
conf = new YamlConfiguration();
conf.set("waxed", waxed);
if (state instanceof Sign) {
Sign sign = (Sign) state;
String[] lines = sign.getLines();
boolean hasText = false;
for (int i = 0; i < lines.length; i++) {
if (lines[i] != null && lines[i].length() > 0) {
hasText = true;
break;
}
}
for (Side side : Side.values()) {
SignSide signSide = sign.getSide(side);
String[] lines = signSide.getLines();
boolean hasText = false;
for (int i = 0; i < lines.length; i++) {
if (lines[i] != null && lines[i].length() > 0) {
hasText = true;
break;
}
DyeColor signColor = sign.getColor();
if (signColor == null) {
signColor = DyeColor.BLACK;
}
if (hasText || signColor != DyeColor.BLACK) {
YamlConfiguration conf = new YamlConfiguration();
if (hasText) {
conf.set("lines", Arrays.asList(lines));
}
DyeColor signColor = signSide.getColor();
if (signColor == null) {
signColor = DyeColor.BLACK;
}
boolean glowing = signSide.isGlowingText();
if (hasText || signColor != DyeColor.BLACK || glowing) {
if (conf == null) {
conf = new YamlConfiguration();
}
ConfigurationSection sideSection = side == Side.FRONT ? conf : conf.createSection(side.name().toLowerCase());
if (hasText) {
sideSection.set("lines", Arrays.asList(lines));
}
if (signColor != DyeColor.BLACK) {
sideSection.set("color", signColor.name());
}
if (glowing) {
sideSection.set("glowing", true);
}
if (signColor != DyeColor.BLACK) {
conf.set("color", signColor.name());
}
return conf;
}
}
return conf;
return null;
}
/**
* This is required for the SignChangeEvent, because we have no updated BlockState there.
* @param state
* This is required for the SignChangeEvent, because we have no BlockState there.
*/
public YamlConfiguration serialize(BlockState state, Side side, String[] lines) {
YamlConfiguration conf = state == null ? null : serialize(state);
if (lines != null) {
if (conf == null) {
conf = new YamlConfiguration();
}
ConfigurationSection sideSection = side == Side.FRONT ? conf : conf.getConfigurationSection(side.name().toLowerCase());
if (sideSection == null) {
sideSection = conf.createSection(side.name().toLowerCase());
}
sideSection.set("lines", Arrays.asList(lines));
}
public static YamlConfiguration serialize(String[] lines) {
YamlConfiguration conf = new YamlConfiguration();
conf.set("lines", Arrays.asList(lines));
return conf;
}
@ -90,138 +59,40 @@ public class BlockStateCodecSign implements BlockStateCodec {
public void deserialize(BlockState state, YamlConfiguration conf) {
if (state instanceof Sign) {
Sign sign = (Sign) state;
DyeColor signColor = DyeColor.BLACK;
List<String> lines = Collections.emptyList();
if (conf != null) {
sign.setWaxed(conf.getBoolean("waxed"));
for (Side side : Side.values()) {
ConfigurationSection sideSection = side == Side.FRONT ? conf : conf.getConfigurationSection(side.name().toLowerCase());
DyeColor signColor = DyeColor.BLACK;
boolean glowing = false;
List<String> lines = Collections.emptyList();
if (sideSection != null) {
if (sideSection.contains("lines")) {
lines = sideSection.getStringList("lines");
}
if (sideSection.contains("color")) {
try {
signColor = DyeColor.valueOf(sideSection.getString("color"));
} catch (IllegalArgumentException | NullPointerException e) {
// ignored
}
}
glowing = sideSection.getBoolean("glowing", false);
}
SignSide signSide = sign.getSide(side);
for (int i = 0; i < 4; i++) {
String line = lines.size() > i && lines.get(i) != null ? lines.get(i) : "";
signSide.setLine(i, line);
}
signSide.setColor(signColor);
signSide.setGlowingText(glowing);
if (conf.contains("lines")) {
lines = conf.getStringList("lines");
}
} else {
sign.setWaxed(false);
for (Side side : Side.values()) {
SignSide signSide = sign.getSide(side);
for (int i = 0; i < 4; i++) {
signSide.setLine(i, "");
}
signSide.setColor(DyeColor.BLACK);
signSide.setGlowingText(false);
}
}
}
}
@Override
public BaseComponent getChangesAsComponent(YamlConfiguration state, YamlConfiguration oldState) {
if (state != null) {
TextComponent tc = new TextComponent();
// StringBuilder sb = new StringBuilder();
boolean isWaxed = state.getBoolean("waxed");
boolean oldWaxed = oldState != null && oldState.getBoolean("waxed");
if (isWaxed != oldWaxed) {
tc.addExtra(isWaxed ? "(waxed)" : "(not waxed)");
}
for (Side side : Side.values()) {
boolean sideHeaderAdded = false;
ConfigurationSection sideSection = side == Side.FRONT ? state : state.getConfigurationSection(side.name().toLowerCase());
List<String> lines = sideSection == null ? Collections.emptyList() : sideSection.getStringList("lines");
List<String> oldLines = Collections.emptyList();
DyeColor signColor = DyeColor.BLACK;
if (sideSection != null && sideSection.contains("color")) {
if (conf.contains("color")) {
try {
signColor = DyeColor.valueOf(sideSection.getString("color"));
signColor = DyeColor.valueOf(conf.getString("color"));
} catch (IllegalArgumentException | NullPointerException e) {
// ignored
}
}
DyeColor oldSignColor = DyeColor.BLACK;
boolean glowing = sideSection != null && sideSection.getBoolean("glowing", false);
boolean oldGlowing = false;
if (oldState != null) {
ConfigurationSection oldSideSection = side == Side.FRONT ? oldState : oldState.getConfigurationSection(side.name().toLowerCase());
if (oldSideSection != null) {
oldLines = oldSideSection.getStringList("lines");
if (oldSideSection.contains("color")) {
try {
oldSignColor = DyeColor.valueOf(oldSideSection.getString("color"));
} catch (IllegalArgumentException | NullPointerException e) {
// ignored
}
}
oldGlowing = oldSideSection.getBoolean("glowing", false);
}
}
if (!lines.equals(oldLines)) {
sideHeaderAdded = addSideHeaderText(tc, side, sideHeaderAdded);
for (String line : lines) {
if (tc.getExtra() != null && !tc.getExtra().isEmpty()) {
tc.addExtra(" ");
}
tc.addExtra("[");
if (line != null && !line.isEmpty()) {
tc.addExtra(new TextComponent(TextComponent.fromLegacyText(line)));
}
tc.addExtra("]");
}
}
if (signColor != oldSignColor) {
sideHeaderAdded = addSideHeaderText(tc, side, sideHeaderAdded);
if (tc.getExtra() != null && !tc.getExtra().isEmpty()) {
tc.addExtra(" ");
}
tc.addExtra("(color: ");
TextComponent colorText = new TextComponent(signColor.name().toLowerCase());
colorText.setColor(ChatColor.of(new Color(signColor.getColor().asARGB())));
tc.addExtra(colorText);
tc.addExtra(")");
}
if (glowing != oldGlowing) {
sideHeaderAdded = addSideHeaderText(tc, side, sideHeaderAdded);
if (tc.getExtra() != null && !tc.getExtra().isEmpty()) {
tc.addExtra(" ");
}
if (glowing) {
tc.addExtra("(glowing)");
} else {
tc.addExtra("(not glowing)");
}
}
}
return tc;
for (int i = 0; i < 4; i++) {
String line = lines.size() > i && lines.get(i) != null ? lines.get(i) : "";
sign.setLine(i, line);
}
sign.setColor(signColor);
}
}
@Override
public String toString(YamlConfiguration conf) {
if (conf != null) {
StringBuilder sb = new StringBuilder();
for (String line : conf.getStringList("lines")) {
if (sb.length() > 0) {
sb.append(" ");
}
sb.append("[").append(line).append("]");
}
return sb.toString();
}
return null;
}
private static boolean addSideHeaderText(TextComponent tc, Side side, boolean wasAdded) {
if (!wasAdded) {
if (tc.getExtra() != null && !tc.getExtra().isEmpty()) {
tc.addExtra(" ");
}
tc.addExtra(side.name() + ":");
}
return true;
}
}

View File

@ -1,30 +1,15 @@
package de.diddiz.LogBlock.blockstate;
import java.util.UUID;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.chat.hover.content.Text;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.BlockState;
import org.bukkit.block.Skull;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.profile.PlayerProfile;
public class BlockStateCodecSkull implements BlockStateCodec {
private static final boolean HAS_PROFILE_API;
static {
boolean hasProfileApi = false;
try {
Skull.class.getMethod("getOwnerProfile");
hasProfileApi = true;
} catch (NoSuchMethodException ignored) {
}
HAS_PROFILE_API = hasProfileApi;
}
@Override
public Material[] getApplicableMaterials() {
return new Material[] { Material.PLAYER_WALL_HEAD, Material.PLAYER_HEAD };
@ -35,14 +20,9 @@ public class BlockStateCodecSkull implements BlockStateCodec {
if (state instanceof Skull) {
Skull skull = (Skull) state;
OfflinePlayer owner = skull.hasOwner() ? skull.getOwningPlayer() : null;
PlayerProfile profile = HAS_PROFILE_API ? skull.getOwnerProfile() : null;
if (owner != null || profile != null) {
if (owner != null) {
YamlConfiguration conf = new YamlConfiguration();
if (profile != null) {
conf.set("profile", profile);
} else if (owner != null) {
conf.set("owner", owner.getUniqueId().toString());
}
conf.set("owner", owner.getUniqueId().toString());
return conf;
}
}
@ -53,37 +33,21 @@ public class BlockStateCodecSkull implements BlockStateCodec {
public void deserialize(BlockState state, YamlConfiguration conf) {
if (state instanceof Skull) {
Skull skull = (Skull) state;
PlayerProfile profile = conf == null || !HAS_PROFILE_API ? null : (PlayerProfile) conf.get("profile");
if (profile != null) {
skull.setOwnerProfile(profile);
UUID ownerId = conf == null ? null : UUID.fromString(conf.getString("owner"));
if (ownerId == null) {
skull.setOwningPlayer(null);
} else {
UUID ownerId = conf == null ? null : UUID.fromString(conf.getString("owner"));
if (ownerId == null) {
skull.setOwningPlayer(null);
} else {
skull.setOwningPlayer(Bukkit.getOfflinePlayer(ownerId));
}
skull.setOwningPlayer(Bukkit.getOfflinePlayer(ownerId));
}
}
}
@Override
public BaseComponent getChangesAsComponent(YamlConfiguration conf, YamlConfiguration oldState) {
if (HAS_PROFILE_API && conf != null) {
PlayerProfile profile = (PlayerProfile) conf.get("profile");
if (profile != null) {
TextComponent tc = new TextComponent("[" + (profile.getName() != null ? profile.getName() : (profile.getUniqueId() != null ? profile.getUniqueId().toString() : "~unknown~")) + "]");
if (profile.getName() != null && profile.getUniqueId() != null) {
tc.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text("UUID: " + profile.getUniqueId().toString())));
}
return tc;
}
}
String ownerIdString = conf == null ? null : conf.getString("owner");
UUID ownerId = ownerIdString == null ? null : UUID.fromString(ownerIdString);
public String toString(YamlConfiguration conf) {
UUID ownerId = conf == null ? null : UUID.fromString(conf.getString("owner"));
if (ownerId != null) {
OfflinePlayer owner = Bukkit.getOfflinePlayer(ownerId);
return new TextComponent("[" + (owner.getName() != null ? owner.getName() : owner.getUniqueId().toString()) + "]");
return "[" + (owner.getName() != null ? owner.getName() : owner.getUniqueId().toString()) + "]";
}
return null;
}

View File

@ -1,8 +1,5 @@
package de.diddiz.LogBlock.blockstate;
import de.diddiz.LogBlock.LogBlock;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.block.CreatureSpawner;
@ -26,9 +23,7 @@ public class BlockStateCodecSpawner implements BlockStateCodec {
conf.set("minSpawnDelay", spawner.getMinSpawnDelay());
conf.set("requiredPlayerRange", spawner.getRequiredPlayerRange());
conf.set("spawnCount", spawner.getSpawnCount());
if (spawner.getSpawnedType() != null) {
conf.set("spawnedType", spawner.getSpawnedType().name());
}
conf.set("spawnedType", spawner.getSpawnedType().name());
conf.set("spawnRange", spawner.getSpawnRange());
return conf;
}
@ -46,27 +41,18 @@ public class BlockStateCodecSpawner implements BlockStateCodec {
spawner.setMinSpawnDelay(conf.getInt("minSpawnDelay"));
spawner.setRequiredPlayerRange(conf.getInt("requiredPlayerRange"));
spawner.setSpawnCount(conf.getInt("spawnCount"));
EntityType spawnedType = null;
String spawnedTypeString = conf.getString("spawnedType");
if (spawnedTypeString != null) {
try {
spawnedType = EntityType.valueOf(spawnedTypeString);
} catch (IllegalArgumentException ignored) {
LogBlock.getInstance().getLogger().warning("Could not find spawner spawned type: " + spawnedTypeString);
}
}
spawner.setSpawnedType(spawnedType);
spawner.setSpawnedType(EntityType.valueOf(conf.getString("spawnedType")));
spawner.setSpawnRange(conf.getInt("spawnRange"));
}
}
}
@Override
public BaseComponent getChangesAsComponent(YamlConfiguration conf, YamlConfiguration oldState) {
public String toString(YamlConfiguration conf) {
if (conf != null) {
EntityType entity = EntityType.valueOf(conf.getString("spawnedType"));
if (entity != null) {
return new TextComponent("[" + entity.getKey().getKey() + "]");
return "[" + entity + "]";
}
}
return null;

View File

@ -1,14 +1,14 @@
package de.diddiz.LogBlock.blockstate;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Map;
import net.md_5.bungee.api.chat.BaseComponent;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.configuration.file.YamlConfiguration;
public class BlockStateCodecs {
private static Map<Material, BlockStateCodec> codecs = new HashMap<>();
private static Map<Material, BlockStateCodec> codecs = new EnumMap<>(Material.class);
public static void registerCodec(BlockStateCodec codec) {
Material[] materials = codec.getApplicableMaterials();
@ -51,10 +51,10 @@ public class BlockStateCodecs {
}
}
public static BaseComponent getChangesAsComponent(Material material, YamlConfiguration state, YamlConfiguration oldState) {
public static String toString(Material material, YamlConfiguration state) {
BlockStateCodec codec = codecs.get(material);
if (codec != null) {
return codec.getChangesAsComponent(state, oldState);
return codec.toString(state);
}
return null;
}

View File

@ -1,7 +1,8 @@
package de.diddiz.LogBlock.config;
import de.diddiz.LogBlock.*;
import de.diddiz.LogBlock.util.ComparableVersion;
import de.diddiz.util.ComparableVersion;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection;
@ -16,8 +17,8 @@ import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.zip.DataFormatException;
import static de.diddiz.LogBlock.util.BukkitUtils.friendlyWorldname;
import static de.diddiz.LogBlock.util.Utils.parseTimeSpec;
import static de.diddiz.util.BukkitUtils.friendlyWorldname;
import static de.diddiz.util.Utils.parseTimeSpec;
import static org.bukkit.Bukkit.*;
public class Config {
@ -28,6 +29,7 @@ public class Config {
public static boolean mysqlUseSSL;
public static boolean mysqlRequireSSL;
public static int delayBetweenRuns, forceToProcessAtLeast, timePerRun;
public static boolean fireCustomEvents;
public static boolean useBukkitScheduler;
public static int queueWarningSize;
public static boolean enableAutoClearLog;
@ -52,14 +54,13 @@ public class Config {
public static List<String> ignoredChat;
public static SimpleDateFormat formatter;
public static SimpleDateFormat formatterShort;
public static boolean safetyIdCheck;
public static boolean debug;
public static boolean logEnvironmentalKills;
// addons
public static boolean worldGuardLoggingFlags;
// Not loaded from config - checked at runtime
public static boolean mb4 = false;
public static final String CURRENT_CONFIG_VERSION = "1.19.0";
public static final String CURRENT_CONFIG_VERSION = "1.16.0";
public static enum LogKillsLevel {
PLAYERS,
@ -81,7 +82,6 @@ public class Config {
worldNames.add("world_the_end");
}
def.put("loggedWorlds", worldNames);
def.put("mysql.protocol", "mysql");
def.put("mysql.host", "localhost");
def.put("mysql.port", 3306);
def.put("mysql.database", "minecraft");
@ -92,6 +92,7 @@ public class Config {
def.put("consumer.delayBetweenRuns", 2);
def.put("consumer.forceToProcessAtLeast", 200);
def.put("consumer.timePerRun", 1000);
def.put("consumer.fireCustomEvents", false);
def.put("consumer.useBukkitScheduler", true);
def.put("consumer.queueWarningSize", 1000);
def.put("clearlog.dumpDeletedLog", false);
@ -164,23 +165,19 @@ public class Config {
def.put("tools.toolblock.mode", "LOOKUP");
def.put("tools.toolblock.permissionDefault", "OP");
def.put("safety.id.check", true);
def.put("addons.worldguardLoggingFlags", false);
def.put("debug", false);
for (final Entry<String, Object> e : def.entrySet()) {
if (!config.contains(e.getKey())) {
config.set(e.getKey(), e.getValue());
}
}
if (config.contains("consumer.fireCustomEvents")) {
config.set("consumer.fireCustomEvents", null);
}
logblock.saveConfig();
ComparableVersion configVersion = new ComparableVersion(config.getString("version"));
boolean oldConfig = configVersion.compareTo(new ComparableVersion(CURRENT_CONFIG_VERSION)) < 0;
mysqlDatabase = getStringIncludingInts(config, "mysql.database");
url = "jdbc:" + config.getString("mysql.protocol") + "://" + config.getString("mysql.host") + ":" + config.getInt("mysql.port") + "/" + mysqlDatabase;
url = "jdbc:mysql://" + config.getString("mysql.host") + ":" + config.getInt("mysql.port") + "/" + mysqlDatabase;
user = getStringIncludingInts(config, "mysql.user");
password = getStringIncludingInts(config, "mysql.password");
mysqlUseSSL = config.getBoolean("mysql.useSSL", true);
@ -188,6 +185,7 @@ public class Config {
delayBetweenRuns = config.getInt("consumer.delayBetweenRuns", 2);
forceToProcessAtLeast = config.getInt("consumer.forceToProcessAtLeast", 0);
timePerRun = config.getInt("consumer.timePerRun", 1000);
fireCustomEvents = config.getBoolean("consumer.fireCustomEvents", false);
useBukkitScheduler = config.getBoolean("consumer.useBukkitScheduler", true);
queueWarningSize = config.getInt("consumer.queueWarningSize", 1000);
enableAutoClearLog = config.getBoolean("clearlog.enableAutoClearLog");
@ -252,6 +250,7 @@ public class Config {
askClearLogs = config.getBoolean("questioner.askClearLogs", true);
askClearLogAfterRollback = config.getBoolean("questioner.askClearLogAfterRollback", true);
askRollbackAfterBan = config.getBoolean("questioner.askRollbackAfterBan", false);
safetyIdCheck = config.getBoolean("safety.id.check", true);
debug = config.getBoolean("debug", false);
banPermission = config.getString("questioner.banPermission");
final List<Tool> tools = new ArrayList<>();
@ -286,7 +285,6 @@ public class Config {
toolsByName.put(alias, tool);
}
}
worldGuardLoggingFlags = config.getBoolean("addons.worldguardLoggingFlags");
final List<String> loggedWorlds = config.getStringList("loggedWorlds");
worldConfigs = new HashMap<>();
if (loggedWorlds.isEmpty()) {
@ -359,11 +357,6 @@ public class Config {
}
return false;
}
public static boolean isLoggingNatualSpawns(World world) {
final WorldConfig wcfg = worldConfigs.get(world.getName());
return wcfg != null && wcfg.logNaturalEntitySpawns;
}
}
class LoggingEnabledMapping {

View File

@ -7,8 +7,8 @@ import java.util.List;
import org.bukkit.entity.EntityType;
public enum EntityLogging {
SPAWN(new String[] { EntityType.ARMOR_STAND.name(), EntityType.ITEM_FRAME.name(), EntityType.SNOWMAN.name() }),
DESTROY(new String[] { EntityType.ARMOR_STAND.name(), EntityType.ITEM_FRAME.name(), EntityType.VILLAGER.name(), EntityType.SNOWMAN.name(), "ANIMAL" }),
SPAWN(new String[] { EntityType.ARMOR_STAND.name(), EntityType.ITEM_FRAME.name(), EntityType.IRON_GOLEM.name(), EntityType.SNOWMAN.name() }),
DESTROY(new String[] { EntityType.ARMOR_STAND.name(), EntityType.ITEM_FRAME.name(), EntityType.VILLAGER.name(), EntityType.IRON_GOLEM.name(), EntityType.SNOWMAN.name(), "ANIMAL" }),
MODIFY(new String[] { "ALL" });
public static final int length = EntityLogging.values().length;

View File

@ -2,7 +2,8 @@ package de.diddiz.LogBlock.config;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.util.BukkitUtils;
import de.diddiz.util.BukkitUtils;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Animals;
import org.bukkit.entity.ArmorStand;
@ -16,8 +17,8 @@ import org.bukkit.entity.WaterMob;
import java.io.File;
import java.io.IOException;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
@ -34,8 +35,6 @@ public class WorldConfig extends LoggingEnabledMapping {
public final String updateEntityUUIDString;
private final EnumMap<EntityLogging, EntityLoggingList> entityLogging = new EnumMap<>(EntityLogging.class);
public final boolean logNaturalEntitySpawns;
public final boolean logAllNamedEntityKills;
public WorldConfig(String world, File file) throws IOException {
this.world = world;
@ -56,18 +55,8 @@ public class WorldConfig extends LoggingEnabledMapping {
if (!(config.get("entity." + el.name().toLowerCase()) instanceof List)) {
config.set("entity." + el.name().toLowerCase(), el.getDefaultEnabled());
}
entityLogging.put(el, new EntityLoggingList(el, config.getStringList("entity." + el.name().toLowerCase())));
entityLogging.put(el, new EntityLoggingList(config.getStringList("entity." + el.name().toLowerCase())));
}
if (!config.isBoolean("entity.logNaturalSpawns")) {
config.set("entity.logNaturalSpawns", false);
}
logNaturalEntitySpawns = config.getBoolean("entity.logNaturalSpawns");
if (!config.isBoolean("entity.logAllNamedEntityKills")) {
config.set("entity.logAllNamedEntityKills", true);
}
logAllNamedEntityKills = config.getBoolean("entity.logAllNamedEntityKills");
config.save(file);
table = config.getString("table");
for (final Logging l : Logging.values()) {
@ -96,19 +85,15 @@ public class WorldConfig extends LoggingEnabledMapping {
}
private class EntityLoggingList {
private final EntityLogging entityAction;
private final HashSet<EntityType> logged = new HashSet<>();
private final EnumSet<EntityType> logged = EnumSet.noneOf(EntityType.class);
private final boolean logAll;
private final boolean logAnimals;
private final boolean logWateranimals;
private final boolean logMonsters;
private final boolean logLiving;
public EntityLoggingList(EntityLogging entityAction, List<String> types) {
this.entityAction = entityAction;
public EntityLoggingList(List<String> types) {
boolean all = false;
boolean animals = false;
boolean wateranimals = false;
boolean monsters = false;
boolean living = false;
for (String type : types) {
@ -120,8 +105,6 @@ public class WorldConfig extends LoggingEnabledMapping {
all = true;
} else if (type.equalsIgnoreCase("animal") || type.equalsIgnoreCase("animals")) {
animals = true;
} else if (type.equalsIgnoreCase("wateranimal") || type.equalsIgnoreCase("wateranimals")) {
wateranimals = true;
} else if (type.equalsIgnoreCase("monster") || type.equalsIgnoreCase("monsters")) {
monsters = true;
} else if (type.equalsIgnoreCase("living")) {
@ -133,7 +116,6 @@ public class WorldConfig extends LoggingEnabledMapping {
}
logAll = all;
logAnimals = animals;
logWateranimals = wateranimals;
logMonsters = monsters;
logLiving = living;
}
@ -149,23 +131,17 @@ public class WorldConfig extends LoggingEnabledMapping {
if (logLiving && LivingEntity.class.isAssignableFrom(entity.getClass()) && !(entity instanceof ArmorStand)) {
return true;
}
if (logAnimals && Animals.class.isAssignableFrom(entity.getClass())) {
return true;
}
if (logWateranimals && WaterMob.class.isAssignableFrom(entity.getClass())) {
if (logAnimals && (Animals.class.isAssignableFrom(entity.getClass()) || WaterMob.class.isAssignableFrom(entity.getClass()))) {
return true;
}
if (logMonsters && (Monster.class.isAssignableFrom(entity.getClass()) || entity.getType() == EntityType.SLIME || entity.getType() == EntityType.WITHER || entity.getType() == EntityType.ENDER_DRAGON || entity.getType() == EntityType.SHULKER || entity.getType() == EntityType.GHAST)) {
return true;
}
if (entityAction == EntityLogging.DESTROY && logAllNamedEntityKills && entity.getCustomName() != null) {
return true;
}
return false;
}
public boolean isLoggingAnyEntities() {
return logAll || logAnimals || logLiving || logMonsters || !logged.isEmpty() || (entityAction == EntityLogging.DESTROY && logAllNamedEntityKills);
return logAll || logAnimals || logLiving || logMonsters || !logged.isEmpty();
}
}
}

View File

@ -1,54 +0,0 @@
package de.diddiz.LogBlock.events;
import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.EntityChange.EntityChangeType;
import org.bukkit.Location;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Entity;
import org.bukkit.event.HandlerList;
public class EntityChangePreLogEvent extends PreLogEvent {
private static final HandlerList handlers = new HandlerList();
private Location location;
private Entity entity;
private EntityChangeType changeType;
private YamlConfiguration changeData;
public EntityChangePreLogEvent(Actor owner, Location location, Entity entity, EntityChangeType changeType, YamlConfiguration changeData) {
super(owner);
this.location = location;
this.entity = entity;
this.changeType = changeType;
this.changeData = changeData;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public Entity getEntity() {
return entity;
}
public EntityChangeType getChangeType() {
return changeType;
}
public YamlConfiguration getChangeData() {
return changeData;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}

View File

@ -6,9 +6,7 @@ import org.bukkit.block.BlockFace;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Bee;
import org.bukkit.entity.EnderCrystal;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Hanging;
import org.bukkit.entity.IronGolem;
import org.bukkit.entity.ItemFrame;
@ -25,7 +23,6 @@ import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityPlaceEvent;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.hanging.HangingBreakEvent;
import org.bukkit.event.hanging.HangingPlaceEvent;
@ -42,8 +39,8 @@ import de.diddiz.LogBlock.EntityChange.EntityChangeType;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.config.EntityLogging;
import de.diddiz.LogBlock.util.LoggingUtil;
import de.diddiz.LogBlock.worldedit.WorldEditHelper;
import de.diddiz.util.LoggingUtil;
import de.diddiz.worldedit.WorldEditHelper;
import java.util.UUID;
public class AdvancedEntityLogging extends LoggingListener {
@ -55,7 +52,6 @@ public class AdvancedEntityLogging extends LoggingListener {
// serialize them before the death event
private UUID lastEntityDamagedForDeathUUID;
private byte[] lastEntityDamagedForDeathSerialized;
private Entity lastEntityDamagedForDeathDamager;
public AdvancedEntityLogging(LogBlock lb) {
super(lb);
@ -73,7 +69,6 @@ public class AdvancedEntityLogging extends LoggingListener {
lastSpawnerEgg = false;
lastEntityDamagedForDeathUUID = null;
lastEntityDamagedForDeathSerialized = null;
lastEntityDamagedForDeathDamager = null;
}
private void setLastSpawner(Player player, Class<? extends Entity> spawning, boolean spawnEgg) {
@ -131,7 +126,7 @@ public class AdvancedEntityLogging extends LoggingListener {
inHand = inHand.clone();
inHand.setAmount(1);
data.set("item", inHand);
consumer.queueEntityModification(actor, entity, EntityChange.EntityChangeType.ADDEQUIP, data);
consumer.queueEntityModification(actor, entity.getUniqueId(), entity.getType(), entity.getLocation(), EntityChange.EntityChangeType.ADDEQUIP, data);
}
}
}
@ -144,10 +139,6 @@ public class AdvancedEntityLogging extends LoggingListener {
if (event.getSpawnReason() == SpawnReason.CUSTOM || event.getSpawnReason() == SpawnReason.BEEHIVE) {
return;
}
if (event.getEntityType() == EntityType.ARMOR_STAND) {
resetOnTick();
return; // logged in the method below
}
LivingEntity entity = event.getEntity();
if (Config.isLogging(entity.getWorld(), EntityLogging.SPAWN, entity)) {
Actor actor = null;
@ -159,9 +150,6 @@ public class AdvancedEntityLogging extends LoggingListener {
}
}
if (actor == null) {
if (event.getSpawnReason() == SpawnReason.NATURAL && !Config.isLoggingNatualSpawns(entity.getWorld())) {
return;
}
actor = new Actor(event.getSpawnReason().toString());
}
queueEntitySpawnOrKill(entity, actor, EntityChange.EntityChangeType.CREATE);
@ -170,23 +158,6 @@ public class AdvancedEntityLogging extends LoggingListener {
resetOnTick();
}
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityPlace(EntityPlaceEvent event) {
if (!event.isCancelled()) {
Entity entity = event.getEntity();
if (Config.isLogging(entity.getWorld(), EntityLogging.SPAWN, entity)) {
Actor actor = null;
if (event.getPlayer() != null) {
actor = Actor.actorFromEntity(event.getPlayer());
}
if (actor == null) {
actor = new Actor("UNKNOWN");
}
queueEntitySpawnOrKill(entity, actor, EntityChange.EntityChangeType.CREATE);
}
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityDeath(EntityDeathEvent event) {
LivingEntity entity = event.getEntity();
@ -199,9 +170,6 @@ public class AdvancedEntityLogging extends LoggingListener {
actor = Actor.actorFromEntity(damager);
}
}
if (actor == null && entity.getKiller() != null) {
actor = Actor.actorFromEntity(entity.getKiller());
}
if (actor == null) {
actor = new Actor(lastDamage == null ? "UNKNOWN" : lastDamage.getCause().toString());
}
@ -249,7 +217,7 @@ public class AdvancedEntityLogging extends LoggingListener {
}
YamlConfiguration data = new YamlConfiguration();
data.set("item", oldItem);
consumer.queueEntityModification(actor, entity, EntityChange.EntityChangeType.REMOVEEQUIP, data);
consumer.queueEntityModification(actor, entity.getUniqueId(), entity.getType(), entity.getLocation(), EntityChange.EntityChangeType.REMOVEEQUIP, data);
}
}
}
@ -257,18 +225,6 @@ public class AdvancedEntityLogging extends LoggingListener {
lastEntityDamagedForDeathUUID = entity.getUniqueId();
lastEntityDamagedForDeathSerialized = WorldEditHelper.serializeEntity(entity);
}
if (entity instanceof EnderCrystal) {
if (Config.isLogging(entity.getWorld(), EntityLogging.DESTROY, entity)) {
if (event instanceof EntityDamageByEntityEvent) {
Entity damager = LoggingUtil.getRealDamager(((EntityDamageByEntityEvent) event).getDamager());
if (lastEntityDamagedForDeathDamager == null || !(damager instanceof EnderCrystal)) {
lastEntityDamagedForDeathDamager = damager;
}
}
Actor actor = lastEntityDamagedForDeathDamager != null ? Actor.actorFromEntity(lastEntityDamagedForDeathDamager) : new Actor(event.getCause().toString());
queueEntitySpawnOrKill(entity, actor, EntityChange.EntityChangeType.KILL);
}
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
@ -277,7 +233,7 @@ public class AdvancedEntityLogging extends LoggingListener {
if (damager instanceof Bee && !((Bee) damager).hasStung()) {
if (Config.isLogging(damager.getWorld(), EntityLogging.MODIFY, damager)) {
Actor actor = Actor.actorFromEntity(event.getEntity());
consumer.queueEntityModification(actor, damager, EntityChange.EntityChangeType.GET_STUNG, null);
consumer.queueEntityModification(actor, damager.getUniqueId(), damager.getType(), damager.getLocation(), EntityChange.EntityChangeType.GET_STUNG, null);
}
}
}
@ -298,13 +254,13 @@ public class AdvancedEntityLogging extends LoggingListener {
YamlConfiguration data = new YamlConfiguration();
data.set("item", oldItem);
data.set("slot", event.getSlot().name());
consumer.queueEntityModification(actor, entity, EntityChange.EntityChangeType.REMOVEEQUIP, data);
consumer.queueEntityModification(actor, entity.getUniqueId(), entity.getType(), entity.getLocation(), EntityChange.EntityChangeType.REMOVEEQUIP, data);
}
if (!newEmpty) {
YamlConfiguration data = new YamlConfiguration();
data.set("item", newItem);
data.set("slot", event.getSlot().name());
consumer.queueEntityModification(actor, entity, EntityChange.EntityChangeType.ADDEQUIP, data);
consumer.queueEntityModification(actor, entity.getUniqueId(), entity.getType(), entity.getLocation(), EntityChange.EntityChangeType.ADDEQUIP, data);
}
}
}
@ -322,6 +278,6 @@ public class AdvancedEntityLogging extends LoggingListener {
} else {
data.set("worldedit", WorldEditHelper.serializeEntity(entity));
}
consumer.queueEntityModification(actor, entity, changeType, data);
consumer.queueEntityModification(actor, entity.getUniqueId(), entity.getType(), location, changeType, data);
}
}

View File

@ -4,7 +4,8 @@ import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.LogBlock.util.BukkitUtils;
import de.diddiz.util.BukkitUtils;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Material;
@ -14,14 +15,13 @@ import org.bukkit.block.data.Waterlogged;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDropItemEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.LogBlock.util.LoggingUtil.smartLogBlockBreak;
import static de.diddiz.LogBlock.util.LoggingUtil.smartLogBlockReplace;
import static de.diddiz.LogBlock.util.LoggingUtil.smartLogFallables;
import static de.diddiz.util.LoggingUtil.smartLogBlockBreak;
import static de.diddiz.util.LoggingUtil.smartLogBlockReplace;
import static de.diddiz.util.LoggingUtil.smartLogFallables;
public class BlockBreakLogging extends LoggingListener {
public BlockBreakLogging(LogBlock lb) {
@ -40,7 +40,7 @@ public class BlockBreakLogging extends LoggingListener {
final Block origin = event.getBlock();
final Material type = origin.getType();
if (wcfg.isLogging(Logging.CHESTACCESS) && BukkitUtils.isContainerBlock(type) && !BukkitUtils.isShulkerBoxBlock(type)) {
if (wcfg.isLogging(Logging.CHESTACCESS) && BukkitUtils.getContainerBlocks().contains(type) && !BukkitUtils.getShulkerBoxBlocks().contains(type)) {
consumer.queueContainerBreak(actor, origin.getState());
} else if (type == Material.ICE) {
// When in creative mode ice doesn't form water
@ -72,17 +72,4 @@ public class BlockBreakLogging extends LoggingListener {
}
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockDropItem(BlockDropItemEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.BLOCKBREAK)) {
Material type = event.getBlock().getType();
if (type == Material.SUSPICIOUS_GRAVEL || type == Material.SUSPICIOUS_SAND) {
Material simplyBroken = type == Material.SUSPICIOUS_SAND ? Material.SAND : Material.GRAVEL;
if (event.getItems().size() != 1 || event.getItems().get(0).getItemStack().getType() != simplyBroken) {
consumer.queueBlockReplace(Actor.actorFromEntity(event.getPlayer()), event.getBlockState(), simplyBroken.createBlockData());
}
}
}
}
}

View File

@ -17,9 +17,9 @@ import org.bukkit.event.block.BlockIgniteEvent.IgniteCause;
import org.bukkit.event.player.PlayerInteractEvent;
import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.LogBlock.util.LoggingUtil.smartLogBlockBreak;
import static de.diddiz.LogBlock.util.LoggingUtil.smartLogBlockReplace;
import static de.diddiz.LogBlock.util.LoggingUtil.smartLogFallables;
import static de.diddiz.util.LoggingUtil.smartLogBlockBreak;
import static de.diddiz.util.LoggingUtil.smartLogBlockReplace;
import static de.diddiz.util.LoggingUtil.smartLogFallables;
public class BlockBurnLogging extends LoggingListener {
public BlockBurnLogging(LogBlock lb) {

View File

@ -1,36 +0,0 @@
package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import org.bukkit.block.BlockState;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockFertilizeEvent;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
public class BlockFertilizeLogging extends LoggingListener {
public BlockFertilizeLogging(LogBlock lb) {
super(lb);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockFertilize(BlockFertilizeEvent event) {
final WorldConfig wcfg = getWorldConfig(event.getBlock().getLocation().getWorld());
if (wcfg != null) {
if (!wcfg.isLogging(Logging.BONEMEALSTRUCTUREGROW)) {
return;
}
final Actor actor;
if (event.getPlayer() != null) {
actor = Actor.actorFromEntity(event.getPlayer());
} else {
actor = new Actor("Dispenser");
}
for (final BlockState state : event.getBlocks()) {
consumer.queueBlockReplace(actor, state.getBlock().getState(), state);
}
}
}
}

View File

@ -4,7 +4,8 @@ import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.util.LoggingUtil;
import de.diddiz.util.LoggingUtil;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;

View File

@ -5,10 +5,6 @@ import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.type.PointedDripstone;
import org.bukkit.block.data.type.PointedDripstone.Thickness;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockSpreadEvent;
@ -26,74 +22,49 @@ public class BlockSpreadLogging extends LoggingListener {
String name;
World world = event.getNewState().getWorld();
Material type = event.getNewState().getType();
World world = event.getBlock().getWorld();
Material type = event.getSource().getType();
if (type == Material.SHORT_GRASS) {
if (!isLogging(world, Logging.GRASSGROWTH)) {
return;
}
name = "GrassGrowth";
} else if (type == Material.MYCELIUM) {
if (!isLogging(world, Logging.MYCELIUMSPREAD)) {
return;
}
name = "MyceliumSpread";
} else if (type == Material.VINE || type == Material.CAVE_VINES || type == Material.CAVE_VINES_PLANT || type == Material.WEEPING_VINES || type == Material.WEEPING_VINES_PLANT || type == Material.TWISTING_VINES || type == Material.TWISTING_VINES_PLANT) {
if (!isLogging(world, Logging.VINEGROWTH)) {
return;
}
name = "VineGrowth";
} else if (type == Material.RED_MUSHROOM || type == Material.BROWN_MUSHROOM) {
if (!isLogging(world, Logging.MUSHROOMSPREAD)) {
return;
}
name = "MushroomSpread";
} else if (type == Material.BAMBOO || type == Material.BAMBOO_SAPLING) {
if (!isLogging(world, Logging.BAMBOOGROWTH)) {
return;
}
name = "BambooGrowth";
if (type == Material.BAMBOO_SAPLING) {
// bamboo sapling gets replaced by bamboo
consumer.queueBlockReplace(new Actor(name), event.getSource().getState(), Material.BAMBOO.createBlockData());
}
} else if (type == Material.POINTED_DRIPSTONE) {
if (!isLogging(world, Logging.DRIPSTONEGROWTH)) {
return;
}
name = "DripstoneGrowth";
PointedDripstone pointed = (PointedDripstone) event.getNewState().getBlockData();
if (pointed.getThickness() != Thickness.TIP_MERGE) {
BlockFace direction = pointed.getVerticalDirection();
Block previousPart = event.getBlock().getRelative(direction.getOppositeFace());
if (previousPart.getType() == Material.POINTED_DRIPSTONE) {
PointedDripstone newBelow = (PointedDripstone) previousPart.getBlockData();
newBelow.setThickness(Thickness.FRUSTUM);
consumer.queueBlockReplace(new Actor(name), previousPart.getState(), newBelow);
previousPart = previousPart.getRelative(direction.getOppositeFace());
if (previousPart.getType() == Material.POINTED_DRIPSTONE) {
Block evenMorePrevious = previousPart.getRelative(direction.getOppositeFace());
newBelow = (PointedDripstone) previousPart.getBlockData();
newBelow.setThickness(evenMorePrevious.getType() == Material.POINTED_DRIPSTONE ? Thickness.MIDDLE : Thickness.BASE);
consumer.queueBlockReplace(new Actor(name), previousPart.getState(), newBelow);
}
switch (type) {
case GRASS:
if (!isLogging(world, Logging.GRASSGROWTH)) {
return;
}
} else {
// special case because the old state is already changed (for one half)
PointedDripstone oldState = (PointedDripstone) event.getNewState().getBlockData();
oldState.setThickness(Thickness.TIP);
consumer.queueBlockReplace(new Actor(name), oldState, event.getNewState());
return;
name = "GrassGrowth";
break;
case MYCELIUM:
if (!isLogging(world, Logging.MYCELIUMSPREAD)) {
return;
}
name = "MyceliumSpread";
break;
case VINE:
if (!isLogging(world, Logging.VINEGROWTH)) {
return;
}
name = "VineGrowth";
break;
case RED_MUSHROOM:
case BROWN_MUSHROOM:
if (!isLogging(world, Logging.MUSHROOMSPREAD)) {
return;
}
name = "MushroomSpread";
break;
case BAMBOO:
case BAMBOO_SAPLING: {
if (!isLogging(world, Logging.BAMBOOGROWTH)) {
return;
}
name = "BambooGrowth";
if (type == Material.BAMBOO_SAPLING) {
// bamboo sapling gets replaced by bamboo
consumer.queueBlockReplace(new Actor(name), event.getSource().getState(), Material.BAMBOO.createBlockData());
}
break;
}
} else if (type == Material.SCULK || type == Material.SCULK_VEIN || type == Material.SCULK_CATALYST || type == Material.SCULK_SENSOR || type == Material.SCULK_SHRIEKER) {
if (!isLogging(world, Logging.SCULKSPREAD)) {
default:
return;
}
name = "SculkSpread";
} else {
return;
}
consumer.queueBlockReplace(new Actor(name), event.getBlock().getState(), event.getNewState());

View File

@ -1,27 +0,0 @@
package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.Config;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.CauldronLevelChangeEvent;
public class CauldronLogging extends LoggingListener {
public CauldronLogging(LogBlock lb) {
super(lb);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onCauldronLevelChange(CauldronLevelChangeEvent event) {
if (Config.isLogging(event.getBlock().getWorld(), Logging.CAULDRONINTERACT)) {
Entity causingEntity = event.getEntity();
if (causingEntity instanceof Player) {
consumer.queueBlockReplace(Actor.actorFromEntity(causingEntity), event.getBlock().getBlockData(), event.getNewState());
}
}
}
}

View File

@ -24,7 +24,7 @@ import java.util.Map;
import java.util.Map.Entry;
import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.LogBlock.util.BukkitUtils.*;
import static de.diddiz.util.BukkitUtils.*;
public class ChestAccessLogging extends LoggingListener {
private class PlayerActiveInventoryModifications {
@ -52,7 +52,7 @@ public class ChestAccessLogging extends LoggingListener {
}
}
// consumer.getLogblock().getLogger().info("Modify container: " + stack + " change: " + amount);
consumer.getLogblock().getLogger().info("Modify container: " + stack + " change: " + amount);
stack = new ItemStack(stack);
stack.setAmount(1);
Integer existing = modifications.get(stack);
@ -70,7 +70,7 @@ public class ChestAccessLogging extends LoggingListener {
ItemStack stack = e.getKey();
int amount = e.getValue();
stack.setAmount(Math.abs(amount));
// consumer.getLogblock().getLogger().info("Store container: " + stack + " take: " + (amount < 0));
consumer.getLogblock().getLogger().info("Store container: " + stack + " take: " + (amount < 0));
consumer.queueChestAccess(Actor.actorFromEntity(actor), location, location.getWorld().getBlockAt(location).getBlockData(), stack, amount < 0);
}
modifications.clear();

View File

@ -4,12 +4,13 @@ import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.LogBlock.util.BukkitUtils;
import de.diddiz.util.BukkitUtils;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.type.TurtleEgg;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@ -26,8 +27,10 @@ public class CreatureInteractLogging extends LoggingListener {
public void onEntityInteract(EntityInteractEvent event) {
final WorldConfig wcfg = getWorldConfig(event.getEntity().getWorld());
final EntityType entityType = event.getEntityType();
// Mobs only
if (event.getEntity() instanceof Player) {
if (event.getEntity() instanceof Player || entityType == null) {
return;
}
@ -39,10 +42,10 @@ public class CreatureInteractLogging extends LoggingListener {
if (type == Material.FARMLAND) {
if (wcfg.isLogging(Logging.CREATURECROPTRAMPLE)) {
// 3 = Dirt ID
consumer.queueBlock(new Actor("CreatureTrample"), loc, type.createBlockData(), Material.DIRT.createBlockData());
consumer.queueBlock(Actor.actorFromEntity(entityType), loc, type.createBlockData(), Material.DIRT.createBlockData());
// Log the crop on top as being broken
Block trampledCrop = clicked.getRelative(BlockFace.UP);
if (BukkitUtils.isCropBlock(trampledCrop.getType())) {
if (BukkitUtils.getCropBlocks().contains(trampledCrop.getType())) {
consumer.queueBlockBreak(new Actor("CreatureTrample"), trampledCrop.getState());
}
}

View File

@ -20,7 +20,7 @@ import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.util.LoggingUtil;
import de.diddiz.util.LoggingUtil;
public class DragonEggLogging extends LoggingListener {

View File

@ -5,12 +5,12 @@ import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.LogBlock.util.BukkitUtils;
import de.diddiz.util.BukkitUtils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.data.type.RespawnAnchor;
import org.bukkit.entity.*;
import org.bukkit.entity.minecart.ExplosiveMinecart;
import org.bukkit.event.EventHandler;
@ -19,12 +19,12 @@ import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockExplodeEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.scheduler.BukkitRunnable;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import static de.diddiz.LogBlock.config.Config.logCreeperExplosionsAsPlayerWhoTriggeredThese;
import static de.diddiz.util.BukkitUtils.getContainerBlocks;
import java.util.UUID;
@ -32,8 +32,6 @@ public class ExplosionLogging extends LoggingListener {
private UUID lastBedInteractionPlayer;
private Location lastBedInteractionLocation;
private UUID lastRespawnAnchorInteractionPlayer;
private Location lastRespawnAnchorInteractionLocation;
public ExplosionLogging(LogBlock lb) {
super(lb);
@ -67,27 +65,15 @@ public class ExplosionLogging extends LoggingListener {
final Entity target = ((Creeper) source).getTarget();
actor = target instanceof Player ? Actor.actorFromEntity(target) : new Actor("Creeper");
} else {
actor = new Actor("Creeper");
new Actor("Creeper");
}
} else if (source instanceof Wither) {
if (!wcfg.isLogging(Logging.WITHER)) {
return;
}
actor = Actor.actorFromEntity(source);
} else if (source instanceof WitherSkull) {
if (!wcfg.isLogging(Logging.WITHER_SKULL)) {
return;
}
actor = Actor.actorFromEntity(source);
} else if (source instanceof Fireball) {
Fireball fireball = (Fireball) source;
ProjectileSource shooter = fireball.getShooter();
if (shooter == null) {
if (!wcfg.isLogging(Logging.MISCEXPLOSION)) {
return;
}
actor = Actor.actorFromEntity(source);
} else if (shooter instanceof Ghast) {
return;
}
if (shooter instanceof Ghast) {
if (!wcfg.isLogging(Logging.GHASTFIREBALLEXPLOSION)) {
return;
}
@ -103,6 +89,17 @@ public class ExplosionLogging extends LoggingListener {
return;
}
actor = Actor.actorFromEntity(source);
} else if (source instanceof Wither) {
if (!wcfg.isLogging(Logging.WITHER)) {
return;
}
actor = Actor.actorFromEntity(source);
} else if (source instanceof WitherSkull) {
if (!wcfg.isLogging(Logging.WITHER_SKULL)) {
return;
}
actor = Actor.actorFromEntity(source);
} else if (source instanceof EnderCrystal) {
if (!wcfg.isLogging(Logging.ENDERCRYSTALEXPLOSION)) {
return;
@ -116,7 +113,7 @@ public class ExplosionLogging extends LoggingListener {
}
for (final Block block : event.blockList()) {
final Material type = block.getType();
if (wcfg.isLogging(Logging.CHESTACCESS) && BukkitUtils.isContainerBlock(type) && !BukkitUtils.isShulkerBoxBlock(type)) {
if (wcfg.isLogging(Logging.CHESTACCESS) && getContainerBlocks().contains(type) && !BukkitUtils.getShulkerBoxBlocks().contains(type)) {
consumer.queueContainerBreak(actor, block.getState());
} else {
consumer.queueBlockBreak(actor, block.getState());
@ -127,48 +124,20 @@ public class ExplosionLogging extends LoggingListener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.hasBlock()) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.hasBlock() && BukkitUtils.isBed(event.getClickedBlock().getType())) {
Block block = event.getClickedBlock();
if (BukkitUtils.isBed(block.getType()) && !block.getWorld().isBedWorks()) {
if (!Config.isLogging(block.getWorld(), Logging.BEDEXPLOSION)) {
return;
}
lastBedInteractionPlayer = event.getPlayer().getUniqueId();
lastBedInteractionLocation = block.getLocation();
new BukkitRunnable() {
@Override
public void run() {
lastBedInteractionPlayer = null;
lastBedInteractionLocation = null;
}
}.runTask(LogBlock.getInstance());
} else if (block.getType() == Material.RESPAWN_ANCHOR && block.getBlockData() instanceof RespawnAnchor data) {
if (!Config.isLogging(block.getWorld(), Logging.RESPAWNANCHOREXPLOSION)) {
return;
}
ItemStack inHand = event.getItem();
int charges = data.getCharges();
if (charges < data.getMaximumCharges() && inHand != null && inHand.getType() == Material.GLOWSTONE) {
// charge
Actor actor = Actor.actorFromEntity(event.getPlayer());
RespawnAnchor blockNew = (RespawnAnchor) data.clone();
blockNew.setCharges(charges + 1);
consumer.queueBlockReplace(actor, block.getState(), blockNew);
} else if (charges > 0 && !block.getWorld().isRespawnAnchorWorks()) {
// explode
Actor actor = Actor.actorFromEntity(event.getPlayer());
consumer.queueBlockBreak(actor, block.getState());
lastRespawnAnchorInteractionPlayer = event.getPlayer().getUniqueId();
lastRespawnAnchorInteractionLocation = block.getLocation();
new BukkitRunnable() {
@Override
public void run() {
lastRespawnAnchorInteractionPlayer = null;
lastRespawnAnchorInteractionLocation = null;
}
}.runTask(LogBlock.getInstance());
}
if (!Config.isLogging(block.getWorld(), Logging.BEDEXPLOSION)) {
return;
}
lastBedInteractionPlayer = event.getPlayer().getUniqueId();
lastBedInteractionLocation = block.getLocation();
new BukkitRunnable() {
@Override
public void run() {
lastBedInteractionPlayer = null;
lastBedInteractionLocation = null;
}
}.runTask(LogBlock.getInstance());
}
}
@ -181,13 +150,6 @@ public class ExplosionLogging extends LoggingListener {
bedCause = Bukkit.getPlayer(lastBedInteractionPlayer);
}
}
Player respawnAnchorCause = null;
if (lastRespawnAnchorInteractionPlayer != null && lastRespawnAnchorInteractionLocation != null) {
Location block = event.getBlock().getLocation();
if (lastRespawnAnchorInteractionLocation.equals(block)) {
respawnAnchorCause = Bukkit.getPlayer(lastRespawnAnchorInteractionPlayer);
}
}
for (final Block block : event.blockList()) {
final WorldConfig wcfg = getWorldConfig(block.getLocation().getWorld());
@ -200,24 +162,13 @@ public class ExplosionLogging extends LoggingListener {
}
if (Config.logBedExplosionsAsPlayerWhoTriggeredThese) {
actor = Actor.actorFromEntity(bedCause);
} else {
actor = new Actor("BedExplosion");
}
} else if (respawnAnchorCause != null) {
if (!wcfg.isLogging(Logging.RESPAWNANCHOREXPLOSION)) {
return;
}
if (Config.logBedExplosionsAsPlayerWhoTriggeredThese) {
actor = Actor.actorFromEntity(respawnAnchorCause);
} else {
actor = new Actor("RespawnAnchorExplosion");
}
} else if (!wcfg.isLogging(Logging.MISCEXPLOSION)) {
return;
}
final Material type = block.getType();
if (wcfg.isLogging(Logging.CHESTACCESS) && BukkitUtils.isContainerBlock(type) && !BukkitUtils.isShulkerBoxBlock(type)) {
if (wcfg.isLogging(Logging.CHESTACCESS) && getContainerBlocks().contains(type) && !BukkitUtils.getShulkerBoxBlocks().contains(type)) {
consumer.queueContainerBreak(actor, block.getState());
} else {
consumer.queueBlockBreak(actor, block.getState());

View File

@ -5,7 +5,8 @@ import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.LogBlock.util.BukkitUtils;
import de.diddiz.util.BukkitUtils;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
@ -45,7 +46,7 @@ public class FluidFlowLogging extends LoggingListener {
final Block to = event.getToBlock();
final Material typeTo = to.getType();
boolean down = event.getFace() == BlockFace.DOWN;
final boolean canFlow = BukkitUtils.isEmpty(typeTo) || BukkitUtils.isNonFluidProofBlock(typeTo);
final boolean canFlow = BukkitUtils.isEmpty(typeTo) || BukkitUtils.getNonFluidProofBlocks().contains(typeTo);
if (typeFrom == Material.LAVA && wcfg.isLogging(Logging.LAVAFLOW)) {
Levelled levelledFrom = (Levelled) blockDataFrom;
if (canFlow) {
@ -53,7 +54,7 @@ public class FluidFlowLogging extends LoggingListener {
consumer.queueBlockReplace(new Actor("LavaFlow", source), to.getState(), Material.COBBLESTONE.createBlockData());
} else {
Levelled newBlock = (Levelled) blockDataFrom.clone();
newBlock.setLevel(down ? 1 : Math.min(levelledFrom.getLevel() + 1, levelledFrom.getMaximumLevel()));
newBlock.setLevel(down ? 1 : levelledFrom.getLevel() + 1);
if (BukkitUtils.isEmpty(typeTo)) {
consumer.queueBlockPlace(new Actor("LavaFlow", source), to.getLocation(), newBlock);
} else {
@ -70,10 +71,10 @@ public class FluidFlowLogging extends LoggingListener {
} else if ((typeFrom == Material.WATER) && wcfg.isLogging(Logging.WATERFLOW)) {
Levelled levelledFrom = fromWaterlogged ? null : (Levelled) blockDataFrom;
Levelled newBlock = (Levelled) Material.WATER.createBlockData();
newBlock.setLevel(fromWaterlogged || down ? 1 : Math.min(levelledFrom.getLevel() + 1, levelledFrom.getMaximumLevel()));
newBlock.setLevel(fromWaterlogged || down ? 1 : levelledFrom.getLevel() + 1);
if (BukkitUtils.isEmpty(typeTo)) {
consumer.queueBlockPlace(new Actor("WaterFlow", source), to.getLocation(), newBlock);
} else if (BukkitUtils.isNonFluidProofBlock(typeTo)) {
} else if (BukkitUtils.getNonFluidProofBlocks().contains(typeTo)) {
consumer.queueBlockReplace(new Actor("WaterFlow", source), to.getState(), newBlock);
} else if (typeTo == Material.LAVA) {
int toLevel = ((Levelled) to.getBlockData()).getLevel();
@ -83,7 +84,7 @@ public class FluidFlowLogging extends LoggingListener {
consumer.queueBlockReplace(new Actor("WaterFlow", source), to.getState(), Material.STONE.createBlockData());
}
}
if (BukkitUtils.isEmpty(typeTo) || BukkitUtils.isNonFluidProofBlock(typeTo)) {
if (BukkitUtils.isEmpty(typeTo) || BukkitUtils.getNonFluidProofBlocks().contains(typeTo)) {
for (final BlockFace face : new BlockFace[] { BlockFace.DOWN, BlockFace.NORTH, BlockFace.WEST, BlockFace.EAST, BlockFace.SOUTH }) {
final Block lower = to.getRelative(face);
if (lower.getType() == Material.LAVA) {

View File

@ -4,10 +4,8 @@ import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.LogBlock.util.BukkitUtils;
import java.util.UUID;
import de.diddiz.util.BukkitUtils;
import org.bukkit.DyeColor;
import org.bukkit.GameEvent;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Note;
@ -18,10 +16,8 @@ import org.bukkit.block.BlockState;
import org.bukkit.block.Sign;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Directional;
import org.bukkit.block.data.Lightable;
import org.bukkit.block.data.Openable;
import org.bukkit.block.data.type.Cake;
import org.bukkit.block.data.type.Candle;
import org.bukkit.block.data.type.Comparator;
import org.bukkit.block.data.type.Comparator.Mode;
import org.bukkit.block.data.type.DaylightDetector;
@ -30,15 +26,11 @@ import org.bukkit.block.data.type.NoteBlock;
import org.bukkit.block.data.type.Repeater;
import org.bukkit.block.data.type.Switch;
import org.bukkit.block.data.type.TurtleEgg;
import org.bukkit.block.sign.Side;
import org.bukkit.block.sign.SignSide;
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.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.world.GenericGameEvent;
import org.bukkit.inventory.ItemStack;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
@ -48,10 +40,6 @@ public class InteractLogging extends LoggingListener {
super(lb);
}
private UUID lastInteractionPlayer;
private BlockData lastInteractionBlockData;
private Location lastInteractionLocation;
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
final WorldConfig wcfg = getWorldConfig(event.getPlayer().getWorld());
@ -64,211 +52,207 @@ public class InteractLogging extends LoggingListener {
final Material type = blockData.getMaterial();
final Player player = event.getPlayer();
final Location loc = clicked.getLocation();
lastInteractionPlayer = player.getUniqueId();
lastInteractionBlockData = blockData;
lastInteractionLocation = loc;
if (BukkitUtils.isFenceGate(type) || BukkitUtils.isWoodenTrapdoor(type)) {
if (wcfg.isLogging(Logging.DOORINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Openable newBlockData = (Openable) blockData.clone();
newBlockData.setOpen(!newBlockData.isOpen());
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
}
} else if (BukkitUtils.isPressurePlate(type)) {
if (wcfg.isLogging(Logging.PRESUREPLATEINTERACT) && event.getAction() == Action.PHYSICAL) {
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, blockData);
}
} else if (BukkitUtils.isWoodenDoor(type)) {
if (wcfg.isLogging(Logging.DOORINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Door newBlockData = (Door) blockData.clone();
newBlockData.setOpen(!newBlockData.isOpen());
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
}
} else if (BukkitUtils.isButton(type) || type == Material.LEVER) {
if (wcfg.isLogging(Logging.SWITCHINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Switch newBlockData = (Switch) blockData.clone();
if (!newBlockData.isPowered() || type == Material.LEVER) {
newBlockData.setPowered(!newBlockData.isPowered());
switch (type) {
case OAK_FENCE_GATE:
case SPRUCE_FENCE_GATE:
case BIRCH_FENCE_GATE:
case JUNGLE_FENCE_GATE:
case ACACIA_FENCE_GATE:
case DARK_OAK_FENCE_GATE:
case WARPED_FENCE_GATE:
case CRIMSON_FENCE_GATE:
case OAK_TRAPDOOR:
case SPRUCE_TRAPDOOR:
case BIRCH_TRAPDOOR:
case JUNGLE_TRAPDOOR:
case ACACIA_TRAPDOOR:
case DARK_OAK_TRAPDOOR:
case WARPED_TRAPDOOR:
case CRIMSON_TRAPDOOR:
if (wcfg.isLogging(Logging.DOORINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Openable newBlockData = (Openable) blockData.clone();
newBlockData.setOpen(!newBlockData.isOpen());
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
}
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
}
} else if (BukkitUtils.isSign(type)) {
if (wcfg.isLogging(Logging.SIGNTEXT) && event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getItem() != null) {
Material itemType = event.getItem().getType();
if (BukkitUtils.isDye(itemType) || itemType == Material.GLOW_INK_SAC || itemType == Material.INK_SAC || itemType == Material.HONEYCOMB) {
final BlockState before = event.getClickedBlock().getState();
if (before instanceof Sign signBefore) {
if (!signBefore.isWaxed()) {
final Sign signAfter = (Sign) event.getClickedBlock().getState();
Side side = BukkitUtils.getFacingSignSide(player, clicked);
SignSide signSideBefore = signBefore.getSide(side);
SignSide signSideAfter = signAfter.getSide(side);
if (itemType == Material.GLOW_INK_SAC) {
if (!signSideBefore.isGlowingText() && hasText(signSideBefore)) {
signSideAfter.setGlowingText(true);
consumer.queueBlockReplace(Actor.actorFromEntity(player), signBefore, signAfter);
}
} else if (itemType == Material.INK_SAC) {
if (signSideBefore.isGlowingText() && hasText(signSideBefore)) {
signSideAfter.setGlowingText(false);
consumer.queueBlockReplace(Actor.actorFromEntity(player), signBefore, signAfter);
}
} else if (itemType == Material.HONEYCOMB) {
signAfter.setWaxed(true);
break;
case CAKE:
if (wcfg.isLogging(Logging.CAKEEAT) && event.getAction() == Action.RIGHT_CLICK_BLOCK && player.getFoodLevel() < 20) {
Cake newBlockData = (Cake) blockData.clone();
if (newBlockData.getBites() < 6) {
newBlockData.setBites(newBlockData.getBites() + 1);
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
} else {
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, Material.AIR.createBlockData());
}
}
break;
case NOTE_BLOCK:
if (wcfg.isLogging(Logging.NOTEBLOCKINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
NoteBlock newBlockData = (NoteBlock) blockData.clone();
if (newBlockData.getNote().getOctave() == 2) {
newBlockData.setNote(new Note(0, Tone.F, true));
} else {
newBlockData.setNote(newBlockData.getNote().sharped());
}
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
}
break;
case REPEATER:
if (wcfg.isLogging(Logging.DIODEINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Repeater newBlockData = (Repeater) blockData.clone();
newBlockData.setDelay((newBlockData.getDelay() % 4) + 1);
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
}
break;
case COMPARATOR:
if (wcfg.isLogging(Logging.COMPARATORINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Comparator newBlockData = (Comparator) blockData.clone();
newBlockData.setMode(newBlockData.getMode() == Mode.COMPARE ? Mode.SUBTRACT : Mode.COMPARE);
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
}
break;
case DAYLIGHT_DETECTOR:
if (wcfg.isLogging(Logging.DAYLIGHTDETECTORINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
DaylightDetector newBlockData = (DaylightDetector) blockData.clone();
newBlockData.setInverted(!newBlockData.isInverted());
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
}
break;
case OAK_PRESSURE_PLATE:
case SPRUCE_PRESSURE_PLATE:
case BIRCH_PRESSURE_PLATE:
case JUNGLE_PRESSURE_PLATE:
case ACACIA_PRESSURE_PLATE:
case DARK_OAK_PRESSURE_PLATE:
case WARPED_PRESSURE_PLATE:
case CRIMSON_PRESSURE_PLATE:
case STONE_PRESSURE_PLATE:
case HEAVY_WEIGHTED_PRESSURE_PLATE:
case LIGHT_WEIGHTED_PRESSURE_PLATE:
if (wcfg.isLogging(Logging.PRESUREPLATEINTERACT) && event.getAction() == Action.PHYSICAL) {
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, blockData);
}
break;
case TRIPWIRE:
if (wcfg.isLogging(Logging.TRIPWIREINTERACT) && event.getAction() == Action.PHYSICAL) {
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, blockData);
}
break;
case FARMLAND:
if (wcfg.isLogging(Logging.CROPTRAMPLE) && event.getAction() == Action.PHYSICAL) {
// 3 = Dirt ID
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, Material.DIRT.createBlockData());
// Log the crop on top as being broken
Block trampledCrop = clicked.getRelative(BlockFace.UP);
if (BukkitUtils.getCropBlocks().contains(trampledCrop.getType())) {
consumer.queueBlockBreak(Actor.actorFromEntity(player), trampledCrop.getState());
}
}
break;
case TURTLE_EGG:
if (wcfg.isLogging(Logging.BLOCKBREAK) && event.getAction() == Action.PHYSICAL) {
TurtleEgg turtleEggData = (TurtleEgg) blockData;
int eggs = turtleEggData.getEggs();
if (eggs > 1) {
TurtleEgg turtleEggData2 = (TurtleEgg) turtleEggData.clone();
turtleEggData2.setEggs(eggs - 1);
consumer.queueBlock(Actor.actorFromEntity(player), loc, turtleEggData, turtleEggData2);
} else {
consumer.queueBlock(Actor.actorFromEntity(player), loc, turtleEggData, Material.AIR.createBlockData());
}
}
break;
case PUMPKIN:
if ((wcfg.isLogging(Logging.BLOCKBREAK) || wcfg.isLogging(Logging.BLOCKPLACE)) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
ItemStack inHand = event.getItem();
if (inHand != null && inHand.getType() == Material.SHEARS) {
BlockFace clickedFace = event.getBlockFace();
Directional newBlockData = (Directional) Material.CARVED_PUMPKIN.createBlockData();
if (clickedFace == BlockFace.NORTH || clickedFace == BlockFace.SOUTH || clickedFace == BlockFace.EAST || clickedFace == BlockFace.WEST) {
newBlockData.setFacing(clickedFace);
} else {
// use player distance to calculate the facing
Location playerLoc = player.getLocation();
playerLoc.subtract(0.5, 0, 0.5);
double dx = playerLoc.getX() - loc.getX();
double dz = playerLoc.getZ() - loc.getZ();
if (Math.abs(dx) > Math.abs(dz)) {
newBlockData.setFacing(dx > 0 ? BlockFace.EAST : BlockFace.WEST);
} else {
newBlockData.setFacing(dz > 0 ? BlockFace.SOUTH : BlockFace.NORTH);
}
}
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
}
}
break;
case OAK_DOOR:
case SPRUCE_DOOR:
case BIRCH_DOOR:
case JUNGLE_DOOR:
case ACACIA_DOOR:
case DARK_OAK_DOOR:
case WARPED_DOOR:
case CRIMSON_DOOR:
if (wcfg.isLogging(Logging.DOORINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Door newBlockData = (Door) blockData.clone();
newBlockData.setOpen(!newBlockData.isOpen());
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
}
break;
case STONE_BUTTON:
case OAK_BUTTON:
case SPRUCE_BUTTON:
case BIRCH_BUTTON:
case JUNGLE_BUTTON:
case ACACIA_BUTTON:
case DARK_OAK_BUTTON:
case WARPED_BUTTON:
case CRIMSON_BUTTON:
case LEVER:
if (wcfg.isLogging(Logging.SWITCHINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Switch newBlockData = (Switch) blockData.clone();
if (!newBlockData.isPowered() || type == Material.LEVER) {
newBlockData.setPowered(!newBlockData.isPowered());
}
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
}
break;
case OAK_SIGN:
case SPRUCE_SIGN:
case BIRCH_SIGN:
case JUNGLE_SIGN:
case ACACIA_SIGN:
case DARK_OAK_SIGN:
case WARPED_SIGN:
case CRIMSON_SIGN:
case OAK_WALL_SIGN:
case SPRUCE_WALL_SIGN:
case BIRCH_WALL_SIGN:
case JUNGLE_WALL_SIGN:
case ACACIA_WALL_SIGN:
case DARK_OAK_WALL_SIGN:
case WARPED_WALL_SIGN:
case CRIMSON_WALL_SIGN:
if (wcfg.isLogging(Logging.SIGNTEXT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
ItemStack stack = event.getItem();
if (stack != null && BukkitUtils.isDye(stack.getType())) {
final BlockState before = event.getClickedBlock().getState();
if (before instanceof Sign) {
DyeColor newColor = BukkitUtils.dyeToDyeColor(stack.getType());
Sign signBefore = (Sign) before;
if (newColor != null && signBefore.getColor() != newColor) {
final Sign signAfter = (Sign) event.getClickedBlock().getState();
signAfter.setColor(newColor);
consumer.queueBlockReplace(Actor.actorFromEntity(player), signBefore, signAfter);
} else if (BukkitUtils.isDye(itemType) && hasText(signSideBefore)) {
DyeColor newColor = BukkitUtils.dyeToDyeColor(itemType);
if (newColor != null && signSideBefore.getColor() != newColor) {
signSideAfter.setColor(newColor);
consumer.queueBlockReplace(Actor.actorFromEntity(player), signBefore, signAfter);
}
}
}
}
}
}
} else if (type == Material.CAKE) {
if (event.hasItem() && BukkitUtils.isCandle(event.getItem().getType()) && event.useItemInHand() != Result.DENY) {
BlockData newBlockData = Material.valueOf(event.getItem().getType().name() + "_CAKE").createBlockData();
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
} else if (wcfg.isLogging(Logging.CAKEEAT) && event.getAction() == Action.RIGHT_CLICK_BLOCK && player.getFoodLevel() < 20) {
Cake newBlockData = (Cake) blockData.clone();
if (newBlockData.getBites() < 6) {
newBlockData.setBites(newBlockData.getBites() + 1);
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
} else {
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, Material.AIR.createBlockData());
}
}
} else if (type == Material.NOTE_BLOCK) {
if (wcfg.isLogging(Logging.NOTEBLOCKINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
NoteBlock newBlockData = (NoteBlock) blockData.clone();
if (newBlockData.getNote().getOctave() == 2) {
newBlockData.setNote(new Note(0, Tone.F, true));
} else {
newBlockData.setNote(newBlockData.getNote().sharped());
}
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
}
} else if (type == Material.REPEATER) {
if (wcfg.isLogging(Logging.DIODEINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Repeater newBlockData = (Repeater) blockData.clone();
newBlockData.setDelay((newBlockData.getDelay() % 4) + 1);
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
}
} else if (type == Material.COMPARATOR) {
if (wcfg.isLogging(Logging.COMPARATORINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Comparator newBlockData = (Comparator) blockData.clone();
newBlockData.setMode(newBlockData.getMode() == Mode.COMPARE ? Mode.SUBTRACT : Mode.COMPARE);
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
}
} else if (type == Material.DAYLIGHT_DETECTOR) {
if (wcfg.isLogging(Logging.DAYLIGHTDETECTORINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
DaylightDetector newBlockData = (DaylightDetector) blockData.clone();
newBlockData.setInverted(!newBlockData.isInverted());
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
}
} else if (type == Material.TRIPWIRE) {
if (wcfg.isLogging(Logging.TRIPWIREINTERACT) && event.getAction() == Action.PHYSICAL) {
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, blockData);
}
} else if (type == Material.FARMLAND) {
if (wcfg.isLogging(Logging.CROPTRAMPLE) && event.getAction() == Action.PHYSICAL) {
// 3 = Dirt ID
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, Material.DIRT.createBlockData());
// Log the crop on top as being broken
Block trampledCrop = clicked.getRelative(BlockFace.UP);
if (BukkitUtils.isCropBlock(trampledCrop.getType())) {
consumer.queueBlockBreak(Actor.actorFromEntity(player), trampledCrop.getState());
}
}
} else if (type == Material.TURTLE_EGG) {
if (wcfg.isLogging(Logging.BLOCKBREAK) && event.getAction() == Action.PHYSICAL) {
TurtleEgg turtleEggData = (TurtleEgg) blockData;
int eggs = turtleEggData.getEggs();
if (eggs > 1) {
TurtleEgg turtleEggData2 = (TurtleEgg) turtleEggData.clone();
turtleEggData2.setEggs(eggs - 1);
consumer.queueBlock(Actor.actorFromEntity(player), loc, turtleEggData, turtleEggData2);
} else {
consumer.queueBlock(Actor.actorFromEntity(player), loc, turtleEggData, Material.AIR.createBlockData());
}
}
} else if (type == Material.PUMPKIN) {
if ((wcfg.isLogging(Logging.BLOCKBREAK) || wcfg.isLogging(Logging.BLOCKPLACE)) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
ItemStack inHand = event.getItem();
if (inHand != null && inHand.getType() == Material.SHEARS) {
BlockFace clickedFace = event.getBlockFace();
Directional newBlockData = (Directional) Material.CARVED_PUMPKIN.createBlockData();
if (clickedFace == BlockFace.NORTH || clickedFace == BlockFace.SOUTH || clickedFace == BlockFace.EAST || clickedFace == BlockFace.WEST) {
newBlockData.setFacing(clickedFace);
} else {
// use player distance to calculate the facing
Location playerLoc = player.getLocation();
playerLoc.subtract(0.5, 0, 0.5);
double dx = playerLoc.getX() - loc.getX();
double dz = playerLoc.getZ() - loc.getZ();
if (Math.abs(dx) > Math.abs(dz)) {
newBlockData.setFacing(dx > 0 ? BlockFace.EAST : BlockFace.WEST);
} else {
newBlockData.setFacing(dz > 0 ? BlockFace.SOUTH : BlockFace.NORTH);
}
}
consumer.queueBlock(Actor.actorFromEntity(player), loc, blockData, newBlockData);
}
}
break;
default:
}
}
}
private boolean hasText(SignSide signSide) {
for (int i = 0; i < 4; i++) {
if (!signSide.getLine(i).isEmpty()) {
return true;
}
}
return false;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onGenericGameEvent(GenericGameEvent event) {
if (lastInteractionPlayer != null && event.getEntity() != null && event.getEntity().getUniqueId().equals(lastInteractionPlayer) && lastInteractionLocation != null && event.getLocation().equals(lastInteractionLocation)) {
if (lastInteractionBlockData instanceof Candle) {
Candle previousCandle = (Candle) lastInteractionBlockData;
if (previousCandle.isLit()) {
BlockData newData = lastInteractionLocation.getBlock().getBlockData();
if (newData instanceof Candle) {
Candle newCandle = (Candle) newData;
if (!newCandle.isLit() && !newCandle.isWaterlogged()) {
// log candle extinguish
consumer.queueBlockReplace(Actor.actorFromEntity(event.getEntity()), lastInteractionLocation, lastInteractionBlockData, newData);
}
}
}
} else if (lastInteractionBlockData instanceof Lightable && BukkitUtils.isCandleCake(lastInteractionBlockData.getMaterial())) {
Lightable previousLightable = (Lightable) lastInteractionBlockData;
BlockData newData = lastInteractionLocation.getBlock().getBlockData();
if (event.getEvent().equals(GameEvent.EAT)) {
final WorldConfig wcfg = getWorldConfig(event.getLocation().getWorld());
if (wcfg.isLogging(Logging.CAKEEAT)) {
// nom nom (don't know why newData is incorrect here)
newData = Material.CAKE.createBlockData();
((Cake) newData).setBites(1);
consumer.queueBlockReplace(Actor.actorFromEntity(event.getEntity()), lastInteractionLocation, lastInteractionBlockData, newData);
}
} else if (previousLightable.isLit()) {
if (newData instanceof Lightable) {
Lightable newLightable = (Lightable) newData;
if (!newLightable.isLit()) {
// log cake extinguish
consumer.queueBlockReplace(Actor.actorFromEntity(event.getEntity()), lastInteractionLocation, lastInteractionBlockData, newData);
}
}
}
}
}
lastInteractionPlayer = null;
lastInteractionBlockData = null;
lastInteractionLocation = null;
}
}

View File

@ -36,8 +36,6 @@ public class KillLogging extends LoggingListener {
return;
}
consumer.queueKill(killer, victim);
} else if (deathEvent.getEntity().getKiller() != null) {
consumer.queueKill(deathEvent.getEntity().getKiller(), victim);
} else if (logEnvironmentalKills) {
if (logKillsLevel == LogKillsLevel.PLAYERS && !(victim instanceof Player)) {
return;

View File

@ -8,8 +8,8 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.block.LeavesDecayEvent;
import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.LogBlock.util.LoggingUtil.smartLogBlockBreak;
import static de.diddiz.LogBlock.util.LoggingUtil.smartLogFallables;
import static de.diddiz.util.LoggingUtil.smartLogBlockBreak;
import static de.diddiz.util.LoggingUtil.smartLogFallables;
public class LeavesDecayLogging extends LoggingListener {
public LeavesDecayLogging(LogBlock lb) {

View File

@ -1,28 +0,0 @@
package de.diddiz.LogBlock.listeners;
import static de.diddiz.LogBlock.config.Config.isLogging;
import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockFormEvent;
public class OxidizationLogging extends LoggingListener {
public OxidizationLogging(LogBlock lb) {
super(lb);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockPhysics(BlockFormEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.OXIDIZATION)) {
final Material type = event.getNewState().getType();
if (type.name().contains("COPPER")) {
consumer.queueBlockReplace(new Actor("NaturalOxidization"), event.getBlock().getState(), event.getNewState());
}
}
}
}

View File

@ -18,7 +18,7 @@ import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.LogBlock.util.LoggingUtil.smartLogFallables;
import static de.diddiz.util.LoggingUtil.smartLogFallables;
public class ScaffoldingLogging extends LoggingListener {
private final static long MAX_SCAFFOLDING_LOG_TIME_MS = 2000;

View File

@ -3,10 +3,6 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import java.util.Objects;
import org.bukkit.block.BlockState;
import org.bukkit.block.Sign;
import org.bukkit.block.sign.SignSide;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.SignChangeEvent;
@ -21,20 +17,7 @@ public class SignChangeLogging extends LoggingListener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onSignChange(SignChangeEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.SIGNTEXT)) {
BlockState newState = event.getBlock().getState();
if (newState instanceof Sign sign) {
SignSide signSide = sign.getSide(event.getSide());
boolean changed = false;
for (int i = 0; i < 4; i++) {
if (!Objects.equals(signSide.getLine(i), event.getLine(i))) {
signSide.setLine(i, event.getLine(i));
changed = true;
}
}
if (changed) {
consumer.queueBlockReplace(Actor.actorFromEntity(event.getPlayer()), event.getBlock().getState(), newState);
}
}
consumer.queueSignChange(Actor.actorFromEntity(event.getPlayer()), event.getBlock().getLocation(), event.getBlock().getBlockData(), event.getLines());
}
}
}

View File

@ -20,14 +20,20 @@ public class StructureGrowLogging extends LoggingListener {
public void onStructureGrow(StructureGrowEvent event) {
final WorldConfig wcfg = getWorldConfig(event.getWorld());
if (wcfg != null) {
if (!wcfg.isLogging(Logging.NATURALSTRUCTUREGROW)) {
return;
}
if (!event.isFromBonemeal()) {
final Actor actor = new Actor("NaturalGrow");
for (final BlockState state : event.getBlocks()) {
consumer.queueBlockReplace(actor, state.getBlock().getState(), state);
final Actor actor;
if (event.getPlayer() != null) {
if (!wcfg.isLogging(Logging.BONEMEALSTRUCTUREGROW)) {
return;
}
actor = Actor.actorFromEntity(event.getPlayer());
} else {
if (!wcfg.isLogging(Logging.NATURALSTRUCTUREGROW)) {
return;
}
actor = new Actor("NaturalGrow");
}
for (final BlockState state : event.getBlocks()) {
consumer.queueBlockReplace(actor, state.getBlock().getState(), state);
}
}
}

View File

@ -2,8 +2,8 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.*;
import de.diddiz.LogBlock.events.ToolUseEvent;
import de.diddiz.LogBlock.util.BukkitUtils;
import de.diddiz.LogBlock.util.CuboidRegion;
import de.diddiz.util.BukkitUtils;
import de.diddiz.util.CuboidRegion;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;

View File

@ -1,27 +0,0 @@
package de.diddiz.LogBlock.util;
import org.bukkit.Bukkit;
public class ReflectionUtil {
private static String versionString;
public static String getVersion() {
if (versionString == null) {
String name = Bukkit.getServer().getClass().getPackage().getName();
versionString = name.substring(name.lastIndexOf('.') + 1);
}
return versionString;
}
public static Class<?> getMinecraftClass(String minecraftClassName) throws ClassNotFoundException {
String clazzName = "net.minecraft." + minecraftClassName;
return Class.forName(clazzName);
}
public static Class<?> getCraftBukkitClass(String craftBukkitClassName) throws ClassNotFoundException {
String clazzName = "org.bukkit.craftbukkit." + getVersion() + "." + craftBukkitClassName;
return Class.forName(clazzName);
}
}

View File

@ -1,4 +1,4 @@
package de.diddiz.LogBlock.util;
package de.diddiz.util;
import net.md_5.bungee.api.ChatColor;

View File

@ -1,4 +1,4 @@
package de.diddiz.LogBlock.util;
package de.diddiz.util;
// Taken from maven-artifact at
// http://grepcode.com/file_/repo1.maven.org/maven2/org.apache.maven/maven-artifact/3.2.3/org/apache/maven/artifact/versioning/ComparableVersion.java/?v=source

View File

@ -1,4 +1,4 @@
package de.diddiz.LogBlock.util;
package de.diddiz.util;
import org.bukkit.Location;
import org.bukkit.World;

View File

@ -1,4 +1,4 @@
package de.diddiz.LogBlock.util;
package de.diddiz.util;
import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.Consumer;
@ -14,8 +14,6 @@ import org.bukkit.block.data.Directional;
import org.bukkit.block.data.type.Bell;
import org.bukkit.block.data.type.Bell.Attachment;
import org.bukkit.block.data.type.Lantern;
import org.bukkit.block.data.type.PointedDripstone;
import org.bukkit.block.data.type.PointedDripstone.Thickness;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed;
@ -54,18 +52,18 @@ public class LoggingUtil {
int initialy = loc.getBlockY();
int y = initialy;
int z = loc.getBlockZ();
while (y > loc.getWorld().getMinHeight() && BukkitUtils.canFallIn(loc.getWorld(), x, (y - 1), z)) {
while (y > 0 && BukkitUtils.canFallIn(loc.getWorld(), x, (y - 1), z)) {
y--;
}
if (initialy != y && !BukkitUtils.isEmpty(replaced.getType())) {
// this is not the final location but the block got removed (vines etc)
consumer.queueBlockBreak(actor, replaced);
}
// If y is minHeight then the block fell out of the world :(
if (y > loc.getWorld().getMinHeight()) {
// If y is 0 then the block fell out of the world :(
if (y != 0) {
// Run this check to avoid false positives
Location finalLoc = new Location(loc.getWorld(), x, y, z);
if (y == initialy || !BukkitUtils.isFallingEntityKiller(finalLoc.getBlock().getType())) {
if (y == initialy || !BukkitUtils.getFallingEntityKillers().contains(finalLoc.getBlock().getType())) {
if (BukkitUtils.isEmpty(finalLoc.getBlock().getType())) {
consumer.queueBlockPlace(actor, finalLoc, placed.getBlockData());
} else {
@ -96,14 +94,14 @@ public class LoggingUtil {
int x = loc.getBlockX();
int y = loc.getBlockY();
int z = loc.getBlockZ();
while (y > loc.getWorld().getMinHeight() && BukkitUtils.canFallIn(loc.getWorld(), x, (y - 1), z)) {
while (y > 0 && BukkitUtils.canFallIn(loc.getWorld(), x, (y - 1), z)) {
y--;
}
// If y is minHeight then the sand block fell out of the world :(
if (y > loc.getWorld().getMinHeight()) {
// If y is 0 then the sand block fell out of the world :(
if (y != 0) {
Location finalLoc = new Location(loc.getWorld(), x, y, z);
// Run this check to avoid false positives
if (!BukkitUtils.isFallingEntityKiller(finalLoc.getBlock().getType())) {
if (!BukkitUtils.getFallingEntityKillers().contains(finalLoc.getBlock().getType())) {
finalLoc.add(0, up, 0); // Add this here after checking for block breakers
if (BukkitUtils.isEmpty(finalLoc.getBlock().getType())) {
consumer.queueBlockPlace(actor, finalLoc, checkBlock.getBlockData());
@ -146,16 +144,10 @@ public class LoggingUtil {
consumer.queueBlockReplace(actor, above.getState(), Material.WEEPING_VINES.createBlockData());
}
}
if (replacedType == Material.CAVE_VINES || replacedType == Material.CAVE_VINES_PLANT) {
Block above = origin.getRelative(BlockFace.UP);
if (above.getType() == Material.CAVE_VINES_PLANT) {
consumer.queueBlockReplace(actor, above.getState(), Material.CAVE_VINES.createBlockData());
}
}
Block checkBlock = origin.getRelative(BlockFace.UP);
Material typeAbove = checkBlock.getType();
if (BukkitUtils.isRelativeTopBreakable(typeAbove)) {
if (BukkitUtils.getRelativeTopBreakabls().contains(typeAbove)) {
if (typeAbove == Material.IRON_DOOR || BukkitUtils.isWoodenDoor(typeAbove)) {
Block doorBlock = checkBlock;
// If the doorBlock is the top half a door the player simply punched a door
@ -185,7 +177,7 @@ public class LoggingUtil {
// check next blocks above
checkBlock = checkBlock.getRelative(BlockFace.UP);
typeAbove = checkBlock.getType();
while (BukkitUtils.isRelativeTopBreakable(typeAbove)) {
while (BukkitUtils.getRelativeTopBreakabls().contains(typeAbove)) {
consumer.queueBlockBreak(actor, checkBlock.getState());
checkBlock = checkBlock.getRelative(BlockFace.UP);
typeAbove = checkBlock.getType();
@ -201,24 +193,6 @@ public class LoggingUtil {
if (bell.getAttachment() == Attachment.FLOOR) {
consumer.queueBlockBreak(actor, checkBlock.getState());
}
} else if (typeAbove == Material.POINTED_DRIPSTONE) {
Block dripStoneBlock = checkBlock;
while (true) {
if (dripStoneBlock.getType() != Material.POINTED_DRIPSTONE) {
break;
}
PointedDripstone dripstone = (PointedDripstone) dripStoneBlock.getBlockData();
if (dripstone.getVerticalDirection() != BlockFace.UP) {
if (dripstone.getThickness() == Thickness.TIP_MERGE) {
PointedDripstone newDripstone = (PointedDripstone) dripstone.clone();
newDripstone.setThickness(Thickness.TIP);
consumer.queueBlockReplace(actor, dripStoneBlock.getState(), newDripstone);
}
break;
}
consumer.queueBlockBreak(actor, dripStoneBlock.getState());
dripStoneBlock = dripStoneBlock.getRelative(BlockFace.UP);
}
}
checkBlock = origin.getRelative(BlockFace.DOWN);
@ -228,55 +202,25 @@ public class LoggingUtil {
if (lantern.isHanging()) {
consumer.queueBlockBreak(actor, checkBlock.getState());
}
} else if (BukkitUtils.isHangingSign(typeBelow)) {
consumer.queueBlockBreak(actor, checkBlock.getState());
} else if (typeBelow == Material.BELL) {
Bell bell = (Bell) checkBlock.getBlockData();
if (bell.getAttachment() == Attachment.CEILING) {
consumer.queueBlockBreak(actor, checkBlock.getState());
}
} else if (typeBelow == Material.WEEPING_VINES || typeBelow == Material.WEEPING_VINES_PLANT || typeBelow == Material.CAVE_VINES || typeBelow == Material.CAVE_VINES_PLANT) {
} else if (typeBelow == Material.WEEPING_VINES || typeBelow == Material.WEEPING_VINES_PLANT) {
consumer.queueBlockBreak(actor, checkBlock.getState());
// check next blocks below
// check next blocks above
checkBlock = checkBlock.getRelative(BlockFace.DOWN);
typeBelow = checkBlock.getType();
while (typeBelow == Material.WEEPING_VINES || typeBelow == Material.WEEPING_VINES_PLANT || typeBelow == Material.CAVE_VINES || typeBelow == Material.CAVE_VINES_PLANT) {
while (typeBelow == Material.WEEPING_VINES || typeBelow == Material.WEEPING_VINES_PLANT) {
consumer.queueBlockBreak(actor, checkBlock.getState());
checkBlock = checkBlock.getRelative(BlockFace.DOWN);
typeBelow = checkBlock.getType();
}
} else if ((replacedType == Material.BIG_DRIPLEAF || replacedType == Material.BIG_DRIPLEAF_STEM) && (typeBelow == Material.BIG_DRIPLEAF || typeBelow == Material.BIG_DRIPLEAF_STEM)) {
consumer.queueBlockBreak(actor, checkBlock.getState());
// check next blocks below
checkBlock = checkBlock.getRelative(BlockFace.DOWN);
typeBelow = checkBlock.getType();
while (typeBelow == Material.BIG_DRIPLEAF || typeBelow == Material.BIG_DRIPLEAF_STEM) {
consumer.queueBlockBreak(actor, checkBlock.getState());
checkBlock = checkBlock.getRelative(BlockFace.DOWN);
typeBelow = checkBlock.getType();
}
} else if (typeBelow == Material.POINTED_DRIPSTONE) {
Block dripStoneBlock = checkBlock;
while (true) {
if (dripStoneBlock.getType() != Material.POINTED_DRIPSTONE) {
break;
}
PointedDripstone dripstone = (PointedDripstone) dripStoneBlock.getBlockData();
if (dripstone.getVerticalDirection() != BlockFace.DOWN) {
if (dripstone.getThickness() == Thickness.TIP_MERGE) {
PointedDripstone newDripstone = (PointedDripstone) dripstone.clone();
newDripstone.setThickness(Thickness.TIP);
consumer.queueBlockReplace(actor, dripStoneBlock.getState(), newDripstone);
}
break;
}
consumer.queueBlockBreak(actor, dripStoneBlock.getState());
dripStoneBlock = dripStoneBlock.getRelative(BlockFace.DOWN);
}
}
List<Location> relativeBreakables = BukkitUtils.getBlocksNearby(origin, BukkitUtils.getRelativeBreakables());
if (!relativeBreakables.isEmpty()) {
if (relativeBreakables.size() != 0) {
for (Location location : relativeBreakables) {
Block block = location.getBlock();
BlockData blockData = block.getBlockData();

View File

@ -1,9 +1,9 @@
package de.diddiz.LogBlock.util;
package de.diddiz.util;
import static de.diddiz.LogBlock.util.ActionColor.CREATE;
import static de.diddiz.LogBlock.util.ActionColor.DESTROY;
import static de.diddiz.LogBlock.util.TypeColor.DEFAULT;
import static de.diddiz.LogBlock.util.Utils.spaces;
import static de.diddiz.util.ActionColor.CREATE;
import static de.diddiz.util.ActionColor.DESTROY;
import static de.diddiz.util.TypeColor.DEFAULT;
import static de.diddiz.util.Utils.spaces;
import de.diddiz.LogBlock.config.Config;
import net.md_5.bungee.api.ChatColor;
@ -49,15 +49,6 @@ public class MessagingUtil {
return createTextComponentWithColor(stateName, TypeColor.STATE.getColor());
}
public static TextComponent prettyState(BaseComponent stateName) {
TextComponent tc = new TextComponent();
tc.setColor(TypeColor.STATE.getColor());
if (stateName != null) {
tc.addExtra(stateName);
}
return tc;
}
public static TextComponent prettyState(int stateValue) {
return prettyState(Integer.toString(stateValue));
}

View File

@ -1,4 +1,4 @@
package de.diddiz.LogBlock.util;
package de.diddiz.util;
import com.zaxxer.hikari.HikariDataSource;
import de.diddiz.LogBlock.config.Config;
@ -43,7 +43,7 @@ public class MySQLConnectionPool implements Closeable {
public Connection getConnection() throws SQLException {
Connection connection = ds.getConnection();
if (Config.mb4) {
connection.createStatement().executeUpdate("SET NAMES utf8mb4");
connection.createStatement().executeQuery("SET NAMES utf8mb4");
}
return connection;
}

View File

@ -1,4 +1,4 @@
package de.diddiz.LogBlock.util;
package de.diddiz.util;
public class SqlUtil {
public static String escapeString(String s) {

View File

@ -1,4 +1,4 @@
package de.diddiz.LogBlock.util;
package de.diddiz.util;
import net.md_5.bungee.api.ChatColor;

View File

@ -1,4 +1,4 @@
package de.diddiz.LogBlock.util;
package de.diddiz.util;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

View File

@ -1,4 +1,4 @@
package de.diddiz.LogBlock.util;
package de.diddiz.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -284,15 +284,4 @@ public class Utils {
public static String serializeForSQL(YamlConfiguration conf) {
return mysqlPrepareBytesForInsertAllowNull(serializeYamlConfiguration(conf));
}
public static double warpDegrees(double degrees) {
double d = degrees % 360.0;
if (d >= 180.0) {
d -= 360.0;
}
if (d < -180.0) {
d += 360.0;
}
return d;
}
}

View File

@ -1,4 +1,4 @@
package de.diddiz.LogBlock.worldedit;
package de.diddiz.worldedit;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -34,7 +34,7 @@ import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.Region;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.util.CuboidRegion;
import de.diddiz.util.CuboidRegion;
public class WorldEditHelper {
private static boolean checkedForWorldEdit;
@ -139,7 +139,7 @@ public class WorldEditHelper {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
NBTOutputStream nbtos = new NBTOutputStream(baos);
CompoundTag nbt = state.getNbtData();
LinkedHashMap<String, Tag<?, ?>> value = new LinkedHashMap<>(nbt.getValue());
LinkedHashMap<String, Tag> value = new LinkedHashMap<>(nbt.getValue());
value.put("Health", new FloatTag(20.0f));
value.put("Motion", new ListTag(DoubleTag.class, Arrays.asList(new DoubleTag[] { new DoubleTag(0), new DoubleTag(0), new DoubleTag(0) })));
value.put("Fire", new ShortTag((short) -20));

View File

@ -1,4 +1,4 @@
package de.diddiz.LogBlock.worldedit;
package de.diddiz.worldedit;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.WorldEdit;
@ -15,7 +15,8 @@ import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.blockstate.BlockStateCodecs;
import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.util.BukkitUtils;
import de.diddiz.util.BukkitUtils;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;

View File

@ -919,10 +919,10 @@
115:15,minecraft:air
116:0,minecraft:enchanting_table
117:0,minecraft:brewing_stand[has_bottle_0=false,has_bottle_1=false,has_bottle_2=false]
118:0,minecraft:cauldron
118:1,minecraft:cauldron
118:2,minecraft:cauldron
118:3,minecraft:cauldron
118:0,minecraft:cauldron[level=0]
118:1,minecraft:cauldron[level=1]
118:2,minecraft:cauldron[level=2]
118:3,minecraft:cauldron[level=3]
118:4,minecraft:air
118:5,minecraft:air
118:6,minecraft:air
@ -1813,7 +1813,7 @@
207:13,minecraft:air
207:14,minecraft:air
207:15,minecraft:air
208:0,minecraft:dirt_path
208:0,minecraft:grass_path
209:0,minecraft:end_gateway
210:0,minecraft:repeating_command_block[conditional=false,facing=down]
210:1,minecraft:repeating_command_block[conditional=false,facing=up]

View File

@ -454,7 +454,7 @@
205:0,minecraft:purpur_slab
206:0,minecraft:end_stone_bricks
207:0,minecraft:beetroots
208:0,minecraft:dirt_path
208:0,minecraft:grass_path
209:0,minecraft:end_gateway
210:0,minecraft:repeating_command_block
211:0,minecraft:chain_command_block

View File

@ -5,8 +5,8 @@ authors: [md_5, ammar2, frymaster]
website: http://dev.bukkit.org/server-mods/logblock/
main: de.diddiz.LogBlock.LogBlock
description: ${project.description}
softdepend: [WorldEdit, WorldGuard]
api-version: 1.20
softdepend: [WorldEdit]
api-version: 1.14
commands:
lb:
description: 'LogBlock plugin commands'

View File

@ -1,8 +1,9 @@
package de.diddiz.LogBlock;
import de.diddiz.util.Utils;
import org.junit.Assert;
import org.junit.Test;
import de.diddiz.LogBlock.util.Utils;
import java.util.Arrays;
import java.util.List;