Skip to content

Commit

Permalink
Merge branch 'master' of /~https://github.com/xdnw/locutus
Browse files Browse the repository at this point in the history
  • Loading branch information
xdnw committed Jan 8, 2024
2 parents 74c878a + 5921382 commit 9df0cde
Show file tree
Hide file tree
Showing 33 changed files with 610 additions and 252 deletions.
5 changes: 3 additions & 2 deletions src/main/java/link/locutus/discord/Locutus.java
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,6 @@ private Locutus() throws SQLException, ClassNotFoundException, LoginException, I

this.commandManager = new CommandManager(this);
System.out.println("remove:|| commandmanager " + (((-start)) + (start = System.currentTimeMillis())));
this.commandManager.registerCommands(discordDB);
System.out.println("remove:|| registercommands " + (((-start)) + (start = System.currentTimeMillis())));
if (Settings.INSTANCE.BOT_TOKEN.isEmpty()) {
throw new IllegalStateException("Please set BOT_TOKEN in " + Settings.INSTANCE.getDefaultFile());
}
Expand Down Expand Up @@ -258,6 +256,9 @@ private Locutus() throws SQLException, ClassNotFoundException, LoginException, I
this.v3 = new PoliticsAndWarV3(v3Pool);
System.out.println("remove:|| v3 " + (((-start)) + (start = System.currentTimeMillis())));

this.commandManager.registerCommands(discordDB);
System.out.println("remove:|| registercommands " + (((-start)) + (start = System.currentTimeMillis())));

if (Settings.INSTANCE.ENABLED_COMPONENTS.EVENTS) {
this.registerEvents();
}
Expand Down
174 changes: 120 additions & 54 deletions src/main/java/link/locutus/discord/apiv3/DataDumpParser.java

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions src/main/java/link/locutus/discord/apiv3/ParsedRow.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public void setRow(CsvRow row) {
}
nation = null;
city = null;
nationLoaded = 0;
}

