-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathHuskyCrates.java
More file actions
455 lines (382 loc) · 19.7 KB
/
HuskyCrates.java
File metadata and controls
455 lines (382 loc) · 19.7 KB
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
package com.codehusky.huskycrates;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.config.DefaultConfig;
import org.spongepowered.api.data.DataQuery;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.block.ChangeBlockEvent;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.EventContextKeys;
import org.spongepowered.api.event.game.GameReloadEvent;
import org.spongepowered.api.event.game.state.GamePostInitializationEvent;
import org.spongepowered.api.event.game.state.GamePreInitializationEvent;
import org.spongepowered.api.event.game.state.GameStartedServerEvent;
import org.spongepowered.api.event.game.state.GameStoppingServerEvent;
import org.spongepowered.api.item.inventory.ItemStackSnapshot;
import org.spongepowered.api.plugin.Dependency;
import org.spongepowered.api.plugin.Plugin;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.scheduler.Task;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import com.codehusky.huskycrates.command.BalanceCommand;
import com.codehusky.huskycrates.command.BlockCommand;
import com.codehusky.huskycrates.command.CommandRegister;
import com.codehusky.huskycrates.command.KeyCommand;
import com.codehusky.huskycrates.crate.listeners.CrateListeners;
import com.codehusky.huskycrates.crate.listeners.SQLUpdateListener;
import com.codehusky.huskycrates.crate.physical.EffectInstance;
import com.codehusky.huskycrates.crate.physical.PhysicalCrate;
import com.codehusky.huskycrates.crate.virtual.Crate;
import com.codehusky.huskycrates.crate.virtual.Key;
import com.codehusky.huskycrates.event.CrateInjectionEvent;
import com.codehusky.huskycrates.exception.ConfigParseError;
import com.google.inject.Inject;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.hocon.HoconConfigurationLoader;
import ninja.leaping.configurate.loader.ConfigurationLoader;
@Plugin(
id="huskycrates",
name = "HuskyCrates",
version = "2.0.0RC3",
description = "A Crate Plugin for Sponge!",
dependencies = {@Dependency(id="huskyui",version = "0.6.0PRE4"), @Dependency(id="placeholderapi", optional = true)})
public class HuskyCrates {
// Added blockplace event to prevent keys to be placed
//@Inject
public Logger logger;
@Inject
public PluginContainer pC;
@Inject
@ConfigDir(sharedRoot = false)
public Path configDir;
@Inject
@DefaultConfig(sharedRoot = false)
public ConfigurationLoader<CommentedConfigurationNode> config;
public CommentedConfigurationNode mainConfig;
public Path crateDirectoryPath;
public ConfigurationLoader<CommentedConfigurationNode> crateLoop;
public Path keyConfigPath;
public ConfigurationLoader<CommentedConfigurationNode> keyConfig;
public CommentedConfigurationNode keys;
public Path generatedItemConfigPath;
public ConfigurationLoader<CommentedConfigurationNode> generatedItemConfig;
public Path generatedInventoryConfigPath;
public ConfigurationLoader<CommentedConfigurationNode> generatedInventoryConfig;
public static Path dupeLogPath;
public static Path storageDirectoryPath;
//TODO unused variable
public Cause genericCause;
public static HuskyCrates instance;
public static Registry registry;
public boolean inErrorState = false;
private CrateListeners crateListeners;
public static boolean KEY_SECURITY = true;
public static boolean FORCE_CRATE_CMD = true;
private static boolean firstBoot = false;
public static KeyCommand.Messages keyCommandMessages;
public static BlockCommand.Messages blockCommandMessages;
public static BalanceCommand.Messages balanceCommandMessages;
public static Crate.Messages crateMessages;
private static ScriptEngineManager mgr = new ScriptEngineManager();
public static ScriptEngine jsengine = mgr.getEngineByName("JavaScript");
public boolean virtualKeyDB = false;
@Listener
public void gameInit(GamePreInitializationEvent event){
registry = new Registry();
logger = LoggerFactory.getLogger(pC.getName());
instance = this;
storageDirectoryPath = configDir.resolve("storage/");
dupeLogPath = configDir.resolve("storage/dupealert.log");
generatedItemConfigPath = configDir.resolve("storage/generateditems.conf");
generatedInventoryConfigPath = configDir.resolve("storage/generatedinventorys.conf");
crateDirectoryPath = configDir.resolve("crates/");
keyConfigPath = configDir.resolve("crates/keys.conf");
keyConfig = HoconConfigurationLoader.builder().setPath(keyConfigPath).build();
generatedItemConfig = HoconConfigurationLoader.builder().setPath(generatedItemConfigPath).build();
generatedInventoryConfig = HoconConfigurationLoader.builder().setPath(generatedInventoryConfigPath).build();
Path crateMigrationPath = configDir.resolve("crates.conf");
Path keysMigrationPath = configDir.resolve("keys.conf");
Path dbMigrationPath = configDir.resolve("data.mv.db");
Path genItemMigrationPath = configDir.resolve("generateditems.conf");
migrateConfigs(crateMigrationPath, "/crates/crates.crate");
migrateConfigs(keysMigrationPath, "/crates/keys.conf");
migrateConfigs(dbMigrationPath, "/storage/data.mv.db");
migrateConfigs(genItemMigrationPath, "/storage/generateditems.conf");
}
private float cumulative = 0;
private int iterations = 0;
private long lastMessage = 0;
@Listener
// pre to post, prevent hc from being loaded before worlds are loaded
public void gamePostInit(GamePostInitializationEvent event){
crateListeners = new CrateListeners();
Sponge.getEventManager().registerListeners(this,crateListeners);
}
public static final String generalDefaultConfig = "# To configure HuskyCrates, please reference the documentation, use the \"/hc generatecrate\" command, or use the HuskyConfigurator!\n\n# For more information: https://discord.gg/FSETtcx";
private void migrateConfigs(Path n, String name){
Path conf = Paths.get(configDir.toString() + name);
if(n.toFile().exists()) {
checkOrInitalizeDirectory(crateDirectoryPath);
checkOrInitalizeDirectory(storageDirectoryPath);
try {
Files.move(n,conf,StandardCopyOption.REPLACE_EXISTING);
}catch(Exception e){
e.printStackTrace();
logger.error("Failed to migrate a config to newer path!");
}
}
}
public void loadConfig() {
if(checkOrInitalizeDirectory(crateDirectoryPath) && checkOrInitalizeDirectory(storageDirectoryPath) && checkOrInitalizeConfig(keyConfigPath,generalDefaultConfig)){
checkOrInitalizeConfig(dupeLogPath,"#Here you'll find a log of information stored after an instance duplication detection!\n#File will not be read, is simply a log");
checkOrInitalizeConfig(generatedItemConfigPath,"# This config contains generated item objects that you create in-game. This file will not be read by the plugin.\n# With the admin permission, try /hc genitem with an item in your hand, then check back here.");
checkOrInitalizeConfig(generatedInventoryConfigPath,"# This config contains generated inventory sets that you create in-game. This file will not be read by the plugin.\n# With the admin permission, try /hc geninvent with an inventory full of items, then check back here.");
try {
mainConfig = config.load();
virtualKeyDB = mainConfig.getNode("virtualkeydatabase").getNode("useRemoteDatabase").getBoolean();
keys = keyConfig.load();
if(virtualKeyDB){
Sponge.getEventManager().registerListeners(this, new SQLUpdateListener());
}
for(CommentedConfigurationNode node : keys.getChildrenMap().values()){
Key thisKey = new Key(node);
registry.registerKey(thisKey);
}
File folder = new File(crateDirectoryPath.toString());
File[] files = folder.listFiles();
List<File> crateFiles = new ArrayList<>();
for (File file : files){
if (file.getName().endsWith(".crate")){
crateFiles.add(file);
}
}
if(crateFiles.size() == 0){
HuskyCrates.instance.logger.debug("The crate directory contains no crates, pushing example config!");
//System.out.println("The crate directory contains no crates, pushing example config!");
if(Sponge.getAssetManager().getAsset(pC, "example.crate").isPresent()){
Sponge.getAssetManager().getAsset(pC, "example.crate").get().copyToFile(crateDirectoryPath.resolve("example.crate"));
}
else{
HuskyCrates.instance.logger.error("Failed to read asset to copy file from!");
//System.out.println("Failed to read asset to copy file from!");
}
}
for (File file : files) {
if (file.isFile() && file.getPath().endsWith(".crate") && file.length() > 0) {
crateLoop = HoconConfigurationLoader.builder().setPath(file.toPath()).build();
CommentedConfigurationNode crateThing;
crateThing = crateLoop.load();
if(!crateThing.getNode("secureKeys").isVirtual() && !crateThing.getNode("secureKeys").hasMapChildren()){
throw new ConfigParseError("\"secureKeys\" must be removed from \""+file.getName()+ "\"!",crateThing.getNode("secureKeys").getPath());
}
for(CommentedConfigurationNode node : crateThing.getChildrenMap().values()){
Crate thisCrate = new Crate(node);
registry.registerCrate(thisCrate);
}
logger.debug("Crate Config File \"" + file.getName() + "\" Has been loaded!");
}
}
if(mainConfig.getNode("virtualkeydatabase").isVirtual()){
CommentedConfigurationNode db = mainConfig.getNode("virtualkeydatabase");
db.getNode("useRemoteDatabase").setValue(false);
db.getNode("type").setValue("mysql");
db.getNode("host").setValue("127.0.0.1");
db.getNode("port").setValue(3306);
db.getNode("database").setValue("huskycrates");
db.getNode("username").setValue("root");
db.getNode("password").setValue("");
}
if(!mainConfig.getNode("crates").isVirtual()){
throw new ConfigParseError("HuskyCrates.conf contains 1.x config data! Please update it using the Config Converter application!",mainConfig.getNode("crates").getPath());
}
if(mainConfig.getNode("secureKeys").isVirtual()){
mainConfig.getNode("secureKeys").setValue(HuskyCrates.KEY_SECURITY);
}else{
HuskyCrates.KEY_SECURITY = mainConfig.getNode("secureKeys").getBoolean(true);
}
if(mainConfig.getNode("forceCrateCMD").isVirtual()){
mainConfig.getNode("forceCrateCMD").setValue(HuskyCrates.FORCE_CRATE_CMD);
}else{
if(firstBoot && mainConfig.getNode("forceCrateCMD").getBoolean(true) != HuskyCrates.FORCE_CRATE_CMD){
logger.error("!!!!!! CRITICAL ERROR !!!!!!");
logger.error("forceCrateCMD changes require a server reboot to apply!");
logger.error("Please reboot immediately!");
logger.error("!!!!!! CRITICAL ERROR !!!!!!");
inErrorState=true;
}else {
HuskyCrates.FORCE_CRATE_CMD = mainConfig.getNode("forceCrateCMD").getBoolean(true);
}
}
firstBoot = true;
keyCommandMessages = new KeyCommand.Messages(mainConfig.getNode("messages","keyCommand"));
blockCommandMessages = new BlockCommand.Messages(mainConfig.getNode("messages","blockCommand"));
balanceCommandMessages = new BalanceCommand.Messages(mainConfig.getNode("messages","balanceCommand"));
crateMessages = new Crate.Messages(mainConfig.getNode("messages","crate"),null);
// k both work. wowowwoowow
config.save(mainConfig);
Sponge.getEventManager().post(new CrateInjectionEvent());
}catch(Exception e){
inErrorState = true;
e.printStackTrace();
logger.error("Failed to register crates and keys. Please review the errors printed above.");
//todo: handle exception based on type
}
}else{
logger.error("Config initialization experienced an error. Please report this to the developer for help.");
}
}
private boolean checkOrInitalizeConfig(Path path, String defaultContent){
if(!path.toFile().exists()) {
try {
boolean success = path.toFile().createNewFile();
if(!success){
logger.error("Failed to create new config at " + path.toAbsolutePath().toString());
return false;
}
PrintWriter pw = new PrintWriter(path.toFile());
pw.println(defaultContent);
pw.close();
return true;
} catch (IOException e) {
inErrorState = true;
e.printStackTrace();
return false;
}
}
return true;
}
private boolean checkOrInitalizeDirectory(Path path){
if(!path.toFile().exists()) {
if(!path.toFile().mkdirs()){
logger.error("Failed to create new directory at " + path.toAbsolutePath().toString());
return false;
}
}
return true;
}
@Listener
public void gameStarted(GameStartedServerEvent event) {
logger.info("Loading Crates...");
loadConfig();
Sponge.getScheduler().createTaskBuilder().execute(new Consumer<Task>() {
@Override
public void accept(Task task) {
try {
long startTime = System.nanoTime();
int particles = 0;
for (Location<World> location : registry.getPhysicalCrates().keySet()) {
PhysicalCrate pcrate = registry.getPhysicalCrate(location);
if (pcrate.getIdleEffect() != null) {
pcrate.getIdleEffect().tick();
particles += pcrate.getIdleEffect().getEffect().getParticleCount();
}
}
long endTime = System.nanoTime();
cumulative += (endTime - startTime);
iterations++;
if(lastMessage + 1000 < System.currentTimeMillis()){
lastMessage = System.currentTimeMillis();
float avg = (cumulative / ((float)iterations));
/*System.out.println("AVG PARTICLE TIME: " + avg + " nanoseconds (" + (avg / 1000000) + " milliseconds)");
System.out.println("EST TIME PER EFFECT: " + (avg / particles) + " nanoseconds (" + (avg / particles / 1000000) + " milliseconds)");
System.out.println("PARTICLES: " + particles);
System.out.println("--------------------------");*/
iterations = 0;
cumulative = 0;
}
//System.out.println("PARTICLE TIME: " + ((endTime - startTime)/1000000.0) + " milliseconds");
ArrayList<EffectInstance> nuke = new ArrayList<>();
for (EffectInstance inst : registry.getEffects()) {
inst.tick();
if (inst.getEffect().isFinished()) {
nuke.add(inst);
}
}
for (EffectInstance inst : nuke) {
inst.resetEffect();
registry.removeEffect(inst);
}
}catch (ConcurrentModificationException e){}
}
}).intervalTicks(1).async().submit(this);
Sponge.getScheduler().createTaskBuilder()
.execute(registry::pushDirty)
.interval(1, TimeUnit.MINUTES)
.submit(this);
HuskyCrates.registry.loadFromDatabase();
CommandRegister.register(this);
if(inErrorState) {
logger.error("Crates has started with errors. Please review the issue(s) above.");
}else {
logger.info("Crates has started successfully.");
}
if(pC.getVersion().get().contains("PRE")) {
logger.warn("You are currently running a pre-release build!");
logger.warn("This is an unstable version of HuskyCrates and, as such,");
logger.warn(" it has not been tested thoroughly and will have bugs!");
logger.warn("Report all issues to codeHusky on the support discord!");
logger.warn("For help configuring, please consult the SRC or the discord.");
logger.warn("Thanks! - codeHusky");
}
logger.info("Running HuskyCrates v" + pC.getVersion().get());
}
public void reload() {
inErrorState = false;
registry.pushDirty();
registry.clearRegistry();
loadConfig();
if(!inErrorState) {
registry.loadFromDatabase();
}
if(inErrorState) {
logger.error("Crates has reloaded with errors. Please review the issue(s) above.");
}else {
logger.info("Crates has reloaded successfully.");
}
}
@Listener
public void gameReloaded(GameReloadEvent event) {
reload();
}
@Listener
public void gameShutdown(GameStoppingServerEvent event){
registry.pushDirty();
logger.info("HuskyCrates has shut down.");
}
/**
*
* Prevent block placement if block is a (potential) key (no accidental loss in keys by placement (lever, tripwire-hook ... ) )
* @param e
*
*/
@Listener
public void onBlockPlaced(ChangeBlockEvent.Place e) {
if (e.getSource() instanceof Player) {
ItemStackSnapshot item = e.getCause().getContext().get(EventContextKeys.USED_ITEM).orElse(null); // get item placed
if (item == null) { //check if item not null (prevent possible issues by wrong place detection)
return;
}
if (item.toContainer().get(DataQuery.of("UnsafeData", "HCKEYID")).isPresent()) { // check if item is a key
e.setCancelled(true); // cancel the block placement.
}
}
}
}