feat(core): add InteractionProcessors and InteractionExecutors and improve Autocomplete Interaction
All checks were successful
github-mirror / push-github (push) Successful in 1m45s
Build / Gradle-Build (push) Successful in 37s
Test / Gradle-Test (push) Successful in 46s

This commit is contained in:
2025-04-06 00:04:17 +02:00
parent ec17952375
commit 991d1c047b
34 changed files with 344 additions and 164 deletions

View File

@@ -2,10 +2,15 @@ package net.tomatentum.marinara;
import org.slf4j.Logger;
import net.tomatentum.marinara.interaction.InteractionType;
import net.tomatentum.marinara.interaction.processor.AutocompleteInteractionProcessor;
import net.tomatentum.marinara.interaction.processor.DirectInteractionProcessor;
import net.tomatentum.marinara.reflection.ReflectedMethodFactory;
import net.tomatentum.marinara.reflection.ReflectedMethodFactoryImpl;
import net.tomatentum.marinara.registry.InteractionCheckRegistry;
import net.tomatentum.marinara.registry.InteractionExecutor;
import net.tomatentum.marinara.registry.InteractionRegistry;
import net.tomatentum.marinara.registry.ProcessorInteractionExecutor;
import net.tomatentum.marinara.util.LoggerUtil;
import net.tomatentum.marinara.wrapper.LibraryWrapper;
@@ -13,7 +18,7 @@ public class Marinara {
private Logger logger = LoggerUtil.getLogger(getClass());
public static <T extends LibraryWrapper> Marinara load(LibraryWrapper wrapper) {
public static Marinara load(LibraryWrapper wrapper) {
return new Marinara(wrapper);
}
@@ -21,12 +26,17 @@ public class Marinara {
private ReflectedMethodFactory reflectedMethodFactory;
private InteractionRegistry registry;
private InteractionCheckRegistry checkRegistry;
private InteractionExecutor interactionExecutor;
private Marinara(LibraryWrapper wrapper) {
this.wrapper = wrapper;
this.reflectedMethodFactory = new ReflectedMethodFactoryImpl(this);
this.registry = new InteractionRegistry(this);
this.checkRegistry = new InteractionCheckRegistry();
this.interactionExecutor = new ProcessorInteractionExecutor(wrapper.createIdentifierProvider(), this)
.addProcessor(new DirectInteractionProcessor(InteractionType.COMMAND, InteractionType.BUTTON))
.addProcessor(new AutocompleteInteractionProcessor());
wrapper.subscribeInteractions(this.interactionExecutor::handle);
logger.info("Marinara loaded successfully!");
}
@@ -45,4 +55,9 @@ public class Marinara {
public ReflectedMethodFactory getReflectedMethodFactory() {
return this.reflectedMethodFactory;
}
public InteractionExecutor getInteractionExecutor() {
return interactionExecutor;
}
}

View File

@@ -5,6 +5,7 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import net.tomatentum.marinara.interaction.annotation.AutoComplete;
import net.tomatentum.marinara.interaction.commands.option.SlashCommandOptionType;
@Target({ElementType.ANNOTATION_TYPE})
@@ -14,11 +15,11 @@ public @interface SlashCommandOption {
public String description() default "";
public SlashCommandOptionType type() default SlashCommandOptionType.STRING;
public boolean required() default false;
public boolean autocomplete() default false;
public AutoComplete[] autocompletes() default {};
public Range range() default @Range;
public CommandChoices choices() default @CommandChoices;
public static enum PlaceHolderEnum {
public enum PlaceHolderEnum {
}
}

View File

@@ -0,0 +1,16 @@
package net.tomatentum.marinara.interaction.commands.option;
import java.util.Arrays;
import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOption;
public record AutocompleteOptionData(String name, Object input) {
public String[] getAutocompleteRefs(SlashCommandOption[] options) {
return Arrays.stream(options)
.filter(o -> o.name().equals(this.name()))
.flatMap(o -> Arrays.stream(o.autocompletes()))
.map(a -> a.value())
.toArray(String[]::new);
}
}

View File

@@ -73,7 +73,7 @@ public class InteractionIdentifier {
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof InteractionIdentifier))
if (!(obj instanceof InteractionIdentifier))
return false;
InteractionIdentifier ident = (InteractionIdentifier) obj;
if (!type().equals(ident.type()))
@@ -83,11 +83,16 @@ public class InteractionIdentifier {
return Objects.equals(parent(), ident.parent());
}
@Override
public int hashCode() {
return Objects.hash(type(), name(), parent());
}
@Override
public String toString() {
if (parent() == null)
return name();
return "{}.{}".formatted(name(), parent().toString());
return "%s.%s".formatted(name(), parent().toString());
}
public static class Builder {

View File

@@ -13,9 +13,8 @@ public class RootCommandIdentifier extends SlashCommandIdentifier {
String description,
InteractionType type,
SlashCommandOption[] options,
long[] serverIds,
String[] autocompleteRef) {
super(parent, name, description, type, options, autocompleteRef);
long[] serverIds) {
super(parent, name, description, type, options);
this.serverIds = serverIds;
}
@@ -92,8 +91,7 @@ public class RootCommandIdentifier extends SlashCommandIdentifier {
description,
InteractionType.COMMAND,
options,
serverIds,
autocompleteRef);
serverIds);
}
}

View File

@@ -6,33 +6,21 @@ import net.tomatentum.marinara.interaction.commands.annotation.SlashCommandOptio
public class SlashCommandIdentifier extends InteractionIdentifier {
private SlashCommandOption[] options;
private String[] autocompleteRef;
protected SlashCommandIdentifier(
InteractionIdentifier parent,
String name,
String description,
InteractionType type,
SlashCommandOption[] options,
String[] autocompleteRef
) {
SlashCommandOption[] options) {
super(parent, name, description, type);
this.options = options;
this.autocompleteRef = autocompleteRef;
}
public SlashCommandOption[] options() {
return this.options;
}
public String[] autocompleteRef() {
return this.autocompleteRef;
}
public SlashCommandIdentifier autocompleteRef(String[] autocompleteRef) {
this.autocompleteRef = autocompleteRef;
return this;
}
public static class Builder {
private InteractionIdentifier parent;
private String name;
@@ -91,8 +79,7 @@ public class SlashCommandIdentifier extends InteractionIdentifier {
name,
description,
InteractionType.COMMAND,
options,
autocompleteRef);
options);
}
}

