Reworked everything to be much easier to read and just over all better (didnt rewrite the ranks part tho)
This commit is contained in:
@@ -1,44 +0,0 @@
|
||||
package com.alttd.boosterapi;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public interface Booster extends Comparable {
|
||||
|
||||
boolean isActive();
|
||||
|
||||
void setActive(Boolean active);
|
||||
|
||||
BoosterType getType();
|
||||
|
||||
void setType(BoosterType boosterType);
|
||||
|
||||
double getMultiplier();
|
||||
|
||||
void setMultiplier(double multiplier);
|
||||
|
||||
Long getStartingTime();
|
||||
|
||||
void setStartingTime(long startingTime);
|
||||
|
||||
Long getEndTime();
|
||||
|
||||
Long getDuration();
|
||||
|
||||
void setDuration(long duration);
|
||||
|
||||
String getActivator();
|
||||
|
||||
void setActivator(String activationReason);
|
||||
|
||||
long getTimeRemaining();
|
||||
|
||||
UUID getUUID();
|
||||
|
||||
void stopBooster();
|
||||
|
||||
void saveBooster();
|
||||
|
||||
void finish();
|
||||
|
||||
boolean finished();
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
package com.alttd.boosterapi;
|
||||
|
||||
import com.alttd.boosterapi.util.Logger;
|
||||
import net.luckperms.api.LuckPerms;
|
||||
|
||||
public interface BoosterAPI {
|
||||
|
||||
static BoosterAPI get() {
|
||||
return BoosterImplementation.get();
|
||||
static BoosterAPI get(Logger logger) {
|
||||
return BoosterImplementation.get(logger);
|
||||
}
|
||||
|
||||
LuckPerms getLuckPerms();
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
package com.alttd.boosterapi;
|
||||
|
||||
import com.alttd.boosterapi.config.Config;
|
||||
import com.alttd.boosterapi.config.ServerConfig;
|
||||
import com.alttd.boosterapi.database.Database;
|
||||
import com.alttd.boosterapi.util.Logger;
|
||||
import net.luckperms.api.LuckPerms;
|
||||
import net.luckperms.api.LuckPermsProvider;
|
||||
|
||||
public class BoosterImplementation implements BoosterAPI {
|
||||
|
||||
private static BoosterAPI instance;
|
||||
private final Logger logger;
|
||||
|
||||
private LuckPerms luckPerms;
|
||||
private Database database;
|
||||
|
||||
public BoosterImplementation() {
|
||||
private BoosterImplementation(Logger logger) {
|
||||
instance = this;
|
||||
this.logger = logger;
|
||||
reloadConfig();
|
||||
|
||||
luckPerms = getLuckPerms();
|
||||
}
|
||||
|
||||
public static BoosterAPI get() {
|
||||
public static BoosterAPI get(Logger logger) {
|
||||
if (instance == null)
|
||||
instance = new BoosterImplementation();
|
||||
instance = new BoosterImplementation(logger);
|
||||
return instance;
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ public class BoosterImplementation implements BoosterAPI {
|
||||
|
||||
@Override
|
||||
public void reloadConfig() {
|
||||
Config.init();
|
||||
Config.reload(logger);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
package com.alttd.boosterapi;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public enum BoosterType {
|
||||
|
||||
/**
|
||||
* MCMMO - implies all mcmmo skills are boosted
|
||||
*/
|
||||
MCMMO("mcmmo"),
|
||||
|
||||
ACROBATICS("acrobatics"),
|
||||
ALCHEMY("alchemy"),
|
||||
ARCHERY("archery"),
|
||||
AXES("axes"),
|
||||
EXCAVATION("excavation"),
|
||||
FISHING("fishing"),
|
||||
HERBALISM("herbalism"),
|
||||
MINING("mining"),
|
||||
REPAIR("repair"),
|
||||
SALVAGE("salvage"),
|
||||
SMELTING("smelting"),
|
||||
SWORDS("swords"),
|
||||
TAMING("taming"),
|
||||
UNARMED("unarmed"),
|
||||
WOODCUTTING("woodcutting"),
|
||||
|
||||
/**
|
||||
* MYPET - Boosts MyPet exp gains
|
||||
*/
|
||||
MYPET("mypet"),
|
||||
/**
|
||||
* VANILLAXP - increases exp gained by killing mobs
|
||||
*/
|
||||
VANILLAXP("vanillaxp"),
|
||||
/**
|
||||
* LUCK - Boosts luck based vanilla features
|
||||
* Caps at max vanilla enchant + 1
|
||||
* Boosts:
|
||||
* - Mining with Fortune
|
||||
* - Adds 1 extra looting level to any mob kills
|
||||
* - Boosts luck of the sea by 1
|
||||
*/
|
||||
LUCK("luck"),
|
||||
/**
|
||||
* PHANTOM - Disables phantom spawns while this booster is active
|
||||
*/
|
||||
PHANTOM("phantom"),
|
||||
/**
|
||||
* IDK
|
||||
*/
|
||||
UNKNOWN("unknown");
|
||||
|
||||
public final String BoosterName;
|
||||
BoosterType(String BoosterName) {
|
||||
this.BoosterName = BoosterName;
|
||||
}
|
||||
|
||||
public String getBoosterName() {
|
||||
return this.BoosterName;
|
||||
}
|
||||
|
||||
public static BoosterType getByName(String text) {
|
||||
for (BoosterType type : BoosterType.values()) {
|
||||
if (type.BoosterName.equalsIgnoreCase(text)) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
return UNKNOWN;
|
||||
}
|
||||
|
||||
public static List<BoosterType> getAllMcMMOBoosters() {
|
||||
return List.of(BoosterType.ACROBATICS,
|
||||
BoosterType.ALCHEMY,
|
||||
BoosterType.ARCHERY,
|
||||
BoosterType.AXES,
|
||||
BoosterType.EXCAVATION,
|
||||
BoosterType.FISHING,
|
||||
BoosterType.HERBALISM,
|
||||
BoosterType.MINING,
|
||||
BoosterType.REPAIR,
|
||||
BoosterType.SALVAGE,
|
||||
BoosterType.SMELTING,
|
||||
BoosterType.SWORDS,
|
||||
BoosterType.TAMING,
|
||||
BoosterType.UNARMED,
|
||||
BoosterType.WOODCUTTING);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package com.alttd.boosterapi.config;
|
||||
|
||||
import com.alttd.boosterapi.util.Logger;
|
||||
import io.leangen.geantyref.TypeToken;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.ConfigurationOptions;
|
||||
import org.spongepowered.configurate.serialize.SerializationException;
|
||||
import org.spongepowered.configurate.yaml.NodeStyle;
|
||||
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@SuppressWarnings({"unused", "SameParameterValue"})
|
||||
abstract class AbstractConfig {
|
||||
File file;
|
||||
private static final Pattern PATH_PATTERN = Pattern.compile("\\.");
|
||||
private static YamlConfigurationLoader configLoader;
|
||||
public static ConfigurationNode config;
|
||||
private static Logger logger = null;
|
||||
private static File CONFIG_FILE;
|
||||
|
||||
AbstractConfig(File file, String filename, Logger logger, Class clazz) {
|
||||
AbstractConfig.logger = logger;
|
||||
init(new File(file.getPath()), filename, clazz);
|
||||
}
|
||||
|
||||
private void init(File file, String filename, Class clazz) {
|
||||
this.file = file;
|
||||
CONFIG_FILE = new File(file, "config.yml");
|
||||
configLoader = YamlConfigurationLoader.builder()
|
||||
.file(CONFIG_FILE)
|
||||
.nodeStyle(NodeStyle.BLOCK)
|
||||
.build();
|
||||
if (!CONFIG_FILE.getParentFile().exists()) {
|
||||
if(!CONFIG_FILE.getParentFile().mkdirs()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!CONFIG_FILE.exists()) {
|
||||
try {
|
||||
if(!CONFIG_FILE.createNewFile()) {
|
||||
return;
|
||||
}
|
||||
} catch (IOException error) {
|
||||
error.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
config = configLoader.load(ConfigurationOptions.defaults().header("").shouldCopyDefaults(false));
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
readConfig(clazz, null);
|
||||
try {
|
||||
configLoader.save(config);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
protected void readConfig(Class<?> clazz, Object instance) {
|
||||
for (Class<?> declaredClass : clazz.getDeclaredClasses()) {
|
||||
for (Method method : declaredClass.getDeclaredMethods()) {
|
||||
if (Modifier.isPrivate(method.getModifiers())) {
|
||||
if (method.getParameterTypes().length == 0 && method.getReturnType() == Void.TYPE) {
|
||||
try {
|
||||
method.setAccessible(true);
|
||||
method.invoke(instance);
|
||||
} catch (InvocationTargetException ex) {
|
||||
throw new RuntimeException(ex.getCause());
|
||||
} catch (Exception ex) {
|
||||
if (logger != null)
|
||||
logger.severe("Error invoking %.", method.toString());
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
saveConfig();
|
||||
}
|
||||
|
||||
private static void saveConfig() {
|
||||
try {
|
||||
configLoader.save(config);
|
||||
} catch (IOException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static Object[] splitPath(String key) {
|
||||
return PATH_PATTERN.split(key);
|
||||
}
|
||||
|
||||
private static void set(String prefix, String path, Object def) {
|
||||
path = prefix + path;
|
||||
if(config.node(splitPath(path)).virtual()) {
|
||||
try {
|
||||
config.node(splitPath(path)).set(def);
|
||||
} catch (SerializationException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
saveConfig();
|
||||
}
|
||||
|
||||
protected static void setString(String path, String def) {
|
||||
try {
|
||||
if(config.node(splitPath(path)).virtual())
|
||||
config.node(splitPath(path)).set(io.leangen.geantyref.TypeToken.get(String.class), def);
|
||||
} catch(SerializationException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
protected static boolean getBoolean(String prefix, String path, boolean def) {
|
||||
set(prefix, path, def);
|
||||
return config.node(splitPath(path)).getBoolean(def);
|
||||
}
|
||||
|
||||
protected static double getDouble(String prefix, String path, double def) {
|
||||
set(prefix, path, def);
|
||||
return config.node(splitPath(path)).getDouble(def);
|
||||
}
|
||||
|
||||
protected static int getInt(String prefix, String path, int def) {
|
||||
set(prefix, path, def);
|
||||
return config.node(splitPath(path)).getInt(def);
|
||||
}
|
||||
|
||||
protected static String getString(String prefix, String path, String def) {
|
||||
setString(path, def);
|
||||
return config.node(splitPath(path)).getString(def);
|
||||
}
|
||||
|
||||
protected static Long getLong(String prefix, String path, Long def) {
|
||||
set(prefix, path, def);
|
||||
return config.node(splitPath(path)).getLong(def);
|
||||
}
|
||||
|
||||
protected static <T> List<String> getList(String prefix, String path, T def) {
|
||||
try {
|
||||
set(prefix, path, def);
|
||||
return config.node(splitPath(path)).getList(TypeToken.get(String.class));
|
||||
} catch(SerializationException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package com.alttd.boosterapi.config;
|
||||
|
||||
import com.alttd.boosterapi.data.Booster;
|
||||
import com.alttd.boosterapi.data.BoosterType;
|
||||
import com.alttd.boosterapi.util.Logger;
|
||||
import com.fasterxml.jackson.core.*;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public class BoosterFileStorage {
|
||||
|
||||
private File CONFIG_FILE;
|
||||
private final Logger logger;
|
||||
public BoosterFileStorage(Logger logger) {
|
||||
this.logger = logger;
|
||||
logger.info("Preparing booster file storage...");
|
||||
init();
|
||||
}
|
||||
|
||||
private void init() {
|
||||
File CONFIG_PATH = new File(System.getProperty("user.home") + File.separator + "share" + File.separator + "configs" + File.separator + "Boosters");
|
||||
if (!CONFIG_PATH.exists()) {
|
||||
if (!CONFIG_PATH.mkdir())
|
||||
logger.severe("Unable to create json storage directory");
|
||||
}
|
||||
CONFIG_FILE = new File(CONFIG_PATH, "storage.json");
|
||||
if (!CONFIG_FILE.exists()) {
|
||||
try {
|
||||
if (!CONFIG_FILE.createNewFile())
|
||||
logger.severe("Unable to create json storeage file");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.enable(SerializationFeature.INDENT_OUTPUT);
|
||||
}
|
||||
|
||||
public synchronized List<Booster> reload() {
|
||||
logger.debug("Reloading boosters...");
|
||||
return loadBoosters();
|
||||
}
|
||||
|
||||
private List<Booster> loadBoosters() {
|
||||
List<Booster> boosters = new LinkedList<>();
|
||||
|
||||
try {
|
||||
JsonParser parser = new JsonFactory().createParser(CONFIG_FILE);
|
||||
if (parser == null) {
|
||||
logger.warning("Unable to load in boosters from storage file.");
|
||||
return boosters;
|
||||
}
|
||||
parser.nextToken();
|
||||
while (parser.currentToken() != null && parser.currentToken().isStructStart()) {
|
||||
Optional<Booster> optionalBooster = loadBooster(parser);
|
||||
if (optionalBooster.isEmpty())
|
||||
continue;
|
||||
Booster booster = optionalBooster.get();
|
||||
logger.debug("Loading booster:" + booster.getBoosterType());
|
||||
boosters.add(booster);
|
||||
if (parser.nextToken() != null && !parser.currentToken().isStructEnd()) {
|
||||
logger.warning("Last loaded booster had more data than expected, skipping it...");
|
||||
while (!parser.nextToken().isStructEnd())
|
||||
;
|
||||
}
|
||||
parser.nextToken();
|
||||
}
|
||||
parser.close();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return boosters;
|
||||
}
|
||||
|
||||
public Optional<Booster> loadBooster(JsonParser parser) throws IOException {
|
||||
JsonToken jsonToken = parser.getCurrentToken();
|
||||
if (!jsonToken.isStructStart())
|
||||
return error("Didn't find struct start");
|
||||
|
||||
jsonToken = parser.nextToken();
|
||||
if (jsonToken != JsonToken.FIELD_NAME || !"boosterUUID".equals(parser.getCurrentName()))
|
||||
return error("Didn't find boosterUUID at expected location");
|
||||
parser.nextValue();
|
||||
UUID boosterUUID = UUID.fromString(parser.getValueAsString());
|
||||
|
||||
jsonToken = parser.nextToken();
|
||||
if (jsonToken != JsonToken.FIELD_NAME || !"activatorName".equals(parser.getCurrentName()))
|
||||
return error("Didn't find activatorName at expected location");
|
||||
parser.nextValue();
|
||||
String activatorName = parser.getValueAsString();
|
||||
|
||||
jsonToken = parser.nextToken();
|
||||
if (jsonToken != JsonToken.FIELD_NAME || !"boosterType".equals(parser.getCurrentName()))
|
||||
return error("Didn't find boosterType at expected location");
|
||||
parser.nextValue();
|
||||
BoosterType boosterType = BoosterType.getByName(parser.getValueAsString());
|
||||
|
||||
jsonToken = parser.nextToken();
|
||||
if (jsonToken != JsonToken.FIELD_NAME || !"startingTime".equals(parser.getCurrentName()))
|
||||
return error("Didn't find startingTime at expected location");
|
||||
parser.nextValue();
|
||||
Instant startingTime = Instant.ofEpochMilli(parser.getValueAsLong());
|
||||
|
||||
jsonToken = parser.nextToken();
|
||||
if (jsonToken != JsonToken.FIELD_NAME || !"duration".equals(parser.getCurrentName()))
|
||||
return error("Didn't find duration at expected location");
|
||||
parser.nextValue();
|
||||
Duration duration = Duration.ofMillis(parser.getValueAsLong());
|
||||
|
||||
jsonToken = parser.nextToken();
|
||||
if (jsonToken != JsonToken.FIELD_NAME || !"multiplier".equals(parser.getCurrentName()))
|
||||
return error("Didn't find multiplier at expected location");
|
||||
parser.nextValue();
|
||||
double multiplier = parser.getValueAsDouble();
|
||||
|
||||
jsonToken = parser.nextToken();
|
||||
if (jsonToken != JsonToken.FIELD_NAME || !"running".equals(parser.getCurrentName()))
|
||||
return error("Didn't find running at expected location");
|
||||
parser.nextValue();
|
||||
boolean running = parser.getValueAsBoolean();
|
||||
parser.nextValue();
|
||||
|
||||
return Optional.of(new Booster(boosterUUID, activatorName, boosterType, startingTime, duration, multiplier, running));
|
||||
}
|
||||
|
||||
private Optional<Booster> error(String error) {
|
||||
logger.severe(error);
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public synchronized void saveBoosters(List<Booster> boosters) {
|
||||
try {
|
||||
JsonGenerator generator = new JsonFactory().createGenerator(CONFIG_FILE, JsonEncoding.UTF8);
|
||||
for (Booster booster : boosters) {
|
||||
saveBooster(booster, generator);
|
||||
}
|
||||
generator.close();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void saveBooster(Booster booster, JsonGenerator generator) throws IOException {
|
||||
generator.writeStartObject();
|
||||
|
||||
generator.writeStringField("boosterUUID", booster.getBoosterUUID().toString());
|
||||
generator.writeStringField("activatorName", booster.getActivatorName());
|
||||
generator.writeStringField("boosterType", booster.getBoosterType().getBoosterName());
|
||||
generator.writeNumberField("startingTime", booster.getStartingTime().toEpochMilli());
|
||||
generator.writeNumberField("duration", booster.getDuration().toMillis());
|
||||
generator.writeNumberField("multiplier", booster.getMultiplier());
|
||||
generator.writeBooleanField("running", booster.getRunning());
|
||||
|
||||
generator.writeEndObject();
|
||||
}
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
package com.alttd.boosterapi.config;
|
||||
|
||||
import com.alttd.boosterapi.Booster;
|
||||
import com.alttd.boosterapi.BoosterType;
|
||||
import com.alttd.boosterapi.util.ALogger;
|
||||
import com.fasterxml.jackson.core.JsonEncoding;
|
||||
import com.fasterxml.jackson.core.JsonFactory;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public abstract class BoosterStorage {
|
||||
|
||||
private File CONFIG_FILE;
|
||||
private final Map<UUID, Booster> boosters;
|
||||
protected BoosterStorage() {
|
||||
ALogger.info("Loading boosters...");
|
||||
init();
|
||||
boosters = loadBoosters();
|
||||
if (Config.DEBUG) {
|
||||
for (Booster value : boosters.values()) {
|
||||
ALogger.info(value.getType().BoosterName);
|
||||
}
|
||||
}
|
||||
}
|
||||
private void init() {
|
||||
File CONFIG_PATH = new File(System.getProperty("user.home") + File.separator + "share" + File.separator + "configs" + File.separator + "Boosters");
|
||||
if (!CONFIG_PATH.exists()) {
|
||||
if (!CONFIG_PATH.mkdir())
|
||||
ALogger.error("Unable to create json storage directory");
|
||||
}
|
||||
CONFIG_FILE = new File(CONFIG_PATH, "storage.json");
|
||||
if (!CONFIG_FILE.exists()) {
|
||||
try {
|
||||
if (!CONFIG_FILE.createNewFile())
|
||||
ALogger.error("Unable to create json storeage file");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.enable(SerializationFeature.INDENT_OUTPUT);
|
||||
}
|
||||
|
||||
public void reload() {
|
||||
if (Config.DEBUG)
|
||||
ALogger.info("Reloading boosters...");
|
||||
boosters.clear();
|
||||
boosters.putAll(loadBoosters());
|
||||
}
|
||||
|
||||
public synchronized Map<UUID, Booster> getBoosters() {
|
||||
return boosters;
|
||||
}
|
||||
|
||||
public synchronized Map<UUID, Booster> loadBoosters() {
|
||||
Map<UUID, Booster> boosters = new HashMap<>();
|
||||
|
||||
try {
|
||||
JsonParser parser = new JsonFactory().createParser(CONFIG_FILE);
|
||||
if (parser == null) {
|
||||
ALogger.warn("Unable to load in boosters from storage file.");
|
||||
return boosters;
|
||||
}
|
||||
parser.nextToken();
|
||||
while (parser.currentToken() != null && parser.currentToken().isStructStart()) {
|
||||
Booster booster = loadBooster(parser);
|
||||
if (Config.DEBUG)
|
||||
ALogger.info("Loading booster [" + booster.getType() + "] activated by [" + booster.getActivator()+ "].");
|
||||
if (booster.getTimeRemaining() < 1)
|
||||
continue;
|
||||
boosters.put(booster.getUUID(), booster);
|
||||
if (parser.nextToken() != null && !parser.currentToken().isStructEnd()) {
|
||||
ALogger.warn("Last loaded booster had more data than expected, skipping it...");
|
||||
while (!parser.nextToken().isStructEnd())
|
||||
;
|
||||
}
|
||||
parser.nextToken();
|
||||
}
|
||||
parser.close();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return boosters;
|
||||
}
|
||||
|
||||
public abstract Booster loadBooster(JsonParser parser) throws IOException;
|
||||
|
||||
public synchronized void saveBoosters(Collection<Booster> boosters) {
|
||||
try {
|
||||
JsonGenerator generator = new JsonFactory().createGenerator(CONFIG_FILE, JsonEncoding.UTF8);
|
||||
Date date = new Date();
|
||||
for (Booster booster : boosters) {
|
||||
if (booster.finished() || (booster.isActive() && new Date(booster.getEndTime()).before(date)))
|
||||
continue;
|
||||
saveBooster(booster, generator);
|
||||
}
|
||||
generator.close();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public void saveBoosters() {
|
||||
saveBoosters(boosters.values());
|
||||
}
|
||||
|
||||
private void saveBooster(Booster booster, JsonGenerator generator) throws IOException {
|
||||
generator.writeStartObject();
|
||||
|
||||
generator.writeStringField("uuid", booster.getUUID().toString());
|
||||
generator.writeStringField("activator", booster.getActivator());
|
||||
generator.writeStringField("type", booster.getType().getBoosterName());
|
||||
generator.writeNumberField("startingTime", booster.getStartingTime());
|
||||
generator.writeNumberField("duration", booster.getDuration());
|
||||
generator.writeNumberField("multiplier", booster.getMultiplier());
|
||||
generator.writeBooleanField("active", booster.isActive());
|
||||
generator.writeBooleanField("finished", booster.finished());
|
||||
|
||||
generator.writeEndObject();
|
||||
}
|
||||
|
||||
public synchronized Collection<Booster> getBoosters(BoosterType type) {
|
||||
return boosters.values().stream().filter(booster -> booster.getType().equals(type)).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public synchronized void add(Booster booster) {
|
||||
boosters.put(booster.getUUID(), booster);
|
||||
};
|
||||
}
|
||||
@@ -1,210 +1,291 @@
|
||||
package com.alttd.boosterapi.config;
|
||||
|
||||
import com.alttd.boosterapi.util.ALogger;
|
||||
import io.leangen.geantyref.TypeToken;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.ConfigurationOptions;
|
||||
import org.spongepowered.configurate.serialize.SerializationException;
|
||||
import org.spongepowered.configurate.yaml.NodeStyle;
|
||||
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
|
||||
import com.alttd.boosterapi.util.Logger;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.List;
|
||||
|
||||
public final class Config {
|
||||
private static final Pattern PATH_PATTERN = Pattern.compile("\\.");
|
||||
private static final String HEADER = "";
|
||||
public final class Config extends AbstractConfig {
|
||||
|
||||
private static File CONFIG_FILE;
|
||||
public static ConfigurationNode config;
|
||||
public static YamlConfigurationLoader configLoader;
|
||||
private static Config config;
|
||||
|
||||
static int version;
|
||||
static boolean verbose;
|
||||
Config(Logger logger) {
|
||||
super(
|
||||
new File(System.getProperty("user.home") + File.separator
|
||||
+ "share" + File.separator
|
||||
+ "configs" + File.separator
|
||||
+ "Boosters"),
|
||||
"config.yml", logger, Config.class);
|
||||
}
|
||||
|
||||
public static File CONFIGPATH;
|
||||
public static void init() {
|
||||
CONFIGPATH = new File(System.getProperty("user.home") + File.separator + "share" + File.separator + "configs" + File.separator + "Boosters");
|
||||
CONFIG_FILE = new File(CONFIGPATH, "config.yml");
|
||||
configLoader = YamlConfigurationLoader.builder()
|
||||
.file(CONFIG_FILE)
|
||||
.nodeStyle(NodeStyle.BLOCK)
|
||||
.build();
|
||||
if (!CONFIG_FILE.getParentFile().exists()) {
|
||||
if(!CONFIG_FILE.getParentFile().mkdirs()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!CONFIG_FILE.exists()) {
|
||||
try {
|
||||
if(!CONFIG_FILE.createNewFile()) {
|
||||
return;
|
||||
}
|
||||
} catch (IOException error) {
|
||||
error.printStackTrace();
|
||||
}
|
||||
}
|
||||
public static void reload(Logger logger) {
|
||||
config = new Config(logger);
|
||||
config.readConfig(Config.class, null);
|
||||
}
|
||||
|
||||
try {
|
||||
config = configLoader.load(ConfigurationOptions.defaults().header(HEADER));
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
public static class LOGGING {
|
||||
private static final String prefix = "logging.";
|
||||
|
||||
verbose = getBoolean("verbose", true);
|
||||
version = getInt("config-version", 1);
|
||||
public static boolean PRINT_DEBUG = false;
|
||||
public static boolean PRINT_WARNINGS = true;
|
||||
|
||||
readConfig(Config.class, null);
|
||||
try {
|
||||
configLoader.save(config);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
private static void load() {
|
||||
PRINT_DEBUG = config.getBoolean(prefix, "print-debug", PRINT_DEBUG);
|
||||
PRINT_WARNINGS = config.getBoolean(prefix, "print-warnings", PRINT_WARNINGS);
|
||||
}
|
||||
}
|
||||
|
||||
public static void readConfig(Class<?> clazz, Object instance) {
|
||||
for (Method method : clazz.getDeclaredMethods()) {
|
||||
if (Modifier.isPrivate(method.getModifiers())) {
|
||||
if (method.getParameterTypes().length == 0 && method.getReturnType() == Void.TYPE) {
|
||||
try {
|
||||
method.setAccessible(true);
|
||||
method.invoke(instance);
|
||||
} catch (InvocationTargetException | IllegalAccessException ex) {
|
||||
ALogger.fatal("Error reading config", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
saveConfig();
|
||||
}
|
||||
public static class SETTINGS {
|
||||
private static final String prefix = "settings";
|
||||
|
||||
public static void saveConfig() {
|
||||
try {
|
||||
configLoader.save(config);
|
||||
} catch (IOException ex) {
|
||||
ALogger.fatal("Error saving config", ex);
|
||||
public static int UPDATE_FREQUENCY_MINUTES = 1;
|
||||
public static String PLUGIN_MESSAGE_CHANNEL = "altitude:boosterplugin";
|
||||
public static long BOOST_ANNOUNCE_CHANNEL = -1L;
|
||||
public static List<String> DONOR_RANKS = List.of("count", "viceroy", "duke", "archduke");
|
||||
|
||||
private static void load() {
|
||||
UPDATE_FREQUENCY_MINUTES = config.getInt(prefix, "update-frequency-minutes", UPDATE_FREQUENCY_MINUTES);
|
||||
BOOST_ANNOUNCE_CHANNEL = config.getLong(prefix, "boost-announce-channel", BOOST_ANNOUNCE_CHANNEL);
|
||||
PLUGIN_MESSAGE_CHANNEL = config.getString(prefix, "plugin-message-channel", PLUGIN_MESSAGE_CHANNEL);
|
||||
DONOR_RANKS = config.getList(prefix, "donor-ranks", DONOR_RANKS);
|
||||
}
|
||||
}
|
||||
|
||||
private static Object[] splitPath(String key) {
|
||||
return PATH_PATTERN.split(key);
|
||||
}
|
||||
public static class GENERIC_MESSAGES {
|
||||
private static final String prefix = "generic-messages";
|
||||
|
||||
private static void set(String path, Object def) {
|
||||
if(config.node(splitPath(path)).virtual()) {
|
||||
try {
|
||||
config.node(splitPath(path)).set(def);
|
||||
} catch (SerializationException e) {
|
||||
}
|
||||
public static String NO_PERMISSION = "<red>You do not have permission to do that command.</red>";
|
||||
public static String PLAYER_NOT_FOUND = "<red><player> is not a valid player.</red>";
|
||||
public static String RELOADED = "<green>Reloaded config.</green>";
|
||||
|
||||
private static void load() {
|
||||
NO_PERMISSION = config.getString(prefix, "no-permission", NO_PERMISSION);
|
||||
PLAYER_NOT_FOUND = config.getString(prefix, "player-not-found", PLAYER_NOT_FOUND);
|
||||
RELOADED = config.getString(prefix, "reloaded", RELOADED);
|
||||
}
|
||||
}
|
||||
|
||||
private static void setString(String path, String def) {
|
||||
try {
|
||||
if(config.node(splitPath(path)).virtual())
|
||||
config.node(splitPath(path)).set(TypeToken.get(String.class), def);
|
||||
} catch(SerializationException ex) {
|
||||
public static class BOOSTER_MESSAGES {
|
||||
private static final String prefix = "booster-messages";
|
||||
|
||||
public static String LIST_BOOSTER_MESSAGE = "Active boosters:\n<active_boosters>\n\nQueued boosters:\n<queued_boosters>";
|
||||
public static String ACTIVE_BOOSTER_PART = "<type> activated by <activator> until <end_time> [UTC], boosts <multiplier> times";
|
||||
public static String QUEUED_BOOSTER_PART = "<type> queued by <activator> will be active for <duration>, boosts <multiplier> times";
|
||||
public static String BOOST_SERVER_MESSAGE = "<light_purple>* <player> activated an <dark_purple><booster></dark_purple> booster!</light_purple>";
|
||||
|
||||
private static void load() {
|
||||
LIST_BOOSTER_MESSAGE = config.getString(prefix, "list-booster-message", LIST_BOOSTER_MESSAGE);
|
||||
ACTIVE_BOOSTER_PART = config.getString(prefix, "active-booster-part", ACTIVE_BOOSTER_PART);
|
||||
QUEUED_BOOSTER_PART = config.getString(prefix, "queued-booster-part", QUEUED_BOOSTER_PART);
|
||||
BOOST_SERVER_MESSAGE = config.getString(prefix, "boost-server-message", BOOST_SERVER_MESSAGE);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean getBoolean(String path, boolean def) {
|
||||
set(path, def);
|
||||
return config.node(splitPath(path)).getBoolean(def);
|
||||
}
|
||||
public static class DONOR_RANK_MESSAGES {
|
||||
private static final String prefix = "donor-rank-messages";
|
||||
|
||||
private static double getDouble(String path, double def) {
|
||||
set(path, def);
|
||||
return config.node(splitPath(path)).getDouble(def);
|
||||
}
|
||||
public static String INVALID_USER = "<red><player> does not exist.</red>";
|
||||
public static String INVALID_ACTION = "<red><action> is not a valid action user promote or demote.</red>";
|
||||
public static String INVALID_DONOR_RANK = "<red><rank> is not a valid donor rank.</red>";
|
||||
public static String DEMOTE_MESSAGE = "<red>Your <rank> rank was refunded and removed. Contact staff if you're unsure what caused this.</red>";
|
||||
public static String PROMOTE_MESSAGE = "<green>Thank you for your support! We applied the <rank> rank to your account.</green>";
|
||||
|
||||
private static int getInt(String path, int def) {
|
||||
set(path, def);
|
||||
return config.node(splitPath(path)).getInt(def);
|
||||
}
|
||||
|
||||
private static String getString(String path, String def) {
|
||||
setString(path, def);
|
||||
return config.node(splitPath(path)).getString(def);
|
||||
}
|
||||
|
||||
private static Long getLong(String path, Long def) {
|
||||
set(path, def);
|
||||
return config.node(splitPath(path)).getLong(def);
|
||||
}
|
||||
|
||||
private static <T> List<String> getList(String path, T def) {
|
||||
try {
|
||||
set(path, def);
|
||||
return config.node(splitPath(path)).getList(TypeToken.get(String.class));
|
||||
} catch(SerializationException ex) {
|
||||
private static void load() {
|
||||
INVALID_USER = config.getString(prefix, "invalid-user", INVALID_USER);
|
||||
INVALID_ACTION = config.getString(prefix, "invalid-action", INVALID_ACTION);
|
||||
INVALID_DONOR_RANK = config.getString(prefix, "invalid-donor-rank", INVALID_DONOR_RANK);
|
||||
DEMOTE_MESSAGE = config.getString(prefix, "demote-message", DEMOTE_MESSAGE);
|
||||
PROMOTE_MESSAGE = config.getString(prefix, "promote-message", PROMOTE_MESSAGE);
|
||||
}
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
/** ONLY EDIT ANYTHING BELOW THIS LINE **/
|
||||
public static String driver = "com.mysql.cj.jdbc.Driver";
|
||||
public static String host = "13.11.1.78";
|
||||
public static String port = "3306";
|
||||
public static String database = "McTestSql";
|
||||
public static String user = "root";
|
||||
public static String password = "foobar";
|
||||
public static String options = "?MaxPooledStatements=250&useSSL=false&autoReconnect=true&maxReconnects=3";
|
||||
private static void databaseSettings() {
|
||||
String path = "database.";
|
||||
driver = getString(path + "driver", driver);
|
||||
host = getString(path + "host", host);
|
||||
port = getString(path + "port", port);
|
||||
database = getString(path + "database", database);
|
||||
user = getString(path + "user", user);
|
||||
password = getString(path + "password", password);
|
||||
options = getString(path + "options", options);
|
||||
}
|
||||
|
||||
public static Long activeTaskCheckFrequency = 1L;
|
||||
public static Long taskCheckFrequency = 1L;
|
||||
private static void boosterTaskSettings() {
|
||||
activeTaskCheckFrequency = getLong("task.queue-frequency", activeTaskCheckFrequency);
|
||||
taskCheckFrequency = getLong("task.check-frequency", taskCheckFrequency);
|
||||
}
|
||||
|
||||
public static String pluginMessageChannel = "altitude:boosterplugin";
|
||||
private static void pluginMessageSettings() {
|
||||
pluginMessageChannel = getString("settings.message-channel", pluginMessageChannel);
|
||||
}
|
||||
|
||||
public static long BOOST_ANNOUNCE_CHANNEL = -1;
|
||||
private static void announceChannels() {
|
||||
BOOST_ANNOUNCE_CHANNEL = getLong("settings.boost-announce-channel", BOOST_ANNOUNCE_CHANNEL);
|
||||
}
|
||||
|
||||
public static List<String> donorRanks = new ArrayList<>();
|
||||
private static void loadDonorStuff() {
|
||||
donorRanks = getList("donor.ranks", donorRanks);
|
||||
}
|
||||
|
||||
public static String INVALID_USER = "<red><player> does not exist.</red>";
|
||||
public static String INVALID_ACTION = "<red><action> is not a valid action user promote or demote.</red>";
|
||||
public static String INVALID_DONOR_RANK = "<red><rank> is not a valid donor rank.</red>";
|
||||
public static String DEMOTE_MESSAGE = "<red>Your <rank> rank was refunded and removed. Contact staff if you're unsure what caused this.</red>";
|
||||
public static String PROMOTE_MESSAGE = "<green>Thank you for your support! We applied the <rank> rank to your account.</green>";
|
||||
public static String BOOST_SERVER_MESSAGE = "<light_purple>* <player> activated an <dark_purple><booster></dark_purple> booster!</light_purple>";
|
||||
private static void loadMessages() {
|
||||
INVALID_USER = getString("messages.invalid-user", INVALID_USER);
|
||||
INVALID_ACTION = getString("messages.invalid-action", INVALID_ACTION);
|
||||
INVALID_DONOR_RANK = getString("messages.invalid-donor-rank", INVALID_DONOR_RANK);
|
||||
DEMOTE_MESSAGE = getString("messages.demote", DEMOTE_MESSAGE);
|
||||
PROMOTE_MESSAGE = getString("messages.promote", PROMOTE_MESSAGE);
|
||||
BOOST_SERVER_MESSAGE = getString("messages.boost-server", BOOST_SERVER_MESSAGE);
|
||||
}
|
||||
|
||||
public static boolean DEBUG = false;
|
||||
private static void loadSettings() {
|
||||
DEBUG = getBoolean("settings.debug", DEBUG);
|
||||
}
|
||||
// private static final Pattern PATH_PATTERN = Pattern.compile("\\.");
|
||||
// private static final String HEADER = "";
|
||||
//
|
||||
// private static File CONFIG_FILE;
|
||||
// public static ConfigurationNode config;
|
||||
// public static YamlConfigurationLoader configLoader;
|
||||
//
|
||||
// static int version;
|
||||
// static boolean verbose;
|
||||
//
|
||||
// public static File CONFIGPATH;
|
||||
// public static void init() {
|
||||
// CONFIGPATH = new File(System.getProperty("user.home") + File.separator + "share" + File.separator + "configs" + File.separator + "Boosters");
|
||||
// CONFIG_FILE = new File(CONFIGPATH, "config.yml");
|
||||
// configLoader = YamlConfigurationLoader.builder()
|
||||
// .file(CONFIG_FILE)
|
||||
// .nodeStyle(NodeStyle.BLOCK)
|
||||
// .build();
|
||||
// if (!CONFIG_FILE.getParentFile().exists()) {
|
||||
// if(!CONFIG_FILE.getParentFile().mkdirs()) {
|
||||
// return;
|
||||
// }
|
||||
// }
|
||||
// if (!CONFIG_FILE.exists()) {
|
||||
// try {
|
||||
// if(!CONFIG_FILE.createNewFile()) {
|
||||
// return;
|
||||
// }
|
||||
// } catch (IOException error) {
|
||||
// error.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// try {
|
||||
// config = configLoader.load(ConfigurationOptions.defaults().header(HEADER));
|
||||
// } catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
//
|
||||
// verbose = getBoolean("verbose", true);
|
||||
// version = getInt("config-version", 1);
|
||||
//
|
||||
// readConfig(Config.class, null);
|
||||
// try {
|
||||
// configLoader.save(config);
|
||||
// } catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public static void readConfig(Class<?> clazz, Object instance) {
|
||||
// for (Method method : clazz.getDeclaredMethods()) {
|
||||
// if (Modifier.isPrivate(method.getModifiers())) {
|
||||
// if (method.getParameterTypes().length == 0 && method.getReturnType() == Void.TYPE) {
|
||||
// try {
|
||||
// method.setAccessible(true);
|
||||
// method.invoke(instance);
|
||||
// } catch (InvocationTargetException | IllegalAccessException ex) {
|
||||
// ALogger.fatal("Error reading config", ex);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// saveConfig();
|
||||
// }
|
||||
//
|
||||
// public static void saveConfig() {
|
||||
// try {
|
||||
// configLoader.save(config);
|
||||
// } catch (IOException ex) {
|
||||
// ALogger.fatal("Error saving config", ex);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private static Object[] splitPath(String key) {
|
||||
// return PATH_PATTERN.split(key);
|
||||
// }
|
||||
//
|
||||
// private static void set(String path, Object def) {
|
||||
// if(config.node(splitPath(path)).virtual()) {
|
||||
// try {
|
||||
// config.node(splitPath(path)).set(def);
|
||||
// } catch (SerializationException e) {
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private static void setString(String path, String def) {
|
||||
// try {
|
||||
// if(config.node(splitPath(path)).virtual())
|
||||
// config.node(splitPath(path)).set(TypeToken.get(String.class), def);
|
||||
// } catch(SerializationException ex) {
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private static boolean getBoolean(String path, boolean def) {
|
||||
// set(path, def);
|
||||
// return config.node(splitPath(path)).getBoolean(def);
|
||||
// }
|
||||
//
|
||||
// private static double getDouble(String path, double def) {
|
||||
// set(path, def);
|
||||
// return config.node(splitPath(path)).getDouble(def);
|
||||
// }
|
||||
//
|
||||
// private static int getInt(String path, int def) {
|
||||
// set(path, def);
|
||||
// return config.node(splitPath(path)).getInt(def);
|
||||
// }
|
||||
//
|
||||
// private static String getString(String path, String def) {
|
||||
// setString(path, def);
|
||||
// return config.node(splitPath(path)).getString(def);
|
||||
// }
|
||||
//
|
||||
// private static Long getLong(String path, Long def) {
|
||||
// set(path, def);
|
||||
// return config.node(splitPath(path)).getLong(def);
|
||||
// }
|
||||
//
|
||||
// private static <T> List<String> getList(String path, T def) {
|
||||
// try {
|
||||
// set(path, def);
|
||||
// return config.node(splitPath(path)).getList(TypeToken.get(String.class));
|
||||
// } catch(SerializationException ex) {
|
||||
// }
|
||||
// return new ArrayList<>();
|
||||
// }
|
||||
//
|
||||
// /** ONLY EDIT ANYTHING BELOW THIS LINE **/
|
||||
// public static String driver = "com.mysql.cj.jdbc.Driver";
|
||||
// public static String host = "13.11.1.78";
|
||||
// public static String port = "3306";
|
||||
// public static String database = "McTestSql";
|
||||
// public static String user = "root";
|
||||
// public static String password = "foobar";
|
||||
// public static String options = "?MaxPooledStatements=250&useSSL=false&autoReconnect=true&maxReconnects=3";
|
||||
// private static void databaseSettings() {
|
||||
// String path = "database.";
|
||||
// driver = getString(path + "driver", driver);
|
||||
// host = getString(path + "host", host);
|
||||
// port = getString(path + "port", port);
|
||||
// database = getString(path + "database", database);
|
||||
// user = getString(path + "user", user);
|
||||
// password = getString(path + "password", password);
|
||||
// options = getString(path + "options", options);
|
||||
// }
|
||||
//
|
||||
// public static Long activeTaskCheckFrequency = 1L;
|
||||
// public static Long taskCheckFrequency = 1L;
|
||||
// private static void boosterTaskSettings() {
|
||||
// activeTaskCheckFrequency = getLong("task.queue-frequency", activeTaskCheckFrequency);
|
||||
// taskCheckFrequency = getLong("task.check-frequency", taskCheckFrequency);
|
||||
// }
|
||||
//
|
||||
// public static String pluginMessageChannel = "altitude:boosterplugin";
|
||||
// private static void pluginMessageSettings() {
|
||||
// pluginMessageChannel = getString("settings.message-channel", pluginMessageChannel);
|
||||
// }
|
||||
//
|
||||
// public static long BOOST_ANNOUNCE_CHANNEL = -1;
|
||||
// private static void announceChannels() {
|
||||
// BOOST_ANNOUNCE_CHANNEL = getLong("settings.boost-announce-channel", BOOST_ANNOUNCE_CHANNEL);
|
||||
// }
|
||||
//
|
||||
// public static List<String> donorRanks = new ArrayList<>();
|
||||
// private static void loadDonorStuff() {
|
||||
// donorRanks = getList("donor.ranks", donorRanks);
|
||||
// }
|
||||
//
|
||||
// public static String INVALID_USER = "<red><player> does not exist.</red>";
|
||||
// public static String INVALID_ACTION = "<red><action> is not a valid action user promote or demote.</red>";
|
||||
// public static String INVALID_DONOR_RANK = "<red><rank> is not a valid donor rank.</red>";
|
||||
// public static String DEMOTE_MESSAGE = "<red>Your <rank> rank was refunded and removed. Contact staff if you're unsure what caused this.</red>";
|
||||
// public static String PROMOTE_MESSAGE = "<green>Thank you for your support! We applied the <rank> rank to your account.</green>";
|
||||
// public static String BOOST_SERVER_MESSAGE = "<light_purple>* <player> activated an <dark_purple><booster></dark_purple> booster!</light_purple>";
|
||||
// private static void loadMessages() {
|
||||
// INVALID_USER = getString("messages.invalid-user", INVALID_USER);
|
||||
// INVALID_ACTION = getString("messages.invalid-action", INVALID_ACTION);
|
||||
// INVALID_DONOR_RANK = getString("messages.invalid-donor-rank", INVALID_DONOR_RANK);
|
||||
// DEMOTE_MESSAGE = getString("messages.demote", DEMOTE_MESSAGE);
|
||||
// PROMOTE_MESSAGE = getString("messages.promote", PROMOTE_MESSAGE);
|
||||
// BOOST_SERVER_MESSAGE = getString("messages.boost-server", BOOST_SERVER_MESSAGE);
|
||||
// }
|
||||
//
|
||||
// public static boolean DEBUG = false;
|
||||
// private static void loadSettings() {
|
||||
// DEBUG = getBoolean("settings.debug", DEBUG);
|
||||
// }
|
||||
}
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
package com.alttd.boosterapi.config;
|
||||
|
||||
import io.leangen.geantyref.TypeToken;
|
||||
import org.spongepowered.configurate.serialize.SerializationException;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class ServerConfig {
|
||||
private static final Pattern PATH_PATTERN = Pattern.compile("\\.");
|
||||
|
||||
private final String serverName;
|
||||
private final String configPath;
|
||||
private final String defaultPath;
|
||||
|
||||
public ServerConfig(String serverName) {
|
||||
this.serverName = serverName;
|
||||
this.configPath = "server-settings." + this.serverName + ".";
|
||||
this.defaultPath = "server-settings.default.";
|
||||
init();
|
||||
}
|
||||
|
||||
public void init() {
|
||||
Config.readConfig(ServerConfig.class, this);
|
||||
Config.saveConfig();
|
||||
}
|
||||
|
||||
public static Object[] splitPath(String key) {
|
||||
return PATH_PATTERN.split(key);
|
||||
}
|
||||
|
||||
private static void set(String path, Object def) {
|
||||
if(Config.config.node(splitPath(path)).virtual()) {
|
||||
try {
|
||||
Config.config.node(splitPath(path)).set(def);
|
||||
} catch (SerializationException ex) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void setString(String path, String def) {
|
||||
try {
|
||||
if(Config.config.node(splitPath(path)).virtual())
|
||||
Config.config.node(splitPath(path)).set(TypeToken.get(String.class), def);
|
||||
} catch(SerializationException ex) {
|
||||
}
|
||||
}
|
||||
|
||||
private boolean getBoolean(String path, boolean def) {
|
||||
set(defaultPath +path, def);
|
||||
return Config.config.node(splitPath(configPath+path)).getBoolean(
|
||||
Config.config.node(splitPath(defaultPath +path)).getBoolean(def));
|
||||
}
|
||||
|
||||
private double getDouble(String path, double def) {
|
||||
set(defaultPath +path, def);
|
||||
return Config.config.node(splitPath(configPath+path)).getDouble(
|
||||
Config.config.node(splitPath(defaultPath +path)).getDouble(def));
|
||||
}
|
||||
|
||||
private int getInt(String path, int def) {
|
||||
set(defaultPath +path, def);
|
||||
return Config.config.node(splitPath(configPath+path)).getInt(
|
||||
Config.config.node(splitPath(defaultPath +path)).getInt(def));
|
||||
}
|
||||
|
||||
private String getString(String path, String def) {
|
||||
set(defaultPath +path, def);
|
||||
return Config.config.node(splitPath(configPath+path)).getString(
|
||||
Config.config.node(splitPath(defaultPath +path)).getString(def));
|
||||
}
|
||||
|
||||
/** DO NOT EDIT ANYTHING ABOVE **/
|
||||
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.alttd.boosterapi.data;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
import java.util.Objects;
|
||||
|
||||
public class Booster implements Comparable<Booster> {
|
||||
|
||||
private final UUID boosterUUID;
|
||||
private final String activatorName;
|
||||
private Instant startingTime;
|
||||
private Duration duration;
|
||||
private final BoosterType boosterType;
|
||||
private final Double multiplier;
|
||||
private Boolean running;
|
||||
|
||||
public Booster(UUID boosterUUID, BoosterType boosterType, String reason, Duration duration, double multiplier) {
|
||||
this.boosterUUID = boosterUUID;
|
||||
this.boosterType = boosterType;
|
||||
this.activatorName = reason;
|
||||
this.duration = duration;
|
||||
this.multiplier = multiplier;
|
||||
this.running = false;
|
||||
this.startingTime = Instant.now();
|
||||
}
|
||||
|
||||
public Booster(BoosterType type, String playerName, Duration duration, double multiplier) {
|
||||
this(UUID.randomUUID(), type, playerName, duration, multiplier);
|
||||
}
|
||||
|
||||
public Booster(UUID boosterUUID, String activatorName, BoosterType boosterType, Instant startingTime,
|
||||
Duration duration, double multiplier, boolean running) {
|
||||
this.boosterUUID = boosterUUID;
|
||||
this.activatorName = activatorName;
|
||||
this.boosterType = boosterType;
|
||||
this.startingTime = startingTime;
|
||||
this.duration = duration;
|
||||
this.multiplier = multiplier;
|
||||
this.running = running;
|
||||
}
|
||||
|
||||
public void updateDuration() {
|
||||
Instant stopTime = Instant.now();
|
||||
Duration elapsedTime = Duration.between(startingTime, stopTime);
|
||||
duration = duration.minus(elapsedTime);
|
||||
}
|
||||
|
||||
public double useMultiplier(double exp) {
|
||||
return exp * (multiplier + 1);
|
||||
}
|
||||
|
||||
public UUID getBoosterUUID() {
|
||||
return boosterUUID;
|
||||
}
|
||||
|
||||
public String getActivatorName() {
|
||||
return activatorName;
|
||||
}
|
||||
|
||||
public Instant getStartingTime() {
|
||||
return startingTime;
|
||||
}
|
||||
|
||||
public Duration getDuration() {
|
||||
return duration;
|
||||
}
|
||||
|
||||
public BoosterType getBoosterType() {
|
||||
return boosterType;
|
||||
}
|
||||
|
||||
public Double getMultiplier() {
|
||||
return multiplier;
|
||||
}
|
||||
|
||||
public Boolean getRunning() {
|
||||
return running;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
Booster other = (Booster) o;
|
||||
return Objects.equals(boosterUUID, other.boosterUUID);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(boosterUUID);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(@NotNull Booster other) {
|
||||
int multiplierComparison = Double.compare(other.multiplier, this.multiplier);
|
||||
if (multiplierComparison != 0) {
|
||||
return multiplierComparison;
|
||||
}
|
||||
|
||||
return this.duration.compareTo(other.duration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Booster{" +
|
||||
"boosterUUID=" + boosterUUID +
|
||||
", activatorName='" + activatorName + '\'' +
|
||||
", startingTime=" + startingTime +
|
||||
", duration=" + duration +
|
||||
", boosterType=" + boosterType +
|
||||
", multiplier=" + multiplier +
|
||||
", running=" + running +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.alttd.boosterapi.data;
|
||||
|
||||
import com.alttd.boosterapi.config.BoosterFileStorage;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class BoosterCache {
|
||||
|
||||
private final HashMap<BoosterType, LinkedList<Booster>> boosters = new HashMap<>();
|
||||
private final BoosterFileStorage boosterFileStorage;
|
||||
|
||||
public BoosterCache(BoosterFileStorage boosterFileStorage) {
|
||||
this.boosterFileStorage = boosterFileStorage;
|
||||
reloadBoosters();
|
||||
}
|
||||
|
||||
public synchronized void reloadBoosters() {
|
||||
boosters.clear();
|
||||
List<Booster> allBoosters = boosterFileStorage.reload();
|
||||
for (Booster booster : allBoosters) {
|
||||
LinkedList<Booster> list = boosters.getOrDefault(booster.getBoosterType(), new LinkedList<>());
|
||||
list.add(booster);
|
||||
boosters.put(booster.getBoosterType(), list);
|
||||
}
|
||||
updateOrder();
|
||||
}
|
||||
|
||||
private void updateOrder() {
|
||||
for (BoosterType boosterType : boosters.keySet()) {
|
||||
updateOrder(boosterType);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateOrder(BoosterType boosterType) {
|
||||
if (!boosters.containsKey(boosterType)) {
|
||||
return;
|
||||
}
|
||||
LinkedList<Booster> list = boosters.get(boosterType);
|
||||
list.sort(Booster::compareTo);
|
||||
}
|
||||
|
||||
public synchronized Optional<Booster> getActiveBooster(BoosterType boosterType) {
|
||||
if (!boosters.containsKey(boosterType))
|
||||
return Optional.empty();
|
||||
LinkedList<Booster> list = boosters.get(boosterType);
|
||||
if (list.isEmpty())
|
||||
return Optional.empty();
|
||||
return Optional.of(list.get(0));
|
||||
}
|
||||
|
||||
public synchronized List<Booster> getAllActiveBoosters() {
|
||||
return boosters.values().stream()
|
||||
.filter(list -> !list.isEmpty())
|
||||
.map(list -> list.get(0))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public synchronized List<Booster> getAllQueuedBoosters() {
|
||||
return boosters.values().stream()
|
||||
.filter(list -> list.size() > 1)
|
||||
.map(list -> list.subList(1, list.size()))
|
||||
.flatMap(List::stream)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public synchronized void addNewBooster(BoosterType boosterType, String activatorName, Duration duration, double multiplier) {
|
||||
List<BoosterType> childBoosters = boosterType.getChildBoosters();
|
||||
if (!childBoosters.isEmpty()) {
|
||||
addNewBoosters(childBoosters, activatorName, duration, multiplier);
|
||||
return;
|
||||
}
|
||||
Booster booster = new Booster(boosterType, activatorName, duration, multiplier);
|
||||
LinkedList<Booster> list = boosters.getOrDefault(boosterType, new LinkedList<>());
|
||||
list.addLast(booster);
|
||||
boosters.put(boosterType, list);
|
||||
updateOrder(boosterType);
|
||||
boosterFileStorage.saveBoosters(boosters.values().stream().flatMap(List::stream).collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
private void addNewBoosters(List<BoosterType> boosterTypes, String activatorName, Duration duration, double multiplier) {
|
||||
for (BoosterType boosterType : boosterTypes) {
|
||||
Booster booster = new Booster(boosterType, activatorName, duration, multiplier);
|
||||
LinkedList<Booster> list = boosters.getOrDefault(boosterType, new LinkedList<>());
|
||||
list.addLast(booster);
|
||||
boosters.put(boosterType, list);
|
||||
updateOrder(boosterType);
|
||||
}
|
||||
boosterFileStorage.saveBoosters(boosters.values().stream().flatMap(List::stream).collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
public synchronized void finishBooster(Booster booster) {
|
||||
BoosterType boosterType = booster.getBoosterType();
|
||||
LinkedList<Booster> list = boosters.get(boosterType);
|
||||
if (list == null)
|
||||
return;
|
||||
list.removeIf(filterBooster -> filterBooster.getBoosterUUID().equals(booster.getBoosterUUID()));
|
||||
boosters.put(boosterType, list);
|
||||
updateOrder(boosterType);
|
||||
boosterFileStorage.saveBoosters(boosters.values().stream().flatMap(List::stream).collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
public synchronized void updateAndSave() {
|
||||
getAllActiveBoosters().forEach(Booster::updateDuration); //TODO test if this needs to be re-added to the map (it shouldn't afaik)
|
||||
boosterFileStorage.saveBoosters(boosters.values().stream().flatMap(List::stream).collect(Collectors.toList()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.alttd.boosterapi.data;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public enum BoosterType {
|
||||
|
||||
/**
|
||||
* MCMMO - implies all mcmmo skills are boosted
|
||||
*/
|
||||
MCMMO("mcmmo", null),
|
||||
|
||||
ACROBATICS("acrobatics", MCMMO),
|
||||
ALCHEMY("alchemy", MCMMO),
|
||||
ARCHERY("archery", MCMMO),
|
||||
AXES("axes", MCMMO),
|
||||
EXCAVATION("excavation", MCMMO),
|
||||
FISHING("fishing", MCMMO),
|
||||
HERBALISM("herbalism", MCMMO),
|
||||
MINING("mining", MCMMO),
|
||||
REPAIR("repair", MCMMO),
|
||||
SALVAGE("salvage", MCMMO),
|
||||
SMELTING("smelting", MCMMO),
|
||||
SWORDS("swords", MCMMO),
|
||||
TAMING("taming", MCMMO),
|
||||
UNARMED("unarmed", MCMMO),
|
||||
WOODCUTTING("woodcutting", MCMMO),
|
||||
|
||||
/**
|
||||
* MYPET - Boosts MyPet exp gains
|
||||
*/
|
||||
MYPET("mypet", null),
|
||||
/**
|
||||
* VANILLAXP - increases exp gained by killing mobs
|
||||
*/
|
||||
VANILLAXP("vanillaxp", null),
|
||||
/**
|
||||
* LUCK - Boosts luck based vanilla features
|
||||
* Caps at max vanilla enchant + 1
|
||||
* Boosts:
|
||||
* - Mining with Fortune
|
||||
* - Adds 1 extra looting level to any mob kills
|
||||
* - Boosts luck of the sea by 1
|
||||
*/
|
||||
LUCK("luck", null),
|
||||
/**
|
||||
* PHANTOM - Disables phantom spawns while this booster is active
|
||||
*/
|
||||
PHANTOM("phantom", null),
|
||||
/**
|
||||
* IDK
|
||||
*/
|
||||
UNKNOWN("unknown", null);
|
||||
|
||||
public final String BoosterName;
|
||||
public final BoosterType parent;
|
||||
BoosterType(String BoosterName, BoosterType parent) {
|
||||
this.BoosterName = BoosterName;
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
public String getBoosterName() {
|
||||
return this.BoosterName;
|
||||
}
|
||||
|
||||
public static BoosterType getByName(String text) {
|
||||
for (BoosterType type : BoosterType.values()) {
|
||||
if (type.BoosterName.equalsIgnoreCase(text)) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
return UNKNOWN;
|
||||
}
|
||||
|
||||
public List<BoosterType> getChildBoosters() {
|
||||
return Arrays.stream(BoosterType.values()).filter(boosterType -> boosterType.parent == this).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package com.alttd.boosterapi.database;
|
||||
|
||||
import com.alttd.boosterapi.config.Config;
|
||||
import com.alttd.boosterapi.util.ALogger;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class Database {
|
||||
|
||||
private static Connection connection;
|
||||
|
||||
public static Connection getConnection() {
|
||||
if (connection == null) {
|
||||
try {
|
||||
Class.forName(Config.driver);
|
||||
|
||||
connection = DriverManager.getConnection("jdbc:mysql://" + Config.host + ":" + Config.port + "/" + Config.database + Config.options, Config.user, Config.password);
|
||||
} catch (ClassNotFoundException | SQLException ex) {
|
||||
ALogger.fatal("Failed to connect to sql.", ex);
|
||||
}
|
||||
}
|
||||
return connection;
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
if (connection != null) {
|
||||
try {
|
||||
connection.close();
|
||||
|
||||
connection = null;
|
||||
|
||||
} catch (SQLException ex) {
|
||||
ALogger.fatal("Failed to disconnect from sql.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.alttd.boosterapi.util;
|
||||
|
||||
public class ALogger {
|
||||
|
||||
private static org.slf4j.Logger logger = null;
|
||||
|
||||
public static void init(org.slf4j.Logger log) {
|
||||
logger = log;
|
||||
}
|
||||
|
||||
public static void warn(String message) {
|
||||
logger.warn(message);
|
||||
}
|
||||
|
||||
public static void info(String message) {
|
||||
logger.info(message);
|
||||
}
|
||||
|
||||
public static void error(String message) {
|
||||
logger.error(message);
|
||||
}
|
||||
|
||||
public static void fatal(String error, Exception exception) {
|
||||
error(error + "\n" + exception);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.alttd.boosterapi.util;
|
||||
|
||||
import com.alttd.boosterapi.data.Booster;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.minimessage.MiniMessage;
|
||||
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
|
||||
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class BoosterParser {
|
||||
|
||||
private final static MiniMessage miniMessage = MiniMessage.miniMessage();
|
||||
|
||||
public static List<Component> parseBoosters(Logger logger, List<Booster> boosters, String message, boolean active) {
|
||||
return boosters.stream().map(booster -> {
|
||||
logger.debug("processing booster: " + booster);
|
||||
TagResolver resolver = TagResolver.resolver(
|
||||
Placeholder.unparsed("type", booster.getBoosterType().getBoosterName()),
|
||||
Placeholder.unparsed("activator", booster.getActivatorName()),
|
||||
Placeholder.unparsed("start_time", DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT).format(booster.getStartingTime().toEpochMilli())),
|
||||
Placeholder.unparsed("duration", booster.getDuration().toHours() + " hours"),
|
||||
Placeholder.unparsed("multiplier", String.valueOf(booster.getMultiplier())),
|
||||
Placeholder.unparsed("end_time", active ? DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT).format(booster.getStartingTime().toEpochMilli() + booster.getDuration().toMillis()) : "unknown")
|
||||
);
|
||||
return miniMessage.deserialize(message, resolver);
|
||||
}).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.alttd.boosterapi.util;
|
||||
|
||||
import com.alttd.boosterapi.config.Config;
|
||||
|
||||
public class Logger {
|
||||
|
||||
private final org.slf4j.Logger logger;
|
||||
|
||||
static private final String RESET = "\u001B[0m";
|
||||
static private final String GREEN = "\u001B[32m";
|
||||
static private final String TEAL = "\u001B[36m";
|
||||
|
||||
public Logger(org.slf4j.Logger logger) {
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public void debug(String debug, String... variables) {
|
||||
if (!Config.LOGGING.PRINT_DEBUG)
|
||||
return;
|
||||
logger.info(TEAL + replace(debug, variables) + RESET);
|
||||
}
|
||||
|
||||
public void info(String info, String... variables) {
|
||||
logger.info(GREEN + replace(info, variables) + RESET);
|
||||
}
|
||||
|
||||
public void warning(String warning, String... variables) {
|
||||
if (!Config.LOGGING.PRINT_WARNINGS)
|
||||
return;
|
||||
logger.warn(replace(warning, variables));
|
||||
}
|
||||
|
||||
public void severe(String severe, String... variables) {
|
||||
logger.error(replace(severe, variables));
|
||||
}
|
||||
|
||||
private String replace(String text, String... variables) {
|
||||
for (String variable : variables) {
|
||||
text = text.replaceFirst("%", variable);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.alttd.boosterapi.util;
|
||||
|
||||
public class StringModifier {
|
||||
|
||||
public static String capitalize(String string) {
|
||||
if (string.length() <= 1)
|
||||
return string.toUpperCase();
|
||||
string = string.toLowerCase();
|
||||
return string.substring(0, 1).toUpperCase() + string.toLowerCase().substring(1);
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.alttd.boosterapi.util;
|
||||
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.minimessage.MiniMessage;
|
||||
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
|
||||
|
||||
public class Utils {
|
||||
|
||||
public static Component parseMiniMessage(String message, TagResolver placeholders) {
|
||||
MiniMessage miniMessage = MiniMessage.miniMessage();
|
||||
if (placeholders == null) {
|
||||
return miniMessage.deserialize(message);
|
||||
} else {
|
||||
return miniMessage.deserialize(message, placeholders);
|
||||
}
|
||||
}
|
||||
|
||||
public static String capitalize(String string) {
|
||||
if (string.length() <= 1)
|
||||
return string.toUpperCase();
|
||||
string = string.toLowerCase();
|
||||
return string.substring(0, 1).toUpperCase() + string.toLowerCase().substring(1);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user