forked from bootswithdefer/LogBlock
/
LogBlock.java
359 lines (336 loc) · 14.5 KB
/
LogBlock.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package de.diddiz.LogBlock;
import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.listeners.*;
import de.diddiz.LogBlock.questioner.Questioner;
import de.diddiz.util.BukkitUtils;
import de.diddiz.util.MySQLConnectionPool;
import de.diddiz.worldedit.WorldEditHelper;
import de.diddiz.worldedit.WorldEditLoggingHook;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import static de.diddiz.LogBlock.config.Config.*;
import static org.bukkit.Bukkit.getPluginManager;
public class LogBlock extends JavaPlugin {
private static LogBlock logblock = null;
private MySQLConnectionPool pool;
private Consumer consumer = null;
private CommandsHandler commandsHandler;
private boolean noDb = false, connected = true;
private PlayerInfoLogging playerInfoLogging;
private ScaffoldingLogging scaffoldingLogging;
private Questioner questioner;
private volatile boolean isCompletelyEnabled;
public static LogBlock getInstance() {
return logblock;
}
public boolean isCompletelyEnabled() {
return isCompletelyEnabled;
}
public Consumer getConsumer() {
return consumer;
}
public CommandsHandler getCommandsHandler() {
return commandsHandler;
}
@Override
public void onEnable() {
logblock = this;
BukkitUtils.isDoublePlant(Material.AIR); // Force static code to run
final PluginManager pm = getPluginManager();
consumer = new Consumer(this);
try {
Config.load(this);
} catch (final Exception ex) {
getLogger().log(Level.SEVERE, "Could not load LogBlock config! " + ex.getMessage());
pm.disablePlugin(this);
return;
}
try {
getLogger().info("Connecting to " + user + "@" + url + "...");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException ignored) {
Class.forName("com.mysql.jdbc.Driver");
}
pool = new MySQLConnectionPool(url, user, password, mysqlUseSSL, mysqlRequireSSL);
final Connection conn = getConnection(true);
if (conn == null) {
noDb = true;
return;
}
final Statement st = conn.createStatement();
final ResultSet rs = st.executeQuery("SHOW CHARACTER SET where charset='utf8mb4';");
if (rs.next()) {
Config.mb4 = true;
// Allegedly JDBC driver since 2010 hasn't needed this. I did.
st.executeQuery("SET NAMES utf8mb4;");
}
conn.close();
Updater updater = new Updater(this);
updater.checkTables();
MaterialConverter.initializeMaterials(getConnection());
MaterialConverter.getOrAddMaterialId(Material.AIR); // AIR must be the first entry
EntityTypeConverter.initializeEntityTypes(getConnection());
if (updater.update()) {
load(this);
}
} catch (final NullPointerException ex) {
getLogger().log(Level.SEVERE, "Error while loading: ", ex);
} catch (final Exception ex) {
getLogger().log(Level.SEVERE, "Error while loading: " + ex.getMessage(), ex);
pm.disablePlugin(this);
return;
}
if (WorldEditHelper.hasWorldEdit()) {
new WorldEditLoggingHook(this).hook();
}
commandsHandler = new CommandsHandler(this);
getCommand("lb").setExecutor(commandsHandler);
if (enableAutoClearLog && autoClearLogDelay > 0) {
getServer().getScheduler().runTaskTimerAsynchronously(this, new AutoClearLog(this), 6000, autoClearLogDelay * 60 * 20);
}
new DumpedLogImporter(this).run();
registerEvents();
consumer.start();
for (final Tool tool : toolsByType.values()) {
if (pm.getPermission("logblock.tools." + tool.name) == null) {
final Permission perm = new Permission("logblock.tools." + tool.name, tool.permissionDefault);
pm.addPermission(perm);
}
}
questioner = new Questioner(this);
isCompletelyEnabled = true;
getServer().getScheduler().runTaskAsynchronously(this, new Updater.PlayerCountChecker(this));
}
private void registerEvents() {
final PluginManager pm = getPluginManager();
pm.registerEvents(new ToolListener(this), this);
pm.registerEvents(playerInfoLogging = new PlayerInfoLogging(this), this);
if (askRollbackAfterBan) {
pm.registerEvents(new BanListener(this), this);
}
if (isLogging(Logging.BLOCKPLACE)) {
pm.registerEvents(new BlockPlaceLogging(this), this);
}
if (isLogging(Logging.LAVAFLOW) || isLogging(Logging.WATERFLOW)) {
pm.registerEvents(new FluidFlowLogging(this), this);
}
if (isLogging(Logging.BLOCKBREAK)) {
pm.registerEvents(new BlockBreakLogging(this), this);
}
if (isLogging(Logging.SIGNTEXT)) {
pm.registerEvents(new SignChangeLogging(this), this);
}
if (isLogging(Logging.FIRE)) {
pm.registerEvents(new BlockBurnLogging(this), this);
}
if (isLogging(Logging.SNOWFORM)) {
pm.registerEvents(new SnowFormLogging(this), this);
}
if (isLogging(Logging.SNOWFADE)) {
pm.registerEvents(new SnowFadeLogging(this), this);
}
if (isLogging(Logging.SCAFFOLDING)) {
pm.registerEvents(scaffoldingLogging = new ScaffoldingLogging(this), this);
}
if (isLogging(Logging.CAULDRONINTERACT)) {
pm.registerEvents(new CauldronLogging(this), this);
}
if (isLogging(Logging.CREEPEREXPLOSION) || isLogging(Logging.TNTEXPLOSION) || isLogging(Logging.GHASTFIREBALLEXPLOSION) || isLogging(Logging.ENDERDRAGON) || isLogging(Logging.MISCEXPLOSION)) {
pm.registerEvents(new ExplosionLogging(this), this);
}
if (isLogging(Logging.LEAVESDECAY)) {
pm.registerEvents(new LeavesDecayLogging(this), this);
}
if (isLogging(Logging.CHESTACCESS)) {
pm.registerEvents(new ChestAccessLogging(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)) {
pm.registerEvents(new InteractLogging(this), this);
}
if (isLogging(Logging.CREATURECROPTRAMPLE)) {
pm.registerEvents(new CreatureInteractLogging(this), this);
}
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);
}
if (isLogging(Logging.ENDERMEN)) {
pm.registerEvents(new EndermenLogging(this), this);
}
if (isLogging(Logging.WITHER)) {
pm.registerEvents(new WitherLogging(this), this);
}
if (isLogging(Logging.NATURALSTRUCTUREGROW)) {
pm.registerEvents(new StructureGrowLogging(this), this);
}
if (isLogging(Logging.BONEMEALSTRUCTUREGROW)) {
pm.registerEvents(new BlockFertilizeLogging(this), this);
}
if (isLogging(Logging.GRASSGROWTH) || isLogging(Logging.MYCELIUMSPREAD) || isLogging(Logging.VINEGROWTH) || isLogging(Logging.MUSHROOMSPREAD) || isLogging(Logging.BAMBOOGROWTH) || isLogging(Logging.DRIPSTONEGROWTH)) {
pm.registerEvents(new BlockSpreadLogging(this), this);
}
if (isLogging(Logging.DRAGONEGGTELEPORT)) {
pm.registerEvents(new DragonEggLogging(this), this);
}
if (isLogging(Logging.LECTERNBOOKCHANGE)) {
pm.registerEvents(new LecternLogging(this), this);
}
if (isLogging(Logging.OXIDIZATION)) {
pm.registerEvents(new OxidizationLogging(this), this);
}
if (Config.isLoggingAnyEntities()) {
if (!WorldEditHelper.hasFullWorldEdit()) {
getLogger().severe("No compatible WorldEdit found, entity logging will not work!");
} else {
pm.registerEvents(new AdvancedEntityLogging(this), this);
getLogger().info("Entity logging enabled!");
}
}
}
@Override
public void onDisable() {
isCompletelyEnabled = false;
getServer().getScheduler().cancelTasks(this);
if (consumer != null) {
if (logPlayerInfo && playerInfoLogging != null) {
for (final Player player : getServer().getOnlinePlayers()) {
playerInfoLogging.onPlayerQuit(player);
}
}
getLogger().info("Waiting for consumer ...");
consumer.shutdown();
if (consumer.getQueueSize() > 0) {
getLogger().info("Remaining queue size: " + consumer.getQueueSize() + ". Trying to write to a local file.");
try {
consumer.writeToFile();
getLogger().info("Successfully dumped queue.");
} catch (final FileNotFoundException ex) {
getLogger().info("Failed to write. Given up.");
}
}
}
if (pool != null) {
pool.close();
}
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (noDb) {
sender.sendMessage(ChatColor.RED + "No database connected. Check your MySQL user/pw and database for typos. Start/restart your MySQL server.");
}
return true;
}
public boolean hasPermission(CommandSender sender, String permission) {
return sender.hasPermission(permission);
}
public Connection getConnection() {
return getConnection(false);
}
public Connection getConnection(boolean testConnection) {
try {
final Connection conn = pool.getConnection();
if (!connected) {
getLogger().info("MySQL connection rebuild");
connected = true;
}
return conn;
} catch (final Exception ex) {
if (testConnection) {
getLogger().log(Level.SEVERE, "Could not connect to the Database! Please check your config! " + ex.getMessage());
} else if (connected) {
getLogger().log(Level.SEVERE, "Error while fetching connection: ", ex);
connected = false;
} else {
getLogger().log(Level.SEVERE, "MySQL connection lost", ex);
}
return null;
}
}
/**
* 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
* to the logblock lookup command i.e /lb lookup <i>query-parameters</i>
*
* Note: this method directly calls a SQL query and is hence a slow blocking function, avoid running
* it on the main game thread
*
* @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 List<BlockChange> getBlockChanges(QueryParams params) throws SQLException {
final Connection conn = getConnection();
Statement state = null;
if (conn == null) {
throw new SQLException("No connection");
}
try {
state = conn.createStatement();
final ResultSet rs = state.executeQuery(params.getQuery());
final List<BlockChange> blockchanges = new ArrayList<>();
while (rs.next()) {
blockchanges.add(new BlockChange(rs, params));
}
return blockchanges;
} finally {
if (state != null) {
state.close();
}
conn.close();
}
}
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()));
}
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;
}
}