View File

@@ -29,11 +29,15 @@ public class AutoCompleteInteractionMethod extends InteractionMethod {
@Override
public Object getParameter(Object context, int index) {
Class<?> type = method().getParameterTypes()[index+1];
Object autocompleteOptionValue = marinara.getWrapper().getContextObjectProvider().getAutocompleteFocusedOption(context);
if (autocompleteOptionValue != null)
Object contextObject = marinara.getWrapper().getContextObjectProvider().getInteractionContextObject(context, type);
if (contextObject != null)
return contextObject;
Object autocompleteOptionValue = marinara.getWrapper().getContextObjectProvider().getAutocompleteFocusedOption(context).input();
if (type.isInstance(autocompleteOptionValue))
return autocompleteOptionValue;
return marinara.getWrapper().getContextObjectProvider().getInteractionContextObject(context, type);
return null;
}
@Override
@@ -50,11 +54,11 @@ public class AutoCompleteInteractionMethod extends InteractionMethod {
@Override
public Optional<ReflectedMethod> produce(Marinara marinara, Method method, Object containingObject) {
ReflectedMethod rMethod = null;
if ((containingObject instanceof InteractionHandler) &&
if ((containingObject instanceof InteractionHandler iHandler) &&
method.isAnnotationPresent(AutoComplete.class) &&
!(method.isAnnotationPresent(SlashCommand.class) ||
method.isAnnotationPresent(SubCommand.class)))
rMethod = new AutoCompleteInteractionMethod(method, (InteractionHandler) containingObject, marinara);
rMethod = new AutoCompleteInteractionMethod(method, iHandler, marinara);
return Optional.ofNullable(rMethod);
}
@@ -63,9 +67,8 @@ public class AutoCompleteInteractionMethod extends InteractionMethod {
public void addParser(ReflectedMethod method, List<AnnotationParser> parser) {
super.addParser(method, parser);
AutoCompleteInteractionMethod imethod = (AutoCompleteInteractionMethod) method;
parser.add(
new AutocompleteParser(method.method(), x -> imethod.autocompleteRef = x[0])
new AutocompleteParser(method.method(), x -> ((AutoCompleteInteractionMethod) method).autocompleteRef = x[0])
);
}

View File

@@ -51,7 +51,7 @@ public abstract class InteractionMethod extends ReflectedMethod {
return this.appliedChecks;
}
public static abstract class Factory implements ReflectedMethodFactory.Factory {
public abstract static class Factory implements ReflectedMethodFactory.Factory {
@Override
public void addParser(ReflectedMethod method, List<AnnotationParser> parser) {

View File

@@ -11,7 +11,6 @@ import net.tomatentum.marinara.interaction.commands.annotation.SubCommand;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.interaction.ident.SlashCommandIdentifier;
import net.tomatentum.marinara.parser.AnnotationParser;
import net.tomatentum.marinara.parser.AutocompleteParser;
import net.tomatentum.marinara.parser.SlashCommandParser;
import net.tomatentum.marinara.reflection.ReflectedMethod;
@@ -38,10 +37,10 @@ public class SlashCommandInteractionMethod extends InteractionMethod {
@Override
public Optional<ReflectedMethod> produce(Marinara marinara, Method method, Object containingObject) {
ReflectedMethod rMethod = null;
if ((containingObject instanceof InteractionHandler) &&
if ((containingObject instanceof InteractionHandler iHandler) &&
(method.isAnnotationPresent(SlashCommand.class) ||
method.isAnnotationPresent(SubCommand.class)))
rMethod = new SlashCommandInteractionMethod(method, (InteractionHandler) containingObject, marinara);
rMethod = new SlashCommandInteractionMethod(method, iHandler, marinara);
return Optional.ofNullable(rMethod);
}
@@ -49,12 +48,8 @@ public class SlashCommandInteractionMethod extends InteractionMethod {
public void addParser(ReflectedMethod method, List<AnnotationParser> parser) {
super.addParser(method, parser);
SlashCommandInteractionMethod imethod = (SlashCommandInteractionMethod) method;
parser.add(
new SlashCommandParser(method.method(), x -> imethod.interactionIdentifier = x)
);
parser.add(
new AutocompleteParser(method.method(), x -> imethod.interactionIdentifier.autocompleteRef(x))
new SlashCommandParser(method.method(), x -> ((SlashCommandInteractionMethod) method).interactionIdentifier = x)
);
}

View File

@@ -0,0 +1,46 @@
package net.tomatentum.marinara.interaction.processor;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import net.tomatentum.marinara.Marinara;
import net.tomatentum.marinara.interaction.InteractionType;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.interaction.ident.SlashCommandIdentifier;
import net.tomatentum.marinara.registry.InteractionEntry;
public class AutocompleteInteractionProcessor implements InteractionProcessor {
@Override
public void process(Object context, InteractionIdentifier identifier, Marinara marinara) {
if (!identifier.type().equals(InteractionType.AUTOCOMPLETE))
return;
Optional<InteractionEntry> entry = marinara.getRegistry().findFor(convertToCommandIdentifier(identifier));
if (entry.isPresent() && entry.get().identifier() instanceof SlashCommandIdentifier sIdent) {
List<String> autocompleteRefs = Arrays.asList(marinara.getWrapper().getContextObjectProvider()
.getAutocompleteFocusedOption(context).getAutocompleteRefs(sIdent.options()));
List<Object> results = marinara.getRegistry().interactions().stream()
.filter(e -> e.type().equals(InteractionType.AUTOCOMPLETE))
.filter(e -> autocompleteRefs.contains(e.identifier().name()))
.map(e -> e.runAll(context))
.flatMap(Arrays::stream)
.filter(Objects::nonNull)
.toList();
if (!results.isEmpty())
marinara.getWrapper().respondAutocomplete(context, results);
}
}
private InteractionIdentifier convertToCommandIdentifier(InteractionIdentifier identifier) {
if (Objects.isNull(identifier))
return null;
return InteractionIdentifier.builder()
.type(InteractionType.COMMAND)
.name(identifier.name())
.parent(convertToCommandIdentifier(identifier.parent()))
.build();
}
}

View File

@@ -0,0 +1,32 @@
package net.tomatentum.marinara.interaction.processor;
import java.util.Set;
import org.slf4j.Logger;
import net.tomatentum.marinara.Marinara;
import net.tomatentum.marinara.interaction.InteractionType;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.util.LoggerUtil;
public class DirectInteractionProcessor implements InteractionProcessor {
private Logger logger = LoggerUtil.getLogger(getClass());
private Set<InteractionType> types;
public DirectInteractionProcessor(InteractionType... types) {
this.types = Set.of(types);
}
@Override
public void process(Object context, InteractionIdentifier identifier, Marinara marinara) {
if (!types.contains(identifier.type()))
return;
logger.debug("Processing {} : {} with context {}", identifier, identifier.type(), context);
marinara.getRegistry().interactions().stream()
.filter(e -> e.identifier().equals(identifier))
.findFirst()
.ifPresent(e -> e.runAll(context));
}
}

View File

@@ -0,0 +1,10 @@
package net.tomatentum.marinara.interaction.processor;
import net.tomatentum.marinara.Marinara;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
public interface InteractionProcessor {
void process(Object context, InteractionIdentifier identifier, Marinara marinara);
}

View File

@@ -1,8 +1,10 @@
package net.tomatentum.marinara.registry;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
import org.slf4j.Logger;
@@ -34,22 +36,25 @@ public class InteractionEntry {
}
public InteractionEntry addMethod(InteractionMethod method) {
InteractionIdentifier identifier = method.identifier();
InteractionIdentifier midentifier = method.identifier();
if (!this.identifier().equals(identifier))
if (!this.identifier().equals(midentifier))
throw new IllegalArgumentException("Method's identifier did not equal the entry's identifier");
this.methods.add(method);
InteractionIdentifier.tryAddDescriptions(identifier, identifier);
InteractionIdentifier.tryAddDescriptions(midentifier, midentifier);
logger.debug("Added method {} to entry {}", method.method().getName(), this.identifier);
return this;
}
public void runAll(Object context) {
this.methods.stream().forEach(x -> {
logger.debug("Running Method {} from {} with context {}", x.toString(), this.toString(), context.toString());
x.run(context);
});
public Object[] runAll(Object context) {
return this.methods.stream()
.map(x -> {
logger.debug("Running Method {} from {} with context {}", x, this, context);
return x.run(context);
})
.flatMap(o -> o instanceof Object[] oArray ? Arrays.stream(oArray) : Stream.<Object>of(o))
.toArray();
}
@Override
@@ -60,6 +65,11 @@ public class InteractionEntry {
return other.identifier().equals(identifier());
}
@Override
public int hashCode() {
return this.identifier().hashCode();
}
@Override
public String toString() {
return "InteractionEntry(%s)".formatted(identifier().toString());

View File

@@ -0,0 +1,7 @@
package net.tomatentum.marinara.registry;
public interface InteractionExecutor {
void handle(Object context);
}

View File

@@ -18,7 +18,6 @@ import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.interaction.ident.RootCommandIdentifier;
import net.tomatentum.marinara.util.LoggerUtil;
import net.tomatentum.marinara.util.ObjectAggregator;
import net.tomatentum.marinara.wrapper.IdentifierProvider;
import net.tomatentum.marinara.interaction.methods.AutoCompleteInteractionMethod;
import net.tomatentum.marinara.interaction.methods.InteractionMethod;
import net.tomatentum.marinara.interaction.methods.SlashCommandInteractionMethod;
@@ -28,13 +27,10 @@ public class InteractionRegistry {
private Logger logger = LoggerUtil.getLogger(getClass());
private Set<InteractionEntry> interactions;
private Marinara marinara;
private IdentifierProvider identifierProvider;
public InteractionRegistry(Marinara marinara) {
this.interactions = new HashSet<>();
this.marinara = marinara;
this.identifierProvider = marinara.getWrapper().createIdentifierProvider();
marinara.getWrapper().subscribeInteractions(this::handle);
marinara.getReflectedMethodFactory()
.addFactory(new AutoCompleteInteractionMethod.Factory())
.addFactory(new SlashCommandInteractionMethod.Factory())
@@ -72,19 +68,13 @@ public class InteractionRegistry {
marinara.getWrapper().getRegisterer().register(defs);
}
public void handle(Object context) {
logger.debug("Received {} interaction ", context);
interactions.forEach((e) -> {
if (e.identifier().equals(this.identifierProvider.provide(context, this))) {
logger.info("Running {} interaction using {}\ncontext: {}", e.type(), e.toString(), context.toString());
e.runAll(context);
}
});
}
public Optional<InteractionEntry> findFor(InteractionIdentifier identifier) {
return this.interactions.stream()
.filter(x -> x.identifier().equals(identifier))
.findFirst();
}
public Set<InteractionEntry> interactions() {
return this.interactions;
}
}

View File

@@ -0,0 +1,41 @@
package net.tomatentum.marinara.registry;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import net.tomatentum.marinara.Marinara;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.interaction.processor.InteractionProcessor;
import net.tomatentum.marinara.util.LoggerUtil;
import net.tomatentum.marinara.wrapper.IdentifierProvider;
public class ProcessorInteractionExecutor implements InteractionExecutor {
private Logger logger = LoggerUtil.getLogger(getClass());
private Set<InteractionProcessor> processors;
private IdentifierProvider identifierProvider;
private Marinara marinara;
public ProcessorInteractionExecutor(IdentifierProvider identifierProvider, Marinara marinara) {
this.processors = new HashSet<>();
this.identifierProvider = identifierProvider;
this.marinara = marinara;
}
public ProcessorInteractionExecutor addProcessor(InteractionProcessor processor) {
this.processors.add(processor);
return this;
}
@Override
public void handle(Object context) {
logger.debug("Received {} interaction ", context);
InteractionIdentifier identifier = this.identifierProvider.provide(context);
logger.debug("Processing {} : {} interaction ", identifier, identifier.type());
processors.forEach(x -> x.process(context, identifier, this.marinara));
}
}

View File

@@ -1,5 +1,7 @@
package net.tomatentum.marinara.wrapper;
import net.tomatentum.marinara.interaction.commands.option.AutocompleteOptionData;
public interface ContextObjectProvider {
public Object convertCommandOption(Object context, String optionName);
@@ -7,5 +9,5 @@ public interface ContextObjectProvider {
public Object getComponentContextObject(Object context, Class<?> type);
public Object getInteractionContextObject(Object context, Class<?> type);
public Object getAutocompleteFocusedOption(Object context);
public AutocompleteOptionData getAutocompleteFocusedOption(Object context);
}

View File

@@ -11,7 +11,6 @@ import org.slf4j.Logger;
import io.leangen.geantyref.GenericTypeReflector;
import net.tomatentum.marinara.interaction.ident.InteractionIdentifier;
import net.tomatentum.marinara.registry.InteractionRegistry;
import net.tomatentum.marinara.util.LoggerUtil;
import net.tomatentum.marinara.util.ReflectionUtil;
@@ -30,30 +29,30 @@ public class IdentifierProvider {
if (conv.getClass().getName().contains("$$Lambda"))
throw new IllegalArgumentException("Lambdas cannot be used for IdentifierConverter because of Type erasure.");
Type type = GenericTypeReflector.getExactSuperType(conv.getClass(), Converter.class);
Type parameterType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
Type parameterType = ((ParameterizedType) type).getActualTypeArguments()[0];
if (!(parameterType instanceof Class))
throw new IllegalArgumentException("Only full Class types are supported by IdentiferConverters");
this.converter.put((Class<?>) parameterType, conv);
}
}
public InteractionIdentifier provide(Object context, InteractionRegistry registry) {
public InteractionIdentifier provide(Object context) {
Type type = ReflectionUtil.getMostSpecificClass(
converter.keySet().stream().filter(x -> x.isAssignableFrom(context.getClass())).toArray(Class<?>[]::new),
context.getClass());
if (type == null)
logger.debug("No Identifier converter found for context {}", context.getClass().toString());
logger.debug("No Identifier converter found for context {}", context.getClass());
@SuppressWarnings("unchecked")
Converter<Object> conv = (Converter<Object>) converter.get(type);
return conv.convert(context, registry);
return conv.convert(context);
}
@FunctionalInterface
public interface Converter<T extends Object> {
InteractionIdentifier convert(T context, InteractionRegistry registry);
InteractionIdentifier convert(T context);
}
public static class LambdaWrapper<T extends Object> implements Converter<T> {
@@ -65,8 +64,8 @@ public class IdentifierProvider {
}
@Override
public InteractionIdentifier convert(T context, InteractionRegistry registry) {
return this.converter.convert(context, registry);
public InteractionIdentifier convert(T context) {
return this.converter.convert(context);
}
}

View File

@@ -12,7 +12,7 @@ public abstract class LibraryWrapper {
}
public void handleInteraction(Object context) {
interactionSubscriber.forEach((o) -> o.accept(context));
interactionSubscriber.forEach(o -> o.accept(context));
}
public void subscribeInteractions(Consumer<Object> consumer) {
@@ -25,5 +25,6 @@ public abstract class LibraryWrapper {
public abstract CommandRegisterer<?> getRegisterer();
public abstract IdentifierProvider createIdentifierProvider();
public abstract ContextObjectProvider getContextObjectProvider();
public abstract void respondAutocomplete(Object context, List<Object> options);
}