Skip to content

Commit

Permalink
rename ParameterDefinition to OptionDataDefinition and fix bug in Con…
Browse files Browse the repository at this point in the history
…straintMiddleware
  • Loading branch information
Kaktushose committed Jan 5, 2025
1 parent df9794e commit 177c4e3
Show file tree
Hide file tree
Showing 12 changed files with 58 additions and 67 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
import com.github.kaktushose.jda.commands.definitions.features.internal.Invokable;
import com.github.kaktushose.jda.commands.definitions.interactions.InteractionDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.ModalDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.command.ParameterDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.command.OptionDataDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.command.SlashCommandDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.component.menu.StringSelectMenuDefinition;
import org.jetbrains.annotations.NotNull;

/// The common interface for all interaction definitions and their sub parts, such as parameters or text inputs, etc.
public sealed interface Definition permits CustomIdJDAEntity, Invokable, JDAEntity, InteractionDefinition,
ModalDefinition.TextInputDefinition, ParameterDefinition, ParameterDefinition.ConstraintDefinition,
ModalDefinition.TextInputDefinition, OptionDataDefinition, OptionDataDefinition.ConstraintDefinition,
SlashCommandDefinition.CooldownDefinition, StringSelectMenuDefinition.SelectOptionDefinition {

/// The id for this definition. Per default this is the hash code of the [#toString()] method.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import com.github.kaktushose.jda.commands.definitions.interactions.ModalDefinition.TextInputDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.command.CommandDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.command.ContextCommandDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.command.ParameterDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.command.OptionDataDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.command.SlashCommandDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.component.ButtonDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.component.ComponentDefinition;
Expand All @@ -20,11 +20,11 @@
/// @see StringSelectMenuDefinition
/// @see SlashCommandDefinition
/// @see ContextCommandDefinition
/// @see ParameterDefinition
/// @see OptionDataDefinition
/// @see SelectOptionDefinition
/// @see TextInputDefinition
public sealed interface JDAEntity<T> extends Definition
permits ComponentDefinition, TextInputDefinition, CommandDefinition, ParameterDefinition, SelectOptionDefinition {
permits ComponentDefinition, TextInputDefinition, CommandDefinition, OptionDataDefinition, SelectOptionDefinition {

/// Transforms this [Definition] into a JDA entity of the given type [T].
///
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import com.github.kaktushose.jda.commands.definitions.description.ParameterDescription;
import com.github.kaktushose.jda.commands.definitions.features.CustomIdJDAEntity;
import com.github.kaktushose.jda.commands.definitions.features.JDAEntity;
import com.github.kaktushose.jda.commands.definitions.interactions.command.ParameterDefinition;
import com.github.kaktushose.jda.commands.dispatching.events.interactions.ModalEvent;
import com.github.kaktushose.jda.commands.internal.Helpers;
import net.dv8tion.jda.api.interactions.components.text.TextInput;
Expand Down Expand Up @@ -108,9 +107,9 @@ public record TextInputDefinition(
boolean required
) implements JDAEntity<TextInput>, Definition {

/// Builds a new [TextInputDefinition] from the given [ParameterDefinition]
/// Builds a new [TextInputDefinition] from the given [ParameterDescription]
///
/// @param parameter the [ParameterDefinition] to build the [TextInputDefinition] from
/// @param parameter the [ParameterDescription] to build the [TextInputDefinition] from
/// @return the new [TextInputDefinition]
public static Optional<TextInputDefinition> build(ParameterDescription parameter) {
var optional = parameter.annotation(com.github.kaktushose.jda.commands.annotations.interactions.TextInput.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
/// @param description the description of the parameter
/// @param choices a [SequencedCollection] of possible [Command.Choice]s for this parameter
/// @param constraints a [Collection] of [ConstraintDefinition]s of this parameter
public record ParameterDefinition(
public record OptionDataDefinition(
@NotNull Class<?> type,
boolean optional,
boolean autoComplete,
Expand Down Expand Up @@ -103,16 +103,16 @@ public record ParameterDefinition(
))
);

/// Builds a new [ParameterDefinition].
/// Builds a new [OptionDataDefinition].
///
/// @param parameter the [ParameterDescription] to build the [ParameterDefinition] from
/// @param parameter the [ParameterDescription] to build the [OptionDataDefinition] from
/// @param autoComplete whether the [ParameterDescription] should support autocomplete
/// @param validatorRegistry the corresponding [ValidatorRegistry]
/// @return the [ParameterDefinition]
/// @return the [OptionDataDefinition]
@NotNull
public static ParameterDefinition build(ParameterDescription parameter,
boolean autoComplete,
@NotNull ValidatorRegistry validatorRegistry) {
public static OptionDataDefinition build(ParameterDescription parameter,
boolean autoComplete,
@NotNull ValidatorRegistry validatorRegistry) {
final var parameterType = TYPE_MAPPINGS.getOrDefault(parameter.type(), parameter.type());

var optional = parameter.annotation(com.github.kaktushose.jda.commands.annotations.interactions.Optional.class);
Expand Down Expand Up @@ -159,7 +159,7 @@ public static ParameterDefinition build(ParameterDescription parameter,
commandChoices.add(new Command.Choice(parsed[0], parsed[1]));
}
}
return new ParameterDefinition(
return new OptionDataDefinition(
parameterType,
optional.isPresent(),
autoComplete,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
/// @param enabledPermissions a possibly-empty [Set] of [Permission]s this command will be enabled for
/// @param localizationFunction the [LocalizationFunction] to use for this command
/// @param description the command description
/// @param commandParameters a [SequencedCollection] of [ParameterDefinition]s
/// @param commandOptions a [SequencedCollection] of [OptionDataDefinition]s
/// @param cooldown the corresponding [CooldownDefinition]
/// @param isAutoComplete whether this command supports auto complete
public record SlashCommandDefinition(
Expand All @@ -50,7 +50,7 @@ public record SlashCommandDefinition(
@NotNull Set<Permission> enabledPermissions,
@NotNull LocalizationFunction localizationFunction,
@NotNull String description,
@NotNull SequencedCollection<ParameterDefinition> commandParameters,
@NotNull SequencedCollection<OptionDataDefinition> commandOptions,
@NotNull CooldownDefinition cooldown,
boolean isAutoComplete
) implements CommandDefinition {
Expand Down Expand Up @@ -78,10 +78,10 @@ public static Optional<SlashCommandDefinition> build(MethodBuildContext context)
.flatMap(Collection::stream)
.anyMatch(name::startsWith);

// build parameter definitions
List<ParameterDefinition> parameters = method.parameters().stream()
// build option data definitions
List<OptionDataDefinition> commandOptions = method.parameters().stream()
.filter(it -> !(CommandEvent.class.isAssignableFrom(it.type())))
.map(parameter -> ParameterDefinition.build(parameter, autoComplete, context.validatorRegistry()))
.map(parameter -> OptionDataDefinition.build(parameter, autoComplete, context.validatorRegistry()))
.toList();

Set<Permission> enabledFor = Set.of(command.enabledFor());
Expand All @@ -91,7 +91,7 @@ public static Optional<SlashCommandDefinition> build(MethodBuildContext context)

List<Class<?>> signature = new ArrayList<>();
signature.add(CommandEvent.class);
parameters.forEach(it -> signature.add(it.type()));
commandOptions.forEach(it -> signature.add(it.type()));
if (Helpers.checkSignature(method, signature)) {
return Optional.empty();
}
Expand All @@ -112,7 +112,7 @@ public static Optional<SlashCommandDefinition> build(MethodBuildContext context)
enabledFor,
context.localizationFunction(),
command.desc(),
parameters,
commandOptions,
cooldownDefinition,
autoComplete
));
Expand All @@ -132,7 +132,7 @@ public SlashCommandData toJDAEntity() {
.setNSFW(nsfw)
.setLocalizationFunction(localizationFunction)
.setDefaultPermissions(DefaultMemberPermissions.enabledFor(enabledPermissions));
commandParameters.forEach(parameter -> {
commandOptions.forEach(parameter -> {
if (CommandEvent.class.isAssignableFrom(parameter.type())) {
return;
}
Expand All @@ -150,7 +150,7 @@ public SubcommandData toSubCommandData(String label) {
description.replaceAll("N/A", "no description")

);
commandParameters.forEach(parameter -> {
commandOptions.forEach(parameter -> {
command.addOptions(parameter.toJDAEntity());
});
return command;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,11 @@
import com.github.kaktushose.jda.commands.embeds.error.ErrorMessageFactory;
import com.github.kaktushose.jda.commands.internal.Helpers;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.*;

@ApiStatus.Internal
public final class SlashCommandHandler extends EventHandler<SlashCommandInteractionEvent> {
Expand All @@ -40,8 +38,10 @@ protected InvocationContext<SlashCommandInteractionEvent> prepare(@NotNull Slash
}

private Optional<List<Object>> parseArguments(SlashCommandDefinition command, SlashCommandInteractionEvent event, Runtime runtime) {
var input = command.commandParameters().stream()
.map(it -> event.getOption(it.name()).getAsString())
var input = command.commandOptions().stream()
.map(it -> event.getOption(it.name()))
.filter(Objects::nonNull)
.map(OptionMapping::getAsString)
.toArray(String[]::new);

List<Object> arguments = new ArrayList<>();
Expand All @@ -50,7 +50,7 @@ private Optional<List<Object>> parseArguments(SlashCommandDefinition command, Sl
ErrorMessageFactory messageFactory = implementationRegistry.getErrorMessageFactory();

log.debug("Type adapting arguments...");
var parameters = List.copyOf(command.commandParameters());
var parameters = List.copyOf(command.commandOptions());
for (int i = 0; i < parameters.size(); i++) {
var parameter = parameters.get(i);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package com.github.kaktushose.jda.commands.dispatching.middleware.impl;

import com.github.kaktushose.jda.commands.definitions.interactions.command.ParameterDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.command.SlashCommandDefinition;
import com.github.kaktushose.jda.commands.dispatching.ImplementationRegistry;
import com.github.kaktushose.jda.commands.dispatching.context.InvocationContext;
import com.github.kaktushose.jda.commands.dispatching.events.Event;
import com.github.kaktushose.jda.commands.dispatching.middleware.Middleware;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
Expand All @@ -12,8 +12,7 @@
import java.util.ArrayList;
import java.util.List;

/// A [Middleware] implementation that will check the parameter constraints a
/// [SlashCommandDefinition] might have.
/// A [Middleware] implementation that will check the parameter constraints a [SlashCommandDefinition] might have.
///
/// @see com.github.kaktushose.jda.commands.dispatching.validation.ValidatorRegistry ValidatorRegistry
public class ConstraintMiddleware implements Middleware {
Expand All @@ -32,27 +31,20 @@ public ConstraintMiddleware(ImplementationRegistry implementationRegistry) {
/// @param context the [InvocationContext] to filter
@Override
public void accept(@NotNull InvocationContext<?> context) {
if (!(context.definition() instanceof SlashCommandDefinition command))
return;
if (!(context.definition() instanceof SlashCommandDefinition command)) return;

var arguments = new ArrayList<>(context.arguments());
List<ParameterDefinition> parameters = List.copyOf(command.commandParameters());
arguments.removeIf(Event.class::isInstance);
var commandOptions = List.copyOf(command.commandOptions());

log.debug("Applying parameter constraints...");
for (int i = 1; i < arguments.size(); i++) {
Object argument = arguments.get(i);
ParameterDefinition parameter = parameters.get(i);
for (ParameterDefinition.ConstraintDefinition constraint : parameter.constraints()) {
log.debug("Found constraint {} for parameter {}", constraint, parameter.type().getName());

boolean validated = constraint.validator().apply(argument, constraint.annotation(), context);

if (!validated) {
context.cancel(
implementationRegistry
.getErrorMessageFactory()
.getConstraintFailedMessage(context, constraint)
);
for (int i = 0; i < arguments.size(); i++) {
var argument = arguments.get(i);
var optionData = commandOptions.get(i);
for (var constraint : optionData.constraints()) {
log.debug("Found constraint {} for parameter {}", constraint, optionData.type().getName());
if (!constraint.validator().apply(argument, constraint.annotation(), context)) {
context.cancel(implementationRegistry.getErrorMessageFactory().getConstraintFailedMessage(context, constraint));
log.debug("Constraint failed!");
return;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.github.kaktushose.jda.commands.embeds.error;

import com.github.kaktushose.jda.commands.definitions.interactions.command.ParameterDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.command.OptionDataDefinition.ConstraintDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.command.SlashCommandDefinition;
import com.github.kaktushose.jda.commands.dispatching.events.interactions.CommandEvent;
import net.dv8tion.jda.api.EmbedBuilder;
Expand All @@ -26,7 +26,7 @@ public MessageCreateData getTypeAdaptingFailedMessage(@NotNull ErrorContext cont
StringBuilder sbExpected = new StringBuilder();
SlashCommandDefinition command = (SlashCommandDefinition) context.definition();

command.commandParameters().forEach(parameter -> {
command.commandOptions().forEach(parameter -> {
if (CommandEvent.class.isAssignableFrom(parameter.type())) {
return;
}
Expand Down Expand Up @@ -72,7 +72,7 @@ public MessageCreateData getInsufficientPermissionsMessage(@NotNull ErrorContext

@NotNull
@Override
public MessageCreateData getConstraintFailedMessage(@NotNull ErrorContext context, @NotNull ParameterDefinition.ConstraintDefinition constraint) {
public MessageCreateData getConstraintFailedMessage(@NotNull ErrorContext context, @NotNull ConstraintDefinition constraint) {
return new MessageCreateBuilder().setEmbeds(new EmbedBuilder()
.setColor(Color.ORANGE)
.setTitle("Parameter Error")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import com.github.kaktushose.jda.commands.annotations.Implementation;
import com.github.kaktushose.jda.commands.definitions.interactions.InteractionDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.command.ParameterDefinition.ConstraintDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.command.OptionDataDefinition.ConstraintDefinition;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.interaction.GenericInteractionCreateEvent;
import net.dv8tion.jda.api.utils.messages.MessageCreateData;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.github.kaktushose.jda.commands.embeds.error;

import com.github.kaktushose.jda.commands.definitions.interactions.command.ParameterDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.command.OptionDataDefinition.ConstraintDefinition;
import com.github.kaktushose.jda.commands.definitions.interactions.command.SlashCommandDefinition;
import com.github.kaktushose.jda.commands.dispatching.events.interactions.CommandEvent;
import com.github.kaktushose.jda.commands.embeds.EmbedCache;
Expand Down Expand Up @@ -34,7 +34,7 @@ public MessageCreateData getTypeAdaptingFailedMessage(@NotNull ErrorContext cont
StringBuilder sbExpected = new StringBuilder();
SlashCommandDefinition command = (SlashCommandDefinition) context.definition();

command.commandParameters().forEach(parameter -> {
command.commandOptions().forEach(parameter -> {
if (CommandEvent.class.isAssignableFrom(parameter.type())) {
return;
}
Expand Down Expand Up @@ -76,7 +76,7 @@ public MessageCreateData getInsufficientPermissionsMessage(@NotNull ErrorContext

@NotNull
@Override
public MessageCreateData getConstraintFailedMessage(@NotNull ErrorContext context, @NotNull ParameterDefinition.ConstraintDefinition constraint) {
public MessageCreateData getConstraintFailedMessage(@NotNull ErrorContext context, @NotNull ConstraintDefinition constraint) {
if (!embedCache.containsEmbed("constraintFailed")) {
return super.getConstraintFailedMessage(context, constraint);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import java.lang.reflect.Method;
import java.util.*;

import static com.github.kaktushose.jda.commands.definitions.interactions.command.ParameterDefinition.TYPE_MAPPINGS;
import static com.github.kaktushose.jda.commands.definitions.interactions.command.OptionDataDefinition.TYPE_MAPPINGS;

/// Collection of helper methods that are used inside the framework.
@ApiStatus.Internal
Expand Down
Loading

0 comments on commit 177c4e3

Please sign in to comment.