public <T> T get(int index, Function<String, T> parse) {
Expand All @@ -54,10 +55,10 @@ public DBNation getNation(DataDumpParser.NationHeader header, boolean allowVM, b
if (!allowDeleted && (nationLoaded & ALLOW_DELETED) != 0 && !nation.isValid()) return null;
return nation;
}
if ((nationLoaded & LOADED) != 0 && (!allowVM || (nationLoaded & ALLOW_VM) != 0) && (!allowDeleted || (nationLoaded & ALLOW_DELETED) != 0)) return null;
if ((nationLoaded & LOADED) != 0 && (!allowVM || (nationLoaded & ALLOW_VM) == 0) && (!allowDeleted || (nationLoaded & ALLOW_DELETED) == 0)) return null;
nationLoaded |= LOADED | (allowVM ? ALLOW_VM : 0) | (allowDeleted ? ALLOW_DELETED : 0);
try {
nation = parser.loadNation(header, row, allowAll, allowVM, allowDeleted);
nation = parser.loadNation(header, row, allowAll, allowAll, allowVM, allowDeleted);
} catch (ParseException e) {
throw new RuntimeException(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ public CommandManager(Locutus locutus) {
this.commandMap = new LinkedHashMap<>();
this.executor = new ScheduledThreadPoolExecutor(256);

modernized = new CommandManager2().registerDefaults();
modernized = new CommandManager2();
}

public boolean isModernPrefix(char prefix) {
Expand Down Expand Up @@ -530,6 +530,9 @@ private void threadDump() {
}

public void registerCommands(DiscordDB db) {
if (modernized != null) {
modernized.registerDefaults();
}
this.register(new RaidCommand());
this.register(new PendingCommand());
this.register(new ForumScrape());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,13 @@
import link.locutus.discord.commands.manager.v2.binding.LocalValueStore;
import link.locutus.discord.commands.manager.v2.binding.MethodParser;
import link.locutus.discord.commands.manager.v2.binding.Parser;
import link.locutus.discord.commands.manager.v2.binding.SimpleValueStore;
import link.locutus.discord.commands.manager.v2.binding.ValueStore;
import link.locutus.discord.commands.manager.v2.binding.annotation.Binding;
import link.locutus.discord.commands.manager.v2.binding.annotation.Me;
import link.locutus.discord.commands.manager.v2.binding.annotation.Switch;
import link.locutus.discord.commands.manager.v2.binding.validator.ValidatorStore;
import link.locutus.discord.commands.manager.v2.command.*;
import link.locutus.discord.commands.manager.v2.impl.pw.CommandManager2;
import link.locutus.discord.commands.manager.v2.impl.pw.binding.PWMath2Type;
import link.locutus.discord.commands.manager.v2.impl.pw.binding.PWType2Math;
import link.locutus.discord.commands.manager.v2.impl.pw.filter.PlaceholdersMap;
import link.locutus.discord.commands.manager.v2.perm.PermissionHandler;
import link.locutus.discord.db.GuildDB;
Expand Down Expand Up @@ -239,9 +236,11 @@ public void register(ValueStore store) {
Method methodSet = this.getClass().getMethod("parseSet", ValueStore.class, String.class);
Method methodPredicate = this.getClass().getMethod("parseFilter", ValueStore.class, String.class);
Method methodFormat = this.getClass().getMethod("getFormatFunction", ValueStore.class, String.class);
Method methodDouble = this.getClass().getMethod("getDoubleFunction", ValueStore.class, String.class);
registerCustom(methodSet, TypeToken.getParameterized(Set.class, this.instanceType).getType());
registerCustom(methodPredicate, TypeToken.getParameterized(Predicate.class, this.instanceType).getType());
registerCustom(methodFormat, TypeToken.getParameterized(TypedFunction.class, this.instanceType, String.class).getType());
registerCustom(methodDouble, TypeToken.getParameterized(TypedFunction.class, this.instanceType, Double.class).getType());
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
Expand Down Expand Up @@ -366,7 +365,7 @@ private Predicate<T> getSingleFilter(ValueStore store, String input) {
}
return f -> {
Object value = func.apply(f);
System.out.println("Value " + f + " | " + value);
if (value instanceof String) return false;
return adapter.test((T) value);
};
}
Expand Down Expand Up @@ -473,19 +472,19 @@ public Set<T> parseSet(ValueStore store2, String input) {
}
}
Object parsed = parseMath(s, param, true);
return ResolvedFunction.create(parsed != null ? parsed.getClass() : Object.class, parsed, s);
return ResolvedFunction.createConstant(parsed != null ? parsed.getClass() : Object.class, parsed, s);
};
List<LazyMathEntity<T>> lazies = ArrayUtil.calculate(input, s -> new LazyMathEntity<>(s, stringToParser, false));
if (lazies.size() == 1) {
LazyMathEntity<T> lazy = lazies.get(0);
Object array = lazy.getOrNull();
Class type = param == null ? Double.class : (Class) param.getType();
if (array != null) {
return TypedFunction.create(type, toObject(array, type, param), input);
return TypedFunction.createConstant(type, toObject(array, type, param), input);
}
return TypedFunction.create(type, f -> {
return TypedFunction.createParents(type, f -> {
return toObject(lazy.resolve(f), type, param);
}, input);
}, input, functions.values());
}
} else if (!hasNonMath) {
if (hasCurlyBracket) {
Expand Down Expand Up @@ -518,10 +517,13 @@ public Set<T> parseSet(ValueStore store2, String input) {
// get function
TypedFunction<T, ?> function = functions.get(section);
if (function != null) {
System.out.println("Return function 1" + function.getName() + " | " + function.getType());
return function;
}
System.out.println("Return non function section " + section);
return new ResolvedFunction<>(String.class, section, section);
}
System.out.println("Multiple sections " + sections);
boolean isResolved = functions.isEmpty() || functions.values().stream().allMatch(ResolvedFunction.class::isInstance);
Function<T, Object> result = f -> {
StringBuilder resultStr = new StringBuilder();
Expand All @@ -538,7 +540,7 @@ public Set<T> parseSet(ValueStore store2, String input) {
if (isResolved) {
return new ResolvedFunction<>(String.class, result.apply(null), input);
}
return TypedFunction.create(String.class, result, input);
return TypedFunction.createParents(String.class, result, input, functions.values());
}

private Object toObject(Object expr, Class type, ParameterData param) {
Expand Down Expand Up @@ -645,7 +647,7 @@ private IllegalArgumentException throwUnknownCommand(String command) {
private TypedFunction<T, ?> evaluateFunction(ValueStore store, String functionContent, int depth, boolean throwError) {
TypedFunction<T, ?> previousFunc = null;
if (functionContent.equalsIgnoreCase("this")) {
return TypedFunction.create(getType(), Function.identity(), "this");
return TypedFunction.createParents(getType(), Function.identity(), "this", null);
}
List<String> split = StringMan.split(functionContent, ".");
if (split.isEmpty()) {
Expand Down Expand Up @@ -706,12 +708,12 @@ private IllegalArgumentException throwUnknownCommand(String command) {
if (previousFunc == null) {
previousFunc = function;
} else if (function.isResolved()){
previousFunc = ResolvedFunction.create(function.getType(), function.applyCached(null), functionContent);
previousFunc = ResolvedFunction.createConstant(function.getType(), function.applyCached(null), functionContent);
} else if (previousFunc.isResolved()) {
Object value = previousFunc.applyCached(null);
previousFunc = ResolvedFunction.create(function.getType(), function.applyCached(value), functionContent);
previousFunc = ResolvedFunction.createConstant(function.getType(), function.applyCached(value), functionContent);
} else {
previousFunc = TypedFunction.create(function.getType(), previousFunc.andThen(function), functionContent);
previousFunc = TypedFunction.createParent(function.getType(), previousFunc.andThen(function), functionContent, previousFunc);
}
}
return previousFunc;
Expand Down Expand Up @@ -757,9 +759,9 @@ private IllegalArgumentException throwUnknownCommand(String command) {
BiFunction<T, Object[], Object> format = (object, paramVals) -> command.call(object, store, paramVals);
if (isResolved) {
Object[] argArr = resolved.apply(null);
return TypedFunction.create(command.getReturnType(), f -> format.apply(f, argArr), "{" + full.toString() + "}");
return TypedFunction.createParents(command.getReturnType(), f -> format.apply(f, argArr), "{" + full.toString() + "}", null);
}
return TypedFunction.create(command.getReturnType(), f -> format.apply(f, resolved.apply(f)), "{" + full.toString() + "}");
return TypedFunction.createParents(command.getReturnType(), f -> format.apply(f, resolved.apply(f)), "{" + full.toString() + "}", null);
}

public abstract String getName(T o);
Expand Down Expand Up @@ -830,6 +832,25 @@ public TypedFunction<T, String> getFormatFunction(ValueStore store, String arg)
return getFormatFunction(store, arg, true);
}

@Binding(value = "Format text containing placeholders")
public TypedFunction<T, Double> getDoubleFunction(ValueStore store, String arg) {
TypedFunction<T, ?> result = this.formatRecursively(store, arg, null, 0, true);
Class type = (Class) result.getType();
if (type == boolean.class || type == Boolean.class) {
return TypedFunction.createParent(Double.class, t -> {
Object value = result.applyCached(t);
return value == null ? 0 : ((Boolean) value) ? 1d : 0d;
}, result.getName(), result);
} else if (type == byte.class || type == Byte.class || type == short.class || type == Short.class || type == int.class || type == Integer.class || type == long.class || type == Long.class || type == float.class || type == Float.class || type == double.class || type == Double.class || type == Number.class) {
return TypedFunction.createParent(Double.class, f -> {
Object value = result.applyCached((T) f);
return value == null ? 0 : ((Number) value).doubleValue();
}, result.getName(), result);
} else {
throw new IllegalArgumentException("Only the following filter types are supported: Number, Boolean, not: `" + ((Class<?>) type).getSimpleName() + "` | input: `" + result.getName() + "`");
}
}

public TypedFunction<T, String> getFormatFunction(ValueStore store, String arg, boolean throwError) {
return getFormatFunction(store, arg, null, throwError);
}
Expand All @@ -845,16 +866,16 @@ public TypedFunction<T, String> getFormatFunction(ValueStore store, String arg,
Object value = result.applyCached(null);
String valueStr = value == null ? null : value.toString();
if (startsWithEquals) valueStr = "=" + valueStr;
return TypedFunction.create(String.class, valueStr, result.getName());
return TypedFunction.createConstant(String.class, valueStr, result.getName());
} else {
return TypedFunction.create(String.class, f -> {
return TypedFunction.createParent(String.class, f -> {
Object value = result.applyCached((T) f);
String str = value == null ? null : value.toString();
if (startsWithEquals && str != null) {
str = "=" + value;
}
return str;
}, result.getName());
}, result.getName(), result);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package link.locutus.discord.commands.manager.v2.binding.bindings;

import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;

import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

Expand All @@ -18,10 +22,14 @@ public String toString() {
return getName();
}

public static <T, V> TypedFunction<T, V> create(Type type, V value, String name) {
public static <T, V> TypedFunction<T, V> createConstant(Type type, V value, String name) {
return new ResolvedFunction<>(type, value, name);
}

public void clearCache() {

}

public V applyCached(T t) {
if (isResolved()) {
return get(t);
Expand All @@ -32,8 +40,12 @@ public V applyCached(T t) {

public abstract V get(T t);

public static <T, V> TypedFunction<T, V> create(Type type, Function<T, V> function, String name) {
Map<T, V> resolved = new HashMap<>();
public static <T, V> TypedFunction<T, V> createParent(Type type, Function<T, V> function, String name, TypedFunction<T, ?> parent) {
return createParents(type, function, name, parent == null ? null : List.of(parent));
}

public static <T, V> TypedFunction<T, V> createParents(Type type, Function<T, V> function, String name, Collection<TypedFunction<T, ?>> parents) {
Map<T, V> resolved = new Object2ObjectOpenHashMap<>();
return new TypedFunction<T, V>() {
@Override
public Type getType() {
Expand All @@ -50,6 +62,16 @@ public V get(T t) {
return resolved.get(t);
}

@Override
public void clearCache() {
resolved.clear();
if (parents != null) {
for (TypedFunction parent : parents) {
parent.clearCache();
}
}
}

@Override
public V applyCached(T t) {
if (resolved.containsKey(t)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,6 @@ public Object call(Object instance, ArgumentStack stack) {

public Object call(Object instance, ValueStore store, Object[] paramVals) {
try {
System.out.println("Instance | " + instance + " | " + method.getDeclaringClass() + " | " + method.getDeclaringClass().isInstance(instance));
Object callOn = isStatic ? null : (!method.getDeclaringClass().isInstance(instance) ? this.object : instance);
return method.invoke(callOn, paramVals);
} catch (IllegalArgumentException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ public List<SlashCommandData> generateCommandData() {
toRegister.add(cmd);
} catch (Throwable e) {
// print command
System.out.println("Error: " + id + " | " + callable.getFullPath());
System.out.println("Slash command error: " + id + " | " + callable.getFullPath());
if (callable instanceof ParametricCallable parametric) {
// print method and class
System.out.println(parametric.getMethod().getName() + " | " + parametric.getMethod().getDeclaringClass());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,10 @@ public static Map<String, String> parseArguments(Set<String> params, String inpu
}

public CommandManager2 registerDefaults() {
getCommands().registerMethod(new AllianceMetricCommands(), List.of("admin", "sync"), "saveMetrics", "saveMetrics");
getCommands().registerMethod(new AllianceMetricCommands(), List.of("stats_tier"), "metricByGroup", "metric_by_group");
getCommands().registerMethod(new AllianceMetricCommands(), List.of("stats_other", "data_csv"), "AlliancesDataByDay", "AlliancesDataByDay");

getCommands().registerMethod(new PlayerSettingCommands(), List.of("alerts", "bank"), "bankAlertRequiredValue", "min_value");
getCommands().registerMethod(new AdminCommands(), List.of("admin", "sync"), "syncWarrooms", "warrooms");
getCommands().registerMethod(new AdminCommands(), List.of("admin", "queue"), "conditionalMessageSettings", "custom_messages");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
import link.locutus.discord.db.entities.grant.GrantTemplateManager;
import link.locutus.discord.db.entities.grant.TemplateTypes;
import link.locutus.discord.db.entities.metric.AllianceMetric;
import link.locutus.discord.db.entities.metric.AllianceMetricMode;
import link.locutus.discord.db.entities.newsletter.Newsletter;
import link.locutus.discord.db.entities.newsletter.NewsletterManager;
import link.locutus.discord.db.guild.GuildSetting;
Expand Down Expand Up @@ -1555,4 +1556,9 @@ public MessageTrigger trigger(String trigger) {
return emum(MessageTrigger.class, trigger);
}

@Binding
public AllianceMetricMode AllianceMetricMode(String mode) {
return emum(AllianceMetricMode.class, mode);
}

}
Loading

0 comments on commit 9df0cde

Please sign in to comment.