3 Commits

Author SHA1 Message Date
edcde2f9b2 Fix pom 2023-09-02 00:52:40 +02:00
b89e863054 fix player names with underscore 2023-09-02 00:45:28 +02:00
7c6b756f18 improve player name parsing 2023-09-02 00:45:28 +02:00
88 changed files with 7478 additions and 8461 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

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

View File

@ -1,182 +1,158 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile; import org.bukkit.entity.Projectile;
import org.bukkit.projectiles.BlockProjectileSource; import org.bukkit.projectiles.BlockProjectileSource;
import org.bukkit.projectiles.ProjectileSource; import org.bukkit.projectiles.ProjectileSource;
import static de.diddiz.LogBlock.util.BukkitUtils.entityName; import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.ResultSet; import java.util.Collection;
import java.sql.SQLException;
import org.bukkit.Bukkit; import static de.diddiz.util.BukkitUtils.entityName;
import org.bukkit.Location; import org.bukkit.Bukkit;
import org.bukkit.block.Block; import org.bukkit.Location;
import org.bukkit.block.Block;
public class Actor {
public class Actor {
@Override
public int hashCode() { @Override
return this.UUID != null ? this.UUID.hashCode() : 0; public int hashCode() {
} return this.UUID != null ? this.UUID.hashCode() : 0;
}
@Override
public boolean equals(Object obj) { @Override
if (obj == null || getClass() != obj.getClass()) { public boolean equals(Object obj) {
return false; if (obj == null || getClass() != obj.getClass()) {
} return false;
final Actor other = (Actor) obj; }
return (this.UUID == null) ? (other.UUID == null) : this.UUID.equals(other.UUID); final Actor other = (Actor) obj;
} return (this.UUID == null) ? (other.UUID == null) : this.UUID.equals(other.UUID);
}
final String name;
final String UUID; final String name;
final Location blockLocation; final String UUID;
final Entity entity; final Location blockLocation;
public Actor(String name, String UUID) { public Actor(String name, String UUID) {
this.name = name; this.name = name;
this.UUID = UUID == null ? "unknown" : (UUID.length() > 36 ? UUID.substring(0, 36) : UUID); this.UUID = UUID == null ? "unknown" : (UUID.length() > 36 ? UUID.substring(0, 36) : UUID);
this.blockLocation = null; this.blockLocation = null;
this.entity = null; }
}
public Actor(String name, String UUID, Block block) {
public Actor(String name, String UUID, Block block) { this.name = name;
this.name = name; this.UUID = UUID == null ? "unknown" : (UUID.length() > 36 ? UUID.substring(0, 36) : UUID);
this.UUID = UUID == null ? "unknown" : (UUID.length() > 36 ? UUID.substring(0, 36) : UUID); this.blockLocation = block == null ? null : block.getLocation();
this.blockLocation = block == null ? null : block.getLocation(); }
this.entity = null;
} public Actor(String name, java.util.UUID UUID) {
this.name = name;
public Actor(String name, java.util.UUID UUID) { this.UUID = UUID.toString();
this.name = name; this.blockLocation = null;
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();
public Actor(String name, java.util.UUID UUID, Block block) { this.blockLocation = block == null ? null : block.getLocation();
this.name = name; }
this.UUID = UUID.toString();
this.blockLocation = block == null ? null : block.getLocation(); public Actor(String name) {
this.entity = null; this(name, generateUUID(name));
} }
public Actor(String name, java.util.UUID UUID, Entity entity) { public Actor(String name, Block block) {
this.name = name; this(name, generateUUID(name), block);
this.UUID = UUID.toString(); }
this.blockLocation = null;
this.entity = entity; public Actor(ResultSet rs) throws SQLException {
} this(rs.getString("playername"), rs.getString("UUID"));
}
public Actor(String name) {
this(name, generateUUID(name)); public String getName() {
} return name;
}
public Actor(String name, Block block) {
this(name, generateUUID(name), block); public String getUUID() {
} return UUID;
}
public Actor(String name, Entity entity) {
this.name = name; public Location getBlockLocation() {
this.UUID = generateUUID(name); return blockLocation;
this.blockLocation = null; }
this.entity = entity;
} public static Actor actorFromEntity(Entity entity) {
if (entity instanceof Player) {
public Actor(ResultSet rs) throws SQLException { return new Actor(entityName(entity), entity.getUniqueId());
this(rs.getString("playername"), rs.getString("UUID")); }
} if (entity instanceof Projectile) {
ProjectileSource shooter = ((Projectile) entity).getShooter();
public String getName() { if (shooter != null) {
return name; return actorFromProjectileSource(shooter);
} }
}
public String getUUID() { return new Actor(entityName(entity));
return UUID; }
}
public static Actor actorFromEntity(EntityType entity) {
public Location getBlockLocation() { return new Actor(entity.name());
return blockLocation; }
}
public static Actor actorFromProjectileSource(ProjectileSource psource) {
/** if (psource instanceof Entity) {
* The acting entity object (if known) return actorFromEntity((Entity) psource);
*/ }
public Entity getEntity() { if (psource instanceof BlockProjectileSource) {
return entity; return new Actor(((BlockProjectileSource) psource).getBlock().getType().toString());
} } else {
return new Actor(psource.toString());
public static Actor actorFromEntity(Entity entity) { }
if (entity instanceof Player) {
return new Actor(entityName(entity), entity.getUniqueId(), entity); }
}
if (entity instanceof Projectile) { /**
ProjectileSource shooter = ((Projectile) entity).getShooter(); * Generate an Actor object from a String name, trying to guess if it's an online player
if (shooter != null) { * and if so, setting the UUID accordingly. This only checks against currently online
return actorFromProjectileSource(shooter); * players and is a "best effort" attempt for use with the pre-UUID API
} * <p>
} * If you know something is an entity (player or otherwise) use the {@link #actorFromEntity(org.bukkit.entity.Entity) }
return new Actor(entityName(entity), entity); * or {@link #actorFromEntity(org.bukkit.entity.EntityType) } methods
} * <p>
* If you know something is a server effect (like gravity) use {@link #Actor(java.lang.String)}
@Deprecated *
public static Actor actorFromEntity(EntityType entity) { * @deprecated Only use this if you have a String of unknown origin
return new Actor(entity.name()); *
} * @param actorName
* String of unknown origin
public static Actor actorFromProjectileSource(ProjectileSource psource) { * @return
if (psource instanceof Entity) { */
return actorFromEntity((Entity) psource); @Deprecated
} public static Actor actorFromString(String actorName) {
if (psource instanceof BlockProjectileSource) { Collection<? extends Player> players = Bukkit.getServer().getOnlinePlayers();
return new Actor(((BlockProjectileSource) psource).getBlock().getType().toString()); for (Player p : players) {
} else { if (p.getName().equalsIgnoreCase(actorName)) {
return new Actor(psource.toString()); return actorFromEntity(p);
} }
}
} // No player found online with that name, assuming non-player entity/effect
return new Actor(actorName);
/** }
* Generate an Actor object from a String name, trying to guess if it's an online player
* and if so, setting the UUID accordingly. This only checks against currently online public static boolean isValidUUID(String uuid) {
* players and is a "best effort" attempt for use with the pre-UUID API try {
* <p> java.util.UUID.fromString(uuid);
* If you know something is an entity (player or otherwise) use the {@link #actorFromEntity(org.bukkit.entity.Entity) } return true;
* or {@link #actorFromEntity(org.bukkit.entity.EntityType) } methods } catch (IllegalArgumentException e) {
* <p> return false;
* If you know something is a server effect (like gravity) use {@link #Actor(java.lang.String)} }
* }
* @deprecated Only use this if you have a String of unknown origin
* public static String generateUUID(String name) {
* @param actorName return "log_" + name;
* String of unknown origin
* @return }
*/
@Deprecated }
public static Actor actorFromString(String actorName) {
Player p = Bukkit.getServer().getPlayerExact(actorName);
if (p != null) {
return actorFromEntity(p);
}
// No player found online with that name, assuming non-player entity/effect
return new Actor(actorName);
}
public static boolean isValidUUID(String uuid) {
try {
java.util.UUID.fromString(uuid);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
public static String generateUUID(String name) {
return "log_" + name;
}
}

View File

@ -1,32 +1,29 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import java.util.Arrays; import java.util.Arrays;
import java.util.logging.Level; import java.util.logging.Level;
import static de.diddiz.LogBlock.config.Config.autoClearLog; import static de.diddiz.LogBlock.config.Config.autoClearLog;
import static org.bukkit.Bukkit.*; import static org.bukkit.Bukkit.*;
public class AutoClearLog implements Runnable { public class AutoClearLog implements Runnable {
private final LogBlock logblock; private final LogBlock logblock;
AutoClearLog(LogBlock logblock) { AutoClearLog(LogBlock logblock) {
this.logblock = logblock; this.logblock = logblock;
} }
@Override @Override
public void run() { public void run() {
final CommandsHandler handler = logblock.getCommandsHandler(); final CommandsHandler handler = logblock.getCommandsHandler();
for (final String paramStr : autoClearLog) { for (final String paramStr : autoClearLog) {
if (!logblock.isCompletelyEnabled()) { try {
return; // do not try when plugin is disabled final QueryParams params = new QueryParams(logblock, getConsoleSender(), Arrays.asList(paramStr.split(" ")));
} params.noForcedLimit = true;
try { handler.new CommandClearLog(getServer().getConsoleSender(), params, false);
final QueryParams params = new QueryParams(logblock, getConsoleSender(), Arrays.asList(paramStr.split(" "))); } catch (final Exception ex) {
params.noForcedLimit = true; getLogger().log(Level.SEVERE, "Failed to schedule auto ClearLog: ", ex);
handler.new CommandClearLog(getServer().getConsoleSender(), params, false); }
} catch (final Exception ex) { }
getLogger().log(Level.SEVERE, "Failed to schedule auto ClearLog: ", ex); }
} }
}
}
}

View File

@ -1,272 +1,253 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import static de.diddiz.LogBlock.util.ActionColor.CREATE; import static de.diddiz.util.ActionColor.CREATE;
import static de.diddiz.LogBlock.util.ActionColor.DESTROY; import static de.diddiz.util.ActionColor.DESTROY;
import static de.diddiz.LogBlock.util.ActionColor.INTERACT; import static de.diddiz.util.ActionColor.INTERACT;
import static de.diddiz.LogBlock.util.MessagingUtil.createTextComponentWithColor; import static de.diddiz.util.TypeColor.DEFAULT;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyDate; import static de.diddiz.util.MessagingUtil.createTextComponentWithColor;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyLocation; import static de.diddiz.util.MessagingUtil.prettyDate;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyMaterial; import static de.diddiz.util.MessagingUtil.prettyLocation;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyState; import static de.diddiz.util.MessagingUtil.prettyMaterial;
import static de.diddiz.LogBlock.util.TypeColor.DEFAULT; import static de.diddiz.util.MessagingUtil.prettyState;
import de.diddiz.LogBlock.blockstate.BlockStateCodecs; import de.diddiz.LogBlock.blockstate.BlockStateCodecs;
import de.diddiz.LogBlock.util.BukkitUtils; import de.diddiz.util.BukkitUtils;
import de.diddiz.LogBlock.util.Utils; import de.diddiz.util.Utils;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.logging.Level; import java.util.logging.Level;
import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Note; import org.bukkit.Note;
import org.bukkit.block.data.BlockData; import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Lightable; import org.bukkit.block.data.Openable;
import org.bukkit.block.data.Openable; import org.bukkit.block.data.Powerable;
import org.bukkit.block.data.Powerable; import org.bukkit.block.data.Waterlogged;
import org.bukkit.block.data.Waterlogged; import org.bukkit.block.data.type.Comparator;
import org.bukkit.block.data.type.Candle; import org.bukkit.block.data.type.DaylightDetector;
import org.bukkit.block.data.type.Comparator; import org.bukkit.block.data.type.Lectern;
import org.bukkit.block.data.type.DaylightDetector; import org.bukkit.block.data.type.NoteBlock;
import org.bukkit.block.data.type.Lectern; import org.bukkit.block.data.type.Repeater;
import org.bukkit.block.data.type.NoteBlock; import org.bukkit.block.data.type.Sign;
import org.bukkit.block.data.type.Repeater; import org.bukkit.block.data.type.Switch;
import org.bukkit.block.data.type.Sign; import org.bukkit.block.data.type.WallSign;
import org.bukkit.block.data.type.Switch; import org.bukkit.inventory.ItemStack;
import org.bukkit.block.data.type.WallSign;
import org.bukkit.inventory.ItemStack; public class BlockChange implements LookupCacheElement {
public final long id, date;
public class BlockChange implements LookupCacheElement { public final Location loc;
public final long id, date; public final Actor actor;
public final Location loc; public final String playerName;
public final Actor actor; public final int replacedMaterial, replacedData, typeMaterial, typeData;
public final String playerName; public final byte[] replacedState, typeState;
public final int replacedMaterial, replacedData, typeMaterial, typeData; public final ChestAccess ca;
public final byte[] replacedState, typeState;
public final ChestAccess ca; public BlockChange(long date, Location loc, Actor actor, int replaced, int replacedData, byte[] replacedState, int type, int typeData, byte[] typeState, ChestAccess ca) {
id = 0;
public BlockChange(long date, Location loc, Actor actor, int replaced, int replacedData, byte[] replacedState, int type, int typeData, byte[] typeState, ChestAccess ca) { this.date = date;
id = 0; this.loc = loc;
this.date = date; this.actor = actor;
this.loc = loc; this.replacedMaterial = replaced;
this.actor = actor; this.replacedData = replacedData;
this.replacedMaterial = replaced; this.replacedState = replacedState;
this.replacedData = replacedData; this.typeMaterial = type;
this.replacedState = replacedState; this.typeData = typeData;
this.typeMaterial = type; this.typeState = typeState;
this.typeData = typeData; this.ca = ca;
this.typeState = typeState; this.playerName = actor == null ? null : actor.getName();
this.ca = ca; }
this.playerName = actor == null ? null : actor.getName();
} public BlockChange(ResultSet rs, QueryParams p) throws SQLException {
id = p.needId ? rs.getInt("id") : 0;
public BlockChange(ResultSet rs, QueryParams p) throws SQLException { date = p.needDate ? rs.getTimestamp("date").getTime() : 0;
id = p.needId ? rs.getLong("id") : 0; loc = p.needCoords ? new Location(p.world, rs.getInt("x"), rs.getInt("y"), rs.getInt("z")) : null;
date = p.needDate ? rs.getTimestamp("date").getTime() : 0; actor = p.needPlayer ? new Actor(rs) : null;
loc = p.needCoords ? new Location(p.world, rs.getInt("x"), rs.getInt("y"), rs.getInt("z")) : null; playerName = p.needPlayer ? rs.getString("playername") : null;
actor = p.needPlayer ? new Actor(rs) : null; replacedMaterial = p.needType ? rs.getInt("replaced") : 0;
playerName = p.needPlayer ? rs.getString("playername") : null; replacedData = p.needType ? rs.getInt("replacedData") : -1;
replacedMaterial = p.needType ? rs.getInt("replaced") : 0; typeMaterial = p.needType ? rs.getInt("type") : 0;
replacedData = p.needType ? rs.getInt("replacedData") : -1; typeData = p.needType ? rs.getInt("typeData") : -1;
typeMaterial = p.needType ? rs.getInt("type") : 0; replacedState = p.needType ? rs.getBytes("replacedState") : null;
typeData = p.needType ? rs.getInt("typeData") : -1; typeState = p.needType ? rs.getBytes("typeState") : null;
replacedState = p.needType ? rs.getBytes("replacedState") : null; ChestAccess catemp = null;
typeState = p.needType ? rs.getBytes("typeState") : null; if (p.needChestAccess) {
ChestAccess catemp = null; ItemStack stack = Utils.loadItemStack(rs.getBytes("item"));
if (p.needChestAccess) { if (stack != null) {
ItemStack stack = Utils.loadItemStack(rs.getBytes("item")); catemp = new ChestAccess(stack, rs.getBoolean("itemremove"), rs.getInt("itemtype"));
if (stack != null) { }
catemp = new ChestAccess(stack, rs.getBoolean("itemremove"), rs.getInt("itemtype")); }
} ca = catemp;
} }
ca = catemp;
} private String getTypeDetails(BlockData type, byte[] typeState) {
String typeDetails = null;
private BaseComponent getTypeDetails(BlockData type, byte[] typeState) {
return getTypeDetails(type, typeState, null, null); if (BlockStateCodecs.hasCodec(type.getMaterial())) {
} try {
typeDetails = BlockStateCodecs.toString(type.getMaterial(), Utils.deserializeYamlConfiguration(typeState));
private BaseComponent getTypeDetails(BlockData type, byte[] typeState, BlockData oldType, byte[] oldTypeState) { } catch (Exception e) {
BaseComponent typeDetails = null; LogBlock.getInstance().getLogger().log(Level.SEVERE, "Could not parse BlockState for " + type.getMaterial(), e);
}
if (BlockStateCodecs.hasCodec(type.getMaterial())) { }
try {
typeDetails = BlockStateCodecs.getChangesAsComponent(type.getMaterial(), Utils.deserializeYamlConfiguration(typeState), type.equals(oldType) ? Utils.deserializeYamlConfiguration(oldTypeState) : null); if (typeDetails == null) {
} catch (Exception e) { return "";
LogBlock.getInstance().getLogger().log(Level.SEVERE, "Could not parse BlockState for " + type.getMaterial(), e); } else {
} return " " + typeDetails;
} }
}
if (typeDetails == null) {
return new TextComponent(""); @Override
} else { public String toString() {
TextComponent component = new TextComponent(" "); return BaseComponent.toPlainText(getLogMessage(-1));
component.addExtra(typeDetails); }
return component;
} @Override
} public BaseComponent[] getLogMessage(int entry) {
TextComponent msg = new TextComponent();
@Override if (date > 0) {
public String toString() { msg.addExtra(prettyDate(date));
return BaseComponent.toPlainText(getLogMessage(-1)); msg.addExtra(" ");
} }
if (actor != null) {
@Override msg.addExtra(actor.getName());
public BaseComponent[] getLogMessage(int entry) { msg.addExtra(" ");
TextComponent msg = new TextComponent(); }
if (date > 0) { BlockData type = getBlockSet();
msg.addExtra(prettyDate(date)); BlockData replaced = getBlockReplaced();
msg.addExtra(" "); if (type == null || replaced == null) {
} msg.addExtra("did an unknown block modification");
if (actor != null) { return new BaseComponent[] { msg };
msg.addExtra(actor.getName()); }
msg.addExtra(" ");
} // Process type details once for later use.
BlockData type = getBlockSet(); String typeDetails = getTypeDetails(type, typeState);
BlockData replaced = getBlockReplaced(); String replacedDetails = getTypeDetails(replaced, replacedState);
if (type == null || replaced == null) {
msg.addExtra("did an unknown block modification"); if (type.getMaterial().equals(replaced.getMaterial())) {
return new BaseComponent[] { msg }; if (BukkitUtils.isEmpty(type.getMaterial())) {
} msg.addExtra(createTextComponentWithColor("did an unspecified action", INTERACT.getColor()));
} else if (ca != null) {
// Process type details once for later use. if (ca.itemStack == null) {
BaseComponent typeDetails = getTypeDetails(type, typeState, replaced, replacedState); msg.addExtra(createTextComponentWithColor("looked inside ", INTERACT.getColor()));
BaseComponent replacedDetails = getTypeDetails(replaced, replacedState); msg.addExtra(prettyMaterial(type));
} else if (ca.remove) {
if (type.getMaterial().equals(replaced.getMaterial()) || (type.getMaterial() == Material.CAKE && BukkitUtils.isCandleCake(replaced.getMaterial()))) { msg.addExtra(createTextComponentWithColor("took ", DESTROY.getColor()));
if (BukkitUtils.isEmpty(type.getMaterial())) { msg.addExtra(BukkitUtils.toString(ca.itemStack));
msg.addExtra(createTextComponentWithColor("did an unspecified action", INTERACT.getColor())); msg.addExtra(createTextComponentWithColor(" from ", DESTROY.getColor()));
} else if (ca != null) { msg.addExtra(prettyMaterial(type));
if (ca.itemStack == null) { } else {
msg.addExtra(createTextComponentWithColor("looked inside ", INTERACT.getColor())); msg.addExtra(createTextComponentWithColor("put ", CREATE.getColor()));
msg.addExtra(prettyMaterial(type)); msg.addExtra(BukkitUtils.toString(ca.itemStack));
} else if (ca.remove) { msg.addExtra(createTextComponentWithColor(" into ", CREATE.getColor()));
msg.addExtra(createTextComponentWithColor("took ", DESTROY.getColor())); msg.addExtra(prettyMaterial(type));
msg.addExtra(BukkitUtils.toString(ca.itemStack)); }
msg.addExtra(createTextComponentWithColor(" from ", DESTROY.getColor())); } else if (type instanceof Waterlogged && ((Waterlogged) type).isWaterlogged() != ((Waterlogged) replaced).isWaterlogged()) {
msg.addExtra(prettyMaterial(type)); if (((Waterlogged) type).isWaterlogged()) {
} else { msg.addExtra(createTextComponentWithColor("waterlogged ", CREATE.getColor()));
msg.addExtra(createTextComponentWithColor("put ", CREATE.getColor())); msg.addExtra(prettyMaterial(type));
msg.addExtra(BukkitUtils.toString(ca.itemStack)); } else {
msg.addExtra(createTextComponentWithColor(" into ", CREATE.getColor())); msg.addExtra(createTextComponentWithColor("dried ", DESTROY.getColor()));
msg.addExtra(prettyMaterial(type)); msg.addExtra(prettyMaterial(type));
} }
} else if (type instanceof Waterlogged && ((Waterlogged) type).isWaterlogged() != ((Waterlogged) replaced).isWaterlogged()) { } else if (BukkitUtils.getContainerBlocks().contains(type.getMaterial())) {
if (((Waterlogged) type).isWaterlogged()) { msg.addExtra(createTextComponentWithColor("opened ", INTERACT.getColor()));
msg.addExtra(createTextComponentWithColor("waterlogged ", CREATE.getColor())); msg.addExtra(prettyMaterial(type));
msg.addExtra(prettyMaterial(type)); } else if (type instanceof Openable && ((Openable) type).isOpen() != ((Openable) replaced).isOpen()) {
} else { // Door, Trapdoor, Fence gate
msg.addExtra(createTextComponentWithColor("dried ", DESTROY.getColor())); msg.addExtra(createTextComponentWithColor(((Openable) type).isOpen() ? "opened " : "closed ", INTERACT.getColor()));
msg.addExtra(prettyMaterial(type)); msg.addExtra(prettyMaterial(type));
} } else if (type.getMaterial() == Material.LEVER && ((Switch) type).isPowered() != ((Switch) replaced).isPowered()) {
} else if (BukkitUtils.isContainerBlock(type.getMaterial())) { msg.addExtra(createTextComponentWithColor("switched ", INTERACT.getColor()));
msg.addExtra(createTextComponentWithColor("opened ", INTERACT.getColor())); msg.addExtra(prettyMaterial(type));
msg.addExtra(prettyMaterial(type)); msg.addExtra(prettyState(((Switch) type).isPowered() ? " on" : " off"));
} else if (type instanceof Openable && ((Openable) type).isOpen() != ((Openable) replaced).isOpen()) { } else if (type instanceof Switch && ((Switch) type).isPowered() != ((Switch) replaced).isPowered()) {
// Door, Trapdoor, Fence gate msg.addExtra(createTextComponentWithColor("pressed ", INTERACT.getColor()));
msg.addExtra(createTextComponentWithColor(((Openable) type).isOpen() ? "opened " : "closed ", INTERACT.getColor())); msg.addExtra(prettyMaterial(type));
msg.addExtra(prettyMaterial(type)); } else if (type.getMaterial() == Material.CAKE) {
} else if (type.getMaterial() == Material.LEVER && ((Switch) type).isPowered() != ((Switch) replaced).isPowered()) { msg.addExtra(createTextComponentWithColor("ate a piece of ", DESTROY.getColor()));
msg.addExtra(createTextComponentWithColor("switched ", INTERACT.getColor())); msg.addExtra(prettyMaterial(type));
msg.addExtra(prettyMaterial(type)); } else if (type.getMaterial() == Material.NOTE_BLOCK) {
msg.addExtra(prettyState(((Switch) type).isPowered() ? " on" : " off")); Note note = ((NoteBlock) type).getNote();
} else if (type instanceof Switch && ((Switch) type).isPowered() != ((Switch) replaced).isPowered()) { msg.addExtra(createTextComponentWithColor("set ", INTERACT.getColor()));
msg.addExtra(createTextComponentWithColor("pressed ", INTERACT.getColor())); msg.addExtra(prettyMaterial(type));
msg.addExtra(prettyMaterial(type)); msg.addExtra(" to ");
} else if (type.getMaterial() == Material.CAKE) { msg.addExtra(prettyState(note.getTone().name() + (note.isSharped() ? "#" : "")));
msg.addExtra(createTextComponentWithColor("ate a piece of ", DESTROY.getColor())); } else if (type.getMaterial() == Material.REPEATER) {
msg.addExtra(prettyMaterial(type)); msg.addExtra(createTextComponentWithColor("set ", INTERACT.getColor()));
} else if (type.getMaterial() == Material.NOTE_BLOCK) { msg.addExtra(prettyMaterial(type));
Note note = ((NoteBlock) type).getNote(); msg.addExtra(" to ");
msg.addExtra(createTextComponentWithColor("set ", INTERACT.getColor())); msg.addExtra(prettyState(((Repeater) type).getDelay()));
msg.addExtra(prettyMaterial(type)); msg.addExtra(createTextComponentWithColor(" ticks delay", DEFAULT.getColor()));
msg.addExtra(" to "); } else if (type.getMaterial() == Material.COMPARATOR) {
msg.addExtra(prettyState(note.getTone().name() + (note.isSharped() ? "#" : ""))); msg.addExtra(createTextComponentWithColor("set ", INTERACT.getColor()));
} else if (type.getMaterial() == Material.REPEATER) { msg.addExtra(prettyMaterial(type));
msg.addExtra(createTextComponentWithColor("set ", INTERACT.getColor())); msg.addExtra(" to ");
msg.addExtra(prettyMaterial(type)); msg.addExtra(prettyState(((Comparator) type).getMode()));
msg.addExtra(" to "); } else if (type.getMaterial() == Material.DAYLIGHT_DETECTOR) {
msg.addExtra(prettyState(((Repeater) type).getDelay())); msg.addExtra(createTextComponentWithColor("set ", INTERACT.getColor()));
msg.addExtra(createTextComponentWithColor(" ticks delay", DEFAULT.getColor())); msg.addExtra(prettyMaterial(type));
} else if (type.getMaterial() == Material.COMPARATOR) { msg.addExtra(" to ");
msg.addExtra(createTextComponentWithColor("set ", INTERACT.getColor())); msg.addExtra(prettyState(((DaylightDetector) type).isInverted() ? "inverted" : "normal"));
msg.addExtra(prettyMaterial(type)); } else if (type instanceof Lectern) {
msg.addExtra(" to "); msg.addExtra(createTextComponentWithColor("changed the book on a ", INTERACT.getColor()));
msg.addExtra(prettyState(((Comparator) type).getMode())); msg.addExtra(prettyMaterial(type));
} else if (type.getMaterial() == Material.DAYLIGHT_DETECTOR) { msg.addExtra(" to");
msg.addExtra(createTextComponentWithColor("set ", INTERACT.getColor())); msg.addExtra(prettyState(typeDetails.length() == 0 ? " empty" : typeDetails));
msg.addExtra(prettyMaterial(type)); } else if (type instanceof Powerable) {
msg.addExtra(" to "); msg.addExtra(createTextComponentWithColor("stepped on ", INTERACT.getColor()));
msg.addExtra(prettyState(((DaylightDetector) type).isInverted() ? "inverted" : "normal")); msg.addExtra(prettyMaterial(type));
} else if (type instanceof Lectern) { } else if (type.getMaterial() == Material.TRIPWIRE) {
msg.addExtra(createTextComponentWithColor("changed the book on a ", INTERACT.getColor())); msg.addExtra(createTextComponentWithColor("ran into ", INTERACT.getColor()));
msg.addExtra(prettyMaterial(type)); msg.addExtra(prettyMaterial(type));
msg.addExtra(" to"); } else if (type instanceof Sign || type instanceof WallSign) {
msg.addExtra(prettyState(typeDetails)); msg.addExtra(createTextComponentWithColor("edited a ", CREATE.getColor()));
} else if (type instanceof Powerable) { msg.addExtra(prettyMaterial(type));
msg.addExtra(createTextComponentWithColor("stepped on ", INTERACT.getColor())); msg.addExtra(createTextComponentWithColor(" to ", CREATE.getColor()));
msg.addExtra(prettyMaterial(type)); msg.addExtra(prettyState(typeDetails));
} else if (type.getMaterial() == Material.TRIPWIRE) { } else {
msg.addExtra(createTextComponentWithColor("ran into ", INTERACT.getColor())); msg.addExtra(createTextComponentWithColor("replaced ", CREATE.getColor()));
msg.addExtra(prettyMaterial(type)); msg.addExtra(prettyMaterial(replaced));
} else if (type instanceof Sign || type instanceof WallSign) { msg.addExtra(prettyState(replacedDetails));
msg.addExtra(createTextComponentWithColor("edited a ", CREATE.getColor())); msg.addExtra(createTextComponentWithColor(" with ", CREATE.getColor()));
msg.addExtra(prettyMaterial(type)); msg.addExtra(prettyMaterial(type));
msg.addExtra(createTextComponentWithColor(" to", CREATE.getColor())); msg.addExtra(prettyState(typeDetails));
msg.addExtra(prettyState(typeDetails)); }
} else if (type instanceof Candle && ((Candle) type).getCandles() != ((Candle) replaced).getCandles()) { } else if (BukkitUtils.isEmpty(type.getMaterial())) {
msg.addExtra(createTextComponentWithColor("added a candle to ", CREATE.getColor())); msg.addExtra(createTextComponentWithColor("destroyed ", DESTROY.getColor()));
msg.addExtra(prettyMaterial(type)); msg.addExtra(prettyMaterial(replaced));
} else if ((type instanceof Candle || BukkitUtils.isCandleCake(type.getMaterial())) && ((Lightable) type).isLit() != ((Lightable) replaced).isLit()) { msg.addExtra(prettyState(replacedDetails));
if (((Lightable) type).isLit()) { } else if (BukkitUtils.isEmpty(replaced.getMaterial())) {
msg.addExtra(createTextComponentWithColor("lit a ", CREATE.getColor())); msg.addExtra(createTextComponentWithColor("created ", CREATE.getColor()));
msg.addExtra(prettyMaterial(type)); msg.addExtra(prettyMaterial(type));
} else { msg.addExtra(prettyState(typeDetails));
msg.addExtra(createTextComponentWithColor("extinguished a ", CREATE.getColor())); } else {
msg.addExtra(prettyMaterial(type)); msg.addExtra(createTextComponentWithColor("replaced ", CREATE.getColor()));
} msg.addExtra(prettyMaterial(replaced));
} else { msg.addExtra(prettyState(replacedDetails));
msg.addExtra(createTextComponentWithColor("replaced ", CREATE.getColor())); msg.addExtra(createTextComponentWithColor(" with ", CREATE.getColor()));
msg.addExtra(prettyMaterial(replaced)); msg.addExtra(prettyMaterial(type));
msg.addExtra(prettyState(replacedDetails)); msg.addExtra(prettyState(typeDetails));
msg.addExtra(createTextComponentWithColor(" with ", CREATE.getColor())); }
msg.addExtra(prettyMaterial(type)); if (loc != null) {
msg.addExtra(prettyState(typeDetails)); msg.addExtra(" at ");
} msg.addExtra(prettyLocation(loc, entry));
} else if (BukkitUtils.isEmpty(type.getMaterial())) { }
msg.addExtra(createTextComponentWithColor("destroyed ", DESTROY.getColor())); return new BaseComponent[] { msg };
msg.addExtra(prettyMaterial(replaced)); }
msg.addExtra(prettyState(replacedDetails));
} else if (BukkitUtils.isEmpty(replaced.getMaterial())) { public BlockData getBlockReplaced() {
msg.addExtra(createTextComponentWithColor("created ", CREATE.getColor())); return MaterialConverter.getBlockData(replacedMaterial, replacedData);
msg.addExtra(prettyMaterial(type)); }
msg.addExtra(prettyState(typeDetails));
} else { public BlockData getBlockSet() {
msg.addExtra(createTextComponentWithColor("replaced ", CREATE.getColor())); return MaterialConverter.getBlockData(typeMaterial, typeData);
msg.addExtra(prettyMaterial(replaced)); }
msg.addExtra(prettyState(replacedDetails));
msg.addExtra(createTextComponentWithColor(" with ", CREATE.getColor())); @Override
msg.addExtra(prettyMaterial(type)); public Location getLocation() {
msg.addExtra(prettyState(typeDetails)); return loc;
} }
if (loc != null) { }
msg.addExtra(" at ");
msg.addExtra(prettyLocation(loc, entry));
}
return new BaseComponent[] { msg };
}
public BlockData getBlockReplaced() {
return MaterialConverter.getBlockData(replacedMaterial, replacedData);
}
public BlockData getBlockSet() {
return MaterialConverter.getBlockData(typeMaterial, typeData);
}
@Override
public Location getLocation() {
return loc;
}
}

View File

@ -1,59 +1,59 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import static de.diddiz.LogBlock.util.LoggingUtil.checkText; import static de.diddiz.util.LoggingUtil.checkText;
import static de.diddiz.LogBlock.util.MessagingUtil.brackets; import static de.diddiz.util.MessagingUtil.brackets;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyDate; import static de.diddiz.util.MessagingUtil.prettyDate;
import de.diddiz.LogBlock.util.MessagingUtil; import de.diddiz.util.MessagingUtil;
import de.diddiz.LogBlock.util.MessagingUtil.BracketType; import de.diddiz.util.MessagingUtil.BracketType;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Location; import org.bukkit.Location;
public class ChatMessage implements LookupCacheElement { public class ChatMessage implements LookupCacheElement {
final long id, date; final long id, date;
final String playerName, message; final String playerName, message;
final Actor player; final Actor player;
public ChatMessage(Actor player, String message) { public ChatMessage(Actor player, String message) {
id = 0; id = 0;
date = System.currentTimeMillis() / 1000; date = System.currentTimeMillis() / 1000;
this.player = player; this.player = player;
this.message = checkText(message); this.message = checkText(message);
this.playerName = player == null ? null : player.getName(); this.playerName = player == null ? null : player.getName();
} }
public ChatMessage(ResultSet rs, QueryParams p) throws SQLException { 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; date = p.needDate ? rs.getTimestamp("date").getTime() : 0;
player = p.needPlayer ? new Actor(rs) : null; player = p.needPlayer ? new Actor(rs) : null;
playerName = p.needPlayer ? rs.getString("playername") : null; playerName = p.needPlayer ? rs.getString("playername") : null;
message = p.needMessage ? rs.getString("message") : null; message = p.needMessage ? rs.getString("message") : null;
} }
@Override @Override
public Location getLocation() { public Location getLocation() {
return null; return null;
} }
@Override @Override
public BaseComponent[] getLogMessage(int entry) { public BaseComponent[] getLogMessage(int entry) {
TextComponent msg = new TextComponent(); TextComponent msg = new TextComponent();
if (date > 0) { if (date > 0) {
msg.addExtra(prettyDate(date)); msg.addExtra(prettyDate(date));
msg.addExtra(" "); msg.addExtra(" ");
} }
if (playerName != null) { if (playerName != null) {
msg.addExtra(brackets(BracketType.ANGLE, MessagingUtil.createTextComponentWithColor(playerName, net.md_5.bungee.api.ChatColor.WHITE))); msg.addExtra(brackets(BracketType.ANGLE, MessagingUtil.createTextComponentWithColor(playerName, net.md_5.bungee.api.ChatColor.WHITE)));
msg.addExtra(" "); msg.addExtra(" ");
} }
if (message != null) { if (message != null) {
for (BaseComponent messageComponent : TextComponent.fromLegacyText(message)) { for (BaseComponent messageComponent : TextComponent.fromLegacyText(message)) {
msg.addExtra(messageComponent); msg.addExtra(messageComponent);
} }
} }
return new BaseComponent[] { msg }; return new BaseComponent[] { msg };
} }
} }

View File

@ -1,15 +1,15 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
public class ChestAccess { public class ChestAccess {
public final ItemStack itemStack; public final ItemStack itemStack;
public final boolean remove; public final boolean remove;
public final int itemType; public final int itemType;
public ChestAccess(ItemStack itemStack, boolean remove, int itemType) { public ChestAccess(ItemStack itemStack, boolean remove, int itemType) {
this.itemStack = itemStack; this.itemStack = itemStack;
this.remove = remove; this.remove = remove;
this.itemType = itemType; this.itemType = itemType;
} }
} }

View File

@ -14,21 +14,21 @@ import static de.diddiz.LogBlock.config.Config.rollbackMaxArea;
import static de.diddiz.LogBlock.config.Config.rollbackMaxTime; import static de.diddiz.LogBlock.config.Config.rollbackMaxTime;
import static de.diddiz.LogBlock.config.Config.toolsByName; import static de.diddiz.LogBlock.config.Config.toolsByName;
import static de.diddiz.LogBlock.config.Config.toolsByType; import static de.diddiz.LogBlock.config.Config.toolsByType;
import static de.diddiz.LogBlock.util.BukkitUtils.giveTool; import static de.diddiz.util.BukkitUtils.giveTool;
import static de.diddiz.LogBlock.util.BukkitUtils.safeSpawnHeight; import static de.diddiz.util.BukkitUtils.saveSpawnHeight;
import static de.diddiz.LogBlock.util.TypeColor.DEFAULT; import static de.diddiz.util.TypeColor.DEFAULT;
import static de.diddiz.LogBlock.util.TypeColor.ERROR; import static de.diddiz.util.TypeColor.ERROR;
import static de.diddiz.LogBlock.util.TypeColor.HEADER; import static de.diddiz.util.TypeColor.HEADER;
import static de.diddiz.LogBlock.util.Utils.isInt; import static de.diddiz.util.Utils.isInt;
import static de.diddiz.LogBlock.util.Utils.listing; import static de.diddiz.util.Utils.listing;
import de.diddiz.LogBlock.QueryParams.BlockChangeType; import de.diddiz.LogBlock.QueryParams.BlockChangeType;
import de.diddiz.LogBlock.QueryParams.Order; import de.diddiz.LogBlock.QueryParams.Order;
import de.diddiz.LogBlock.QueryParams.SummarizationMode; import de.diddiz.LogBlock.QueryParams.SummarizationMode;
import de.diddiz.LogBlock.config.Config; import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.config.WorldConfig; import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.LogBlock.util.MessagingUtil; import de.diddiz.util.MessagingUtil;
import de.diddiz.LogBlock.util.Utils; import de.diddiz.util.Utils;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.File; import java.io.File;
@ -48,7 +48,6 @@ import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.command.Command; import org.bukkit.command.Command;
@ -281,16 +280,13 @@ public class CommandsHandler implements CommandExecutor {
} }
} else if (command.equals("page")) { } else if (command.equals("page")) {
if (args.length == 2 && isInt(args[1])) { if (args.length == 2 && isInt(args[1])) {
sender.sendMessage("");
showPage(sender, Integer.valueOf(args[1])); showPage(sender, Integer.valueOf(args[1]));
} else { } else {
sender.sendMessage(ChatColor.RED + "You have to specify a page"); sender.sendMessage(ChatColor.RED + "You have to specify a page");
} }
} else if (command.equals("next") || command.equals("+")) { } else if (command.equals("next") || command.equals("+")) {
sender.sendMessage("");
showPage(sender, getSession(sender).page + 1); showPage(sender, getSession(sender).page + 1);
} else if (command.equals("prev") || command.equals("-")) { } else if (command.equals("prev") || command.equals("-")) {
sender.sendMessage("");
showPage(sender, getSession(sender).page - 1); showPage(sender, getSession(sender).page - 1);
} else if (args[0].equalsIgnoreCase("savequeue")) { } else if (args[0].equalsIgnoreCase("savequeue")) {
if (logblock.hasPermission(sender, "logblock.rollback")) { if (logblock.hasPermission(sender, "logblock.rollback")) {
@ -374,7 +370,7 @@ public class CommandsHandler implements CommandExecutor {
if (pos >= 0 && pos < session.lookupCache.length) { if (pos >= 0 && pos < session.lookupCache.length) {
final Location loc = session.lookupCache[pos].getLocation(); final Location loc = session.lookupCache[pos].getLocation();
if (loc != null) { 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()); player.sendMessage(ChatColor.LIGHT_PURPLE + "Teleported to " + loc.getBlockX() + ":" + loc.getBlockY() + ":" + loc.getBlockZ());
} else { } else {
sender.sendMessage(ChatColor.RED + "There is no location associated with that. Did you forget coords parameter?"); sender.sendMessage(ChatColor.RED + "There is no location associated with that. Did you forget coords parameter?");
@ -544,7 +540,6 @@ public class CommandsHandler implements CommandExecutor {
} }
state = conn.createStatement(); state = conn.createStatement();
rs = executeQuery(state, params.getQuery()); rs = executeQuery(state, params.getQuery());
sender.sendMessage("");
sender.sendMessage(ChatColor.DARK_AQUA + params.getTitle() + ":"); sender.sendMessage(ChatColor.DARK_AQUA + params.getTitle() + ":");
final List<LookupCacheElement> blockchanges = new ArrayList<>(); final List<LookupCacheElement> blockchanges = new ArrayList<>();
final LookupCacheElementFactory factory = new LookupCacheElementFactory(params, sender instanceof Player ? 2 / 3f : 1); final LookupCacheElementFactory factory = new LookupCacheElementFactory(params, sender instanceof Player ? 2 / 3f : 1);
@ -700,12 +695,10 @@ public class CommandsHandler implements CommandExecutor {
logblock.getServer().getScheduler().scheduleSyncDelayedTask(logblock, new Runnable() { logblock.getServer().getScheduler().scheduleSyncDelayedTask(logblock, new Runnable() {
@Override @Override
public void run() { public void run() {
if (player.getGameMode() != GameMode.SPECTATOR) { final int y2 = saveSpawnHeight(loc);
final int y2 = safeSpawnHeight(loc); loc.setY(y2);
loc.setY(y2);
sender.sendMessage(ChatColor.GREEN + "You were teleported " + Math.abs(y2 - y) + " blocks " + (y2 - y > 0 ? "above" : "below"));
}
player.teleport(loc); player.teleport(loc);
sender.sendMessage(ChatColor.GREEN + "You were teleported " + Math.abs(y2 - y) + " blocks " + (y2 - y > 0 ? "above" : "below"));
} }
}); });
} else { } else {
@ -968,14 +961,14 @@ public class CommandsHandler implements CommandExecutor {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (params.bct == BlockChangeType.CHAT) { if (params.bct == BlockChangeType.CHAT) {
sb.append("INSERT INTO `lb-chat` (`id`, `date`, `playerid`, `message`) VALUES ("); 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.getTimestamp("date").getTime() / 1000).append("), ");
sb.append(rs.getInt("playerid")).append(", '"); sb.append(rs.getInt("playerid")).append(", '");
sb.append(Utils.mysqlTextEscape(rs.getString("message"))); sb.append(Utils.mysqlTextEscape(rs.getString("message")));
sb.append("');\n"); sb.append("');\n");
} else if (params.bct == BlockChangeType.KILLS) { } 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("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.getTimestamp("date").getTime() / 1000).append("), ");
sb.append(rs.getInt("killerid")).append(", "); sb.append(rs.getInt("killerid")).append(", ");
sb.append(rs.getInt("victimid")).append(", "); sb.append(rs.getInt("victimid")).append(", ");
@ -988,7 +981,7 @@ public class CommandsHandler implements CommandExecutor {
} else { } else {
sb.append("INSERT INTO `").append(tableBase).append("-blocks` (`id`, `date`, `playerid`, `replaced`, `replacedData`, `type`, `typeData`, `x`, `y`, `z`) VALUES ("); 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.getTimestamp("date").getTime() / 1000).append("), ");
sb.append(rs.getInt("playerid")).append(", "); sb.append(rs.getInt("playerid")).append(", ");
sb.append(rs.getInt("replaced")).append(", "); sb.append(rs.getInt("replaced")).append(", ");
@ -1003,7 +996,7 @@ public class CommandsHandler implements CommandExecutor {
byte[] typeState = rs.getBytes("typeState"); byte[] typeState = rs.getBytes("typeState");
if (replacedState != null || typeState != null) { if (replacedState != null || typeState != null) {
sb.append("INSERT INTO `").append(tableBase).append("-state` (`id`, `replacedState`, `typeState`) VALUES ("); 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(replacedState)).append(", ");
sb.append(Utils.mysqlPrepareBytesForInsertAllowNull(typeState)); sb.append(Utils.mysqlPrepareBytesForInsertAllowNull(typeState));
sb.append(");\n"); sb.append(");\n");
@ -1011,7 +1004,7 @@ public class CommandsHandler implements CommandExecutor {
byte[] item = rs.getBytes("item"); byte[] item = rs.getBytes("item");
if (item != null) { if (item != null) {
sb.append("INSERT INTO `").append(tableBase).append("-chestdata` (`id`, `item`, `itemremove`, `itemtype`) VALUES ("); 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(Utils.mysqlPrepareBytesForInsertAllowNull(item)).append(", ");
sb.append(rs.getInt("itemremove")).append(", "); sb.append(rs.getInt("itemremove")).append(", ");
sb.append(rs.getInt("itemtype")); sb.append(rs.getInt("itemtype"));

File diff suppressed because it is too large Load Diff

View File

@ -1,147 +1,148 @@
package de.diddiz.LogBlock; 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.io.*; import java.sql.Connection;
import java.sql.Connection; import java.sql.SQLException;
import java.sql.SQLException; import java.sql.Statement;
import java.sql.Statement; import java.util.Arrays;
import java.util.Arrays; import java.util.Comparator;
import java.util.Comparator; import java.util.logging.Level;
import java.util.logging.Level; import java.util.regex.Pattern;
import java.util.regex.Pattern;
import static de.diddiz.util.Utils.newline;
public class DumpedLogImporter implements Runnable {
private final LogBlock logblock; public class DumpedLogImporter implements Runnable {
private final LogBlock logblock;
DumpedLogImporter(LogBlock logblock) {
this.logblock = logblock; DumpedLogImporter(LogBlock logblock) {
} this.logblock = logblock;
}
@Override
public void run() { @Override
final File[] imports = new File(logblock.getDataFolder(), "import").listFiles(new ExtensionFilenameFilter("sql")); public void run() {
if (imports != null && imports.length > 0) { final File[] imports = new File(logblock.getDataFolder(), "import").listFiles(new ExtensionFilenameFilter("sql"));
logblock.getLogger().info("Found " + imports.length + " imports."); if (imports != null && imports.length > 0) {
Arrays.sort(imports, new ImportsComparator()); logblock.getLogger().info("Found " + imports.length + " imports.");
Connection conn = null; Arrays.sort(imports, new ImportsComparator());
try { Connection conn = null;
conn = logblock.getConnection(); try {
if (conn == null) { conn = logblock.getConnection();
return; if (conn == null) {
} return;
conn.setAutoCommit(false); }
final Statement st = conn.createStatement(); conn.setAutoCommit(false);
final BufferedWriter writer = new BufferedWriter(new FileWriter(new File(logblock.getDataFolder(), "import/failed.txt"))); final Statement st = conn.createStatement();
int successes = 0, errors = 0; final BufferedWriter writer = new BufferedWriter(new FileWriter(new File(logblock.getDataFolder(), "import/failed.txt")));
try { int successes = 0, errors = 0;
for (final File sqlFile : imports) { try {
String line = null; for (final File sqlFile : imports) {
try { String line = null;
logblock.getLogger().info("Trying to import " + sqlFile.getName() + " ..."); try {
// first try batch import the whole file logblock.getLogger().info("Trying to import " + sqlFile.getName() + " ...");
final BufferedReader reader = new BufferedReader(new FileReader(sqlFile)); // first try batch import the whole file
int statements = 0; final BufferedReader reader = new BufferedReader(new FileReader(sqlFile));
while ((line = reader.readLine()) != null) { int statements = 0;
if (line.endsWith(";")) { while ((line = reader.readLine()) != null) {
line = line.substring(0, line.length() - 1); if (line.endsWith(";")) {
} line = line.substring(0, line.length() - 1);
if (!line.isEmpty()) { }
statements++; if (!line.isEmpty()) {
st.addBatch(line); statements++;
} st.addBatch(line);
} }
st.executeBatch(); }
conn.commit(); st.executeBatch();
reader.close(); conn.commit();
sqlFile.delete(); reader.close();
successes += statements; sqlFile.delete();
logblock.getLogger().info("Successfully imported " + sqlFile.getName() + "."); successes += statements;
} catch (final Exception ignored) { logblock.getLogger().info("Successfully imported " + sqlFile.getName() + ".");
// if the batch import did not work, retry line by line } catch (final Exception ignored) {
try { // if the batch import did not work, retry line by line
final BufferedReader reader = new BufferedReader(new FileReader(sqlFile)); try {
while ((line = reader.readLine()) != null) { final BufferedReader reader = new BufferedReader(new FileReader(sqlFile));
if (line.endsWith(";")) { while ((line = reader.readLine()) != null) {
line = line.substring(0, line.length() - 1); if (line.endsWith(";")) {
} line = line.substring(0, line.length() - 1);
if (!line.isEmpty()) { }
try { if (!line.isEmpty()) {
st.execute(line); try {
successes++; st.execute(line);
} catch (final SQLException ex) { successes++;
logblock.getLogger().severe("Error while importing: '" + line + "': " + ex.getMessage()); } catch (final SQLException ex) {
writer.write(line + newline); logblock.getLogger().severe("Error while importing: '" + line + "': " + ex.getMessage());
errors++; writer.write(line + newline);
} errors++;
} }
} }
conn.commit(); }
reader.close(); conn.commit();
sqlFile.delete(); reader.close();
logblock.getLogger().info("Successfully imported " + sqlFile.getName() + "."); sqlFile.delete();
} catch (final Exception ex) { logblock.getLogger().info("Successfully imported " + sqlFile.getName() + ".");
logblock.getLogger().severe("Error while importing " + sqlFile.getName() + ": " + ex.getMessage()); } catch (final Exception ex) {
errors++; logblock.getLogger().severe("Error while importing " + sqlFile.getName() + ": " + ex.getMessage());
} errors++;
} }
} }
} finally { }
writer.close(); } finally {
} writer.close();
st.close(); }
logblock.getLogger().info("Successfully imported stored queue. (" + successes + " rows imported, " + errors + " errors)"); st.close();
} catch (final Exception ex) { logblock.getLogger().info("Successfully imported stored queue. (" + successes + " rows imported, " + errors + " errors)");
logblock.getLogger().log(Level.WARNING, "Error while importing: ", ex); } catch (final Exception ex) {
} finally { logblock.getLogger().log(Level.WARNING, "Error while importing: ", ex);
if (conn != null) { } finally {
try { if (conn != null) {
conn.close(); try {
} catch (final SQLException ex) { conn.close();
} } catch (final SQLException ex) {
} }
} }
} }
} }
}
private static class ImportsComparator implements Comparator<File> {
private final Pattern splitPattern = Pattern.compile("[\\-\\.]"); private static class ImportsComparator implements Comparator<File> {
private final Pattern splitPattern = Pattern.compile("[\\-\\.]");
@Override
public int compare(File o1, File o2) { @Override
String[] name1 = splitPattern.split(o1.getName()); public int compare(File o1, File o2) {
String[] name2 = splitPattern.split(o2.getName()); String[] name1 = splitPattern.split(o1.getName());
if (name1.length > name2.length) { String[] name2 = splitPattern.split(o2.getName());
return 1; if (name1.length > name2.length) {
} else if (name1.length < name2.length) { return 1;
return -1; } else if (name1.length < name2.length) {
} return -1;
for (int i = 0; i < name1.length; i++) { }
String part1 = name1[i]; for (int i = 0; i < name1.length; i++) {
String part2 = name2[i]; String part1 = name1[i];
if (part1.length() > 0 && part2.length() > 0) { String part2 = name2[i];
char first1 = part1.charAt(0); if (part1.length() > 0 && part2.length() > 0) {
char first2 = part2.charAt(0); char first1 = part1.charAt(0);
if (first1 >= '0' && first1 <= '9' && first2 >= '0' && first2 <= '9') { char first2 = part2.charAt(0);
try { if (first1 >= '0' && first1 <= '9' && first2 >= '0' && first2 <= '9') {
long long1 = Long.parseLong(part1); try {
long long2 = Long.parseLong(part2); long long1 = Long.parseLong(part1);
if (long1 == long2) { long long2 = Long.parseLong(part2);
continue; if (long1 == long2) {
} continue;
return long1 > long2 ? 1 : -1; }
} catch (NumberFormatException e) { return long1 > long2 ? 1 : -1;
// fallthrough to string compare } catch (NumberFormatException e) {
} // fallthrough to string compare
} }
} }
int compareString = part1.compareTo(part2); }
if (compareString != 0) { int compareString = part1.compareTo(part2);
return compareString; if (compareString != 0) {
} return compareString;
} }
return 0; }
} return 0;
} }
} }
}

View File

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

View File

@ -1,12 +1,11 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import static de.diddiz.LogBlock.util.ActionColor.DESTROY; import static de.diddiz.util.ActionColor.DESTROY;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyDate; import static de.diddiz.util.MessagingUtil.prettyDate;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyLocation; import static de.diddiz.util.MessagingUtil.prettyLocation;
import static de.diddiz.LogBlock.util.MessagingUtil.prettyMaterial; import static de.diddiz.util.MessagingUtil.prettyMaterial;
import de.diddiz.util.BukkitUtils;
import de.diddiz.LogBlock.util.BukkitUtils; import de.diddiz.util.MessagingUtil;
import de.diddiz.LogBlock.util.MessagingUtil;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import net.md_5.bungee.api.chat.BaseComponent; 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 { 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; 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; loc = p.needCoords ? new Location(p.world, rs.getInt("x"), rs.getInt("y"), rs.getInt("z")) : null;
killerName = p.needKiller ? rs.getString("killer") : null; killerName = p.needKiller ? rs.getString("killer") : null;

View File

@ -1,386 +1,350 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import de.diddiz.LogBlock.addons.worldguard.WorldGuardLoggingFlagsAddon; import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.config.Config; import de.diddiz.LogBlock.listeners.*;
import de.diddiz.LogBlock.listeners.*; import de.diddiz.LogBlock.questioner.Questioner;
import de.diddiz.LogBlock.questioner.Questioner; import de.diddiz.util.BukkitUtils;
import de.diddiz.LogBlock.util.BukkitUtils; import de.diddiz.util.MySQLConnectionPool;
import de.diddiz.LogBlock.util.MySQLConnectionPool; import de.diddiz.worldedit.WorldEditHelper;
import de.diddiz.LogBlock.worldedit.WorldEditHelper; import de.diddiz.worldedit.WorldEditLoggingHook;
import de.diddiz.LogBlock.worldedit.WorldEditLoggingHook; import org.bukkit.ChatColor;
import org.bukkit.ChatColor; import org.bukkit.Material;
import org.bukkit.Material; import org.bukkit.command.Command;
import org.bukkit.command.Command; import org.bukkit.command.CommandSender;
import org.bukkit.command.CommandSender; import org.bukkit.entity.Player;
import org.bukkit.entity.Player; import org.bukkit.permissions.Permission;
import org.bukkit.permissions.Permission; import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.File; import java.io.FileNotFoundException;
import java.io.FileNotFoundException; import java.sql.Connection;
import java.sql.Connection; import java.sql.ResultSet;
import java.sql.ResultSet; import java.sql.SQLException;
import java.sql.SQLException; import java.sql.Statement;
import java.sql.Statement; import java.util.ArrayList;
import java.util.ArrayList; import java.util.List;
import java.util.List; import java.util.logging.Level;
import java.util.logging.Level;
import static de.diddiz.LogBlock.config.Config.*;
import static de.diddiz.LogBlock.config.Config.*; import static org.bukkit.Bukkit.getPluginManager;
import static org.bukkit.Bukkit.getPluginManager;
public class LogBlock extends JavaPlugin {
public class LogBlock extends JavaPlugin { private static LogBlock logblock = null;
private static LogBlock logblock = null; private MySQLConnectionPool pool;
private MySQLConnectionPool pool; private Consumer consumer = null;
private Consumer consumer = null; private CommandsHandler commandsHandler;
private CommandsHandler commandsHandler; private boolean noDb = false, connected = true;
private boolean noDb = false, connected = true; private PlayerInfoLogging playerInfoLogging;
private PlayerInfoLogging playerInfoLogging; private ScaffoldingLogging scaffoldingLogging;
private ScaffoldingLogging scaffoldingLogging; private Questioner questioner;
private Questioner questioner; private volatile boolean isCompletelyEnabled;
private WorldGuardLoggingFlagsAddon worldGuardLoggingFlagsAddon;
private boolean isConfigLoaded; public static LogBlock getInstance() {
private volatile boolean isCompletelyEnabled; return logblock;
}
public static LogBlock getInstance() {
return logblock; public boolean isCompletelyEnabled() {
} return isCompletelyEnabled;
}
public boolean isCompletelyEnabled() {
return isCompletelyEnabled; public Consumer getConsumer() {
} return consumer;
}
public Consumer getConsumer() {
return consumer; public CommandsHandler getCommandsHandler() {
} return commandsHandler;
}
public CommandsHandler getCommandsHandler() {
return commandsHandler; @Override
} public void onEnable() {
logblock = this;
@Override
public void onLoad() { BukkitUtils.isDoublePlant(Material.AIR); // Force static code to run
logblock = this; final PluginManager pm = getPluginManager();
BukkitUtils.isDoublePlant(Material.AIR); // Force static code to run
try { consumer = new Consumer(this);
Config.load(this); try {
isConfigLoaded = true; Config.load(this);
} catch (final Exception ex) { } catch (final Exception ex) {
getLogger().log(Level.SEVERE, "Could not load LogBlock config! " + ex.getMessage(), ex); getLogger().log(Level.SEVERE, "Could not load LogBlock config! " + ex.getMessage());
} pm.disablePlugin(this);
if (Config.worldGuardLoggingFlags) { return;
if (getServer().getPluginManager().getPlugin("WorldGuard") == null) { }
getLogger().log(Level.SEVERE, "Invalid config! addons.worldguardLoggingFlags is set to true, but WorldGuard is not loaded."); try {
} else { getLogger().info("Connecting to " + user + "@" + url + "...");
worldGuardLoggingFlagsAddon = new WorldGuardLoggingFlagsAddon(this); try {
worldGuardLoggingFlagsAddon.onPluginLoad(); Class.forName("com.mysql.cj.jdbc.Driver");
} } catch (ClassNotFoundException ignored) {
} Class.forName("com.mysql.jdbc.Driver");
} }
pool = new MySQLConnectionPool(url, user, password, mysqlUseSSL, mysqlRequireSSL);
@Override final Connection conn = getConnection(true);
public void onEnable() { if (conn == null) {
final PluginManager pm = getPluginManager(); noDb = true;
if (!isConfigLoaded) { return;
pm.disablePlugin(this); }
return; final Statement st = conn.createStatement();
} final ResultSet rs = st.executeQuery("SHOW CHARACTER SET where charset='utf8mb4';");
consumer = new Consumer(this); if (rs.next()) {
try { Config.mb4 = true;
getLogger().info("Connecting to " + user + "@" + url + "..."); // Allegedly JDBC driver since 2010 hasn't needed this. I did.
try { st.executeQuery("SET NAMES utf8mb4;");
Class.forName("com.mysql.cj.jdbc.Driver"); }
} catch (ClassNotFoundException ignored) { conn.close();
Class.forName("com.mysql.jdbc.Driver"); Updater updater = new Updater(this);
} updater.checkTables();
pool = new MySQLConnectionPool(url, user, password, mysqlUseSSL, mysqlRequireSSL); MaterialConverter.initializeMaterials(getConnection());
final Connection conn = getConnection(true); MaterialConverter.getOrAddMaterialId(Material.AIR); // AIR must be the first entry
if (conn == null) { EntityTypeConverter.initializeEntityTypes(getConnection());
noDb = true; if (updater.update()) {
return; load(this);
} }
final Statement st = conn.createStatement(); } catch (final NullPointerException ex) {
try { getLogger().log(Level.SEVERE, "Error while loading: ", ex);
final ResultSet rs = st.executeQuery("SHOW CHARACTER SET where charset='utf8mb4';"); } catch (final Exception ex) {
if (rs.next()) { getLogger().log(Level.SEVERE, "Error while loading: " + ex.getMessage(), ex);
Config.mb4 = true; pm.disablePlugin(this);
// Allegedly JDBC driver since 2010 hasn't needed this. I did. return;
try { }
st.executeUpdate("SET NAMES utf8mb4;");
} catch (Exception ex) { if (WorldEditHelper.hasWorldEdit()) {
getLogger().severe("could not set names to utf8mb4: " + ex.getMessage()); new WorldEditLoggingHook(this).hook();
} }
} commandsHandler = new CommandsHandler(this);
} catch (Exception ex) { getCommand("lb").setExecutor(commandsHandler);
getLogger().severe("could not verify character set: " + ex.getMessage()); if (enableAutoClearLog && autoClearLogDelay > 0) {
} getServer().getScheduler().runTaskTimerAsynchronously(this, new AutoClearLog(this), 6000, autoClearLogDelay * 60 * 20);
conn.close(); }
Updater updater = new Updater(this); new DumpedLogImporter(this).run();
updater.checkTables(); registerEvents();
MaterialConverter.initializeMaterials(getConnection()); consumer.start();
MaterialConverter.getOrAddMaterialId(Material.AIR); // AIR must be the first entry for (final Tool tool : toolsByType.values()) {
EntityTypeConverter.initializeEntityTypes(getConnection()); if (pm.getPermission("logblock.tools." + tool.name) == null) {
if (updater.update()) { final Permission perm = new Permission("logblock.tools." + tool.name, tool.permissionDefault);
load(this); pm.addPermission(perm);
} }
} catch (final NullPointerException ex) { }
getLogger().log(Level.SEVERE, "Error while loading: ", ex); questioner = new Questioner(this);
} catch (final Exception ex) { isCompletelyEnabled = true;
getLogger().log(Level.SEVERE, "Error while loading: " + ex.getMessage(), ex); getServer().getScheduler().runTaskAsynchronously(this, new Updater.PlayerCountChecker(this));
pm.disablePlugin(this); }
return;
} private void registerEvents() {
final PluginManager pm = getPluginManager();
if (WorldEditHelper.hasWorldEdit()) { pm.registerEvents(new ToolListener(this), this);
new WorldEditLoggingHook(this).hook(); pm.registerEvents(playerInfoLogging = new PlayerInfoLogging(this), this);
} if (askRollbackAfterBan) {
commandsHandler = new CommandsHandler(this); pm.registerEvents(new BanListener(this), this);
getCommand("lb").setExecutor(commandsHandler); }
if (enableAutoClearLog && autoClearLogDelay > 0) { if (isLogging(Logging.BLOCKPLACE)) {
getServer().getScheduler().runTaskTimerAsynchronously(this, new AutoClearLog(this), 6000, autoClearLogDelay * 60 * 20); pm.registerEvents(new BlockPlaceLogging(this), this);
} }
new DumpedLogImporter(this).run(); if (isLogging(Logging.LAVAFLOW) || isLogging(Logging.WATERFLOW)) {
registerEvents(); pm.registerEvents(new FluidFlowLogging(this), this);
consumer.start(); }
for (final Tool tool : toolsByType.values()) { if (isLogging(Logging.BLOCKBREAK)) {
if (pm.getPermission("logblock.tools." + tool.name) == null) { pm.registerEvents(new BlockBreakLogging(this), this);
final Permission perm = new Permission("logblock.tools." + tool.name, tool.permissionDefault); }
pm.addPermission(perm); if (isLogging(Logging.SIGNTEXT)) {
} pm.registerEvents(new SignChangeLogging(this), this);
} }
questioner = new Questioner(this); if (isLogging(Logging.FIRE)) {
if (worldGuardLoggingFlagsAddon != null) { pm.registerEvents(new BlockBurnLogging(this), this);
worldGuardLoggingFlagsAddon.onPluginEnable(); }
} if (isLogging(Logging.SNOWFORM)) {
isCompletelyEnabled = true; pm.registerEvents(new SnowFormLogging(this), this);
getServer().getScheduler().runTaskAsynchronously(this, new Updater.PlayerCountChecker(this)); }
} if (isLogging(Logging.SNOWFADE)) {
pm.registerEvents(new SnowFadeLogging(this), this);
private void registerEvents() { }
final PluginManager pm = getPluginManager(); if (isLogging(Logging.SCAFFOLDING)) {
pm.registerEvents(new ToolListener(this), this); pm.registerEvents(scaffoldingLogging = new ScaffoldingLogging(this), this);
pm.registerEvents(playerInfoLogging = new PlayerInfoLogging(this), this); }
if (askRollbackAfterBan) { if (isLogging(Logging.CREEPEREXPLOSION) || isLogging(Logging.TNTEXPLOSION) || isLogging(Logging.GHASTFIREBALLEXPLOSION) || isLogging(Logging.ENDERDRAGON) || isLogging(Logging.MISCEXPLOSION)) {
pm.registerEvents(new BanListener(this), this); pm.registerEvents(new ExplosionLogging(this), this);
} }
if (isLogging(Logging.BLOCKPLACE)) { if (isLogging(Logging.LEAVESDECAY)) {
pm.registerEvents(new BlockPlaceLogging(this), this); pm.registerEvents(new LeavesDecayLogging(this), this);
} }
if (isLogging(Logging.LAVAFLOW) || isLogging(Logging.WATERFLOW)) { if (isLogging(Logging.CHESTACCESS)) {
pm.registerEvents(new FluidFlowLogging(this), this); pm.registerEvents(new ChestAccessLogging(this), this);
} }
if (isLogging(Logging.BLOCKBREAK)) { if (isLogging(Logging.BLOCKBREAK) || isLogging(Logging.BLOCKPLACE) || isLogging(Logging.SWITCHINTERACT) || isLogging(Logging.DOORINTERACT) || isLogging(Logging.CAKEEAT) || isLogging(Logging.DIODEINTERACT) || isLogging(Logging.COMPARATORINTERACT) || isLogging(Logging.NOTEBLOCKINTERACT)
pm.registerEvents(new BlockBreakLogging(this), this); || isLogging(Logging.PRESUREPLATEINTERACT) || isLogging(Logging.TRIPWIREINTERACT) || isLogging(Logging.CROPTRAMPLE)) {
} pm.registerEvents(new InteractLogging(this), this);
if (isLogging(Logging.SIGNTEXT)) { }
pm.registerEvents(new SignChangeLogging(this), this); if (isLogging(Logging.CREATURECROPTRAMPLE)) {
} pm.registerEvents(new CreatureInteractLogging(this), this);
if (isLogging(Logging.FIRE)) { }
pm.registerEvents(new BlockBurnLogging(this), this); if (isLogging(Logging.KILL)) {
} pm.registerEvents(new KillLogging(this), this);
if (isLogging(Logging.SNOWFORM)) { }
pm.registerEvents(new SnowFormLogging(this), this); if (isLogging(Logging.CHAT) || isLogging(Logging.PLAYER_COMMANDS) || isLogging(Logging.CONSOLE_COMMANDS) || isLogging(Logging.COMMANDBLOCK_COMMANDS)) {
} pm.registerEvents(new ChatLogging(this), this);
if (isLogging(Logging.SNOWFADE)) { }
pm.registerEvents(new SnowFadeLogging(this), this); if (isLogging(Logging.ENDERMEN)) {
} pm.registerEvents(new EndermenLogging(this), this);
if (isLogging(Logging.SCAFFOLDING)) { }
pm.registerEvents(scaffoldingLogging = new ScaffoldingLogging(this), this); if (isLogging(Logging.WITHER)) {
} pm.registerEvents(new WitherLogging(this), this);
if (isLogging(Logging.CAULDRONINTERACT)) { }
pm.registerEvents(new CauldronLogging(this), this); if (isLogging(Logging.NATURALSTRUCTUREGROW) || isLogging(Logging.BONEMEALSTRUCTUREGROW)) {
} pm.registerEvents(new StructureGrowLogging(this), this);
if (isLogging(Logging.CREEPEREXPLOSION) || isLogging(Logging.TNTEXPLOSION) || isLogging(Logging.GHASTFIREBALLEXPLOSION) || isLogging(Logging.ENDERDRAGON) || isLogging(Logging.MISCEXPLOSION)) { }
pm.registerEvents(new ExplosionLogging(this), this); if (isLogging(Logging.GRASSGROWTH) || isLogging(Logging.MYCELIUMSPREAD) || isLogging(Logging.VINEGROWTH) || isLogging(Logging.MUSHROOMSPREAD)) {
} pm.registerEvents(new BlockSpreadLogging(this), this);
if (isLogging(Logging.LEAVESDECAY)) { }
pm.registerEvents(new LeavesDecayLogging(this), this); if (isLogging(Logging.DRAGONEGGTELEPORT)) {
} pm.registerEvents(new DragonEggLogging(this), this);
if (isLogging(Logging.CHESTACCESS)) { }
pm.registerEvents(new ChestAccessLogging(this), this); if (isLogging(Logging.LECTERNBOOKCHANGE)) {
} pm.registerEvents(new LecternLogging(this), this);
if (isLogging(Logging.BLOCKBREAK) || isLogging(Logging.BLOCKPLACE) || isLogging(Logging.SWITCHINTERACT) || isLogging(Logging.DOORINTERACT) || isLogging(Logging.CAKEEAT) || isLogging(Logging.DIODEINTERACT) || isLogging(Logging.COMPARATORINTERACT) || isLogging(Logging.NOTEBLOCKINTERACT) }
|| isLogging(Logging.PRESUREPLATEINTERACT) || isLogging(Logging.TRIPWIREINTERACT) || isLogging(Logging.CROPTRAMPLE)) { if (Config.isLoggingAnyEntities()) {
pm.registerEvents(new InteractLogging(this), this); if (!WorldEditHelper.hasFullWorldEdit()) {
} getLogger().severe("No compatible WorldEdit found, entity logging will not work!");
if (isLogging(Logging.CREATURECROPTRAMPLE)) { } else {
pm.registerEvents(new CreatureInteractLogging(this), this); pm.registerEvents(new AdvancedEntityLogging(this), this);
} getLogger().info("Entity logging enabled!");
if (isLogging(Logging.KILL)) { }
pm.registerEvents(new KillLogging(this), this); }
} }
if (isLogging(Logging.CHAT) || isLogging(Logging.PLAYER_COMMANDS) || isLogging(Logging.CONSOLE_COMMANDS) || isLogging(Logging.COMMANDBLOCK_COMMANDS)) {
pm.registerEvents(new ChatLogging(this), this); @Override
} public void onDisable() {
if (isLogging(Logging.ENDERMEN)) { isCompletelyEnabled = false;
pm.registerEvents(new EndermenLogging(this), this); getServer().getScheduler().cancelTasks(this);
} if (consumer != null) {
if (isLogging(Logging.WITHER)) { if (logPlayerInfo && playerInfoLogging != null) {
pm.registerEvents(new WitherLogging(this), this); for (final Player player : getServer().getOnlinePlayers()) {
} playerInfoLogging.onPlayerQuit(player);
if (isLogging(Logging.NATURALSTRUCTUREGROW)) { }
pm.registerEvents(new StructureGrowLogging(this), this); }
} getLogger().info("Waiting for consumer ...");
if (isLogging(Logging.BONEMEALSTRUCTUREGROW)) { consumer.shutdown();
pm.registerEvents(new BlockFertilizeLogging(this), this); if (consumer.getQueueSize() > 0) {
} getLogger().info("Remaining queue size: " + consumer.getQueueSize() + ". Trying to write to a local file.");
if (isLogging(Logging.GRASSGROWTH) || isLogging(Logging.MYCELIUMSPREAD) || isLogging(Logging.VINEGROWTH) || isLogging(Logging.MUSHROOMSPREAD) || isLogging(Logging.BAMBOOGROWTH) || isLogging(Logging.DRIPSTONEGROWTH) || isLogging(Logging.SCULKSPREAD)) { try {
pm.registerEvents(new BlockSpreadLogging(this), this); consumer.writeToFile();
} getLogger().info("Successfully dumped queue.");
if (isLogging(Logging.DRAGONEGGTELEPORT)) { } catch (final FileNotFoundException ex) {
pm.registerEvents(new DragonEggLogging(this), this); getLogger().info("Failed to write. Given up.");
} }
if (isLogging(Logging.LECTERNBOOKCHANGE)) { }
pm.registerEvents(new LecternLogging(this), this); }
} if (pool != null) {
if (isLogging(Logging.OXIDIZATION)) { pool.close();
pm.registerEvents(new OxidizationLogging(this), this); }
} }
if (Config.isLoggingAnyEntities()) {
if (!WorldEditHelper.hasFullWorldEdit()) { @Override
getLogger().severe("No compatible WorldEdit found, entity logging will not work!"); public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
} else { if (noDb) {
pm.registerEvents(new AdvancedEntityLogging(this), this); sender.sendMessage(ChatColor.RED + "No database connected. Check your MySQL user/pw and database for typos. Start/restart your MySQL server.");
getLogger().info("Entity logging enabled!"); }
} return true;
} }
}
public boolean hasPermission(CommandSender sender, String permission) {
@Override return sender.hasPermission(permission);
public void onDisable() { }
isCompletelyEnabled = false;
getServer().getScheduler().cancelTasks(this); public Connection getConnection() {
if (consumer != null) { return getConnection(false);
if (logPlayerInfo && playerInfoLogging != null) { }
for (final Player player : getServer().getOnlinePlayers()) {
playerInfoLogging.onPlayerQuit(player); public Connection getConnection(boolean testConnection) {
} try {
} final Connection conn = pool.getConnection();
getLogger().info("Waiting for consumer ..."); if (!connected) {
consumer.shutdown(); getLogger().info("MySQL connection rebuild");
if (consumer.getQueueSize() > 0) { connected = true;
getLogger().info("Remaining queue size: " + consumer.getQueueSize() + ". Trying to write to a local file."); }
try { return conn;
consumer.writeToFile(); } catch (final Exception ex) {
getLogger().info("Successfully dumped queue."); if (testConnection) {
} catch (final FileNotFoundException ex) { getLogger().log(Level.SEVERE, "Could not connect to the Database! Please check your config! " + ex.getMessage());
getLogger().info("Failed to write. Given up."); } else if (connected) {
} getLogger().log(Level.SEVERE, "Error while fetching connection: ", ex);
} connected = false;
} } else {
if (pool != null) { getLogger().log(Level.SEVERE, "MySQL connection lost", ex);
pool.close(); }
} return null;
} }
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { /**
if (noDb) { * Returns a list of block changes based on the given query parameters, the query parameters
sender.sendMessage(ChatColor.RED + "No database connected. Check your MySQL user/pw and database for typos. Start/restart your MySQL server."); * are essentially programmatic versions of the parameters a player would pass
} * to the logblock lookup command i.e /lb lookup <i>query-parameters</i>
return true; *
} * Note: this method directly calls a SQL query and is hence a slow blocking function, avoid running
* it on the main game thread
public boolean hasPermission(CommandSender sender, String permission) { *
return sender.hasPermission(permission); * @param params QueryParams that contains the needed columns (all other will be filled with default values) and the params. World is required.
} * @return Returns a list of block changes based on the given query parameters
* @throws SQLException if a sql exception occurs while looking up the block changes
public Connection getConnection() { */
return getConnection(false); public List<BlockChange> getBlockChanges(QueryParams params) throws SQLException {
} final Connection conn = getConnection();
Statement state = null;
public Connection getConnection(boolean testConnection) { if (conn == null) {
try { throw new SQLException("No connection");
final Connection conn = pool.getConnection(); }
if (!connected) { try {
getLogger().info("MySQL connection rebuild"); state = conn.createStatement();
connected = true; final ResultSet rs = state.executeQuery(params.getQuery());
} final List<BlockChange> blockchanges = new ArrayList<>();
return conn; while (rs.next()) {
} catch (final Exception ex) { blockchanges.add(new BlockChange(rs, params));
if (testConnection) { }
getLogger().log(Level.SEVERE, "Could not connect to the Database! Please check your config! " + ex.getMessage()); return blockchanges;
} else if (connected) { } finally {
getLogger().log(Level.SEVERE, "Error while fetching connection: ", ex); if (state != null) {
connected = false; state.close();
} else { }
getLogger().log(Level.SEVERE, "MySQL connection lost", ex); conn.close();
} }
return null; }
}
} public int getCount(QueryParams params) throws SQLException {
if (params == null || params.world == null || !Config.isLogged(params.world)) {
/** throw new IllegalArgumentException("World is not logged: " + ((params == null || params.world == null) ? "null" : params.world.getName()));
* Returns a list of block changes based on the given query parameters, the query parameters }
* are essentially programmatic versions of the parameters a player would pass final Connection conn = getConnection();
* to the logblock lookup command i.e /lb lookup <i>query-parameters</i> Statement state = null;
* if (conn == null) {
* Note: this method directly calls a SQL query and is hence a slow blocking function, avoid running throw new SQLException("No connection");
* it on the main game thread }
* try {
* @param params QueryParams that contains the needed columns (all other will be filled with default values) and the params. World is required. state = conn.createStatement();
* @return Returns a list of block changes based on the given query parameters final QueryParams p = params.clone();
* @throws SQLException if a sql exception occurs while looking up the block changes p.needCount = true;
*/ final ResultSet rs = state.executeQuery(p.getQuery());
public List<BlockChange> getBlockChanges(QueryParams params) throws SQLException { if (!rs.next()) {
final Connection conn = getConnection(); return 0;
Statement state = null; }
if (conn == null) { return rs.getInt(1);
throw new SQLException("No connection"); } finally {
} if (state != null) {
try { state.close();
state = conn.createStatement(); }
final ResultSet rs = state.executeQuery(params.getQuery()); conn.close();
final List<BlockChange> blockchanges = new ArrayList<>(); }
while (rs.next()) { }
blockchanges.add(new BlockChange(rs, params));
} @Override
return blockchanges; public File getFile() {
} finally { return super.getFile();
if (state != null) { }
state.close();
} public Questioner getQuestioner() {
conn.close(); return questioner;
} }
}
public ScaffoldingLogging getScaffoldingLogging() {
public int getCount(QueryParams params) throws SQLException { return scaffoldingLogging;
if (params == null || params.world == null || !Config.isLogged(params.world)) { }
throw new IllegalArgumentException("World is not logged: " + ((params == null || params.world == null) ? "null" : params.world.getName())); }
}
final Connection conn = getConnection();
Statement state = null;
if (conn == null) {
throw new SQLException("No connection");
}
try {
state = conn.createStatement();
final QueryParams p = params.clone();
p.needCount = true;
final ResultSet rs = state.executeQuery(p.getQuery());
if (!rs.next()) {
return 0;
}
return rs.getInt(1);
} finally {
if (state != null) {
state.close();
}
conn.close();
}
}
@Override
public File getFile() {
return super.getFile();
}
public Questioner getQuestioner() {
return questioner;
}
public ScaffoldingLogging getScaffoldingLogging() {
return scaffoldingLogging;
}
}

View File

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

View File

@ -1,18 +1,18 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.BaseComponent;
import org.bukkit.Location; import org.bukkit.Location;
public interface LookupCacheElement { public interface LookupCacheElement {
public Location getLocation(); public Location getLocation();
public default BaseComponent[] getLogMessage() { public default BaseComponent[] getLogMessage() {
return getLogMessage(-1); return getLogMessage(-1);
} }
public BaseComponent[] getLogMessage(int entry); public BaseComponent[] getLogMessage(int entry);
public default int getNumChanges() { public default int getNumChanges() {
return 1; return 1;
} }
} }

View File

@ -1,40 +1,40 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import de.diddiz.LogBlock.QueryParams.BlockChangeType; import de.diddiz.LogBlock.QueryParams.BlockChangeType;
import de.diddiz.LogBlock.QueryParams.SummarizationMode; import de.diddiz.LogBlock.QueryParams.SummarizationMode;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class LookupCacheElementFactory { public class LookupCacheElementFactory {
private final QueryParams params; private final QueryParams params;
private final float spaceFactor; private final float spaceFactor;
public LookupCacheElementFactory(QueryParams params, float spaceFactor) { public LookupCacheElementFactory(QueryParams params, float spaceFactor) {
this.params = params; this.params = params;
this.spaceFactor = spaceFactor; this.spaceFactor = spaceFactor;
} }
public LookupCacheElement getLookupCacheElement(ResultSet rs) throws SQLException { public LookupCacheElement getLookupCacheElement(ResultSet rs) throws SQLException {
if (params.bct == BlockChangeType.CHAT) { if (params.bct == BlockChangeType.CHAT) {
return new ChatMessage(rs, params); return new ChatMessage(rs, params);
} }
if (params.bct == BlockChangeType.KILLS) { if (params.bct == BlockChangeType.KILLS) {
if (params.sum == SummarizationMode.NONE) { if (params.sum == SummarizationMode.NONE) {
return new Kill(rs, params); return new Kill(rs, params);
} else if (params.sum == SummarizationMode.PLAYERS) { } else if (params.sum == SummarizationMode.PLAYERS) {
return new SummedKills(rs, params, spaceFactor); return new SummedKills(rs, params, spaceFactor);
} }
} }
if (params.bct == BlockChangeType.ENTITIES || params.bct == BlockChangeType.ENTITIES_CREATED || params.bct == BlockChangeType.ENTITIES_KILLED) { if (params.bct == BlockChangeType.ENTITIES || params.bct == BlockChangeType.ENTITIES_CREATED || params.bct == BlockChangeType.ENTITIES_KILLED) {
if (params.sum == SummarizationMode.NONE) { if (params.sum == SummarizationMode.NONE) {
return new EntityChange(rs, params); return new EntityChange(rs, params);
} }
return new SummedEntityChanges(rs, params, spaceFactor); return new SummedEntityChanges(rs, params, spaceFactor);
} }
if (params.sum == SummarizationMode.NONE) { if (params.sum == SummarizationMode.NONE) {
return new BlockChange(rs, params); return new BlockChange(rs, params);
} }
return new SummedBlockChanges(rs, params, spaceFactor); return new SummedBlockChanges(rs, params, spaceFactor);
} }
} }

View File

@ -1,11 +1,11 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import de.diddiz.LogBlock.config.Config; import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.util.BukkitUtils; import de.diddiz.util.BukkitUtils;
import de.diddiz.LogBlock.util.CuboidRegion; import de.diddiz.util.CuboidRegion;
import de.diddiz.LogBlock.util.SqlUtil; import de.diddiz.util.SqlUtil;
import de.diddiz.LogBlock.util.Utils; import de.diddiz.util.Utils;
import de.diddiz.LogBlock.worldedit.WorldEditHelper; import de.diddiz.worldedit.WorldEditHelper;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.NamespacedKey; 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.Session.getSession;
import static de.diddiz.LogBlock.config.Config.*; import static de.diddiz.LogBlock.config.Config.*;
import static de.diddiz.LogBlock.util.BukkitUtils.friendlyWorldname; import static de.diddiz.util.BukkitUtils.friendlyWorldname;
import static de.diddiz.LogBlock.util.Utils.*; import static de.diddiz.util.Utils.*;
public final class QueryParams implements Cloneable { public final class QueryParams implements Cloneable {
private static final HashMap<String, Integer> keywords = new HashMap<>(); private static final HashMap<String, Integer> keywords = new HashMap<>();
@ -857,9 +857,6 @@ public final class QueryParams implements Cloneable {
if (values[0].startsWith("p")) { if (values[0].startsWith("p")) {
sum = SummarizationMode.PLAYERS; sum = SummarizationMode.PLAYERS;
} else if (values[0].startsWith("b") || values[0].startsWith("e")) { } else if (values[0].startsWith("b") || values[0].startsWith("e")) {
if (values[0].startsWith("e")) {
bct = BlockChangeType.ENTITIES;
}
sum = SummarizationMode.TYPES; sum = SummarizationMode.TYPES;
} else if (values[0].startsWith("n")) { } else if (values[0].startsWith("n")) {
sum = SummarizationMode.NONE; sum = SummarizationMode.NONE;

View File

@ -1,49 +1,49 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static de.diddiz.LogBlock.config.Config.toolsByType; import static de.diddiz.LogBlock.config.Config.toolsByType;
import static org.bukkit.Bukkit.getServer; import static org.bukkit.Bukkit.getServer;
public class Session { public class Session {
private static final Map<String, Session> sessions = new HashMap<>(); private static final Map<String, Session> sessions = new HashMap<>();
public QueryParams lastQuery = null; public QueryParams lastQuery = null;
public LookupCacheElement[] lookupCache = null; public LookupCacheElement[] lookupCache = null;
public int page = 1; public int page = 1;
public Map<Tool, ToolData> toolData; public Map<Tool, ToolData> toolData;
private Session(Player player) { private Session(Player player) {
toolData = new HashMap<>(); toolData = new HashMap<>();
final LogBlock logblock = LogBlock.getInstance(); final LogBlock logblock = LogBlock.getInstance();
if (player != null) { if (player != null) {
for (final Tool tool : toolsByType.values()) { for (final Tool tool : toolsByType.values()) {
toolData.put(tool, new ToolData(tool, logblock, player)); toolData.put(tool, new ToolData(tool, logblock, player));
} }
} }
} }
public static boolean hasSession(CommandSender sender) { public static boolean hasSession(CommandSender sender) {
return sessions.containsKey(sender.getName().toLowerCase()); return sessions.containsKey(sender.getName().toLowerCase());
} }
public static boolean hasSession(String playerName) { public static boolean hasSession(String playerName) {
return sessions.containsKey(playerName.toLowerCase()); return sessions.containsKey(playerName.toLowerCase());
} }
public static Session getSession(CommandSender sender) { public static Session getSession(CommandSender sender) {
return getSession(sender.getName()); return getSession(sender.getName());
} }
public static Session getSession(String playerName) { public static Session getSession(String playerName) {
Session session = sessions.get(playerName.toLowerCase()); Session session = sessions.get(playerName.toLowerCase());
if (session == null) { if (session == null) {
session = new Session(getServer().getPlayer(playerName)); session = new Session(getServer().getPlayer(playerName));
sessions.put(playerName.toLowerCase(), session); sessions.put(playerName.toLowerCase(), session);
} }
return session; return session;
} }
} }

View File

@ -1,43 +1,42 @@
package de.diddiz.LogBlock; 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.QueryParams.SummarizationMode; import de.diddiz.util.MessagingUtil;
import de.diddiz.LogBlock.util.MessagingUtil; import java.sql.ResultSet;
import java.sql.ResultSet; import java.sql.SQLException;
import java.sql.SQLException; import java.util.Objects;
import java.util.Objects; import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.Location;
import org.bukkit.Location;
public class SummedBlockChanges implements LookupCacheElement {
public class SummedBlockChanges implements LookupCacheElement { private final int type;
private final int type; private final int created, destroyed;
private final int created, destroyed; private final float spaceFactor;
private final float spaceFactor; private final Actor actor;
private final Actor actor;
public SummedBlockChanges(ResultSet rs, QueryParams p, float spaceFactor) throws SQLException {
public SummedBlockChanges(ResultSet rs, QueryParams p, float spaceFactor) throws SQLException { // Actor currently useless here as we don't yet output UUID in results anywhere
// Actor currently useless here as we don't yet output UUID in results anywhere actor = p.sum == SummarizationMode.PLAYERS ? new Actor(rs) : null;
actor = p.sum == SummarizationMode.PLAYERS ? new Actor(rs) : null; type = p.sum == SummarizationMode.TYPES ? rs.getInt("type") : 0;
type = p.sum == SummarizationMode.TYPES ? rs.getInt("type") : 0; created = rs.getInt("created");
created = rs.getInt("created"); destroyed = rs.getInt("destroyed");
destroyed = rs.getInt("destroyed"); this.spaceFactor = spaceFactor;
this.spaceFactor = spaceFactor; }
}
@Override
@Override public Location getLocation() {
public Location getLocation() { return null;
return null; }
}
@Override
@Override public BaseComponent[] getLogMessage(int entry) {
public BaseComponent[] getLogMessage(int entry) { return MessagingUtil.formatSummarizedChanges(created, destroyed, actor != null ? new TextComponent(actor.getName()) : prettyMaterial(Objects.toString(MaterialConverter.getMaterial(type))), 10, 10, spaceFactor);
return MessagingUtil.formatSummarizedChanges(created, destroyed, actor != null ? new TextComponent(actor.getName()) : prettyMaterial(Objects.toString(MaterialConverter.getMaterial(type))), 10, 10, spaceFactor); }
}
@Override
@Override public int getNumChanges() {
public int getNumChanges() { return created + destroyed;
return created + destroyed; }
} }
}

View File

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

View File

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

View File

@ -1,35 +1,35 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.permissions.PermissionDefault; import org.bukkit.permissions.PermissionDefault;
import java.util.List; import java.util.List;
public class Tool { public class Tool {
public final String name; public final String name;
public final List<String> aliases; public final List<String> aliases;
public final ToolBehavior leftClickBehavior, rightClickBehavior; public final ToolBehavior leftClickBehavior, rightClickBehavior;
public final boolean defaultEnabled; public final boolean defaultEnabled;
public final Material item; public final Material item;
public final boolean canDrop; public final boolean canDrop;
public final QueryParams params; public final QueryParams params;
public final ToolMode mode; public final ToolMode mode;
public final PermissionDefault permissionDefault; public final PermissionDefault permissionDefault;
public final boolean removeOnDisable; public final boolean removeOnDisable;
public final boolean dropToDisable; public final boolean dropToDisable;
public Tool(String name, List<String> aliases, ToolBehavior leftClickBehavior, ToolBehavior rightClickBehavior, boolean defaultEnabled, Material item, boolean canDrop, QueryParams params, ToolMode mode, PermissionDefault permissionDefault, boolean removeOnDisable, boolean dropToDisable) { public Tool(String name, List<String> aliases, ToolBehavior leftClickBehavior, ToolBehavior rightClickBehavior, boolean defaultEnabled, Material item, boolean canDrop, QueryParams params, ToolMode mode, PermissionDefault permissionDefault, boolean removeOnDisable, boolean dropToDisable) {
this.name = name; this.name = name;
this.aliases = aliases; this.aliases = aliases;
this.leftClickBehavior = leftClickBehavior; this.leftClickBehavior = leftClickBehavior;
this.rightClickBehavior = rightClickBehavior; this.rightClickBehavior = rightClickBehavior;
this.defaultEnabled = defaultEnabled; this.defaultEnabled = defaultEnabled;
this.item = item; this.item = item;
this.canDrop = canDrop; this.canDrop = canDrop;
this.params = params; this.params = params;
this.mode = mode; this.mode = mode;
this.permissionDefault = permissionDefault; this.permissionDefault = permissionDefault;
this.removeOnDisable = removeOnDisable; this.removeOnDisable = removeOnDisable;
this.dropToDisable = dropToDisable; this.dropToDisable = dropToDisable;
} }
} }

View File

@ -1,7 +1,7 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
public enum ToolBehavior { public enum ToolBehavior {
TOOL, TOOL,
BLOCK, BLOCK,
NONE NONE
} }

View File

@ -1,15 +1,15 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
public class ToolData { public class ToolData {
public boolean enabled; public boolean enabled;
public QueryParams params; public QueryParams params;
public ToolMode mode; public ToolMode mode;
public ToolData(Tool tool, LogBlock logblock, Player player) { public ToolData(Tool tool, LogBlock logblock, Player player) {
enabled = tool.defaultEnabled && logblock.hasPermission(player, "logblock.tools." + tool.name); enabled = tool.defaultEnabled && logblock.hasPermission(player, "logblock.tools." + tool.name);
params = tool.params.clone(); params = tool.params.clone();
mode = tool.mode; mode = tool.mode;
} }
} }

View File

@ -1,18 +1,18 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
public enum ToolMode { public enum ToolMode {
CLEARLOG("logblock.clearlog"), CLEARLOG("logblock.clearlog"),
LOOKUP("logblock.lookup"), LOOKUP("logblock.lookup"),
REDO("logblock.rollback"), REDO("logblock.rollback"),
ROLLBACK("logblock.rollback"), ROLLBACK("logblock.rollback"),
WRITELOGFILE("logblock.rollback"); WRITELOGFILE("logblock.rollback");
private final String permission; private final String permission;
private ToolMode(String permission) { private ToolMode(String permission) {
this.permission = permission; this.permission = permission;
} }
public String getPermission() { public String getPermission() {
return permission; return permission;
} }
} }

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -6,7 +6,7 @@ import java.sql.SQLException;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import de.diddiz.LogBlock.QueryParams.BlockChangeType; import de.diddiz.LogBlock.QueryParams.BlockChangeType;
import de.diddiz.LogBlock.util.Utils; import de.diddiz.util.Utils;
public class WorldEditorEditFactory { public class WorldEditorEditFactory {
private final WorldEditor editor; 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; package de.diddiz.LogBlock.blockstate;
import net.md_5.bungee.api.chat.BaseComponent;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
@ -12,5 +11,5 @@ public interface BlockStateCodec {
void deserialize(BlockState state, YamlConfiguration conf); 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; package de.diddiz.LogBlock.blockstate;
import java.util.List; import java.util.List;
import net.md_5.bungee.api.chat.BaseComponent;
import org.bukkit.DyeColor; import org.bukkit.DyeColor;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Banner; import org.bukkit.block.Banner;
@ -64,7 +64,7 @@ public class BlockStateCodecBanner implements BlockStateCodec {
} }
@Override @Override
public BaseComponent getChangesAsComponent(YamlConfiguration conf, YamlConfiguration oldState) { public String toString(YamlConfiguration conf) {
return null; return null;
} }
} }

View File

@ -1,7 +1,5 @@
package de.diddiz.LogBlock.blockstate; 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.Material;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.block.Lectern; import org.bukkit.block.Lectern;
@ -45,10 +43,12 @@ public class BlockStateCodecLectern implements BlockStateCodec {
} }
@Override @Override
public BaseComponent getChangesAsComponent(YamlConfiguration conf, YamlConfiguration oldState) { public String toString(YamlConfiguration conf) {
if (conf != null) { 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.Logging;
import de.diddiz.LogBlock.config.WorldConfig; import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.LogBlock.util.BukkitUtils; import de.diddiz.util.BukkitUtils;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.block.ShulkerBox; import org.bukkit.block.ShulkerBox;
@ -16,7 +14,7 @@ import org.bukkit.inventory.ItemStack;
public class BlockStateCodecShulkerBox implements BlockStateCodec { public class BlockStateCodecShulkerBox implements BlockStateCodec {
@Override @Override
public Material[] getApplicableMaterials() { public Material[] getApplicableMaterials() {
return BukkitUtils.getShulkerBoxBlocks().toArray(Material[]::new); return BukkitUtils.getShulkerBoxBlocks().toArray(new Material[BukkitUtils.getShulkerBoxBlocks().size()]);
} }
@Override @Override
@ -62,7 +60,7 @@ public class BlockStateCodecShulkerBox implements BlockStateCodec {
} }
@Override @Override
public BaseComponent getChangesAsComponent(YamlConfiguration conf, YamlConfiguration oldState) { public String toString(YamlConfiguration conf) {
if (conf != null) { if (conf != null) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("["); sb.append("[");
@ -80,7 +78,7 @@ public class BlockStateCodecShulkerBox implements BlockStateCodec {
} }
} }
sb.append("]"); sb.append("]");
return anySlot ? new TextComponent(sb.toString()) : null; return anySlot ? sb.toString() : null;
} }
return null; return null;
} }

View File

@ -1,88 +1,57 @@
package de.diddiz.LogBlock.blockstate; package de.diddiz.LogBlock.blockstate;
import de.diddiz.LogBlock.util.BukkitUtils; import de.diddiz.util.BukkitUtils;
import java.awt.Color;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; 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.DyeColor;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.block.Sign; 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; import org.bukkit.configuration.file.YamlConfiguration;
public class BlockStateCodecSign implements BlockStateCodec { public class BlockStateCodecSign implements BlockStateCodec {
@Override @Override
public Material[] getApplicableMaterials() { public Material[] getApplicableMaterials() {
return BukkitUtils.getAllSignMaterials().toArray(Material[]::new); return BukkitUtils.getAllSignsArray();
} }
@Override @Override
public YamlConfiguration serialize(BlockState state) { public YamlConfiguration serialize(BlockState state) {
YamlConfiguration conf = null; if (state instanceof Sign) {
if (state instanceof Sign sign) { Sign sign = (Sign) state;
boolean waxed = sign.isWaxed(); String[] lines = sign.getLines();
if (waxed) { boolean hasText = false;
conf = new YamlConfiguration(); for (int i = 0; i < lines.length; i++) {
conf.set("waxed", waxed); if (lines[i] != null && lines[i].length() > 0) {
hasText = true;
break;
}
} }
for (Side side : Side.values()) { DyeColor signColor = sign.getColor();
SignSide signSide = sign.getSide(side); if (signColor == null) {
String[] lines = signSide.getLines(); signColor = DyeColor.BLACK;
boolean hasText = false; }
for (int i = 0; i < lines.length; i++) { if (hasText || signColor != DyeColor.BLACK) {
if (lines[i] != null && lines[i].length() > 0) { YamlConfiguration conf = new YamlConfiguration();
hasText = true; if (hasText) {
break; conf.set("lines", Arrays.asList(lines));
}
} }
DyeColor signColor = signSide.getColor(); if (signColor != DyeColor.BLACK) {
if (signColor == null) { conf.set("color", signColor.name());
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);
}
} }
return conf;
} }
} }
return conf; return null;
} }
/** /**
* This is required for the SignChangeEvent, because we have no updated BlockState there. * This is required for the SignChangeEvent, because we have no BlockState there.
* @param state
*/ */
public YamlConfiguration serialize(BlockState state, Side side, String[] lines) { public static YamlConfiguration serialize(String[] lines) {
YamlConfiguration conf = state == null ? null : serialize(state); YamlConfiguration conf = new YamlConfiguration();
if (lines != null) { conf.set("lines", Arrays.asList(lines));
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));
}
return conf; return conf;
} }
@ -90,138 +59,40 @@ public class BlockStateCodecSign implements BlockStateCodec {
public void deserialize(BlockState state, YamlConfiguration conf) { public void deserialize(BlockState state, YamlConfiguration conf) {
if (state instanceof Sign) { if (state instanceof Sign) {
Sign sign = (Sign) state; Sign sign = (Sign) state;
DyeColor signColor = DyeColor.BLACK;
List<String> lines = Collections.emptyList();
if (conf != null) { if (conf != null) {
sign.setWaxed(conf.getBoolean("waxed")); if (conf.contains("lines")) {
for (Side side : Side.values()) { lines = conf.getStringList("lines");
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);
} }
} else { if (conf.contains("color")) {
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")) {
try { try {
signColor = DyeColor.valueOf(sideSection.getString("color")); signColor = DyeColor.valueOf(conf.getString("color"));
} catch (IllegalArgumentException | NullPointerException e) { } catch (IllegalArgumentException | NullPointerException e) {
// ignored // 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; 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; package de.diddiz.LogBlock.blockstate;
import java.util.UUID; 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.Bukkit;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.block.Skull; import org.bukkit.block.Skull;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.profile.PlayerProfile;
public class BlockStateCodecSkull implements BlockStateCodec { 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 @Override
public Material[] getApplicableMaterials() { public Material[] getApplicableMaterials() {
return new Material[] { Material.PLAYER_WALL_HEAD, Material.PLAYER_HEAD }; return new Material[] { Material.PLAYER_WALL_HEAD, Material.PLAYER_HEAD };
@ -35,14 +20,9 @@ public class BlockStateCodecSkull implements BlockStateCodec {
if (state instanceof Skull) { if (state instanceof Skull) {
Skull skull = (Skull) state; Skull skull = (Skull) state;
OfflinePlayer owner = skull.hasOwner() ? skull.getOwningPlayer() : null; OfflinePlayer owner = skull.hasOwner() ? skull.getOwningPlayer() : null;
PlayerProfile profile = HAS_PROFILE_API ? skull.getOwnerProfile() : null; if (owner != null) {
if (owner != null || profile != null) {
YamlConfiguration conf = new YamlConfiguration(); YamlConfiguration conf = new YamlConfiguration();
if (profile != null) { conf.set("owner", owner.getUniqueId().toString());
conf.set("profile", profile);
} else if (owner != null) {
conf.set("owner", owner.getUniqueId().toString());
}
return conf; return conf;
} }
} }
@ -53,37 +33,21 @@ public class BlockStateCodecSkull implements BlockStateCodec {
public void deserialize(BlockState state, YamlConfiguration conf) { public void deserialize(BlockState state, YamlConfiguration conf) {
if (state instanceof Skull) { if (state instanceof Skull) {
Skull skull = (Skull) state; Skull skull = (Skull) state;
PlayerProfile profile = conf == null || !HAS_PROFILE_API ? null : (PlayerProfile) conf.get("profile"); UUID ownerId = conf == null ? null : UUID.fromString(conf.getString("owner"));
if (profile != null) { if (ownerId == null) {
skull.setOwnerProfile(profile); skull.setOwningPlayer(null);
} else { } else {
UUID ownerId = conf == null ? null : UUID.fromString(conf.getString("owner")); skull.setOwningPlayer(Bukkit.getOfflinePlayer(ownerId));
if (ownerId == null) {
skull.setOwningPlayer(null);
} else {
skull.setOwningPlayer(Bukkit.getOfflinePlayer(ownerId));
}
} }
} }
} }
@Override @Override
public BaseComponent getChangesAsComponent(YamlConfiguration conf, YamlConfiguration oldState) { public String toString(YamlConfiguration conf) {
if (HAS_PROFILE_API && conf != null) { UUID ownerId = conf == null ? null : UUID.fromString(conf.getString("owner"));
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);
if (ownerId != null) { if (ownerId != null) {
OfflinePlayer owner = Bukkit.getOfflinePlayer(ownerId); 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; return null;
} }

View File

@ -1,8 +1,5 @@
package de.diddiz.LogBlock.blockstate; 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.Material;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.block.CreatureSpawner; import org.bukkit.block.CreatureSpawner;
@ -26,9 +23,7 @@ public class BlockStateCodecSpawner implements BlockStateCodec {
conf.set("minSpawnDelay", spawner.getMinSpawnDelay()); conf.set("minSpawnDelay", spawner.getMinSpawnDelay());
conf.set("requiredPlayerRange", spawner.getRequiredPlayerRange()); conf.set("requiredPlayerRange", spawner.getRequiredPlayerRange());
conf.set("spawnCount", spawner.getSpawnCount()); 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()); conf.set("spawnRange", spawner.getSpawnRange());
return conf; return conf;
} }
@ -46,27 +41,18 @@ public class BlockStateCodecSpawner implements BlockStateCodec {
spawner.setMinSpawnDelay(conf.getInt("minSpawnDelay")); spawner.setMinSpawnDelay(conf.getInt("minSpawnDelay"));
spawner.setRequiredPlayerRange(conf.getInt("requiredPlayerRange")); spawner.setRequiredPlayerRange(conf.getInt("requiredPlayerRange"));
spawner.setSpawnCount(conf.getInt("spawnCount")); spawner.setSpawnCount(conf.getInt("spawnCount"));
EntityType spawnedType = null; spawner.setSpawnedType(EntityType.valueOf(conf.getString("spawnedType")));
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.setSpawnRange(conf.getInt("spawnRange")); spawner.setSpawnRange(conf.getInt("spawnRange"));
} }
} }
} }
@Override @Override
public BaseComponent getChangesAsComponent(YamlConfiguration conf, YamlConfiguration oldState) { public String toString(YamlConfiguration conf) {
if (conf != null) { if (conf != null) {
EntityType entity = EntityType.valueOf(conf.getString("spawnedType")); EntityType entity = EntityType.valueOf(conf.getString("spawnedType"));
if (entity != null) { if (entity != null) {
return new TextComponent("[" + entity.getKey().getKey() + "]"); return "[" + entity + "]";
} }
} }
return null; return null;

View File

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

View File

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

View File

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

View File

@ -1,171 +1,147 @@
package de.diddiz.LogBlock.config; package de.diddiz.LogBlock.config;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; 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.configuration.file.YamlConfiguration;
import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Animals;
import org.bukkit.entity.Entity; import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.EntityType; import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity; import org.bukkit.entity.EntityType;
import org.bukkit.entity.Monster; import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player; import org.bukkit.entity.Monster;
import org.bukkit.entity.WaterMob; import org.bukkit.entity.Player;
import org.bukkit.entity.WaterMob;
import java.io.File;
import java.io.IOException; import java.io.File;
import java.util.EnumMap; import java.io.IOException;
import java.util.HashMap; import java.util.EnumMap;
import java.util.HashSet; import java.util.EnumSet;
import java.util.List; import java.util.HashMap;
import java.util.Map; import java.util.List;
import java.util.Map.Entry; import java.util.Map;
import java.util.logging.Level; import java.util.Map.Entry;
import java.util.logging.Level;
public class WorldConfig extends LoggingEnabledMapping {
public final String world; public class WorldConfig extends LoggingEnabledMapping {
public final String table; public final String world;
public final String insertBlockStatementString; public final String table;
public final String selectBlockActorIdStatementString; public final String insertBlockStatementString;
public final String insertBlockStateStatementString; public final String selectBlockActorIdStatementString;
public final String insertBlockChestDataStatementString; public final String insertBlockStateStatementString;
public final String insertEntityStatementString; public final String insertBlockChestDataStatementString;
public final String updateEntityUUIDString; public final String insertEntityStatementString;
public final String updateEntityUUIDString;
private final EnumMap<EntityLogging, EntityLoggingList> entityLogging = new EnumMap<>(EntityLogging.class);
public final boolean logNaturalEntitySpawns; private final EnumMap<EntityLogging, EntityLoggingList> entityLogging = new EnumMap<>(EntityLogging.class);
public final boolean logAllNamedEntityKills;
public WorldConfig(String world, File file) throws IOException {
public WorldConfig(String world, File file) throws IOException { this.world = world;
this.world = world; final Map<String, Object> def = new HashMap<>();
final Map<String, Object> def = new HashMap<>(); // "Before MySQL 5.1.6, database and table names cannot contain "/", "\", ".", or characters that are not permitted in file names" - MySQL manual
// "Before MySQL 5.1.6, database and table names cannot contain "/", "\", ".", or characters that are not permitted in file names" - MySQL manual // They _can_ contain spaces, but replace them as well
// They _can_ contain spaces, but replace them as well def.put("table", "lb-" + file.getName().substring(0, file.getName().length() - 4).replaceAll("[ ./\\\\]", "_"));
def.put("table", "lb-" + file.getName().substring(0, file.getName().length() - 4).replaceAll("[ ./\\\\]", "_")); for (final Logging l : Logging.values()) {
for (final Logging l : Logging.values()) { def.put("logging." + l.toString(), l.isDefaultEnabled());
def.put("logging." + l.toString(), l.isDefaultEnabled()); }
} final YamlConfiguration config = YamlConfiguration.loadConfiguration(file);
final YamlConfiguration config = YamlConfiguration.loadConfiguration(file); for (final Entry<String, Object> e : def.entrySet()) {
for (final Entry<String, Object> e : def.entrySet()) { if (config.get(e.getKey()) == null) {
if (config.get(e.getKey()) == null) { config.set(e.getKey(), e.getValue());
config.set(e.getKey(), e.getValue()); }
} }
} for (EntityLogging el : EntityLogging.values()) {
for (EntityLogging el : EntityLogging.values()) { if (!(config.get("entity." + el.name().toLowerCase()) instanceof List)) {
if (!(config.get("entity." + el.name().toLowerCase()) instanceof List)) { config.set("entity." + el.name().toLowerCase(), el.getDefaultEnabled());
config.set("entity." + el.name().toLowerCase(), el.getDefaultEnabled()); }
} entityLogging.put(el, new EntityLoggingList(config.getStringList("entity." + el.name().toLowerCase())));
entityLogging.put(el, new EntityLoggingList(el, config.getStringList("entity." + el.name().toLowerCase()))); }
} config.save(file);
if (!config.isBoolean("entity.logNaturalSpawns")) { table = config.getString("table");
config.set("entity.logNaturalSpawns", false); for (final Logging l : Logging.values()) {
} setLogging(l, config.getBoolean("logging." + l.toString()));
logNaturalEntitySpawns = config.getBoolean("entity.logNaturalSpawns"); }
if (!config.isBoolean("entity.logAllNamedEntityKills")) { insertBlockStatementString = "INSERT INTO `" + table + "-blocks` (date, playerid, replaced, replaceddata, type, typedata, x, y, z) VALUES (FROM_UNIXTIME(?), ?, ?, ?, ?, ?, ?, ?, ?)";
config.set("entity.logAllNamedEntityKills", true); selectBlockActorIdStatementString = "SELECT playerid FROM `" + table + "-blocks` WHERE x = ? AND y = ? AND z = ? ORDER BY date DESC LIMIT 1";
} insertBlockStateStatementString = "INSERT INTO `" + table + "-state` (replacedState, typeState, id) VALUES(?, ?, ?)";
logAllNamedEntityKills = config.getBoolean("entity.logAllNamedEntityKills"); insertBlockChestDataStatementString = "INSERT INTO `" + table + "-chestdata` (item, itemremove, id, itemtype) values (?, ?, ?, ?)";
insertEntityStatementString = "INSERT INTO `" + table + "-entities` (date, playerid, entityid, entitytypeid, x, y, z, action, data) VALUES (FROM_UNIXTIME(?), ?, ?, ?, ?, ?, ?, ?, ?)";
config.save(file); updateEntityUUIDString = "UPDATE `" + table + "-entityids` SET entityuuid = ? WHERE entityid = ?";
table = config.getString("table"); }
for (final Logging l : Logging.values()) {
setLogging(l, config.getBoolean("logging." + l.toString())); public boolean isLogging(EntityLogging logging, Entity entity) {
} return entityLogging.get(logging).isLogging(entity);
}
insertBlockStatementString = "INSERT INTO `" + table + "-blocks` (date, playerid, replaced, replaceddata, type, typedata, x, y, z) VALUES (FROM_UNIXTIME(?), ?, ?, ?, ?, ?, ?, ?, ?)";
selectBlockActorIdStatementString = "SELECT playerid FROM `" + table + "-blocks` WHERE x = ? AND y = ? AND z = ? ORDER BY date DESC LIMIT 1"; public boolean isLoggingAnyEntities() {
insertBlockStateStatementString = "INSERT INTO `" + table + "-state` (replacedState, typeState, id) VALUES(?, ?, ?)"; for (EntityLoggingList list : entityLogging.values()) {
insertBlockChestDataStatementString = "INSERT INTO `" + table + "-chestdata` (item, itemremove, id, itemtype) values (?, ?, ?, ?)"; if (list.isLoggingAnyEntities()) {
insertEntityStatementString = "INSERT INTO `" + table + "-entities` (date, playerid, entityid, entitytypeid, x, y, z, action, data) VALUES (FROM_UNIXTIME(?), ?, ?, ?, ?, ?, ?, ?, ?)"; return true;
updateEntityUUIDString = "UPDATE `" + table + "-entityids` SET entityuuid = ? WHERE entityid = ?"; }
} }
return false;
public boolean isLogging(EntityLogging logging, Entity entity) { }
return entityLogging.get(logging).isLogging(entity);
} private class EntityLoggingList {
private final EnumSet<EntityType> logged = EnumSet.noneOf(EntityType.class);
public boolean isLoggingAnyEntities() { private final boolean logAll;
for (EntityLoggingList list : entityLogging.values()) { private final boolean logAnimals;
if (list.isLoggingAnyEntities()) { private final boolean logMonsters;
return true; private final boolean logLiving;
}
} public EntityLoggingList(List<String> types) {
return false; boolean all = false;
} boolean animals = false;
boolean monsters = false;
private class EntityLoggingList { boolean living = false;
private final EntityLogging entityAction; for (String type : types) {
private final HashSet<EntityType> logged = new HashSet<>(); EntityType et = BukkitUtils.matchEntityType(type);
private final boolean logAll; if (et != null) {
private final boolean logAnimals; logged.add(et);
private final boolean logWateranimals; } else {
private final boolean logMonsters; if (type.equalsIgnoreCase("all")) {
private final boolean logLiving; all = true;
} else if (type.equalsIgnoreCase("animal") || type.equalsIgnoreCase("animals")) {
public EntityLoggingList(EntityLogging entityAction, List<String> types) { animals = true;
this.entityAction = entityAction; } else if (type.equalsIgnoreCase("monster") || type.equalsIgnoreCase("monsters")) {
boolean all = false; monsters = true;
boolean animals = false; } else if (type.equalsIgnoreCase("living")) {
boolean wateranimals = false; living = true;
boolean monsters = false; } else {
boolean living = false; LogBlock.getInstance().getLogger().log(Level.WARNING, "Unkown entity type in config for " + world + ": " + type);
for (String type : types) { }
EntityType et = BukkitUtils.matchEntityType(type); }
if (et != null) { }
logged.add(et); logAll = all;
} else { logAnimals = animals;
if (type.equalsIgnoreCase("all")) { logMonsters = monsters;
all = true; logLiving = living;
} else if (type.equalsIgnoreCase("animal") || type.equalsIgnoreCase("animals")) { }
animals = true;
} else if (type.equalsIgnoreCase("wateranimal") || type.equalsIgnoreCase("wateranimals")) { public boolean isLogging(Entity entity) {
wateranimals = true; if (entity == null || (entity instanceof Player)) {
} else if (type.equalsIgnoreCase("monster") || type.equalsIgnoreCase("monsters")) { return false;
monsters = true; }
} else if (type.equalsIgnoreCase("living")) { EntityType type = entity.getType();
living = true; if (logAll || logged.contains(type)) {
} else { return true;
LogBlock.getInstance().getLogger().log(Level.WARNING, "Unkown entity type in config for " + world + ": " + type); }
} if (logLiving && LivingEntity.class.isAssignableFrom(entity.getClass()) && !(entity instanceof ArmorStand)) {
} return true;
} }
logAll = all; if (logAnimals && (Animals.class.isAssignableFrom(entity.getClass()) || WaterMob.class.isAssignableFrom(entity.getClass()))) {
logAnimals = animals; return true;
logWateranimals = wateranimals; }
logMonsters = monsters; 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)) {
logLiving = living; return true;
} }
return false;
public boolean isLogging(Entity entity) { }
if (entity == null || (entity instanceof Player)) {
return false; public boolean isLoggingAnyEntities() {
} return logAll || logAnimals || logLiving || logMonsters || !logged.isEmpty();
EntityType type = entity.getType(); }
if (logAll || logged.contains(type)) { }
return true; }
}
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())) {
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);
}
}
}

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

@ -42,8 +42,8 @@ import de.diddiz.LogBlock.EntityChange.EntityChangeType;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.config.Config; import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.config.EntityLogging; import de.diddiz.LogBlock.config.EntityLogging;
import de.diddiz.LogBlock.util.LoggingUtil; import de.diddiz.util.LoggingUtil;
import de.diddiz.LogBlock.worldedit.WorldEditHelper; import de.diddiz.worldedit.WorldEditHelper;
import java.util.UUID; import java.util.UUID;
public class AdvancedEntityLogging extends LoggingListener { public class AdvancedEntityLogging extends LoggingListener {
@ -131,7 +131,7 @@ public class AdvancedEntityLogging extends LoggingListener {
inHand = inHand.clone(); inHand = inHand.clone();
inHand.setAmount(1); inHand.setAmount(1);
data.set("item", inHand); 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);
} }
} }
} }
@ -159,9 +159,6 @@ public class AdvancedEntityLogging extends LoggingListener {
} }
} }
if (actor == null) { if (actor == null) {
if (event.getSpawnReason() == SpawnReason.NATURAL && !Config.isLoggingNatualSpawns(entity.getWorld())) {
return;
}
actor = new Actor(event.getSpawnReason().toString()); actor = new Actor(event.getSpawnReason().toString());
} }
queueEntitySpawnOrKill(entity, actor, EntityChange.EntityChangeType.CREATE); queueEntitySpawnOrKill(entity, actor, EntityChange.EntityChangeType.CREATE);
@ -249,7 +246,7 @@ public class AdvancedEntityLogging extends LoggingListener {
} }
YamlConfiguration data = new YamlConfiguration(); YamlConfiguration data = new YamlConfiguration();
data.set("item", oldItem); 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);
} }
} }
} }
@ -277,7 +274,7 @@ public class AdvancedEntityLogging extends LoggingListener {
if (damager instanceof Bee && !((Bee) damager).hasStung()) { if (damager instanceof Bee && !((Bee) damager).hasStung()) {
if (Config.isLogging(damager.getWorld(), EntityLogging.MODIFY, damager)) { if (Config.isLogging(damager.getWorld(), EntityLogging.MODIFY, damager)) {
Actor actor = Actor.actorFromEntity(event.getEntity()); 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 +295,13 @@ public class AdvancedEntityLogging extends LoggingListener {
YamlConfiguration data = new YamlConfiguration(); YamlConfiguration data = new YamlConfiguration();
data.set("item", oldItem); data.set("item", oldItem);
data.set("slot", event.getSlot().name()); 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) { if (!newEmpty) {
YamlConfiguration data = new YamlConfiguration(); YamlConfiguration data = new YamlConfiguration();
data.set("item", newItem); data.set("item", newItem);
data.set("slot", event.getSlot().name()); 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 +319,6 @@ public class AdvancedEntityLogging extends LoggingListener {
} else { } else {
data.set("worldedit", WorldEditHelper.serializeEntity(entity)); data.set("worldedit", WorldEditHelper.serializeEntity(entity));
} }
consumer.queueEntityModification(actor, entity, changeType, data); consumer.queueEntityModification(actor, entity.getUniqueId(), entity.getType(), location, changeType, data);
} }
} }

View File

@ -1,48 +1,48 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.CommandsHandler; import de.diddiz.LogBlock.CommandsHandler;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.QueryParams; import de.diddiz.LogBlock.QueryParams;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import static de.diddiz.LogBlock.config.Config.banPermission; import static de.diddiz.LogBlock.config.Config.banPermission;
import static de.diddiz.LogBlock.config.Config.isLogged; import static de.diddiz.LogBlock.config.Config.isLogged;
import static org.bukkit.Bukkit.getScheduler; import static org.bukkit.Bukkit.getScheduler;
public class BanListener implements Listener { public class BanListener implements Listener {
private final CommandsHandler handler; private final CommandsHandler handler;
private final LogBlock logblock; private final LogBlock logblock;
public BanListener(LogBlock logblock) { public BanListener(LogBlock logblock) {
this.logblock = logblock; this.logblock = logblock;
handler = logblock.getCommandsHandler(); handler = logblock.getCommandsHandler();
} }
@EventHandler @EventHandler
public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) { public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) {
final String[] split = event.getMessage().split(" "); final String[] split = event.getMessage().split(" ");
if (split.length > 1 && split[0].equalsIgnoreCase("/ban") && logblock.hasPermission(event.getPlayer(), banPermission)) { if (split.length > 1 && split[0].equalsIgnoreCase("/ban") && logblock.hasPermission(event.getPlayer(), banPermission)) {
final QueryParams p = new QueryParams(logblock); final QueryParams p = new QueryParams(logblock);
p.setPlayer(split[1].equalsIgnoreCase("g") ? split[2] : split[1]); p.setPlayer(split[1].equalsIgnoreCase("g") ? split[2] : split[1]);
p.since = 0; p.since = 0;
p.silent = false; p.silent = false;
getScheduler().runTaskAsynchronously(logblock, new Runnable() { getScheduler().runTaskAsynchronously(logblock, new Runnable() {
@Override @Override
public void run() { public void run() {
for (final World world : logblock.getServer().getWorlds()) { for (final World world : logblock.getServer().getWorlds()) {
if (isLogged(world)) { if (isLogged(world)) {
p.world = world; p.world = world;
try { try {
handler.new CommandRollback(event.getPlayer(), p, false); handler.new CommandRollback(event.getPlayer(), p, false);
} catch (final Exception ex) { } catch (final Exception ex) {
} }
} }
} }
} }
}); });
} }
} }
} }

View File

@ -1,88 +1,75 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig; 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.Bukkit;
import org.bukkit.Material; import org.bukkit.GameMode;
import org.bukkit.block.Block; import org.bukkit.Material;
import org.bukkit.block.data.BlockData; import org.bukkit.block.Block;
import org.bukkit.block.data.Waterlogged; import org.bukkit.block.data.BlockData;
import org.bukkit.event.EventHandler; import org.bukkit.block.data.Waterlogged;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventHandler;
import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockDropItemEvent; import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.player.PlayerBucketFillEvent; import org.bukkit.event.player.PlayerBucketFillEvent;
import static de.diddiz.LogBlock.config.Config.getWorldConfig; import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import static de.diddiz.LogBlock.config.Config.isLogging; import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.LogBlock.util.LoggingUtil.smartLogBlockBreak; import static de.diddiz.util.LoggingUtil.smartLogBlockBreak;
import static de.diddiz.LogBlock.util.LoggingUtil.smartLogBlockReplace; import static de.diddiz.util.LoggingUtil.smartLogBlockReplace;
import static de.diddiz.LogBlock.util.LoggingUtil.smartLogFallables; import static de.diddiz.util.LoggingUtil.smartLogFallables;
public class BlockBreakLogging extends LoggingListener { public class BlockBreakLogging extends LoggingListener {
public BlockBreakLogging(LogBlock lb) { public BlockBreakLogging(LogBlock lb) {
super(lb); super(lb);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) { public void onBlockBreak(BlockBreakEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.BLOCKBREAK)) { if (isLogging(event.getBlock().getWorld(), Logging.BLOCKBREAK)) {
WorldConfig wcfg = getWorldConfig(event.getBlock().getWorld()); WorldConfig wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg == null) { if (wcfg == null) {
return; return;
} }
final Actor actor = Actor.actorFromEntity(event.getPlayer()); final Actor actor = Actor.actorFromEntity(event.getPlayer());
final Block origin = event.getBlock(); final Block origin = event.getBlock();
final Material type = origin.getType(); 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()); consumer.queueContainerBreak(actor, origin.getState());
} else if (type == Material.ICE) { } else if (type == Material.ICE) {
// When in creative mode ice doesn't form water // When in creative mode ice doesn't form water
if (event.getPlayer().getGameMode().equals(GameMode.CREATIVE)) { if (event.getPlayer().getGameMode().equals(GameMode.CREATIVE)) {
smartLogBlockBreak(consumer, actor, origin); smartLogBlockBreak(consumer, actor, origin);
} else { } else {
smartLogBlockReplace(consumer, actor, origin, Bukkit.createBlockData(Material.WATER)); smartLogBlockReplace(consumer, actor, origin, Bukkit.createBlockData(Material.WATER));
} }
} else { } else {
smartLogBlockBreak(consumer, actor, origin); smartLogBlockBreak(consumer, actor, origin);
} }
smartLogFallables(consumer, actor, origin); smartLogFallables(consumer, actor, origin);
} }
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerBucketFill(PlayerBucketFillEvent event) { public void onPlayerBucketFill(PlayerBucketFillEvent event) {
if (isLogging(event.getBlockClicked().getWorld(), Logging.BLOCKBREAK)) { if (isLogging(event.getBlockClicked().getWorld(), Logging.BLOCKBREAK)) {
BlockData clickedBlockData = event.getBlockClicked().getBlockData(); BlockData clickedBlockData = event.getBlockClicked().getBlockData();
if (clickedBlockData instanceof Waterlogged) { if (clickedBlockData instanceof Waterlogged) {
Waterlogged clickedWaterlogged = (Waterlogged) clickedBlockData; Waterlogged clickedWaterlogged = (Waterlogged) clickedBlockData;
if (clickedWaterlogged.isWaterlogged()) { if (clickedWaterlogged.isWaterlogged()) {
Waterlogged clickedWaterloggedWithoutWater = (Waterlogged) clickedWaterlogged.clone(); Waterlogged clickedWaterloggedWithoutWater = (Waterlogged) clickedWaterlogged.clone();
clickedWaterloggedWithoutWater.setWaterlogged(false); clickedWaterloggedWithoutWater.setWaterlogged(false);
consumer.queueBlockReplace(Actor.actorFromEntity(event.getPlayer()), event.getBlockClicked().getLocation(), clickedWaterlogged, clickedWaterloggedWithoutWater); consumer.queueBlockReplace(Actor.actorFromEntity(event.getPlayer()), event.getBlockClicked().getLocation(), clickedWaterlogged, clickedWaterloggedWithoutWater);
} }
} else { } else {
consumer.queueBlockBreak(Actor.actorFromEntity(event.getPlayer()), event.getBlockClicked().getState()); consumer.queueBlockBreak(Actor.actorFromEntity(event.getPlayer()), event.getBlockClicked().getState());
} }
} }
} }
}
@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

@ -1,72 +1,72 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.Config; import de.diddiz.LogBlock.config.Config;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.Action; import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBurnEvent; import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockIgniteEvent; import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockIgniteEvent.IgniteCause; import org.bukkit.event.block.BlockIgniteEvent.IgniteCause;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import static de.diddiz.LogBlock.config.Config.isLogging; import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.LogBlock.util.LoggingUtil.smartLogBlockBreak; import static de.diddiz.util.LoggingUtil.smartLogBlockBreak;
import static de.diddiz.LogBlock.util.LoggingUtil.smartLogBlockReplace; import static de.diddiz.util.LoggingUtil.smartLogBlockReplace;
import static de.diddiz.LogBlock.util.LoggingUtil.smartLogFallables; import static de.diddiz.util.LoggingUtil.smartLogFallables;
public class BlockBurnLogging extends LoggingListener { public class BlockBurnLogging extends LoggingListener {
public BlockBurnLogging(LogBlock lb) { public BlockBurnLogging(LogBlock lb) {
super(lb); super(lb);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockBurn(BlockBurnEvent event) { public void onBlockBurn(BlockBurnEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.FIRE)) { if (isLogging(event.getBlock().getWorld(), Logging.FIRE)) {
smartLogBlockReplace(consumer, new Actor("Fire", Config.logFireSpreadAsPlayerWhoCreatedIt ? event.getIgnitingBlock() : null), event.getBlock(), Material.FIRE.createBlockData()); smartLogBlockReplace(consumer, new Actor("Fire", Config.logFireSpreadAsPlayerWhoCreatedIt ? event.getIgnitingBlock() : null), event.getBlock(), Material.FIRE.createBlockData());
smartLogFallables(consumer, new Actor("Fire", Config.logFireSpreadAsPlayerWhoCreatedIt ? event.getIgnitingBlock() : null), event.getBlock()); smartLogFallables(consumer, new Actor("Fire", Config.logFireSpreadAsPlayerWhoCreatedIt ? event.getIgnitingBlock() : null), event.getBlock());
} }
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockIgnite(BlockIgniteEvent event) { public void onBlockIgnite(BlockIgniteEvent event) {
Actor actor = new Actor("Fire", Config.logFireSpreadAsPlayerWhoCreatedIt ? event.getIgnitingBlock() : null); Actor actor = new Actor("Fire", Config.logFireSpreadAsPlayerWhoCreatedIt ? event.getIgnitingBlock() : null);
if (event.getCause() == IgniteCause.FLINT_AND_STEEL) { if (event.getCause() == IgniteCause.FLINT_AND_STEEL) {
if (event.getIgnitingEntity() != null) { if (event.getIgnitingEntity() != null) {
return; // handled in block place return; // handled in block place
} else { } else {
actor = new Actor("Dispenser"); actor = new Actor("Dispenser");
} }
} else if (event.getCause() == IgniteCause.LIGHTNING) { } else if (event.getCause() == IgniteCause.LIGHTNING) {
actor = new Actor("Lightning"); actor = new Actor("Lightning");
} else if (event.getCause() == IgniteCause.EXPLOSION) { } else if (event.getCause() == IgniteCause.EXPLOSION) {
actor = new Actor("Explosion"); actor = new Actor("Explosion");
} else if (event.getCause() == IgniteCause.LAVA) { } else if (event.getCause() == IgniteCause.LAVA) {
actor = new Actor("Lava"); actor = new Actor("Lava");
} else if (event.getCause() == IgniteCause.ENDER_CRYSTAL) { } else if (event.getCause() == IgniteCause.ENDER_CRYSTAL) {
actor = new Actor("EnderCrystal"); actor = new Actor("EnderCrystal");
} }
if (isLogging(event.getBlock().getWorld(), Logging.FIRE)) { if (isLogging(event.getBlock().getWorld(), Logging.FIRE)) {
consumer.queueBlockPlace(actor, event.getBlock().getLocation(), Material.FIRE.createBlockData()); consumer.queueBlockPlace(actor, event.getBlock().getLocation(), Material.FIRE.createBlockData());
} }
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onExtinguish(PlayerInteractEvent event) { public void onExtinguish(PlayerInteractEvent event) {
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
Player player = event.getPlayer(); Player player = event.getPlayer();
Block block = event.getClickedBlock().getRelative(event.getBlockFace()); Block block = event.getClickedBlock().getRelative(event.getBlockFace());
if (block.getType().equals(Material.FIRE) && isLogging(player.getWorld(), Logging.FIRE)) { if (block.getType().equals(Material.FIRE) && isLogging(player.getWorld(), Logging.FIRE)) {
Actor actor = Actor.actorFromEntity(player); Actor actor = Actor.actorFromEntity(player);
smartLogBlockBreak(consumer, actor, block); smartLogBlockBreak(consumer, actor, block);
smartLogFallables(consumer, actor, block); smartLogFallables(consumer, actor, block);
} }
} }
} }
} }

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

@ -1,67 +1,68 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.Config; 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.Material;
import org.bukkit.block.BlockState; import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData; import org.bukkit.block.BlockState;
import org.bukkit.block.data.Waterlogged; import org.bukkit.block.data.BlockData;
import org.bukkit.event.EventHandler; import org.bukkit.block.data.Waterlogged;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventHandler;
import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.LogBlock.config.Config.isLogging;
public class BlockPlaceLogging extends LoggingListener {
public BlockPlaceLogging(LogBlock lb) { public class BlockPlaceLogging extends LoggingListener {
super(lb); public BlockPlaceLogging(LogBlock lb) {
} super(lb);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
if (Config.isLogging(event.getBlock().getWorld(), Logging.BLOCKPLACE)) { public void onBlockPlace(BlockPlaceEvent event) {
final BlockState before = event.getBlockReplacedState(); if (Config.isLogging(event.getBlock().getWorld(), Logging.BLOCKPLACE)) {
final BlockState after = event.getBlockPlaced().getState(); final BlockState before = event.getBlockReplacedState();
final Actor actor = Actor.actorFromEntity(event.getPlayer()); final BlockState after = event.getBlockPlaced().getState();
if (before.getType() == Material.LECTERN && after.getType() == Material.LECTERN) { final Actor actor = Actor.actorFromEntity(event.getPlayer());
return; if (before.getType() == Material.LECTERN && after.getType() == Material.LECTERN) {
} return;
LoggingUtil.smartLogBlockPlace(consumer, actor, before, after); }
} LoggingUtil.smartLogBlockPlace(consumer, actor, before, after);
} }
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
if (isLogging(event.getPlayer().getWorld(), Logging.BLOCKPLACE)) { public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
Material placedMaterial = event.getBucket() == Material.LAVA_BUCKET ? Material.LAVA : Material.WATER; if (isLogging(event.getPlayer().getWorld(), Logging.BLOCKPLACE)) {
BlockData clickedBlockData = event.getBlockClicked().getBlockData(); Material placedMaterial = event.getBucket() == Material.LAVA_BUCKET ? Material.LAVA : Material.WATER;
if (placedMaterial == Material.WATER && clickedBlockData instanceof Waterlogged) { BlockData clickedBlockData = event.getBlockClicked().getBlockData();
Waterlogged clickedWaterlogged = (Waterlogged) clickedBlockData; if (placedMaterial == Material.WATER && clickedBlockData instanceof Waterlogged) {
if (!clickedWaterlogged.isWaterlogged()) { Waterlogged clickedWaterlogged = (Waterlogged) clickedBlockData;
Waterlogged clickedWaterloggedWithWater = (Waterlogged) clickedWaterlogged.clone(); if (!clickedWaterlogged.isWaterlogged()) {
clickedWaterloggedWithWater.setWaterlogged(true); Waterlogged clickedWaterloggedWithWater = (Waterlogged) clickedWaterlogged.clone();
consumer.queueBlockReplace(Actor.actorFromEntity(event.getPlayer()), event.getBlockClicked().getLocation(), clickedWaterlogged, clickedWaterloggedWithWater); clickedWaterloggedWithWater.setWaterlogged(true);
return; consumer.queueBlockReplace(Actor.actorFromEntity(event.getPlayer()), event.getBlockClicked().getLocation(), clickedWaterlogged, clickedWaterloggedWithWater);
} return;
} }
Block placedAt = event.getBlockClicked().getRelative(event.getBlockFace()); }
if (placedAt.isEmpty()) { Block placedAt = event.getBlockClicked().getRelative(event.getBlockFace());
consumer.queueBlockPlace(Actor.actorFromEntity(event.getPlayer()), placedAt.getLocation(), placedMaterial.createBlockData()); if (placedAt.isEmpty()) {
} else { consumer.queueBlockPlace(Actor.actorFromEntity(event.getPlayer()), placedAt.getLocation(), placedMaterial.createBlockData());
BlockData placedAtBlock = placedAt.getBlockData(); } else {
if (placedAtBlock instanceof Waterlogged && !(((Waterlogged) placedAtBlock).isWaterlogged())) { BlockData placedAtBlock = placedAt.getBlockData();
Waterlogged clickedWaterloggedWithWater = (Waterlogged) placedAtBlock.clone(); if (placedAtBlock instanceof Waterlogged && !(((Waterlogged) placedAtBlock).isWaterlogged())) {
clickedWaterloggedWithWater.setWaterlogged(true); Waterlogged clickedWaterloggedWithWater = (Waterlogged) placedAtBlock.clone();
consumer.queueBlockReplace(Actor.actorFromEntity(event.getPlayer()), placedAt.getLocation(), placedAtBlock, clickedWaterloggedWithWater); clickedWaterloggedWithWater.setWaterlogged(true);
} else { consumer.queueBlockReplace(Actor.actorFromEntity(event.getPlayer()), placedAt.getLocation(), placedAtBlock, clickedWaterloggedWithWater);
consumer.queueBlockReplace(Actor.actorFromEntity(event.getPlayer()), placedAt.getLocation(), placedAtBlock, placedMaterial.createBlockData()); } else {
} consumer.queueBlockReplace(Actor.actorFromEntity(event.getPlayer()), placedAt.getLocation(), placedAtBlock, placedMaterial.createBlockData());
} }
} }
} }
} }
}

View File

@ -5,10 +5,6 @@ import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.World; 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.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockSpreadEvent; import org.bukkit.event.block.BlockSpreadEvent;
@ -26,74 +22,49 @@ public class BlockSpreadLogging extends LoggingListener {
String name; String name;
World world = event.getNewState().getWorld(); World world = event.getBlock().getWorld();
Material type = event.getNewState().getType(); Material type = event.getSource().getType();
if (type == Material.SHORT_GRASS) { switch (type) {
if (!isLogging(world, Logging.GRASSGROWTH)) { case GRASS:
return; 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);
}
} }
} else { name = "GrassGrowth";
// special case because the old state is already changed (for one half) break;
PointedDripstone oldState = (PointedDripstone) event.getNewState().getBlockData(); case MYCELIUM:
oldState.setThickness(Thickness.TIP); if (!isLogging(world, Logging.MYCELIUMSPREAD)) {
consumer.queueBlockReplace(new Actor(name), oldState, event.getNewState()); return;
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) { default:
if (!isLogging(world, Logging.SCULKSPREAD)) {
return; return;
}
name = "SculkSpread";
} else {
return;
} }
consumer.queueBlockReplace(new Actor(name), event.getBlock().getState(), event.getNewState()); 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

@ -1,58 +1,58 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import org.bukkit.command.BlockCommandSender; import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.minecart.CommandMinecart; import org.bukkit.entity.minecart.CommandMinecart;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.server.ServerCommandEvent; import org.bukkit.event.server.ServerCommandEvent;
import static de.diddiz.LogBlock.config.Config.isLogging; import static de.diddiz.LogBlock.config.Config.isLogging;
public class ChatLogging extends LoggingListener { public class ChatLogging extends LoggingListener {
public ChatLogging(LogBlock lb) { public ChatLogging(LogBlock lb) {
super(lb); super(lb);
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
if (isLogging(event.getPlayer().getWorld(), Logging.PLAYER_COMMANDS)) { if (isLogging(event.getPlayer().getWorld(), Logging.PLAYER_COMMANDS)) {
consumer.queueChat(Actor.actorFromEntity(event.getPlayer()), event.getMessage()); consumer.queueChat(Actor.actorFromEntity(event.getPlayer()), event.getMessage());
} }
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onPlayerChat(AsyncPlayerChatEvent event) { public void onPlayerChat(AsyncPlayerChatEvent event) {
if (isLogging(event.getPlayer().getWorld(), Logging.CHAT)) { if (isLogging(event.getPlayer().getWorld(), Logging.CHAT)) {
consumer.queueChat(Actor.actorFromEntity(event.getPlayer()), event.getMessage()); consumer.queueChat(Actor.actorFromEntity(event.getPlayer()), event.getMessage());
} }
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onServerCommand(ServerCommandEvent event) { public void onServerCommand(ServerCommandEvent event) {
CommandSender sender = event.getSender(); CommandSender sender = event.getSender();
Actor actor; Actor actor;
if (sender instanceof BlockCommandSender) { if (sender instanceof BlockCommandSender) {
if (!isLogging(((BlockCommandSender) sender).getBlock().getWorld(), Logging.COMMANDBLOCK_COMMANDS)) { if (!isLogging(((BlockCommandSender) sender).getBlock().getWorld(), Logging.COMMANDBLOCK_COMMANDS)) {
return; return;
} }
actor = new Actor("CommandBlock"); actor = new Actor("CommandBlock");
} else if (sender instanceof CommandMinecart) { } else if (sender instanceof CommandMinecart) {
if (!isLogging(((CommandMinecart) sender).getWorld(), Logging.COMMANDBLOCK_COMMANDS)) { if (!isLogging(((CommandMinecart) sender).getWorld(), Logging.COMMANDBLOCK_COMMANDS)) {
return; return;
} }
actor = new Actor("CommandMinecart"); actor = new Actor("CommandMinecart");
} else { } else {
if (!isLogging(Logging.CONSOLE_COMMANDS)) { if (!isLogging(Logging.CONSOLE_COMMANDS)) {
return; return;
} }
actor = new Actor("Console"); actor = new Actor("Console");
} }
consumer.queueChat(actor, "/" + event.getCommand()); consumer.queueChat(actor, "/" + event.getCommand());
} }
} }

View File

@ -1,303 +1,303 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.block.DoubleChest; import org.bukkit.block.DoubleChest;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.inventory.ClickType; import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent; import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import static de.diddiz.LogBlock.config.Config.isLogging; 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 { public class ChestAccessLogging extends LoggingListener {
private class PlayerActiveInventoryModifications { private class PlayerActiveInventoryModifications {
private final HumanEntity actor; private final HumanEntity actor;
private final Location location; private final Location location;
private final HashMap<ItemStack, Integer> modifications; private final HashMap<ItemStack, Integer> modifications;
public PlayerActiveInventoryModifications(HumanEntity actor, Location location) { public PlayerActiveInventoryModifications(HumanEntity actor, Location location) {
this.actor = actor; this.actor = actor;
this.location = location; this.location = location;
this.modifications = new HashMap<>(); this.modifications = new HashMap<>();
} }
public void addModification(ItemStack stack, int amount) { public void addModification(ItemStack stack, int amount) {
if (amount == 0) { if (amount == 0) {
return; return;
} }
// if we have other viewers, we have to flush their changes // if we have other viewers, we have to flush their changes
ArrayList<PlayerActiveInventoryModifications> allViewers = containersByLocation.get(location); ArrayList<PlayerActiveInventoryModifications> allViewers = containersByLocation.get(location);
if (allViewers.size() > 1) { if (allViewers.size() > 1) {
for (PlayerActiveInventoryModifications other : allViewers) { for (PlayerActiveInventoryModifications other : allViewers) {
if (other != this) { if (other != this) {
other.flush(); other.flush();
} }
} }
} }
// consumer.getLogblock().getLogger().info("Modify container: " + stack + " change: " + amount); // consumer.getLogblock().getLogger().info("Modify container: " + stack + " change: " + amount);
stack = new ItemStack(stack); stack = new ItemStack(stack);
stack.setAmount(1); stack.setAmount(1);
Integer existing = modifications.get(stack); Integer existing = modifications.get(stack);
int newTotal = amount + (existing == null ? 0 : existing); int newTotal = amount + (existing == null ? 0 : existing);
if (newTotal == 0) { if (newTotal == 0) {
modifications.remove(stack); modifications.remove(stack);
} else { } else {
modifications.put(stack, newTotal); modifications.put(stack, newTotal);
} }
} }
public void flush() { public void flush() {
if (!modifications.isEmpty()) { if (!modifications.isEmpty()) {
for (Entry<ItemStack, Integer> e : modifications.entrySet()) { for (Entry<ItemStack, Integer> e : modifications.entrySet()) {
ItemStack stack = e.getKey(); ItemStack stack = e.getKey();
int amount = e.getValue(); int amount = e.getValue();
stack.setAmount(Math.abs(amount)); 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); consumer.queueChestAccess(Actor.actorFromEntity(actor), location, location.getWorld().getBlockAt(location).getBlockData(), stack, amount < 0);
} }
modifications.clear(); modifications.clear();
} }
} }
public HumanEntity getActor() { public HumanEntity getActor() {
return actor; return actor;
} }
public Location getLocation() { public Location getLocation() {
return location; return location;
} }
} }
private final Map<HumanEntity, PlayerActiveInventoryModifications> containersByOwner = new HashMap<>(); private final Map<HumanEntity, PlayerActiveInventoryModifications> containersByOwner = new HashMap<>();
private final Map<Location, ArrayList<PlayerActiveInventoryModifications>> containersByLocation = new HashMap<>(); private final Map<Location, ArrayList<PlayerActiveInventoryModifications>> containersByLocation = new HashMap<>();
public ChestAccessLogging(LogBlock lb) { public ChestAccessLogging(LogBlock lb) {
super(lb); super(lb);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryClose(InventoryCloseEvent event) { public void onInventoryClose(InventoryCloseEvent event) {
final HumanEntity player = event.getPlayer(); final HumanEntity player = event.getPlayer();
if (!isLogging(player.getWorld(), Logging.CHESTACCESS)) { if (!isLogging(player.getWorld(), Logging.CHESTACCESS)) {
return; return;
} }
InventoryHolder holder = event.getInventory().getHolder(); InventoryHolder holder = event.getInventory().getHolder();
if (holder instanceof BlockState || holder instanceof DoubleChest) { if (holder instanceof BlockState || holder instanceof DoubleChest) {
final PlayerActiveInventoryModifications modifications = containersByOwner.remove(player); final PlayerActiveInventoryModifications modifications = containersByOwner.remove(player);
if (modifications != null) { if (modifications != null) {
final Location loc = modifications.getLocation(); final Location loc = modifications.getLocation();
ArrayList<PlayerActiveInventoryModifications> atLocation = containersByLocation.get(loc); ArrayList<PlayerActiveInventoryModifications> atLocation = containersByLocation.get(loc);
atLocation.remove(modifications); atLocation.remove(modifications);
if (atLocation.isEmpty()) { if (atLocation.isEmpty()) {
containersByLocation.remove(loc); containersByLocation.remove(loc);
} }
modifications.flush(); modifications.flush();
} }
} }
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryOpen(InventoryOpenEvent event) { public void onInventoryOpen(InventoryOpenEvent event) {
final HumanEntity player = event.getPlayer(); final HumanEntity player = event.getPlayer();
if (!isLogging(player.getWorld(), Logging.CHESTACCESS)) { if (!isLogging(player.getWorld(), Logging.CHESTACCESS)) {
return; return;
} }
if (event.getInventory() != null) { if (event.getInventory() != null) {
InventoryHolder holder = event.getInventory().getHolder(); InventoryHolder holder = event.getInventory().getHolder();
if (holder instanceof BlockState || holder instanceof DoubleChest) { if (holder instanceof BlockState || holder instanceof DoubleChest) {
if (getInventoryHolderType(holder) != Material.CRAFTING_TABLE) { if (getInventoryHolderType(holder) != Material.CRAFTING_TABLE) {
PlayerActiveInventoryModifications modifications = new PlayerActiveInventoryModifications(event.getPlayer(), getInventoryHolderLocation(holder)); PlayerActiveInventoryModifications modifications = new PlayerActiveInventoryModifications(event.getPlayer(), getInventoryHolderLocation(holder));
containersByOwner.put(modifications.getActor(), modifications); containersByOwner.put(modifications.getActor(), modifications);
containersByLocation.compute(modifications.getLocation(), (k, v) -> { containersByLocation.compute(modifications.getLocation(), (k, v) -> {
if (v == null) { if (v == null) {
v = new ArrayList<>(); v = new ArrayList<>();
} }
v.add(modifications); v.add(modifications);
return v; return v;
}); });
} }
} }
} }
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event) { public void onInventoryClick(InventoryClickEvent event) {
final HumanEntity player = event.getWhoClicked(); final HumanEntity player = event.getWhoClicked();
if (!isLogging(player.getWorld(), Logging.CHESTACCESS)) { if (!isLogging(player.getWorld(), Logging.CHESTACCESS)) {
return; return;
} }
InventoryHolder holder = event.getInventory().getHolder(); InventoryHolder holder = event.getInventory().getHolder();
if (holder instanceof BlockState || holder instanceof DoubleChest) { if (holder instanceof BlockState || holder instanceof DoubleChest) {
final PlayerActiveInventoryModifications modifications = containersByOwner.get(player); final PlayerActiveInventoryModifications modifications = containersByOwner.get(player);
if (modifications != null) { if (modifications != null) {
switch (event.getAction()) { switch (event.getAction()) {
case PICKUP_ONE: case PICKUP_ONE:
case DROP_ONE_SLOT: case DROP_ONE_SLOT:
if (event.getRawSlot() < event.getView().getTopInventory().getSize()) { if (event.getRawSlot() < event.getView().getTopInventory().getSize()) {
modifications.addModification(event.getCurrentItem(), -1); modifications.addModification(event.getCurrentItem(), -1);
} }
break; break;
case PICKUP_HALF: case PICKUP_HALF:
// server behaviour: round up // server behaviour: round up
if (event.getRawSlot() < event.getView().getTopInventory().getSize()) { if (event.getRawSlot() < event.getView().getTopInventory().getSize()) {
modifications.addModification(event.getCurrentItem(), -(event.getCurrentItem().getAmount() + 1) / 2); modifications.addModification(event.getCurrentItem(), -(event.getCurrentItem().getAmount() + 1) / 2);
} }
break; break;
case PICKUP_SOME: // oversized stack - can not take all when clicking case PICKUP_SOME: // oversized stack - can not take all when clicking
// server behaviour: leave a full stack in the slot, take everything else // server behaviour: leave a full stack in the slot, take everything else
if (event.getRawSlot() < event.getView().getTopInventory().getSize()) { if (event.getRawSlot() < event.getView().getTopInventory().getSize()) {
int taken = event.getCurrentItem().getAmount() - event.getCurrentItem().getMaxStackSize(); int taken = event.getCurrentItem().getAmount() - event.getCurrentItem().getMaxStackSize();
modifications.addModification(event.getCursor(), -taken); modifications.addModification(event.getCursor(), -taken);
} }
break; break;
case PICKUP_ALL: case PICKUP_ALL:
case DROP_ALL_SLOT: case DROP_ALL_SLOT:
if (event.getRawSlot() < event.getView().getTopInventory().getSize()) { if (event.getRawSlot() < event.getView().getTopInventory().getSize()) {
modifications.addModification(event.getCurrentItem(), -event.getCurrentItem().getAmount()); modifications.addModification(event.getCurrentItem(), -event.getCurrentItem().getAmount());
} }
break; break;
case PLACE_ONE: case PLACE_ONE:
if (event.getRawSlot() < event.getView().getTopInventory().getSize()) { if (event.getRawSlot() < event.getView().getTopInventory().getSize()) {
modifications.addModification(event.getCursor(), 1); modifications.addModification(event.getCursor(), 1);
} }
break; break;
case PLACE_SOME: // not enough free place in target slot case PLACE_SOME: // not enough free place in target slot
// server behaviour: place as much as possible // server behaviour: place as much as possible
if (event.getRawSlot() < event.getView().getTopInventory().getSize()) { if (event.getRawSlot() < event.getView().getTopInventory().getSize()) {
int placeable = event.getCurrentItem().getMaxStackSize() - event.getCurrentItem().getAmount(); int placeable = event.getCurrentItem().getMaxStackSize() - event.getCurrentItem().getAmount();
modifications.addModification(event.getCursor(), placeable); modifications.addModification(event.getCursor(), placeable);
} }
break; break;
case PLACE_ALL: case PLACE_ALL:
if (event.getRawSlot() < event.getView().getTopInventory().getSize()) { if (event.getRawSlot() < event.getView().getTopInventory().getSize()) {
modifications.addModification(event.getCursor(), event.getCursor().getAmount()); modifications.addModification(event.getCursor(), event.getCursor().getAmount());
} }
break; break;
case SWAP_WITH_CURSOR: case SWAP_WITH_CURSOR:
if (event.getRawSlot() < event.getView().getTopInventory().getSize()) { if (event.getRawSlot() < event.getView().getTopInventory().getSize()) {
modifications.addModification(event.getCursor(), event.getCursor().getAmount()); modifications.addModification(event.getCursor(), event.getCursor().getAmount());
modifications.addModification(event.getCurrentItem(), -event.getCurrentItem().getAmount()); modifications.addModification(event.getCurrentItem(), -event.getCurrentItem().getAmount());
} }
break; break;
case MOVE_TO_OTHER_INVENTORY: // shift + click case MOVE_TO_OTHER_INVENTORY: // shift + click
boolean removed = event.getRawSlot() < event.getView().getTopInventory().getSize(); boolean removed = event.getRawSlot() < event.getView().getTopInventory().getSize();
modifications.addModification(event.getCurrentItem(), event.getCurrentItem().getAmount() * (removed ? -1 : 1)); modifications.addModification(event.getCurrentItem(), event.getCurrentItem().getAmount() * (removed ? -1 : 1));
break; break;
case COLLECT_TO_CURSOR: // double click case COLLECT_TO_CURSOR: // double click
// server behaviour: first collect all with an amount != maxstacksize, then others, starting from slot 0 (container) // server behaviour: first collect all with an amount != maxstacksize, then others, starting from slot 0 (container)
ItemStack cursor = event.getCursor(); ItemStack cursor = event.getCursor();
if (cursor == null) { if (cursor == null) {
return; return;
} }
int toPickUp = cursor.getMaxStackSize() - cursor.getAmount(); int toPickUp = cursor.getMaxStackSize() - cursor.getAmount();
int takenFromContainer = 0; int takenFromContainer = 0;
boolean takeFromFullStacks = false; boolean takeFromFullStacks = false;
Inventory top = event.getView().getTopInventory(); Inventory top = event.getView().getTopInventory();
Inventory bottom = event.getView().getBottomInventory(); Inventory bottom = event.getView().getBottomInventory();
while (toPickUp > 0) { while (toPickUp > 0) {
for (ItemStack stack : top.getStorageContents()) { for (ItemStack stack : top.getStorageContents()) {
if (cursor.isSimilar(stack)) { if (cursor.isSimilar(stack)) {
if (takeFromFullStacks == (stack.getAmount() == stack.getMaxStackSize())) { if (takeFromFullStacks == (stack.getAmount() == stack.getMaxStackSize())) {
int take = Math.min(toPickUp, stack.getAmount()); int take = Math.min(toPickUp, stack.getAmount());
toPickUp -= take; toPickUp -= take;
takenFromContainer += take; takenFromContainer += take;
if (toPickUp <= 0) { if (toPickUp <= 0) {
break; break;
} }
} }
} }
} }
if (toPickUp <= 0) { if (toPickUp <= 0) {
break; break;
} }
for (ItemStack stack : bottom.getStorageContents()) { for (ItemStack stack : bottom.getStorageContents()) {
if (cursor.isSimilar(stack)) { if (cursor.isSimilar(stack)) {
if (takeFromFullStacks == (stack.getAmount() == stack.getMaxStackSize())) { if (takeFromFullStacks == (stack.getAmount() == stack.getMaxStackSize())) {
int take = Math.min(toPickUp, stack.getAmount()); int take = Math.min(toPickUp, stack.getAmount());
toPickUp -= take; toPickUp -= take;
if (toPickUp <= 0) { if (toPickUp <= 0) {
break; break;
} }
} }
} }
} }
if (takeFromFullStacks) { if (takeFromFullStacks) {
break; break;
} else { } else {
takeFromFullStacks = true; takeFromFullStacks = true;
} }
} }
if (takenFromContainer > 0) { if (takenFromContainer > 0) {
modifications.addModification(event.getCursor(), -takenFromContainer); modifications.addModification(event.getCursor(), -takenFromContainer);
} }
break; break;
case HOTBAR_SWAP: // number key or offhand key case HOTBAR_SWAP: // number key or offhand key
case HOTBAR_MOVE_AND_READD: // something was in the other slot case HOTBAR_MOVE_AND_READD: // something was in the other slot
if (event.getRawSlot() < event.getView().getTopInventory().getSize()) { if (event.getRawSlot() < event.getView().getTopInventory().getSize()) {
ItemStack otherSlot = (event.getClick() == ClickType.SWAP_OFFHAND) ? event.getWhoClicked().getInventory().getItemInOffHand() : event.getWhoClicked().getInventory().getItem(event.getHotbarButton()); ItemStack otherSlot = (event.getClick() == ClickType.SWAP_OFFHAND) ? event.getWhoClicked().getInventory().getItemInOffHand() : event.getWhoClicked().getInventory().getItem(event.getHotbarButton());
if (event.getCurrentItem() != null && event.getCurrentItem().getType() != Material.AIR) { if (event.getCurrentItem() != null && event.getCurrentItem().getType() != Material.AIR) {
modifications.addModification(event.getCurrentItem(), -event.getCurrentItem().getAmount()); modifications.addModification(event.getCurrentItem(), -event.getCurrentItem().getAmount());
} }
if (otherSlot != null && otherSlot.getType() != Material.AIR) { if (otherSlot != null && otherSlot.getType() != Material.AIR) {
modifications.addModification(otherSlot, otherSlot.getAmount()); modifications.addModification(otherSlot, otherSlot.getAmount());
} }
} }
break; break;
case DROP_ALL_CURSOR: case DROP_ALL_CURSOR:
case DROP_ONE_CURSOR: case DROP_ONE_CURSOR:
case CLONE_STACK: case CLONE_STACK:
case NOTHING: case NOTHING:
// only the cursor or nothing (but not the inventory) was modified // only the cursor or nothing (but not the inventory) was modified
break; break;
case UNKNOWN: case UNKNOWN:
default: default:
// unable to log something we don't know // unable to log something we don't know
consumer.getLogblock().getLogger().warning("Unknown inventory action by " + event.getWhoClicked().getName() + ": " + event.getAction() + " Slot: " + event.getSlot() + " Slot type: " + event.getSlotType()); consumer.getLogblock().getLogger().warning("Unknown inventory action by " + event.getWhoClicked().getName() + ": " + event.getAction() + " Slot: " + event.getSlot() + " Slot type: " + event.getSlotType());
break; break;
} }
} }
} }
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryDrag(InventoryDragEvent event) { public void onInventoryDrag(InventoryDragEvent event) {
final HumanEntity player = event.getWhoClicked(); final HumanEntity player = event.getWhoClicked();
if (!isLogging(player.getWorld(), Logging.CHESTACCESS)) { if (!isLogging(player.getWorld(), Logging.CHESTACCESS)) {
return; return;
} }
InventoryHolder holder = event.getInventory().getHolder(); InventoryHolder holder = event.getInventory().getHolder();
if (holder instanceof BlockState || holder instanceof DoubleChest) { if (holder instanceof BlockState || holder instanceof DoubleChest) {
final PlayerActiveInventoryModifications modifications = containersByOwner.get(player); final PlayerActiveInventoryModifications modifications = containersByOwner.get(player);
if (modifications != null) { if (modifications != null) {
Inventory container = event.getView().getTopInventory(); Inventory container = event.getView().getTopInventory();
int containerSize = container.getSize(); int containerSize = container.getSize();
for (Entry<Integer, ItemStack> e : event.getNewItems().entrySet()) { for (Entry<Integer, ItemStack> e : event.getNewItems().entrySet()) {
int slot = e.getKey(); int slot = e.getKey();
if (slot < containerSize) { if (slot < containerSize) {
ItemStack old = container.getItem(slot); ItemStack old = container.getItem(slot);
int oldAmount = (old == null || old.getType() == Material.AIR) ? 0 : old.getAmount(); int oldAmount = (old == null || old.getType() == Material.AIR) ? 0 : old.getAmount();
modifications.addModification(e.getValue(), e.getValue().getAmount() - oldAmount); modifications.addModification(e.getValue(), e.getValue().getAmount() - oldAmount);
} }
} }
} }
} }
} }
} }

View File

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

View File

@ -1,24 +1,24 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import org.bukkit.entity.Enderman; import org.bukkit.entity.Enderman;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityChangeBlockEvent;
import static de.diddiz.LogBlock.config.Config.isLogging; import static de.diddiz.LogBlock.config.Config.isLogging;
public class EndermenLogging extends LoggingListener { public class EndermenLogging extends LoggingListener {
public EndermenLogging(LogBlock lb) { public EndermenLogging(LogBlock lb) {
super(lb); super(lb);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) { public void onEntityChangeBlock(EntityChangeBlockEvent event) {
if (event.getEntity() instanceof Enderman && isLogging(event.getBlock().getWorld(), Logging.ENDERMEN)) { if (event.getEntity() instanceof Enderman && isLogging(event.getBlock().getWorld(), Logging.ENDERMEN)) {
consumer.queueBlockReplace(new Actor("Enderman"), event.getBlock().getState(), event.getBlockData()); // Figure out how to get the data of the placed block; consumer.queueBlockReplace(new Actor("Enderman"), event.getBlock().getState(), event.getBlockData()); // Figure out how to get the data of the placed block;
} }
} }
} }

View File

@ -1,228 +1,180 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.Config; import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.config.WorldConfig; 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.Bukkit;
import org.bukkit.Material; import org.bukkit.Location;
import org.bukkit.block.Block; import org.bukkit.Material;
import org.bukkit.block.data.type.RespawnAnchor; import org.bukkit.block.Block;
import org.bukkit.entity.*; import org.bukkit.entity.*;
import org.bukkit.entity.minecart.ExplosiveMinecart; import org.bukkit.entity.minecart.ExplosiveMinecart;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.Action; import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockExplodeEvent; import org.bukkit.event.block.BlockExplodeEvent;
import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.projectiles.ProjectileSource; import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitRunnable;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import static de.diddiz.LogBlock.config.Config.getWorldConfig; import static de.diddiz.LogBlock.config.Config.logCreeperExplosionsAsPlayerWhoTriggeredThese;
import static de.diddiz.LogBlock.config.Config.logCreeperExplosionsAsPlayerWhoTriggeredThese; import static de.diddiz.util.BukkitUtils.getContainerBlocks;
import java.util.UUID; import java.util.UUID;
public class ExplosionLogging extends LoggingListener { public class ExplosionLogging extends LoggingListener {
private UUID lastBedInteractionPlayer; private UUID lastBedInteractionPlayer;
private Location lastBedInteractionLocation; private Location lastBedInteractionLocation;
private UUID lastRespawnAnchorInteractionPlayer;
private Location lastRespawnAnchorInteractionLocation; public ExplosionLogging(LogBlock lb) {
super(lb);
public ExplosionLogging(LogBlock lb) { }
super(lb);
} @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) final WorldConfig wcfg = getWorldConfig(event.getLocation().getWorld());
public void onEntityExplode(EntityExplodeEvent event) { if (wcfg != null) {
final WorldConfig wcfg = getWorldConfig(event.getLocation().getWorld()); Actor actor = new Actor("Explosion");
if (wcfg != null) { Entity source = event.getEntity();
Actor actor = new Actor("Explosion"); if (source == null) {
Entity source = event.getEntity(); if (!wcfg.isLogging(Logging.MISCEXPLOSION)) {
if (source == null) { return;
if (!wcfg.isLogging(Logging.MISCEXPLOSION)) { }
return; } else if (source instanceof TNTPrimed) {
} if (!wcfg.isLogging(Logging.TNTEXPLOSION)) {
} else if (source instanceof TNTPrimed) { return;
if (!wcfg.isLogging(Logging.TNTEXPLOSION)) { }
return; actor = new Actor("TNT");
} } else if (source instanceof ExplosiveMinecart) {
actor = new Actor("TNT"); if (!wcfg.isLogging(Logging.TNTMINECARTEXPLOSION)) {
} else if (source instanceof ExplosiveMinecart) { return;
if (!wcfg.isLogging(Logging.TNTMINECARTEXPLOSION)) { }
return; actor = new Actor("TNTMinecart");
} } else if (source instanceof Creeper) {
actor = new Actor("TNTMinecart"); if (!wcfg.isLogging(Logging.CREEPEREXPLOSION)) {
} else if (source instanceof Creeper) { return;
if (!wcfg.isLogging(Logging.CREEPEREXPLOSION)) { }
return; if (logCreeperExplosionsAsPlayerWhoTriggeredThese) {
} final Entity target = ((Creeper) source).getTarget();
if (logCreeperExplosionsAsPlayerWhoTriggeredThese) { actor = target instanceof Player ? Actor.actorFromEntity(target) : new Actor("Creeper");
final Entity target = ((Creeper) source).getTarget(); } else {
actor = target instanceof Player ? Actor.actorFromEntity(target) : new Actor("Creeper"); actor = new Actor("Creeper");
} else { }
actor = new Actor("Creeper"); } else if (source instanceof Wither) {
} if (!wcfg.isLogging(Logging.WITHER)) {
} else if (source instanceof Wither) { return;
if (!wcfg.isLogging(Logging.WITHER)) { }
return; actor = Actor.actorFromEntity(source);
} } else if (source instanceof WitherSkull) {
actor = Actor.actorFromEntity(source); if (!wcfg.isLogging(Logging.WITHER_SKULL)) {
} else if (source instanceof WitherSkull) { return;
if (!wcfg.isLogging(Logging.WITHER_SKULL)) { }
return; actor = Actor.actorFromEntity(source);
} } else if (source instanceof Fireball) {
actor = Actor.actorFromEntity(source); Fireball fireball = (Fireball) source;
} else if (source instanceof Fireball) { ProjectileSource shooter = fireball.getShooter();
Fireball fireball = (Fireball) source; if (shooter == null) {
ProjectileSource shooter = fireball.getShooter(); if (!wcfg.isLogging(Logging.MISCEXPLOSION)) {
if (shooter == null) { return;
if (!wcfg.isLogging(Logging.MISCEXPLOSION)) { }
return; actor = Actor.actorFromEntity(source);
} } else if (shooter instanceof Ghast) {
actor = Actor.actorFromEntity(source); if (!wcfg.isLogging(Logging.GHASTFIREBALLEXPLOSION)) {
} else if (shooter instanceof Ghast) { return;
if (!wcfg.isLogging(Logging.GHASTFIREBALLEXPLOSION)) { }
return; actor = Actor.actorFromProjectileSource(shooter);
} } else if (shooter instanceof Wither) {
actor = Actor.actorFromProjectileSource(shooter); if (!wcfg.isLogging(Logging.WITHER)) {
} else if (shooter instanceof Wither) { return;
if (!wcfg.isLogging(Logging.WITHER)) { }
return; actor = Actor.actorFromProjectileSource(shooter);
} }
actor = Actor.actorFromProjectileSource(shooter); } else if (source instanceof EnderDragon) {
} if (!wcfg.isLogging(Logging.ENDERDRAGON)) {
} else if (source instanceof EnderDragon) { return;
if (!wcfg.isLogging(Logging.ENDERDRAGON)) { }
return; actor = Actor.actorFromEntity(source);
} } else if (source instanceof EnderCrystal) {
actor = Actor.actorFromEntity(source); if (!wcfg.isLogging(Logging.ENDERCRYSTALEXPLOSION)) {
} else if (source instanceof EnderCrystal) { return;
if (!wcfg.isLogging(Logging.ENDERCRYSTALEXPLOSION)) { }
return; actor = Actor.actorFromEntity(source);
}
actor = Actor.actorFromEntity(source); } else {
if (!wcfg.isLogging(Logging.MISCEXPLOSION)) {
} else { return;
if (!wcfg.isLogging(Logging.MISCEXPLOSION)) { }
return; }
} for (final Block block : event.blockList()) {
} final Material type = block.getType();
for (final Block block : event.blockList()) { if (wcfg.isLogging(Logging.CHESTACCESS) && getContainerBlocks().contains(type) && !BukkitUtils.getShulkerBoxBlocks().contains(type)) {
final Material type = block.getType(); consumer.queueContainerBreak(actor, block.getState());
if (wcfg.isLogging(Logging.CHESTACCESS) && BukkitUtils.isContainerBlock(type) && !BukkitUtils.isShulkerBoxBlock(type)) { } else {
consumer.queueContainerBreak(actor, block.getState()); consumer.queueBlockBreak(actor, block.getState());
} else { }
consumer.queueBlockBreak(actor, block.getState()); }
} }
} }
}
} @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.hasBlock() && BukkitUtils.isBed(event.getClickedBlock().getType())) {
public void onPlayerInteract(PlayerInteractEvent event) { Block block = event.getClickedBlock();
if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.hasBlock()) { if (!Config.isLogging(block.getWorld(), Logging.BEDEXPLOSION)) {
Block block = event.getClickedBlock(); return;
if (BukkitUtils.isBed(block.getType()) && !block.getWorld().isBedWorks()) { }
if (!Config.isLogging(block.getWorld(), Logging.BEDEXPLOSION)) { lastBedInteractionPlayer = event.getPlayer().getUniqueId();
return; lastBedInteractionLocation = block.getLocation();
} new BukkitRunnable() {
lastBedInteractionPlayer = event.getPlayer().getUniqueId(); @Override
lastBedInteractionLocation = block.getLocation(); public void run() {
new BukkitRunnable() { lastBedInteractionPlayer = null;
@Override lastBedInteractionLocation = null;
public void run() { }
lastBedInteractionPlayer = null; }.runTask(LogBlock.getInstance());
lastBedInteractionLocation = null; }
} }
}.runTask(LogBlock.getInstance());
} else if (block.getType() == Material.RESPAWN_ANCHOR && block.getBlockData() instanceof RespawnAnchor data) { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
if (!Config.isLogging(block.getWorld(), Logging.RESPAWNANCHOREXPLOSION)) { public void onBlockExplode(BlockExplodeEvent event) {
return; Player bedCause = null;
} if (lastBedInteractionPlayer != null && lastBedInteractionLocation != null) {
ItemStack inHand = event.getItem(); Location block = event.getBlock().getLocation();
int charges = data.getCharges(); if (lastBedInteractionLocation.getWorld() == block.getWorld() && block.distanceSquared(lastBedInteractionLocation) <= 1) {
if (charges < data.getMaximumCharges() && inHand != null && inHand.getType() == Material.GLOWSTONE) { bedCause = Bukkit.getPlayer(lastBedInteractionPlayer);
// charge }
Actor actor = Actor.actorFromEntity(event.getPlayer()); }
RespawnAnchor blockNew = (RespawnAnchor) data.clone();
blockNew.setCharges(charges + 1); for (final Block block : event.blockList()) {
consumer.queueBlockReplace(actor, block.getState(), blockNew); final WorldConfig wcfg = getWorldConfig(block.getLocation().getWorld());
} else if (charges > 0 && !block.getWorld().isRespawnAnchorWorks()) {
// explode if (wcfg != null) {
Actor actor = Actor.actorFromEntity(event.getPlayer()); Actor actor = new Actor("Explosion");
consumer.queueBlockBreak(actor, block.getState()); if (bedCause != null) {
lastRespawnAnchorInteractionPlayer = event.getPlayer().getUniqueId(); if (!wcfg.isLogging(Logging.BEDEXPLOSION)) {
lastRespawnAnchorInteractionLocation = block.getLocation(); return;
new BukkitRunnable() { }
@Override if (Config.logBedExplosionsAsPlayerWhoTriggeredThese) {
public void run() { actor = Actor.actorFromEntity(bedCause);
lastRespawnAnchorInteractionPlayer = null; }
lastRespawnAnchorInteractionLocation = null; } else if (!wcfg.isLogging(Logging.MISCEXPLOSION)) {
} return;
}.runTask(LogBlock.getInstance()); }
}
} final Material type = block.getType();
} if (wcfg.isLogging(Logging.CHESTACCESS) && getContainerBlocks().contains(type) && !BukkitUtils.getShulkerBoxBlocks().contains(type)) {
} consumer.queueContainerBreak(actor, block.getState());
} else {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) consumer.queueBlockBreak(actor, block.getState());
public void onBlockExplode(BlockExplodeEvent event) { }
Player bedCause = null; }
if (lastBedInteractionPlayer != null && lastBedInteractionLocation != null) { }
Location block = event.getBlock().getLocation(); }
if (lastBedInteractionLocation.getWorld() == block.getWorld() && block.distanceSquared(lastBedInteractionLocation) <= 1) { }
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());
if (wcfg != null) {
Actor actor = new Actor("Explosion");
if (bedCause != null) {
if (!wcfg.isLogging(Logging.BEDEXPLOSION)) {
return;
}
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)) {
consumer.queueContainerBreak(actor, block.getState());
} else {
consumer.queueBlockBreak(actor, block.getState());
}
}
}
}
}

View File

@ -1,127 +1,128 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.Config; import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.config.WorldConfig; 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.Material;
import org.bukkit.block.BlockFace; import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData; import org.bukkit.block.BlockFace;
import org.bukkit.block.data.Levelled; import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Waterlogged; import org.bukkit.block.data.Levelled;
import org.bukkit.event.EventHandler; import org.bukkit.block.data.Waterlogged;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventHandler;
import org.bukkit.event.block.BlockFormEvent; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockFromToEvent; import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
public class FluidFlowLogging extends LoggingListener {
public class FluidFlowLogging extends LoggingListener {
public FluidFlowLogging(LogBlock lb) {
super(lb); public FluidFlowLogging(LogBlock lb) {
} super(lb);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockFromTo(BlockFromToEvent event) { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
final WorldConfig wcfg = getWorldConfig(event.getBlock().getWorld()); public void onBlockFromTo(BlockFromToEvent event) {
if (wcfg != null && (wcfg.isLogging(Logging.WATERFLOW) || wcfg.isLogging(Logging.LAVAFLOW))) { final WorldConfig wcfg = getWorldConfig(event.getBlock().getWorld());
final BlockData blockDataFrom = event.getBlock().getBlockData(); if (wcfg != null && (wcfg.isLogging(Logging.WATERFLOW) || wcfg.isLogging(Logging.LAVAFLOW))) {
Material typeFrom = blockDataFrom.getMaterial(); final BlockData blockDataFrom = event.getBlock().getBlockData();
boolean fromWaterlogged = false; Material typeFrom = blockDataFrom.getMaterial();
if (blockDataFrom instanceof Waterlogged) { boolean fromWaterlogged = false;
typeFrom = Material.WATER; if (blockDataFrom instanceof Waterlogged) {
fromWaterlogged = true; typeFrom = Material.WATER;
} fromWaterlogged = true;
if (typeFrom == Material.SEAGRASS || typeFrom == Material.KELP_PLANT || typeFrom == Material.KELP) { }
typeFrom = Material.WATER; if (typeFrom == Material.SEAGRASS || typeFrom == Material.KELP_PLANT || typeFrom == Material.KELP) {
fromWaterlogged = true; typeFrom = Material.WATER;
} fromWaterlogged = true;
}
Block source = Config.logFluidFlowAsPlayerWhoTriggeredIt ? event.getBlock() : null;
final Block to = event.getToBlock(); Block source = Config.logFluidFlowAsPlayerWhoTriggeredIt ? event.getBlock() : null;
final Material typeTo = to.getType(); final Block to = event.getToBlock();
boolean down = event.getFace() == BlockFace.DOWN; final Material typeTo = to.getType();
final boolean canFlow = BukkitUtils.isEmpty(typeTo) || BukkitUtils.isNonFluidProofBlock(typeTo); boolean down = event.getFace() == BlockFace.DOWN;
if (typeFrom == Material.LAVA && wcfg.isLogging(Logging.LAVAFLOW)) { final boolean canFlow = BukkitUtils.isEmpty(typeTo) || BukkitUtils.getNonFluidProofBlocks().contains(typeTo);
Levelled levelledFrom = (Levelled) blockDataFrom; if (typeFrom == Material.LAVA && wcfg.isLogging(Logging.LAVAFLOW)) {
if (canFlow) { Levelled levelledFrom = (Levelled) blockDataFrom;
if (isSurroundedByWater(to) && levelledFrom.getLevel() <= 2) { if (canFlow) {
consumer.queueBlockReplace(new Actor("LavaFlow", source), to.getState(), Material.COBBLESTONE.createBlockData()); if (isSurroundedByWater(to) && levelledFrom.getLevel() <= 2) {
} else { consumer.queueBlockReplace(new Actor("LavaFlow", source), to.getState(), Material.COBBLESTONE.createBlockData());
Levelled newBlock = (Levelled) blockDataFrom.clone(); } else {
newBlock.setLevel(down ? 1 : Math.min(levelledFrom.getLevel() + 1, levelledFrom.getMaximumLevel())); Levelled newBlock = (Levelled) blockDataFrom.clone();
if (BukkitUtils.isEmpty(typeTo)) { newBlock.setLevel(down ? 1 : levelledFrom.getLevel() + 1);
consumer.queueBlockPlace(new Actor("LavaFlow", source), to.getLocation(), newBlock); if (BukkitUtils.isEmpty(typeTo)) {
} else { consumer.queueBlockPlace(new Actor("LavaFlow", source), to.getLocation(), newBlock);
consumer.queueBlockReplace(new Actor("LavaFlow", source), to.getState(), newBlock); } else {
} consumer.queueBlockReplace(new Actor("LavaFlow", source), to.getState(), newBlock);
} }
} else if (typeTo == Material.WATER) { }
if (down) { } else if (typeTo == Material.WATER) {
consumer.queueBlockReplace(new Actor("LavaFlow", source), to.getState(), Material.STONE.createBlockData()); if (down) {
} else { consumer.queueBlockReplace(new Actor("LavaFlow", source), to.getState(), Material.STONE.createBlockData());
consumer.queueBlockReplace(new Actor("LavaFlow", source), to.getState(), Material.COBBLESTONE.createBlockData()); } else {
} consumer.queueBlockReplace(new Actor("LavaFlow", source), to.getState(), Material.COBBLESTONE.createBlockData());
} }
} else if ((typeFrom == Material.WATER) && wcfg.isLogging(Logging.WATERFLOW)) { }
Levelled levelledFrom = fromWaterlogged ? null : (Levelled) blockDataFrom; } else if ((typeFrom == Material.WATER) && wcfg.isLogging(Logging.WATERFLOW)) {
Levelled newBlock = (Levelled) Material.WATER.createBlockData(); Levelled levelledFrom = fromWaterlogged ? null : (Levelled) blockDataFrom;
newBlock.setLevel(fromWaterlogged || down ? 1 : Math.min(levelledFrom.getLevel() + 1, levelledFrom.getMaximumLevel())); Levelled newBlock = (Levelled) Material.WATER.createBlockData();
if (BukkitUtils.isEmpty(typeTo)) { newBlock.setLevel(fromWaterlogged || down ? 1 : levelledFrom.getLevel() + 1);
consumer.queueBlockPlace(new Actor("WaterFlow", source), to.getLocation(), newBlock); if (BukkitUtils.isEmpty(typeTo)) {
} else if (BukkitUtils.isNonFluidProofBlock(typeTo)) { consumer.queueBlockPlace(new Actor("WaterFlow", source), to.getLocation(), newBlock);
consumer.queueBlockReplace(new Actor("WaterFlow", source), to.getState(), newBlock); } else if (BukkitUtils.getNonFluidProofBlocks().contains(typeTo)) {
} else if (typeTo == Material.LAVA) { consumer.queueBlockReplace(new Actor("WaterFlow", source), to.getState(), newBlock);
int toLevel = ((Levelled) to.getBlockData()).getLevel(); } else if (typeTo == Material.LAVA) {
if (toLevel == 0) { int toLevel = ((Levelled) to.getBlockData()).getLevel();
consumer.queueBlockReplace(new Actor("WaterFlow", source), to.getState(), Material.OBSIDIAN.createBlockData()); if (toLevel == 0) {
} else if (event.getFace() == BlockFace.DOWN) { consumer.queueBlockReplace(new Actor("WaterFlow", source), to.getState(), Material.OBSIDIAN.createBlockData());
consumer.queueBlockReplace(new Actor("WaterFlow", source), to.getState(), Material.STONE.createBlockData()); } else if (event.getFace() == BlockFace.DOWN) {
} consumer.queueBlockReplace(new Actor("WaterFlow", source), to.getState(), Material.STONE.createBlockData());
} }
if (BukkitUtils.isEmpty(typeTo) || BukkitUtils.isNonFluidProofBlock(typeTo)) { }
for (final BlockFace face : new BlockFace[] { BlockFace.DOWN, BlockFace.NORTH, BlockFace.WEST, BlockFace.EAST, BlockFace.SOUTH }) { if (BukkitUtils.isEmpty(typeTo) || BukkitUtils.getNonFluidProofBlocks().contains(typeTo)) {
final Block lower = to.getRelative(face); for (final BlockFace face : new BlockFace[] { BlockFace.DOWN, BlockFace.NORTH, BlockFace.WEST, BlockFace.EAST, BlockFace.SOUTH }) {
if (lower.getType() == Material.LAVA) { final Block lower = to.getRelative(face);
int toLevel = ((Levelled) lower.getBlockData()).getLevel(); if (lower.getType() == Material.LAVA) {
if (toLevel == 0) { int toLevel = ((Levelled) lower.getBlockData()).getLevel();
consumer.queueBlockReplace(new Actor("WaterFlow", source), lower.getState(), Material.OBSIDIAN.createBlockData()); if (toLevel == 0) {
} else if (event.getFace() == BlockFace.DOWN) { consumer.queueBlockReplace(new Actor("WaterFlow", source), lower.getState(), Material.OBSIDIAN.createBlockData());
consumer.queueBlockReplace(new Actor("WaterFlow", source), lower.getState(), Material.STONE.createBlockData()); } else if (event.getFace() == BlockFace.DOWN) {
} consumer.queueBlockReplace(new Actor("WaterFlow", source), lower.getState(), Material.STONE.createBlockData());
} }
} }
} }
} }
} }
} }
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockForm(BlockFormEvent event) { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
final WorldConfig wcfg = getWorldConfig(event.getBlock().getWorld()); public void onBlockForm(BlockFormEvent event) {
if (wcfg != null && (wcfg.isLogging(Logging.WATERFLOW) || wcfg.isLogging(Logging.LAVAFLOW))) { final WorldConfig wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg.isLogging(Logging.LAVAFLOW) && event.getBlock().getType() == Material.WATER && event.getNewState().getType() == Material.COBBLESTONE) { if (wcfg != null && (wcfg.isLogging(Logging.WATERFLOW) || wcfg.isLogging(Logging.LAVAFLOW))) {
consumer.queueBlockReplace(new Actor("LavaFlow"), event.getBlock().getBlockData(), event.getNewState()); if (wcfg.isLogging(Logging.LAVAFLOW) && event.getBlock().getType() == Material.WATER && event.getNewState().getType() == Material.COBBLESTONE) {
} consumer.queueBlockReplace(new Actor("LavaFlow"), event.getBlock().getBlockData(), event.getNewState());
if (wcfg.isLogging(Logging.WATERFLOW) && event.getBlock().getType() == Material.LAVA) { }
consumer.queueBlockReplace(new Actor("WaterFlow"), event.getBlock().getBlockData(), event.getNewState()); if (wcfg.isLogging(Logging.WATERFLOW) && event.getBlock().getType() == Material.LAVA) {
} consumer.queueBlockReplace(new Actor("WaterFlow"), event.getBlock().getBlockData(), event.getNewState());
if (wcfg.isLogging(Logging.WATERFLOW) && BukkitUtils.isConcreteBlock(event.getNewState().getType())) { }
consumer.queueBlockReplace(new Actor("WaterFlow"), event.getBlock().getBlockData(), event.getNewState()); if (wcfg.isLogging(Logging.WATERFLOW) && BukkitUtils.isConcreteBlock(event.getNewState().getType())) {
} consumer.queueBlockReplace(new Actor("WaterFlow"), event.getBlock().getBlockData(), event.getNewState());
} }
} }
}
private static boolean isSurroundedByWater(Block block) {
for (final BlockFace face : new BlockFace[] { BlockFace.NORTH, BlockFace.WEST, BlockFace.EAST, BlockFace.SOUTH }) { private static boolean isSurroundedByWater(Block block) {
if (block.getRelative(face).getType() == Material.WATER) { for (final BlockFace face : new BlockFace[] { BlockFace.NORTH, BlockFace.WEST, BlockFace.EAST, BlockFace.SOUTH }) {
return true; if (block.getRelative(face).getType() == Material.WATER) {
} return true;
} }
return false; }
} return false;
} }
}

View File

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

@ -1,51 +1,51 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.Config.*; import de.diddiz.LogBlock.config.Config.*;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity; import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Monster; import org.bukkit.entity.Monster;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityDeathEvent;
import static de.diddiz.LogBlock.config.Config.*; import static de.diddiz.LogBlock.config.Config.*;
public class KillLogging extends LoggingListener { public class KillLogging extends LoggingListener {
public KillLogging(LogBlock lb) { public KillLogging(LogBlock lb) {
super(lb); super(lb);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityDeath(EntityDeathEvent deathEvent) { public void onEntityDeath(EntityDeathEvent deathEvent) {
EntityDamageEvent event = deathEvent.getEntity().getLastDamageCause(); EntityDamageEvent event = deathEvent.getEntity().getLastDamageCause();
// For a death event, there should always be a damage event and it should not be cancelled. Check anyway. // For a death event, there should always be a damage event and it should not be cancelled. Check anyway.
if (event != null && event.isCancelled() == false && isLogging(event.getEntity().getWorld(), Logging.KILL) && event.getEntity() instanceof LivingEntity) { if (event != null && event.isCancelled() == false && isLogging(event.getEntity().getWorld(), Logging.KILL) && event.getEntity() instanceof LivingEntity) {
final LivingEntity victim = (LivingEntity) event.getEntity(); final LivingEntity victim = (LivingEntity) event.getEntity();
if (event instanceof EntityDamageByEntityEvent) { if (event instanceof EntityDamageByEntityEvent) {
final Entity killer = ((EntityDamageByEntityEvent) event).getDamager(); final Entity killer = ((EntityDamageByEntityEvent) event).getDamager();
if (logKillsLevel == LogKillsLevel.PLAYERS && !(victim instanceof Player && killer instanceof Player)) { if (logKillsLevel == LogKillsLevel.PLAYERS && !(victim instanceof Player && killer instanceof Player)) {
return; return;
} else if (logKillsLevel == LogKillsLevel.MONSTERS && !((victim instanceof Player || victim instanceof Monster) && killer instanceof Player || killer instanceof Monster)) { } else if (logKillsLevel == LogKillsLevel.MONSTERS && !((victim instanceof Player || victim instanceof Monster) && killer instanceof Player || killer instanceof Monster)) {
return; return;
} }
consumer.queueKill(killer, victim); consumer.queueKill(killer, victim);
} else if (deathEvent.getEntity().getKiller() != null) { } else if (deathEvent.getEntity().getKiller() != null) {
consumer.queueKill(deathEvent.getEntity().getKiller(), victim); consumer.queueKill(deathEvent.getEntity().getKiller(), victim);
} else if (logEnvironmentalKills) { } else if (logEnvironmentalKills) {
if (logKillsLevel == LogKillsLevel.PLAYERS && !(victim instanceof Player)) { if (logKillsLevel == LogKillsLevel.PLAYERS && !(victim instanceof Player)) {
return; return;
} else if (logKillsLevel == LogKillsLevel.MONSTERS && !((victim instanceof Player || victim instanceof Monster))) { } else if (logKillsLevel == LogKillsLevel.MONSTERS && !((victim instanceof Player || victim instanceof Monster))) {
return; return;
} }
consumer.queueKill(new Actor(event.getCause().toString()), victim); consumer.queueKill(new Actor(event.getCause().toString()), victim);
} }
} }
} }
} }

View File

@ -1,26 +1,26 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.LeavesDecayEvent; import org.bukkit.event.block.LeavesDecayEvent;
import static de.diddiz.LogBlock.config.Config.isLogging; import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.LogBlock.util.LoggingUtil.smartLogBlockBreak; import static de.diddiz.util.LoggingUtil.smartLogBlockBreak;
import static de.diddiz.LogBlock.util.LoggingUtil.smartLogFallables; import static de.diddiz.util.LoggingUtil.smartLogFallables;
public class LeavesDecayLogging extends LoggingListener { public class LeavesDecayLogging extends LoggingListener {
public LeavesDecayLogging(LogBlock lb) { public LeavesDecayLogging(LogBlock lb) {
super(lb); super(lb);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onLeavesDecay(LeavesDecayEvent event) { public void onLeavesDecay(LeavesDecayEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.LEAVESDECAY)) { if (isLogging(event.getBlock().getWorld(), Logging.LEAVESDECAY)) {
smartLogBlockBreak(consumer, new Actor("LeavesDecay"), event.getBlock()); smartLogBlockBreak(consumer, new Actor("LeavesDecay"), event.getBlock());
smartLogFallables(consumer, new Actor("LeavesDecay"), event.getBlock()); smartLogFallables(consumer, new Actor("LeavesDecay"), event.getBlock());
} }
} }
} }

View File

@ -1,13 +1,13 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Consumer; import de.diddiz.LogBlock.Consumer;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
public class LoggingListener implements Listener { public class LoggingListener implements Listener {
protected final Consumer consumer; protected final Consumer consumer;
public LoggingListener(LogBlock lb) { public LoggingListener(LogBlock lb) {
consumer = lb.getConsumer(); consumer = lb.getConsumer();
} }
} }

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

@ -1,43 +1,43 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.config.Config; import de.diddiz.LogBlock.config.Config;
import java.util.HashMap; import java.util.HashMap;
import java.util.UUID; import java.util.UUID;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
public class PlayerInfoLogging extends LoggingListener { public class PlayerInfoLogging extends LoggingListener {
private final HashMap<UUID, Long> playerLogins = new HashMap<>(); private final HashMap<UUID, Long> playerLogins = new HashMap<>();
public PlayerInfoLogging(LogBlock lb) { public PlayerInfoLogging(LogBlock lb) {
super(lb); super(lb);
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onPlayerJoin(PlayerJoinEvent event) { public void onPlayerJoin(PlayerJoinEvent event) {
playerLogins.put(event.getPlayer().getUniqueId(), System.currentTimeMillis()); playerLogins.put(event.getPlayer().getUniqueId(), System.currentTimeMillis());
consumer.queueJoin(event.getPlayer()); consumer.queueJoin(event.getPlayer());
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onPlayerQuit(PlayerQuitEvent event) { public void onPlayerQuit(PlayerQuitEvent event) {
onPlayerQuit(event.getPlayer()); onPlayerQuit(event.getPlayer());
} }
public void onPlayerQuit(Player player) { public void onPlayerQuit(Player player) {
Long joinTime = playerLogins.remove(player.getUniqueId()); Long joinTime = playerLogins.remove(player.getUniqueId());
if (Config.logPlayerInfo && joinTime != null) { if (Config.logPlayerInfo && joinTime != null) {
long onlineTime = (System.currentTimeMillis() - joinTime) / 1000; long onlineTime = (System.currentTimeMillis() - joinTime) / 1000;
if (onlineTime > 0) { if (onlineTime > 0) {
consumer.queueLeave(player, onlineTime); consumer.queueLeave(player, onlineTime);
} }
} }
} }
} }

View File

@ -18,7 +18,7 @@ import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.BlockPlaceEvent;
import static de.diddiz.LogBlock.config.Config.isLogging; 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 { public class ScaffoldingLogging extends LoggingListener {
private final static long MAX_SCAFFOLDING_LOG_TIME_MS = 2000; private final static long MAX_SCAFFOLDING_LOG_TIME_MS = 2000;

View File

@ -1,40 +1,23 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import java.util.Objects; import org.bukkit.event.EventHandler;
import org.bukkit.block.BlockState; import org.bukkit.event.EventPriority;
import org.bukkit.block.Sign; import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.block.sign.SignSide;
import org.bukkit.event.EventHandler; import static de.diddiz.LogBlock.config.Config.isLogging;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.SignChangeEvent; public class SignChangeLogging extends LoggingListener {
public SignChangeLogging(LogBlock lb) {
import static de.diddiz.LogBlock.config.Config.isLogging; super(lb);
}
public class SignChangeLogging extends LoggingListener {
public SignChangeLogging(LogBlock lb) { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
super(lb); public void onSignChange(SignChangeEvent event) {
} if (isLogging(event.getBlock().getWorld(), Logging.SIGNTEXT)) {
consumer.queueSignChange(Actor.actorFromEntity(event.getPlayer()), event.getBlock().getLocation(), event.getBlock().getBlockData(), event.getLines());
@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);
}
}
}
}
}

View File

@ -1,28 +1,28 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockFadeEvent; import org.bukkit.event.block.BlockFadeEvent;
import static de.diddiz.LogBlock.config.Config.isLogging; import static de.diddiz.LogBlock.config.Config.isLogging;
public class SnowFadeLogging extends LoggingListener { public class SnowFadeLogging extends LoggingListener {
public SnowFadeLogging(LogBlock lb) { public SnowFadeLogging(LogBlock lb) {
super(lb); super(lb);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockFade(BlockFadeEvent event) { public void onBlockFade(BlockFadeEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.SNOWFADE)) { if (isLogging(event.getBlock().getWorld(), Logging.SNOWFADE)) {
final Material type = event.getBlock().getType(); final Material type = event.getBlock().getType();
if (type == Material.SNOW || type == Material.ICE) { if (type == Material.SNOW || type == Material.ICE) {
consumer.queueBlockReplace(new Actor("SnowFade"), event.getBlock().getState(), event.getNewState()); consumer.queueBlockReplace(new Actor("SnowFade"), event.getBlock().getState(), event.getNewState());
} }
} }
} }
} }

View File

@ -1,28 +1,28 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockFormEvent; import org.bukkit.event.block.BlockFormEvent;
import static de.diddiz.LogBlock.config.Config.isLogging; import static de.diddiz.LogBlock.config.Config.isLogging;
public class SnowFormLogging extends LoggingListener { public class SnowFormLogging extends LoggingListener {
public SnowFormLogging(LogBlock lb) { public SnowFormLogging(LogBlock lb) {
super(lb); super(lb);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockForm(BlockFormEvent event) { public void onBlockForm(BlockFormEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.SNOWFORM)) { if (isLogging(event.getBlock().getWorld(), Logging.SNOWFORM)) {
final Material type = event.getNewState().getType(); final Material type = event.getNewState().getType();
if (type == Material.SNOW || type == Material.ICE) { if (type == Material.SNOW || type == Material.ICE) {
consumer.queueBlockReplace(new Actor("SnowForm"), event.getBlock().getState(), event.getNewState()); consumer.queueBlockReplace(new Actor("SnowForm"), event.getBlock().getState(), event.getNewState());
} }
} }
} }
} }

View File

@ -1,34 +1,40 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig; import de.diddiz.LogBlock.config.WorldConfig;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.world.StructureGrowEvent; import org.bukkit.event.world.StructureGrowEvent;
import static de.diddiz.LogBlock.config.Config.getWorldConfig; import static de.diddiz.LogBlock.config.Config.getWorldConfig;
public class StructureGrowLogging extends LoggingListener { public class StructureGrowLogging extends LoggingListener {
public StructureGrowLogging(LogBlock lb) { public StructureGrowLogging(LogBlock lb) {
super(lb); super(lb);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onStructureGrow(StructureGrowEvent event) { public void onStructureGrow(StructureGrowEvent event) {
final WorldConfig wcfg = getWorldConfig(event.getWorld()); final WorldConfig wcfg = getWorldConfig(event.getWorld());
if (wcfg != null) { if (wcfg != null) {
if (!wcfg.isLogging(Logging.NATURALSTRUCTUREGROW)) { final Actor actor;
return; if (event.getPlayer() != null) {
} if (!wcfg.isLogging(Logging.BONEMEALSTRUCTUREGROW)) {
if (!event.isFromBonemeal()) { return;
final Actor actor = new Actor("NaturalGrow"); }
for (final BlockState state : event.getBlocks()) { actor = Actor.actorFromEntity(event.getPlayer());
consumer.queueBlockReplace(actor, state.getBlock().getState(), state); } 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

@ -1,151 +1,151 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.*; import de.diddiz.LogBlock.*;
import de.diddiz.LogBlock.events.ToolUseEvent; import de.diddiz.LogBlock.events.ToolUseEvent;
import de.diddiz.LogBlock.util.BukkitUtils; import de.diddiz.util.BukkitUtils;
import de.diddiz.LogBlock.util.CuboidRegion; import de.diddiz.util.CuboidRegion;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.block.Action; import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import java.util.Map.Entry; import java.util.Map.Entry;
import static de.diddiz.LogBlock.Session.getSession; import static de.diddiz.LogBlock.Session.getSession;
import static de.diddiz.LogBlock.Session.hasSession; import static de.diddiz.LogBlock.Session.hasSession;
import static de.diddiz.LogBlock.config.Config.isLogged; import static de.diddiz.LogBlock.config.Config.isLogged;
import static de.diddiz.LogBlock.config.Config.toolsByType; import static de.diddiz.LogBlock.config.Config.toolsByType;
public class ToolListener implements Listener { public class ToolListener implements Listener {
private final CommandsHandler handler; private final CommandsHandler handler;
private final LogBlock logblock; private final LogBlock logblock;
public ToolListener(LogBlock logblock) { public ToolListener(LogBlock logblock) {
this.logblock = logblock; this.logblock = logblock;
handler = logblock.getCommandsHandler(); handler = logblock.getCommandsHandler();
} }
@EventHandler @EventHandler
public void onPlayerInteract(PlayerInteractEvent event) { public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getMaterial() != null) { if (event.getMaterial() != null) {
final Action action = event.getAction(); final Action action = event.getAction();
final Material type = event.getMaterial(); final Material type = event.getMaterial();
final Tool tool = toolsByType.get(type); final Tool tool = toolsByType.get(type);
final Player player = event.getPlayer(); final Player player = event.getPlayer();
if (tool != null && (action == Action.RIGHT_CLICK_BLOCK || action == Action.LEFT_CLICK_BLOCK) && logblock.hasPermission(player, "logblock.tools." + tool.name)) { if (tool != null && (action == Action.RIGHT_CLICK_BLOCK || action == Action.LEFT_CLICK_BLOCK) && logblock.hasPermission(player, "logblock.tools." + tool.name)) {
final ToolBehavior behavior = action == Action.RIGHT_CLICK_BLOCK ? tool.rightClickBehavior : tool.leftClickBehavior; final ToolBehavior behavior = action == Action.RIGHT_CLICK_BLOCK ? tool.rightClickBehavior : tool.leftClickBehavior;
final ToolData toolData = getSession(player).toolData.get(tool); final ToolData toolData = getSession(player).toolData.get(tool);
if (behavior != ToolBehavior.NONE && toolData.enabled) { if (behavior != ToolBehavior.NONE && toolData.enabled) {
if (!isLogged(player.getWorld())) { if (!isLogged(player.getWorld())) {
player.sendMessage(ChatColor.RED + "This world is not currently logged."); player.sendMessage(ChatColor.RED + "This world is not currently logged.");
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
final Block block = event.getClickedBlock(); final Block block = event.getClickedBlock();
final QueryParams params = toolData.params.clone(); final QueryParams params = toolData.params.clone();
params.loc = null; params.loc = null;
params.sel = null; params.sel = null;
if (behavior == ToolBehavior.BLOCK) { if (behavior == ToolBehavior.BLOCK) {
params.setLocation(block.getRelative(event.getBlockFace()).getLocation()); params.setLocation(block.getRelative(event.getBlockFace()).getLocation());
} else if (tool.params.radius != 0) { } else if (tool.params.radius != 0) {
params.setLocation(block.getLocation()); params.setLocation(block.getLocation());
} else { } else {
Block otherHalfChest = BukkitUtils.getConnectedChest(block); Block otherHalfChest = BukkitUtils.getConnectedChest(block);
if (otherHalfChest == null) { if (otherHalfChest == null) {
params.setLocation(block.getLocation()); params.setLocation(block.getLocation());
} else { } else {
params.setSelection(CuboidRegion.fromCorners(block.getLocation().getWorld(), block.getLocation(), otherHalfChest.getLocation())); params.setSelection(CuboidRegion.fromCorners(block.getLocation().getWorld(), block.getLocation(), otherHalfChest.getLocation()));
} }
} }
try { try {
params.validate(); params.validate();
if (this.callToolUseEvent(new ToolUseEvent(player, tool, behavior, params))) { if (this.callToolUseEvent(new ToolUseEvent(player, tool, behavior, params))) {
return; return;
} }
if (toolData.mode == ToolMode.ROLLBACK) { if (toolData.mode == ToolMode.ROLLBACK) {
handler.new CommandRollback(player, params, true); handler.new CommandRollback(player, params, true);
} else if (toolData.mode == ToolMode.REDO) { } else if (toolData.mode == ToolMode.REDO) {
handler.new CommandRedo(player, params, true); handler.new CommandRedo(player, params, true);
} else if (toolData.mode == ToolMode.CLEARLOG) { } else if (toolData.mode == ToolMode.CLEARLOG) {
handler.new CommandClearLog(player, params, true); handler.new CommandClearLog(player, params, true);
} else if (toolData.mode == ToolMode.WRITELOGFILE) { } else if (toolData.mode == ToolMode.WRITELOGFILE) {
handler.new CommandWriteLogFile(player, params, true); handler.new CommandWriteLogFile(player, params, true);
} else { } else {
handler.new CommandLookup(player, params, true); handler.new CommandLookup(player, params, true);
} }
} catch (final Exception ex) { } catch (final Exception ex) {
player.sendMessage(ChatColor.RED + ex.getMessage()); player.sendMessage(ChatColor.RED + ex.getMessage());
} }
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
} }
private boolean callToolUseEvent(ToolUseEvent event) { private boolean callToolUseEvent(ToolUseEvent event) {
this.logblock.getServer().getPluginManager().callEvent(event); this.logblock.getServer().getPluginManager().callEvent(event);
return event.isCancelled(); return event.isCancelled();
} }
@EventHandler @EventHandler
public void onPlayerChangedWorld(PlayerChangedWorldEvent event) { public void onPlayerChangedWorld(PlayerChangedWorldEvent event) {
final Player player = event.getPlayer(); final Player player = event.getPlayer();
if (hasSession(player)) { if (hasSession(player)) {
final Session session = getSession(player); final Session session = getSession(player);
for (final Entry<Tool, ToolData> entry : session.toolData.entrySet()) { for (final Entry<Tool, ToolData> entry : session.toolData.entrySet()) {
final Tool tool = entry.getKey(); final Tool tool = entry.getKey();
final ToolData toolData = entry.getValue(); final ToolData toolData = entry.getValue();
if (toolData.enabled && !logblock.hasPermission(player, "logblock.tools." + tool.name)) { if (toolData.enabled && !logblock.hasPermission(player, "logblock.tools." + tool.name)) {
toolData.enabled = false; toolData.enabled = false;
if (tool.removeOnDisable && logblock.hasPermission(player, "logblock.spawnTools")) { if (tool.removeOnDisable && logblock.hasPermission(player, "logblock.spawnTools")) {
player.getInventory().removeItem(new ItemStack(tool.item, 1)); player.getInventory().removeItem(new ItemStack(tool.item, 1));
} }
player.sendMessage(ChatColor.GREEN + "Tool disabled."); player.sendMessage(ChatColor.GREEN + "Tool disabled.");
} }
} }
} }
} }
@EventHandler @EventHandler
public void onPlayerDropItem(PlayerDropItemEvent event) { public void onPlayerDropItem(PlayerDropItemEvent event) {
final Player player = event.getPlayer(); final Player player = event.getPlayer();
if (hasSession(player)) { if (hasSession(player)) {
final Session session = getSession(player); final Session session = getSession(player);
for (final Entry<Tool, ToolData> entry : session.toolData.entrySet()) { for (final Entry<Tool, ToolData> entry : session.toolData.entrySet()) {
final Tool tool = entry.getKey(); final Tool tool = entry.getKey();
final ToolData toolData = entry.getValue(); final ToolData toolData = entry.getValue();
final Material item = event.getItemDrop().getItemStack().getType(); final Material item = event.getItemDrop().getItemStack().getType();
if (item == tool.item && toolData.enabled) { if (item == tool.item && toolData.enabled) {
if (tool.dropToDisable) { if (tool.dropToDisable) {
toolData.enabled = false; toolData.enabled = false;
ItemStack stack = event.getItemDrop().getItemStack(); ItemStack stack = event.getItemDrop().getItemStack();
if (tool.removeOnDisable && logblock.hasPermission(player, "logblock.spawnTools")) { if (tool.removeOnDisable && logblock.hasPermission(player, "logblock.spawnTools")) {
if (stack.isSimilar(new ItemStack(item))) { if (stack.isSimilar(new ItemStack(item))) {
if (stack.getAmount() > 1) { if (stack.getAmount() > 1) {
stack.setAmount(stack.getAmount() - 1); stack.setAmount(stack.getAmount() - 1);
event.getItemDrop().setItemStack(stack); event.getItemDrop().setItemStack(stack);
} else { } else {
event.getItemDrop().remove(); event.getItemDrop().remove();
} }
} }
} }
if (BukkitUtils.hasInventoryStorageSpaceFor(player.getInventory(), stack)) { if (BukkitUtils.hasInventoryStorageSpaceFor(player.getInventory(), stack)) {
event.setCancelled(true); event.setCancelled(true);
} }
player.sendMessage(ChatColor.GREEN + "Tool disabled."); player.sendMessage(ChatColor.GREEN + "Tool disabled.");
} else if (!tool.canDrop) { } else if (!tool.canDrop) {
player.sendMessage(ChatColor.RED + "You cannot drop this tool."); player.sendMessage(ChatColor.RED + "You cannot drop this tool.");
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
} }
} }
} }

View File

@ -1,24 +1,24 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import org.bukkit.entity.Wither; import org.bukkit.entity.Wither;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityChangeBlockEvent;
import static de.diddiz.LogBlock.config.Config.isLogging; import static de.diddiz.LogBlock.config.Config.isLogging;
public class WitherLogging extends LoggingListener { public class WitherLogging extends LoggingListener {
public WitherLogging(LogBlock lb) { public WitherLogging(LogBlock lb) {
super(lb); super(lb);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) { public void onEntityChangeBlock(EntityChangeBlockEvent event) {
if (event.getEntity() instanceof Wither && isLogging(event.getBlock().getWorld(), Logging.WITHER)) { if (event.getEntity() instanceof Wither && isLogging(event.getBlock().getWorld(), Logging.WITHER)) {
consumer.queueBlockReplace(Actor.actorFromEntity(event.getEntity()), event.getBlock().getState(), event.getBlockData()); // Wither walked through a block. consumer.queueBlockReplace(Actor.actorFromEntity(event.getEntity()), event.getBlock().getState(), event.getBlockData()); // Wither walked through a 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; import net.md_5.bungee.api.ChatColor;

View File

@ -1,424 +1,424 @@
package de.diddiz.LogBlock.util; package de.diddiz.util;
// Taken from maven-artifact at // 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 // 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
/* /*
* Licensed to the Apache Software Foundation (ASF) under one * Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file * or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file * regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the * to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance * "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at * with the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an * software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
import java.math.BigInteger; import java.math.BigInteger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.Locale; import java.util.Locale;
import java.util.Properties; import java.util.Properties;
import java.util.Stack; import java.util.Stack;
/** /**
* Generic implementation of version comparison. * Generic implementation of version comparison.
* *
* <p>Features: * <p>Features:
* <ul> * <ul>
* <li>mixing of '<code>-</code>' (dash) and '<code>.</code>' (dot) separators,</li> * <li>mixing of '<code>-</code>' (dash) and '<code>.</code>' (dot) separators,</li>
* <li>transition between characters and digits also constitutes a separator: * <li>transition between characters and digits also constitutes a separator:
* <code>1.0alpha1 =&gt; [1, 0, alpha, 1]</code></li> * <code>1.0alpha1 =&gt; [1, 0, alpha, 1]</code></li>
* <li>unlimited number of version components,</li> * <li>unlimited number of version components,</li>
* <li>version components in the text can be digits or strings,</li> * <li>version components in the text can be digits or strings,</li>
* <li>strings are checked for well-known qualifiers and the qualifier ordering is used for version ordering. * <li>strings are checked for well-known qualifiers and the qualifier ordering is used for version ordering.
* Well-known qualifiers (case insensitive) are:<ul> * Well-known qualifiers (case insensitive) are:<ul>
* <li><code>alpha</code> or <code>a</code></li> * <li><code>alpha</code> or <code>a</code></li>
* <li><code>beta</code> or <code>b</code></li> * <li><code>beta</code> or <code>b</code></li>
* <li><code>milestone</code> or <code>m</code></li> * <li><code>milestone</code> or <code>m</code></li>
* <li><code>rc</code> or <code>cr</code></li> * <li><code>rc</code> or <code>cr</code></li>
* <li><code>snapshot</code></li> * <li><code>snapshot</code></li>
* <li><code>(the empty string)</code> or <code>ga</code> or <code>final</code></li> * <li><code>(the empty string)</code> or <code>ga</code> or <code>final</code></li>
* <li><code>sp</code></li> * <li><code>sp</code></li>
* </ul> * </ul>
* Unknown qualifiers are considered after known qualifiers, with lexical order (always case insensitive), * Unknown qualifiers are considered after known qualifiers, with lexical order (always case insensitive),
* </li> * </li>
* <li>a dash usually precedes a qualifier, and is always less important than something preceded with a dot.</li> * <li>a dash usually precedes a qualifier, and is always less important than something preceded with a dot.</li>
* </ul></p> * </ul></p>
* *
* @see <a href="https://cwiki.apache.org/confluence/display/MAVENOLD/Versioning">"Versioning" on Maven Wiki</a> * @see <a href="https://cwiki.apache.org/confluence/display/MAVENOLD/Versioning">"Versioning" on Maven Wiki</a>
* @author <a href="mailto:kenney@apache.org">Kenney Westerhof</a> * @author <a href="mailto:kenney@apache.org">Kenney Westerhof</a>
* @author <a href="mailto:hboutemy@apache.org">Hervé Boutemy</a> * @author <a href="mailto:hboutemy@apache.org">Hervé Boutemy</a>
*/ */
public class ComparableVersion implements Comparable<ComparableVersion> { public class ComparableVersion implements Comparable<ComparableVersion> {
private String value; private String value;
private String canonical; private String canonical;
private ListItem items; private ListItem items;
private interface Item { private interface Item {
int INTEGER_ITEM = 0; int INTEGER_ITEM = 0;
int STRING_ITEM = 1; int STRING_ITEM = 1;
int LIST_ITEM = 2; int LIST_ITEM = 2;
int compareTo(Item item); int compareTo(Item item);
int getType(); int getType();
boolean isNull(); boolean isNull();
} }
/** /**
* Represents a numeric item in the version item list. * Represents a numeric item in the version item list.
*/ */
private static class IntegerItem implements Item { private static class IntegerItem implements Item {
private static final BigInteger BIG_INTEGER_ZERO = new BigInteger("0"); private static final BigInteger BIG_INTEGER_ZERO = new BigInteger("0");
private final BigInteger value; private final BigInteger value;
public static final IntegerItem ZERO = new IntegerItem(); public static final IntegerItem ZERO = new IntegerItem();
private IntegerItem() { private IntegerItem() {
this.value = BIG_INTEGER_ZERO; this.value = BIG_INTEGER_ZERO;
} }
public IntegerItem(String str) { public IntegerItem(String str) {
this.value = new BigInteger(str); this.value = new BigInteger(str);
} }
@Override @Override
public int getType() { public int getType() {
return INTEGER_ITEM; return INTEGER_ITEM;
} }
@Override @Override
public boolean isNull() { public boolean isNull() {
return BIG_INTEGER_ZERO.equals(value); return BIG_INTEGER_ZERO.equals(value);
} }
@Override @Override
public int compareTo(Item item) { public int compareTo(Item item) {
if (item == null) { if (item == null) {
return BIG_INTEGER_ZERO.equals(value) ? 0 : 1; // 1.0 == 1, 1.1 > 1 return BIG_INTEGER_ZERO.equals(value) ? 0 : 1; // 1.0 == 1, 1.1 > 1
} }
switch (item.getType()) { switch (item.getType()) {
case INTEGER_ITEM: case INTEGER_ITEM:
return value.compareTo(((IntegerItem) item).value); return value.compareTo(((IntegerItem) item).value);
case STRING_ITEM: case STRING_ITEM:
return 1; // 1.1 > 1-sp return 1; // 1.1 > 1-sp
case LIST_ITEM: case LIST_ITEM:
return 1; // 1.1 > 1-1 return 1; // 1.1 > 1-1
default: default:
throw new RuntimeException("invalid item: " + item.getClass()); throw new RuntimeException("invalid item: " + item.getClass());
} }
} }
@Override @Override
public String toString() { public String toString() {
return value.toString(); return value.toString();
} }
} }
/** /**
* Represents a string in the version item list, usually a qualifier. * Represents a string in the version item list, usually a qualifier.
*/ */
private static class StringItem implements Item { private static class StringItem implements Item {
private static final String[] QUALIFIERS = { "alpha", "beta", "milestone", "rc", "snapshot", "", "sp" }; private static final String[] QUALIFIERS = { "alpha", "beta", "milestone", "rc", "snapshot", "", "sp" };
private static final List<String> _QUALIFIERS = Arrays.asList(QUALIFIERS); private static final List<String> _QUALIFIERS = Arrays.asList(QUALIFIERS);
private static final Properties ALIASES = new Properties(); private static final Properties ALIASES = new Properties();
static { static {
ALIASES.put("ga", ""); ALIASES.put("ga", "");
ALIASES.put("final", ""); ALIASES.put("final", "");
ALIASES.put("cr", "rc"); ALIASES.put("cr", "rc");
} }
/** /**
* A comparable value for the empty-string qualifier. This one is used to determine if a given qualifier makes * A comparable value for the empty-string qualifier. This one is used to determine if a given qualifier makes
* the version older than one without a qualifier, or more recent. * the version older than one without a qualifier, or more recent.
*/ */
private static final String RELEASE_VERSION_INDEX = String.valueOf(_QUALIFIERS.indexOf("")); private static final String RELEASE_VERSION_INDEX = String.valueOf(_QUALIFIERS.indexOf(""));
private String value; private String value;
public StringItem(String value, boolean followedByDigit) { public StringItem(String value, boolean followedByDigit) {
if (followedByDigit && value.length() == 1) { if (followedByDigit && value.length() == 1) {
// a1 = alpha-1, b1 = beta-1, m1 = milestone-1 // a1 = alpha-1, b1 = beta-1, m1 = milestone-1
switch (value.charAt(0)) { switch (value.charAt(0)) {
case 'a': case 'a':
value = "alpha"; value = "alpha";
break; break;
case 'b': case 'b':
value = "beta"; value = "beta";
break; break;
case 'm': case 'm':
value = "milestone"; value = "milestone";
break; break;
} }
} }
this.value = ALIASES.getProperty(value, value); this.value = ALIASES.getProperty(value, value);
} }
@Override @Override
public int getType() { public int getType() {
return STRING_ITEM; return STRING_ITEM;
} }
@Override @Override
public boolean isNull() { public boolean isNull() {
return (comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX) == 0); return (comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX) == 0);
} }
/** /**
* Returns a comparable value for a qualifier. * Returns a comparable value for a qualifier.
* *
* This method takes into account the ordering of known qualifiers then unknown qualifiers with lexical ordering. * This method takes into account the ordering of known qualifiers then unknown qualifiers with lexical ordering.
* *
* just returning an Integer with the index here is faster, but requires a lot of if/then/else to check for -1 * just returning an Integer with the index here is faster, but requires a lot of if/then/else to check for -1
* or QUALIFIERS.size and then resort to lexical ordering. Most comparisons are decided by the first character, * or QUALIFIERS.size and then resort to lexical ordering. Most comparisons are decided by the first character,
* so this is still fast. If more characters are needed then it requires a lexical sort anyway. * so this is still fast. If more characters are needed then it requires a lexical sort anyway.
* *
* @param qualifier * @param qualifier
* @return an equivalent value that can be used with lexical comparison * @return an equivalent value that can be used with lexical comparison
*/ */
public static String comparableQualifier(String qualifier) { public static String comparableQualifier(String qualifier) {
int i = _QUALIFIERS.indexOf(qualifier); int i = _QUALIFIERS.indexOf(qualifier);
return i == -1 ? (_QUALIFIERS.size() + "-" + qualifier) : String.valueOf(i); return i == -1 ? (_QUALIFIERS.size() + "-" + qualifier) : String.valueOf(i);
} }
@Override @Override
public int compareTo(Item item) { public int compareTo(Item item) {
if (item == null) { if (item == null) {
// 1-rc < 1, 1-ga > 1 // 1-rc < 1, 1-ga > 1
return comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX); return comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX);
} }
switch (item.getType()) { switch (item.getType()) {
case INTEGER_ITEM: case INTEGER_ITEM:
return -1; // 1.any < 1.1 ? return -1; // 1.any < 1.1 ?
case STRING_ITEM: case STRING_ITEM:
return comparableQualifier(value).compareTo(comparableQualifier(((StringItem) item).value)); return comparableQualifier(value).compareTo(comparableQualifier(((StringItem) item).value));
case LIST_ITEM: case LIST_ITEM:
return -1; // 1.any < 1-1 return -1; // 1.any < 1-1
default: default:
throw new RuntimeException("invalid item: " + item.getClass()); throw new RuntimeException("invalid item: " + item.getClass());
} }
} }
@Override @Override
public String toString() { public String toString() {
return value; return value;
} }
} }
/** /**
* Represents a version list item. This class is used both for the global item list and for sub-lists (which start * Represents a version list item. This class is used both for the global item list and for sub-lists (which start
* with '-(number)' in the version specification). * with '-(number)' in the version specification).
*/ */
private static class ListItem extends ArrayList<Item> implements Item { private static class ListItem extends ArrayList<Item> implements Item {
private static final long serialVersionUID = 5914575811857700009L; private static final long serialVersionUID = 5914575811857700009L;
@Override @Override
public int getType() { public int getType() {
return LIST_ITEM; return LIST_ITEM;
} }
@Override @Override
public boolean isNull() { public boolean isNull() {
return (size() == 0); return (size() == 0);
} }
void normalize() { void normalize() {
for (ListIterator<Item> iterator = listIterator(size()); iterator.hasPrevious();) { for (ListIterator<Item> iterator = listIterator(size()); iterator.hasPrevious();) {
Item item = iterator.previous(); Item item = iterator.previous();
if (item.isNull()) { if (item.isNull()) {
iterator.remove(); // remove null trailing items: 0, "", empty list iterator.remove(); // remove null trailing items: 0, "", empty list
} else { } else {
break; break;
} }
} }
} }
@Override @Override
public int compareTo(Item item) { public int compareTo(Item item) {
if (item == null) { if (item == null) {
if (size() == 0) { if (size() == 0) {
return 0; // 1-0 = 1- (normalize) = 1 return 0; // 1-0 = 1- (normalize) = 1
} }
Item first = get(0); Item first = get(0);
return first.compareTo(null); return first.compareTo(null);
} }
switch (item.getType()) { switch (item.getType()) {
case INTEGER_ITEM: case INTEGER_ITEM:
return -1; // 1-1 < 1.0.x return -1; // 1-1 < 1.0.x
case STRING_ITEM: case STRING_ITEM:
return 1; // 1-1 > 1-sp return 1; // 1-1 > 1-sp
case LIST_ITEM: case LIST_ITEM:
Iterator<Item> left = iterator(); Iterator<Item> left = iterator();
Iterator<Item> right = ((ListItem) item).iterator(); Iterator<Item> right = ((ListItem) item).iterator();
while (left.hasNext() || right.hasNext()) { while (left.hasNext() || right.hasNext()) {
Item l = left.hasNext() ? left.next() : null; Item l = left.hasNext() ? left.next() : null;
Item r = right.hasNext() ? right.next() : null; Item r = right.hasNext() ? right.next() : null;
// if this is shorter, then invert the compare and mul with -1 // if this is shorter, then invert the compare and mul with -1
int result = l == null ? (r == null ? 0 : -1 * r.compareTo(l)) : l.compareTo(r); int result = l == null ? (r == null ? 0 : -1 * r.compareTo(l)) : l.compareTo(r);
if (result != 0) { if (result != 0) {
return result; return result;
} }
} }
return 0; return 0;
default: default:
throw new RuntimeException("invalid item: " + item.getClass()); throw new RuntimeException("invalid item: " + item.getClass());
} }
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder buffer = new StringBuilder("("); StringBuilder buffer = new StringBuilder("(");
for (Iterator<Item> iter = iterator(); iter.hasNext();) { for (Iterator<Item> iter = iterator(); iter.hasNext();) {
buffer.append(iter.next()); buffer.append(iter.next());
if (iter.hasNext()) { if (iter.hasNext()) {
buffer.append(','); buffer.append(',');
} }
} }
buffer.append(')'); buffer.append(')');
return buffer.toString(); return buffer.toString();
} }
} }
public ComparableVersion(String version) { public ComparableVersion(String version) {
parseVersion(version); parseVersion(version);
} }
public final void parseVersion(String version) { public final void parseVersion(String version) {
this.value = version; this.value = version;
items = new ListItem(); items = new ListItem();
version = version.toLowerCase(Locale.ENGLISH); version = version.toLowerCase(Locale.ENGLISH);
ListItem list = items; ListItem list = items;
Stack<Item> stack = new Stack<>(); Stack<Item> stack = new Stack<>();
stack.push(list); stack.push(list);
boolean isDigit = false; boolean isDigit = false;
int startIndex = 0; int startIndex = 0;
for (int i = 0; i < version.length(); i++) { for (int i = 0; i < version.length(); i++) {
char c = version.charAt(i); char c = version.charAt(i);
if (c == '.') { if (c == '.') {
if (i == startIndex) { if (i == startIndex) {
list.add(IntegerItem.ZERO); list.add(IntegerItem.ZERO);
} else { } else {
list.add(parseItem(isDigit, version.substring(startIndex, i))); list.add(parseItem(isDigit, version.substring(startIndex, i)));
} }
startIndex = i + 1; startIndex = i + 1;
} else if (c == '-') { } else if (c == '-') {
if (i == startIndex) { if (i == startIndex) {
list.add(IntegerItem.ZERO); list.add(IntegerItem.ZERO);
} else { } else {
list.add(parseItem(isDigit, version.substring(startIndex, i))); list.add(parseItem(isDigit, version.substring(startIndex, i)));
} }
startIndex = i + 1; startIndex = i + 1;
if (isDigit) { if (isDigit) {
list.normalize(); // 1.0-* = 1-* list.normalize(); // 1.0-* = 1-*
if ((i + 1 < version.length()) && Character.isDigit(version.charAt(i + 1))) { if ((i + 1 < version.length()) && Character.isDigit(version.charAt(i + 1))) {
// new ListItem only if previous were digits and new char is a digit, // new ListItem only if previous were digits and new char is a digit,
// ie need to differentiate only 1.1 from 1-1 // ie need to differentiate only 1.1 from 1-1
list.add(list = new ListItem()); list.add(list = new ListItem());
stack.push(list); stack.push(list);
} }
} }
} else if (Character.isDigit(c)) { } else if (Character.isDigit(c)) {
if (!isDigit && i > startIndex) { if (!isDigit && i > startIndex) {
list.add(new StringItem(version.substring(startIndex, i), true)); list.add(new StringItem(version.substring(startIndex, i), true));
startIndex = i; startIndex = i;
} }
isDigit = true; isDigit = true;
} else { } else {
if (isDigit && i > startIndex) { if (isDigit && i > startIndex) {
list.add(parseItem(true, version.substring(startIndex, i))); list.add(parseItem(true, version.substring(startIndex, i)));
startIndex = i; startIndex = i;
} }
isDigit = false; isDigit = false;
} }
} }
if (version.length() > startIndex) { if (version.length() > startIndex) {
list.add(parseItem(isDigit, version.substring(startIndex))); list.add(parseItem(isDigit, version.substring(startIndex)));
} }
while (!stack.isEmpty()) { while (!stack.isEmpty()) {
list = (ListItem) stack.pop(); list = (ListItem) stack.pop();
list.normalize(); list.normalize();
} }
canonical = items.toString(); canonical = items.toString();
} }
private static Item parseItem(boolean isDigit, String buf) { private static Item parseItem(boolean isDigit, String buf) {
return isDigit ? new IntegerItem(buf) : new StringItem(buf, false); return isDigit ? new IntegerItem(buf) : new StringItem(buf, false);
} }
@Override @Override
public int compareTo(ComparableVersion o) { public int compareTo(ComparableVersion o) {
return items.compareTo(o.items); return items.compareTo(o.items);
} }
public int compareTo(String version) { public int compareTo(String version) {
return compareTo(new ComparableVersion(version)); return compareTo(new ComparableVersion(version));
} }
@Override @Override
public String toString() { public String toString() {
return value; return value;
} }
public String toCanonicalString() { public String toCanonicalString() {
return canonical; return canonical;
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
return (o instanceof ComparableVersion) && canonical.equals(((ComparableVersion) o).canonical); return (o instanceof ComparableVersion) && canonical.equals(((ComparableVersion) o).canonical);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return canonical.hashCode(); return canonical.hashCode();
} }
} }

View File

@ -1,4 +1,4 @@
package de.diddiz.LogBlock.util; package de.diddiz.util;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World; 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.Actor;
import de.diddiz.LogBlock.Consumer; 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;
import org.bukkit.block.data.type.Bell.Attachment; import org.bukkit.block.data.type.Bell.Attachment;
import org.bukkit.block.data.type.Lantern; 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.Entity;
import org.bukkit.entity.Projectile; import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed; import org.bukkit.entity.TNTPrimed;
@ -54,18 +52,18 @@ public class LoggingUtil {
int initialy = loc.getBlockY(); int initialy = loc.getBlockY();
int y = initialy; int y = initialy;
int z = loc.getBlockZ(); 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--; y--;
} }
if (initialy != y && !BukkitUtils.isEmpty(replaced.getType())) { if (initialy != y && !BukkitUtils.isEmpty(replaced.getType())) {
// this is not the final location but the block got removed (vines etc) // this is not the final location but the block got removed (vines etc)
consumer.queueBlockBreak(actor, replaced); consumer.queueBlockBreak(actor, replaced);
} }
// If y is minHeight then the block fell out of the world :( // If y is 0 then the block fell out of the world :(
if (y > loc.getWorld().getMinHeight()) { if (y != 0) {
// Run this check to avoid false positives // Run this check to avoid false positives
Location finalLoc = new Location(loc.getWorld(), x, y, z); 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())) { if (BukkitUtils.isEmpty(finalLoc.getBlock().getType())) {
consumer.queueBlockPlace(actor, finalLoc, placed.getBlockData()); consumer.queueBlockPlace(actor, finalLoc, placed.getBlockData());
} else { } else {
@ -96,14 +94,14 @@ public class LoggingUtil {
int x = loc.getBlockX(); int x = loc.getBlockX();
int y = loc.getBlockY(); int y = loc.getBlockY();
int z = loc.getBlockZ(); 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--; y--;
} }
// If y is minHeight then the sand block fell out of the world :( // If y is 0 then the sand block fell out of the world :(
if (y > loc.getWorld().getMinHeight()) { if (y != 0) {
Location finalLoc = new Location(loc.getWorld(), x, y, z); Location finalLoc = new Location(loc.getWorld(), x, y, z);
// Run this check to avoid false positives // 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 finalLoc.add(0, up, 0); // Add this here after checking for block breakers
if (BukkitUtils.isEmpty(finalLoc.getBlock().getType())) { if (BukkitUtils.isEmpty(finalLoc.getBlock().getType())) {
consumer.queueBlockPlace(actor, finalLoc, checkBlock.getBlockData()); consumer.queueBlockPlace(actor, finalLoc, checkBlock.getBlockData());
@ -146,16 +144,10 @@ public class LoggingUtil {
consumer.queueBlockReplace(actor, above.getState(), Material.WEEPING_VINES.createBlockData()); 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); Block checkBlock = origin.getRelative(BlockFace.UP);
Material typeAbove = checkBlock.getType(); Material typeAbove = checkBlock.getType();
if (BukkitUtils.isRelativeTopBreakable(typeAbove)) { if (BukkitUtils.getRelativeTopBreakabls().contains(typeAbove)) {
if (typeAbove == Material.IRON_DOOR || BukkitUtils.isWoodenDoor(typeAbove)) { if (typeAbove == Material.IRON_DOOR || BukkitUtils.isWoodenDoor(typeAbove)) {
Block doorBlock = checkBlock; Block doorBlock = checkBlock;
// If the doorBlock is the top half a door the player simply punched a door // 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 // check next blocks above
checkBlock = checkBlock.getRelative(BlockFace.UP); checkBlock = checkBlock.getRelative(BlockFace.UP);
typeAbove = checkBlock.getType(); typeAbove = checkBlock.getType();
while (BukkitUtils.isRelativeTopBreakable(typeAbove)) { while (BukkitUtils.getRelativeTopBreakabls().contains(typeAbove)) {
consumer.queueBlockBreak(actor, checkBlock.getState()); consumer.queueBlockBreak(actor, checkBlock.getState());
checkBlock = checkBlock.getRelative(BlockFace.UP); checkBlock = checkBlock.getRelative(BlockFace.UP);
typeAbove = checkBlock.getType(); typeAbove = checkBlock.getType();
@ -201,24 +193,6 @@ public class LoggingUtil {
if (bell.getAttachment() == Attachment.FLOOR) { if (bell.getAttachment() == Attachment.FLOOR) {
consumer.queueBlockBreak(actor, checkBlock.getState()); 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); checkBlock = origin.getRelative(BlockFace.DOWN);
@ -228,55 +202,25 @@ public class LoggingUtil {
if (lantern.isHanging()) { if (lantern.isHanging()) {
consumer.queueBlockBreak(actor, checkBlock.getState()); consumer.queueBlockBreak(actor, checkBlock.getState());
} }
} else if (BukkitUtils.isHangingSign(typeBelow)) {
consumer.queueBlockBreak(actor, checkBlock.getState());
} else if (typeBelow == Material.BELL) { } else if (typeBelow == Material.BELL) {
Bell bell = (Bell) checkBlock.getBlockData(); Bell bell = (Bell) checkBlock.getBlockData();
if (bell.getAttachment() == Attachment.CEILING) { if (bell.getAttachment() == Attachment.CEILING) {
consumer.queueBlockBreak(actor, checkBlock.getState()); 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()); consumer.queueBlockBreak(actor, checkBlock.getState());
// check next blocks below // check next blocks above
checkBlock = checkBlock.getRelative(BlockFace.DOWN); checkBlock = checkBlock.getRelative(BlockFace.DOWN);
typeBelow = checkBlock.getType(); 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()); consumer.queueBlockBreak(actor, checkBlock.getState());
checkBlock = checkBlock.getRelative(BlockFace.DOWN); checkBlock = checkBlock.getRelative(BlockFace.DOWN);
typeBelow = checkBlock.getType(); 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()); List<Location> relativeBreakables = BukkitUtils.getBlocksNearby(origin, BukkitUtils.getRelativeBreakables());
if (!relativeBreakables.isEmpty()) { if (relativeBreakables.size() != 0) {
for (Location location : relativeBreakables) { for (Location location : relativeBreakables) {
Block block = location.getBlock(); Block block = location.getBlock();
BlockData blockData = block.getBlockData(); 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.util.ActionColor.CREATE;
import static de.diddiz.LogBlock.util.ActionColor.DESTROY; import static de.diddiz.util.ActionColor.DESTROY;
import static de.diddiz.LogBlock.util.TypeColor.DEFAULT; import static de.diddiz.util.TypeColor.DEFAULT;
import static de.diddiz.LogBlock.util.Utils.spaces; import static de.diddiz.util.Utils.spaces;
import de.diddiz.LogBlock.config.Config; import de.diddiz.LogBlock.config.Config;
import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ChatColor;
@ -49,15 +49,6 @@ public class MessagingUtil {
return createTextComponentWithColor(stateName, TypeColor.STATE.getColor()); 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) { public static TextComponent prettyState(int stateValue) {
return prettyState(Integer.toString(stateValue)); return prettyState(Integer.toString(stateValue));
} }

View File

@ -1,51 +1,51 @@
package de.diddiz.LogBlock.util; package de.diddiz.util;
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
import de.diddiz.LogBlock.config.Config; import de.diddiz.LogBlock.config.Config;
import java.io.Closeable; import java.io.Closeable;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
public class MySQLConnectionPool implements Closeable { public class MySQLConnectionPool implements Closeable {
private final HikariDataSource ds; private final HikariDataSource ds;
public MySQLConnectionPool(String url, String user, String password, boolean useSSL, boolean requireSSL) { public MySQLConnectionPool(String url, String user, String password, boolean useSSL, boolean requireSSL) {
this.ds = new HikariDataSource(); this.ds = new HikariDataSource();
ds.setJdbcUrl(url); ds.setJdbcUrl(url);
ds.setUsername(user); ds.setUsername(user);
ds.setPassword(password); ds.setPassword(password);
ds.setMinimumIdle(2); ds.setMinimumIdle(2);
ds.setMaximumPoolSize(15); ds.setMaximumPoolSize(15);
ds.setPoolName("LogBlock-Connection-Pool"); ds.setPoolName("LogBlock-Connection-Pool");
ds.addDataSourceProperty("useUnicode", "true"); ds.addDataSourceProperty("useUnicode", "true");
ds.addDataSourceProperty("characterEncoding", "utf-8"); ds.addDataSourceProperty("characterEncoding", "utf-8");
ds.addDataSourceProperty("rewriteBatchedStatements", "true"); ds.addDataSourceProperty("rewriteBatchedStatements", "true");
ds.addDataSourceProperty("cachePrepStmts", "true"); ds.addDataSourceProperty("cachePrepStmts", "true");
ds.addDataSourceProperty("prepStmtCacheSize", "250"); ds.addDataSourceProperty("prepStmtCacheSize", "250");
ds.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); ds.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
ds.addDataSourceProperty("useServerPrepStmts", "true"); ds.addDataSourceProperty("useServerPrepStmts", "true");
ds.addDataSourceProperty("useSSL", Boolean.toString(useSSL)); ds.addDataSourceProperty("useSSL", Boolean.toString(useSSL));
ds.addDataSourceProperty("requireSSL", Boolean.toString(requireSSL)); ds.addDataSourceProperty("requireSSL", Boolean.toString(requireSSL));
ds.addDataSourceProperty("verifyServerCertificate", "false"); ds.addDataSourceProperty("verifyServerCertificate", "false");
} }
@Override @Override
public void close() { public void close() {
ds.close(); ds.close();
} }
public Connection getConnection() throws SQLException { public Connection getConnection() throws SQLException {
Connection connection = ds.getConnection(); Connection connection = ds.getConnection();
if (Config.mb4) { if (Config.mb4) {
connection.createStatement().executeUpdate("SET NAMES utf8mb4"); connection.createStatement().executeQuery("SET NAMES utf8mb4");
} }
return connection; return connection;
} }
} }

View File

@ -1,4 +1,4 @@
package de.diddiz.LogBlock.util; package de.diddiz.util;
public class SqlUtil { public class SqlUtil {
public static String escapeString(String s) { 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; import net.md_5.bungee.api.ChatColor;

View File

@ -1,61 +1,61 @@
package de.diddiz.LogBlock.util; package de.diddiz.util;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray; import com.google.gson.JsonArray;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
// Adapted from https://gist.github.com/evilmidget38/26d70114b834f71fb3b4 // Adapted from https://gist.github.com/evilmidget38/26d70114b834f71fb3b4
public class UUIDFetcher { public class UUIDFetcher {
private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft"; private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft";
private static final Gson gson = new GsonBuilder().setLenient().create(); private static final Gson gson = new GsonBuilder().setLenient().create();
public static Map<String, UUID> getUUIDs(List<String> names) throws Exception { public static Map<String, UUID> getUUIDs(List<String> names) throws Exception {
Map<String, UUID> uuidMap = new HashMap<>(); Map<String, UUID> uuidMap = new HashMap<>();
HttpURLConnection connection = createConnection(); HttpURLConnection connection = createConnection();
String body = gson.toJson(names); String body = gson.toJson(names);
writeBody(connection, body); writeBody(connection, body);
JsonArray array = gson.fromJson(new InputStreamReader(connection.getInputStream()), JsonArray.class); JsonArray array = gson.fromJson(new InputStreamReader(connection.getInputStream()), JsonArray.class);
for (JsonElement profile : array) { for (JsonElement profile : array) {
JsonObject jsonProfile = (JsonObject) profile; JsonObject jsonProfile = (JsonObject) profile;
String id = jsonProfile.get("id").getAsString(); String id = jsonProfile.get("id").getAsString();
String name = jsonProfile.get("name").getAsString(); String name = jsonProfile.get("name").getAsString();
UUID uuid = getUUID(id); UUID uuid = getUUID(id);
uuidMap.put(name, uuid); uuidMap.put(name, uuid);
} }
return uuidMap; return uuidMap;
} }
private static void writeBody(HttpURLConnection connection, String body) throws Exception { private static void writeBody(HttpURLConnection connection, String body) throws Exception {
OutputStream stream = connection.getOutputStream(); OutputStream stream = connection.getOutputStream();
stream.write(body.getBytes()); stream.write(body.getBytes());
stream.flush(); stream.flush();
stream.close(); stream.close();
} }
private static HttpURLConnection createConnection() throws Exception { private static HttpURLConnection createConnection() throws Exception {
URL url = new URL(PROFILE_URL); URL url = new URL(PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(false); connection.setUseCaches(false);
connection.setDoInput(true); connection.setDoInput(true);
connection.setDoOutput(true); connection.setDoOutput(true);
return connection; return connection;
} }
private static UUID getUUID(String id) { private static UUID getUUID(String id) {
return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32)); return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32));
} }
} }

View File

@ -1,298 +1,287 @@
package de.diddiz.LogBlock.util; package de.diddiz.util;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FilenameFilter; import java.io.FilenameFilter;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipException; import java.util.zip.ZipException;
import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
public class Utils { public class Utils {
public static String newline = System.getProperty("line.separator"); public static String newline = System.getProperty("line.separator");
public static boolean isInt(String str) { public static boolean isInt(String str) {
try { try {
Integer.parseInt(str); Integer.parseInt(str);
return true; return true;
} catch (final NumberFormatException ex) { } catch (final NumberFormatException ex) {
} }
return false; return false;
} }
public static boolean isShort(String str) { public static boolean isShort(String str) {
try { try {
Short.parseShort(str); Short.parseShort(str);
return true; return true;
} catch (final NumberFormatException ex) { } catch (final NumberFormatException ex) {
} }
return false; return false;
} }
public static boolean isByte(String str) { public static boolean isByte(String str) {
try { try {
Byte.parseByte(str); Byte.parseByte(str);
return true; return true;
} catch (final NumberFormatException ex) { } catch (final NumberFormatException ex) {
} }
return false; return false;
} }
public static String listing(String[] entries, String delimiter, String finalDelimiter) { public static String listing(String[] entries, String delimiter, String finalDelimiter) {
final int len = entries.length; final int len = entries.length;
if (len == 0) { if (len == 0) {
return ""; return "";
} }
if (len == 1) { if (len == 1) {
return entries[0]; return entries[0];
} }
final StringBuilder builder = new StringBuilder(entries[0]); final StringBuilder builder = new StringBuilder(entries[0]);
for (int i = 1; i < len - 1; i++) { for (int i = 1; i < len - 1; i++) {
builder.append(delimiter).append(entries[i]); builder.append(delimiter).append(entries[i]);
} }
builder.append(finalDelimiter).append(entries[len - 1]); builder.append(finalDelimiter).append(entries[len - 1]);
return builder.toString(); return builder.toString();
} }
public static String listing(List<?> entries, String delimiter, String finalDelimiter) { public static String listing(List<?> entries, String delimiter, String finalDelimiter) {
final int len = entries.size(); final int len = entries.size();
if (len == 0) { if (len == 0) {
return ""; return "";
} }
if (len == 1) { if (len == 1) {
return entries.get(0).toString(); return entries.get(0).toString();
} }
final StringBuilder builder = new StringBuilder(entries.get(0).toString()); final StringBuilder builder = new StringBuilder(entries.get(0).toString());
for (int i = 1; i < len - 1; i++) { for (int i = 1; i < len - 1; i++) {
builder.append(delimiter).append(entries.get(i).toString()); builder.append(delimiter).append(entries.get(i).toString());
} }
builder.append(finalDelimiter).append(entries.get(len - 1).toString()); builder.append(finalDelimiter).append(entries.get(len - 1).toString());
return builder.toString(); return builder.toString();
} }
public static int parseTimeSpec(String[] spec) { public static int parseTimeSpec(String[] spec) {
if (spec == null || spec.length < 1 || spec.length > 2) { if (spec == null || spec.length < 1 || spec.length > 2) {
return -1; return -1;
} }
if (spec.length == 1 && isInt(spec[0])) { if (spec.length == 1 && isInt(spec[0])) {
return Integer.valueOf(spec[0]); return Integer.valueOf(spec[0]);
} }
if (!spec[0].contains(":") && !spec[0].contains(".")) { if (!spec[0].contains(":") && !spec[0].contains(".")) {
if (spec.length == 2) { if (spec.length == 2) {
if (!isInt(spec[0])) { if (!isInt(spec[0])) {
return -1; return -1;
} }
int min = Integer.parseInt(spec[0]); int min = Integer.parseInt(spec[0]);
if (spec[1].startsWith("h")) { if (spec[1].startsWith("h")) {
min *= 60; min *= 60;
} else if (spec[1].startsWith("d")) { } else if (spec[1].startsWith("d")) {
min *= 1440; min *= 1440;
} }
return min; return min;
} else if (spec.length == 1) { } else if (spec.length == 1) {
int days = 0, hours = 0, minutes = 0; int days = 0, hours = 0, minutes = 0;
int lastIndex = 0, currIndex = 1; int lastIndex = 0, currIndex = 1;
while (currIndex <= spec[0].length()) { while (currIndex <= spec[0].length()) {
while (currIndex <= spec[0].length() && isInt(spec[0].substring(lastIndex, currIndex))) { while (currIndex <= spec[0].length() && isInt(spec[0].substring(lastIndex, currIndex))) {
currIndex++; currIndex++;
} }
if (currIndex - 1 != lastIndex) { if (currIndex - 1 != lastIndex) {
if (currIndex > spec[0].length()) { if (currIndex > spec[0].length()) {
return -1; return -1;
} }
final String param = spec[0].substring(currIndex - 1, currIndex).toLowerCase(); final String param = spec[0].substring(currIndex - 1, currIndex).toLowerCase();
if (param.equals("d")) { if (param.equals("d")) {
days = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1)); days = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1));
} else if (param.equals("h")) { } else if (param.equals("h")) {
hours = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1)); hours = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1));
} else if (param.equals("m")) { } else if (param.equals("m")) {
minutes = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1)); minutes = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1));
} }
} }
lastIndex = currIndex; lastIndex = currIndex;
currIndex++; currIndex++;
} }
if (days == 0 && hours == 0 && minutes == 0) { if (days == 0 && hours == 0 && minutes == 0) {
return -1; return -1;
} }
return minutes + hours * 60 + days * 1440; return minutes + hours * 60 + days * 1440;
} else { } else {
return -1; return -1;
} }
} }
final String timestamp; final String timestamp;
if (spec.length == 1) { if (spec.length == 1) {
if (spec[0].contains(":")) { if (spec[0].contains(":")) {
timestamp = new SimpleDateFormat("dd.MM.yyyy").format(System.currentTimeMillis()) + " " + spec[0]; timestamp = new SimpleDateFormat("dd.MM.yyyy").format(System.currentTimeMillis()) + " " + spec[0];
} else { } else {
timestamp = spec[0] + " 00:00:00"; timestamp = spec[0] + " 00:00:00";
} }
} else { } else {
timestamp = spec[0] + " " + spec[1]; timestamp = spec[0] + " " + spec[1];
} }
try { try {
return (int) ((System.currentTimeMillis() - new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").parse(timestamp).getTime()) / 60000); return (int) ((System.currentTimeMillis() - new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").parse(timestamp).getTime()) / 60000);
} catch (final ParseException ex) { } catch (final ParseException ex) {
return -1; return -1;
} }
} }
public static String spaces(int count) { public static String spaces(int count) {
final StringBuilder filled = new StringBuilder(count); final StringBuilder filled = new StringBuilder(count);
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
filled.append(' '); filled.append(' ');
} }
return filled.toString(); return filled.toString();
} }
public static String join(String[] s, String delimiter) { public static String join(String[] s, String delimiter) {
if (s == null || s.length == 0) { if (s == null || s.length == 0) {
return ""; return "";
} }
final int len = s.length; final int len = s.length;
final StringBuilder builder = new StringBuilder(s[0]); final StringBuilder builder = new StringBuilder(s[0]);
for (int i = 1; i < len; i++) { for (int i = 1; i < len; i++) {
builder.append(delimiter).append(s[i]); builder.append(delimiter).append(s[i]);
} }
return builder.toString(); return builder.toString();
} }
/** /**
* Converts a list of arguments e.g ['lb', 'clearlog', 'world', '"my', 'world', 'of', 'swag"'] * Converts a list of arguments e.g ['lb', 'clearlog', 'world', '"my', 'world', 'of', 'swag"']
* into a list of arguments with any text encapsulated by quotes treated as one word * into a list of arguments with any text encapsulated by quotes treated as one word
* For this particular example: ['lb', 'clearlog', 'world', '"my world of swag"'] * For this particular example: ['lb', 'clearlog', 'world', '"my world of swag"']
* *
* @param args The list of arguments * @param args The list of arguments
* @return A new list with the quoted arguments parsed to single values * @return A new list with the quoted arguments parsed to single values
*/ */
public static List<String> parseQuotes(List<String> args) { public static List<String> parseQuotes(List<String> args) {
List<String> newArguments = new ArrayList<>(); List<String> newArguments = new ArrayList<>();
String subjectString = join(args.toArray(new String[args.size()]), " "); String subjectString = join(args.toArray(new String[args.size()]), " ");
Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'"); Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
Matcher regexMatcher = regex.matcher(subjectString); Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) { while (regexMatcher.find()) {
newArguments.add(regexMatcher.group()); newArguments.add(regexMatcher.group());
} }
return newArguments; return newArguments;
} }
public static class ExtensionFilenameFilter implements FilenameFilter { public static class ExtensionFilenameFilter implements FilenameFilter {
private final String ext; private final String ext;
public ExtensionFilenameFilter(String ext) { public ExtensionFilenameFilter(String ext) {
this.ext = "." + ext; this.ext = "." + ext;
} }
@Override @Override
public boolean accept(File dir, String name) { public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(ext); return name.toLowerCase().endsWith(ext);
} }
} }
private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String mysqlEscapeBytes(byte[] bytes) { public static String mysqlEscapeBytes(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2 + 2]; char[] hexChars = new char[bytes.length * 2 + 2];
hexChars[0] = '0'; hexChars[0] = '0';
hexChars[1] = 'x'; hexChars[1] = 'x';
for (int j = 0; j < bytes.length; j++) { for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF; int v = bytes[j] & 0xFF;
hexChars[j * 2 + 2] = hexArray[v >>> 4]; hexChars[j * 2 + 2] = hexArray[v >>> 4];
hexChars[j * 2 + 3] = hexArray[v & 0x0F]; hexChars[j * 2 + 3] = hexArray[v & 0x0F];
} }
return new String(hexChars); return new String(hexChars);
} }
public static String mysqlPrepareBytesForInsertAllowNull(byte[] bytes) { public static String mysqlPrepareBytesForInsertAllowNull(byte[] bytes) {
if (bytes == null) { if (bytes == null) {
return "null"; return "null";
} }
return "'" + mysqlEscapeBytes(bytes) + "'"; return "'" + mysqlEscapeBytes(bytes) + "'";
} }
public static String mysqlTextEscape(String untrusted) { public static String mysqlTextEscape(String untrusted) {
return untrusted.replace("\\", "\\\\").replace("'", "\\'"); return untrusted.replace("\\", "\\\\").replace("'", "\\'");
} }
public static ItemStack loadItemStack(byte[] data) { public static ItemStack loadItemStack(byte[] data) {
if (data == null || data.length == 0) { if (data == null || data.length == 0) {
return null; return null;
} }
YamlConfiguration conf = deserializeYamlConfiguration(data); YamlConfiguration conf = deserializeYamlConfiguration(data);
return conf == null ? null : conf.getItemStack("stack"); return conf == null ? null : conf.getItemStack("stack");
} }
public static byte[] saveItemStack(ItemStack stack) { public static byte[] saveItemStack(ItemStack stack) {
if (stack == null || BukkitUtils.isEmpty(stack.getType())) { if (stack == null || BukkitUtils.isEmpty(stack.getType())) {
return null; return null;
} }
YamlConfiguration conf = new YamlConfiguration(); YamlConfiguration conf = new YamlConfiguration();
conf.set("stack", stack); conf.set("stack", stack);
return serializeYamlConfiguration(conf); return serializeYamlConfiguration(conf);
} }
public static YamlConfiguration deserializeYamlConfiguration(byte[] data) { public static YamlConfiguration deserializeYamlConfiguration(byte[] data) {
if (data == null || data.length == 0) { if (data == null || data.length == 0) {
return null; return null;
} }
YamlConfiguration conf = new YamlConfiguration(); YamlConfiguration conf = new YamlConfiguration();
try { try {
InputStreamReader reader = new InputStreamReader(new GZIPInputStream(new ByteArrayInputStream(data)), "UTF-8"); InputStreamReader reader = new InputStreamReader(new GZIPInputStream(new ByteArrayInputStream(data)), "UTF-8");
conf.load(reader); conf.load(reader);
reader.close(); reader.close();
return conf; return conf;
} catch (ZipException | InvalidConfigurationException e) { } catch (ZipException | InvalidConfigurationException e) {
LogBlock.getInstance().getLogger().warning("Could not deserialize YamlConfiguration: " + e.getMessage()); LogBlock.getInstance().getLogger().warning("Could not deserialize YamlConfiguration: " + e.getMessage());
return conf; return conf;
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("IOException should be impossible for ByteArrayInputStream", e); throw new RuntimeException("IOException should be impossible for ByteArrayInputStream", e);
} }
} }
public static byte[] serializeYamlConfiguration(YamlConfiguration conf) { public static byte[] serializeYamlConfiguration(YamlConfiguration conf) {
if (conf == null || conf.getKeys(false).isEmpty()) { if (conf == null || conf.getKeys(false).isEmpty()) {
return null; return null;
} }
try { try {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(new GZIPOutputStream(baos), "UTF-8"); OutputStreamWriter writer = new OutputStreamWriter(new GZIPOutputStream(baos), "UTF-8");
writer.write(conf.saveToString()); writer.write(conf.saveToString());
writer.close(); writer.close();
return baos.toByteArray(); return baos.toByteArray();
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("IOException should be impossible for ByteArrayOutputStream", e); throw new RuntimeException("IOException should be impossible for ByteArrayOutputStream", e);
} }
} }
public static String serializeForSQL(YamlConfiguration conf) { public static String serializeForSQL(YamlConfiguration conf) {
return mysqlPrepareBytesForInsertAllowNull(serializeYamlConfiguration(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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@ -34,7 +34,7 @@ import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.util.CuboidRegion; import de.diddiz.util.CuboidRegion;
public class WorldEditHelper { public class WorldEditHelper {
private static boolean checkedForWorldEdit; private static boolean checkedForWorldEdit;
@ -139,7 +139,7 @@ public class WorldEditHelper {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
NBTOutputStream nbtos = new NBTOutputStream(baos); NBTOutputStream nbtos = new NBTOutputStream(baos);
CompoundTag nbt = state.getNbtData(); 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("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("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)); 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.EditSession;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
@ -15,7 +15,8 @@ import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.blockstate.BlockStateCodecs; import de.diddiz.LogBlock.blockstate.BlockStateCodecs;
import de.diddiz.LogBlock.config.Config; import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.util.BukkitUtils; import de.diddiz.util.BukkitUtils;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.World; import org.bukkit.World;

View File

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

View File

@ -454,7 +454,7 @@
205:0,minecraft:purpur_slab 205:0,minecraft:purpur_slab
206:0,minecraft:end_stone_bricks 206:0,minecraft:end_stone_bricks
207:0,minecraft:beetroots 207:0,minecraft:beetroots
208:0,minecraft:dirt_path 208:0,minecraft:grass_path
209:0,minecraft:end_gateway 209:0,minecraft:end_gateway
210:0,minecraft:repeating_command_block 210:0,minecraft:repeating_command_block
211:0,minecraft:chain_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/ website: http://dev.bukkit.org/server-mods/logblock/
main: de.diddiz.LogBlock.LogBlock main: de.diddiz.LogBlock.LogBlock
description: ${project.description} description: ${project.description}
softdepend: [WorldEdit, WorldGuard] softdepend: [WorldEdit]
api-version: 1.20 api-version: 1.14
commands: commands:
lb: lb:
description: 'LogBlock plugin commands' description: 'LogBlock plugin commands'

View File

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