Search in sources :

Example 1 with Preset

use of net.robinfriedli.aiode.entities.Preset in project aiode by robinfriedli.

the class GuildPropertyInterceptor method updatePresets.

private void updatePresets(AbstractGuildProperty argumentPrefixProperty, Character oldArgumentPrefix, char newArgumentPrefix, Session session) {
    List<Preset> presets = queryBuilderFactory.find(Preset.class).build(session).getResultList();
    String defaultValue = argumentPrefixProperty.getDefaultValue();
    char[] chars = defaultValue.toCharArray();
    char defaultArgPrefix;
    if (chars.length == 1) {
        defaultArgPrefix = chars[0];
    } else {
        defaultArgPrefix = ArgumentPrefixProperty.DEFAULT_FALLBACK;
    }
    char argPrefix = oldArgumentPrefix != null ? oldArgumentPrefix : defaultArgPrefix;
    ArgumentPrefixProperty.Config argumentPrefixConfig = new ArgumentPrefixProperty.Config(argPrefix, defaultArgPrefix);
    for (Preset preset : presets) {
        Aiode aiode = Aiode.get();
        AbstractCommand command = preset.instantiateCommand(aiode.getCommandManager(), commandContext, preset.getName());
        String oldPreset = preset.getPreset();
        StringBuilder newPresetBuilder = new StringBuilder(oldPreset);
        List<Integer> oldPrefixOccurrences = Lists.newArrayList();
        CommandParser commandParser = new CommandParser(command, argumentPrefixConfig, new CommandParseListener() {

            @Override
            public void onModeSwitch(CommandParser.Mode previousMode, CommandParser.Mode newMode, int index, char character) {
                // they are in fact argument prefixes
                if (newMode instanceof ArgumentBuildingMode) {
                    oldPrefixOccurrences.add(index);
                }
            }
        });
        commandParser.parse(oldPreset);
        for (int oldPrefixOccurrence : oldPrefixOccurrences) {
            newPresetBuilder.setCharAt(oldPrefixOccurrence, newArgumentPrefix);
        }
        String newPreset = newPresetBuilder.toString();
        if (!oldPreset.equals(newPreset)) {
            preset.setPreset(newPreset);
        }
    }
}
Also used : Preset(net.robinfriedli.aiode.entities.Preset) ArgumentPrefixProperty(net.robinfriedli.aiode.discord.property.properties.ArgumentPrefixProperty) AbstractCommand(net.robinfriedli.aiode.command.AbstractCommand) ArgumentBuildingMode(net.robinfriedli.aiode.command.parser.ArgumentBuildingMode) Aiode(net.robinfriedli.aiode.Aiode) CommandParser(net.robinfriedli.aiode.command.parser.CommandParser) CommandParseListener(net.robinfriedli.aiode.command.parser.CommandParseListener)

Example 2 with Preset

use of net.robinfriedli.aiode.entities.Preset in project aiode by robinfriedli.

the class PresetCommand method doRun.

@Override
public void doRun() {
    Session session = getContext().getSession();
    if (argumentSet("delete")) {
        Preset preset = SearchEngine.searchPreset(session, getCommandInput());
        if (preset == null) {
            throw new InvalidCommandException(String.format("No preset found for '%s'", getCommandInput()));
        }
        invoke(() -> session.delete(preset));
    } else if (getCommandInput().isBlank()) {
        List<Preset> presets = getQueryBuilderFactory().find(Preset.class).build(session).getResultList();
        EmbedBuilder embedBuilder = new EmbedBuilder();
        if (presets.isEmpty()) {
            embedBuilder.setDescription("No presets saved");
        } else {
            EmbedTable table = new EmbedTable(embedBuilder);
            table.addColumn("Name", presets, Preset::getName);
            table.addColumn("Preset", presets, Preset::getPreset);
            table.build();
        }
        sendMessage(embedBuilder);
    } else {
        String presetString = getCommandInput();
        String name = getArgumentValue("as");
        Preset existingPreset = SearchEngine.searchPreset(getContext().getSession(), name);
        if (existingPreset != null) {
            throw new InvalidCommandException("Preset " + name + " already exists");
        }
        Preset preset = new Preset(name, presetString, getContext().getGuild(), getContext().getUser());
        String testString = presetString.contains("%s") ? name + " test" : name;
        AbstractCommand abstractCommand = preset.instantiateCommand(getManager(), getContext(), testString);
        CommandParser commandParser = new CommandParser(abstractCommand, ArgumentPrefixProperty.getForCurrentContext());
        commandParser.parse();
        abstractCommand.verify();
        invoke(() -> session.persist(preset));
    }
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) Preset(net.robinfriedli.aiode.entities.Preset) AbstractCommand(net.robinfriedli.aiode.command.AbstractCommand) List(java.util.List) EmbedTable(net.robinfriedli.aiode.util.EmbedTable) Session(org.hibernate.Session) CommandParser(net.robinfriedli.aiode.command.parser.CommandParser)

Example 3 with Preset

use of net.robinfriedli.aiode.entities.Preset in project aiode by robinfriedli.

the class CommandManager method instantiateCommandForContext.

public Optional<AbstractCommand> instantiateCommandForContext(CommandContext context, Session session, boolean includeScripts) {
    String commandBody = context.getCommandBody();
    if (commandBody.isBlank()) {
        return Optional.empty();
    }
    String formattedCommandInput = commandBody.toLowerCase();
    CommandContribution commandContribution = getCommandContributionForInput(commandBody);
    AbstractCommand commandInstance;
    // find a preset where the preset name matches the beginning of the command, find the longest matching preset name
    // corresponds to lower(name) = substring(lower('" + commandBody.replaceAll("'", "''") + "'), 0, length(name) + 1)
    Optional<Preset> optionalPreset = queryBuilderFactory.find(Preset.class).where((cb, root) -> cb.equal(cb.lower(root.get("name")), cb.substring(cb.literal(formattedCommandInput), cb.literal(1), cb.length(root.get("name"))))).orderBy((root, cb) -> cb.desc(cb.length(root.get("name")))).build(session).setMaxResults(1).setCacheable(true).uniqueResultOptional();
    Optional<StoredScript> optionalStoredScript;
    if (includeScripts) {
        optionalStoredScript = queryBuilderFactory.find(StoredScript.class).where(((cb, root, subQueryFactory) -> cb.and(cb.equal(cb.lower(root.get("identifier")), cb.substring(cb.literal(formattedCommandInput), cb.literal(1), cb.length(root.get("identifier")))), cb.equal(root.get("scriptUsage"), subQueryFactory.createUncorrelatedSubQuery(StoredScript.ScriptUsage.class, "pk").where((cb1, root1) -> cb1.equal(root1.get("uniqueId"), "script")).build(session))))).orderBy((root, cb) -> cb.desc(cb.length(root.get("identifier")))).build(session).setMaxResults(1).setCacheable(true).uniqueResultOptional();
    } else {
        optionalStoredScript = Optional.empty();
    }
    // A ∧ B ∧ C
    if (commandContribution != null && optionalPreset.isPresent() && optionalStoredScript.isPresent()) {
        Preset preset = optionalPreset.get();
        String identifier = commandContribution.getIdentifier();
        StoredScript storedScript = optionalStoredScript.get();
        if (preset.getName().length() > identifier.length() && preset.getName().length() >= storedScript.getIdentifier().length()) {
            commandInstance = preset.instantiateCommand(this, context, commandBody);
        } else if (storedScript.getIdentifier().length() > identifier.length() && storedScript.getIdentifier().length() > preset.getName().length()) {
            commandInstance = storedScript.asCommand(this, context, commandBody);
        } else {
            String commandInput = commandBody.substring(identifier.length()).trim();
            commandInstance = commandContribution.instantiate(this, context, commandInput);
        }
    } else if (commandContribution != null && optionalPreset.isPresent()) {
        // A ∧ B ∧ !C
        String identifier = commandContribution.getIdentifier();
        Preset preset = optionalPreset.get();
        if (preset.getName().length() > identifier.length()) {
            commandInstance = preset.instantiateCommand(this, context, commandBody);
        } else {
            String commandInput = commandBody.substring(identifier.length()).trim();
            commandInstance = commandContribution.instantiate(this, context, commandInput);
        }
    } else if (optionalPreset.isPresent() && optionalStoredScript.isPresent()) {
        // !A ∧ B ∧ C
        Preset preset = optionalPreset.get();
        StoredScript storedScript = optionalStoredScript.get();
        if (storedScript.getIdentifier().length() > preset.getName().length()) {
            commandInstance = storedScript.asCommand(this, context, commandBody);
        } else {
            commandInstance = preset.instantiateCommand(this, context, commandBody);
        }
    } else if (commandContribution != null && optionalStoredScript.isPresent()) {
        // A ∧ !B ∧ C
        StoredScript storedScript = optionalStoredScript.get();
        String identifier = commandContribution.getIdentifier();
        if (storedScript.getIdentifier().length() > identifier.length()) {
            commandInstance = storedScript.asCommand(this, context, commandBody);
        } else {
            String commandInput = commandBody.substring(identifier.length()).trim();
            commandInstance = commandContribution.instantiate(this, context, commandInput);
        }
    } else if (optionalStoredScript.isPresent()) {
        // !A ∧ !B ∧ C
        commandInstance = optionalStoredScript.get().asCommand(this, context, commandBody);
    } else if (optionalPreset.isPresent()) {
        // !A ∧ B ∧ !C
        commandInstance = optionalPreset.get().instantiateCommand(this, context, commandBody);
    } else if (commandContribution != null) {
        // A ∧ !B ∧ !C
        String commandInput = commandBody.substring(commandContribution.getIdentifier().length()).trim();
        commandInstance = commandContribution.instantiate(this, context, commandInput);
    } else {
        // !A ∧ !B ∧ !C
        return Optional.empty();
    }
    return Optional.of(commandInstance);
}
Also used : Arrays(java.util.Arrays) CommandInterceptorContribution(net.robinfriedli.aiode.entities.xml.CommandInterceptorContribution) ThreadExecutionQueue(net.robinfriedli.aiode.concurrent.ThreadExecutionQueue) JxpBackend(net.robinfriedli.jxp.api.JxpBackend) LoggerFactory(org.slf4j.LoggerFactory) Session(org.hibernate.Session) Preset(net.robinfriedli.aiode.entities.Preset) Value(org.springframework.beans.factory.annotation.Value) ExecutionContext(net.robinfriedli.aiode.concurrent.ExecutionContext) QueryBuilderFactory(net.robinfriedli.aiode.persist.qb.QueryBuilderFactory) Lists(com.google.common.collect.Lists) EventWaiter(net.robinfriedli.aiode.discord.listeners.EventWaiter) CommandInterceptorChain(net.robinfriedli.aiode.command.interceptor.CommandInterceptorChain) ThreadContext(net.robinfriedli.aiode.concurrent.ThreadContext) CommandContribution(net.robinfriedli.aiode.entities.xml.CommandContribution) Resource(org.springframework.core.io.Resource) Context(net.robinfriedli.jxp.persist.Context) CommandListener(net.robinfriedli.aiode.discord.listeners.CommandListener) Logger(org.slf4j.Logger) MessageService(net.robinfriedli.aiode.discord.MessageService) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) RateLimitException(net.robinfriedli.aiode.exceptions.RateLimitException) Set(java.util.Set) IOException(java.io.IOException) Conditions(net.robinfriedli.jxp.queries.Conditions) Collectors(java.util.stream.Collectors) CommandExceptionHandlerExecutor(net.robinfriedli.aiode.exceptions.handler.CommandExceptionHandlerExecutor) Aiode(net.robinfriedli.aiode.Aiode) List(java.util.List) Component(org.springframework.stereotype.Component) StoredScript(net.robinfriedli.aiode.entities.StoredScript) Optional(java.util.Optional) CommandExecutionTask(net.robinfriedli.aiode.concurrent.CommandExecutionTask) CommandRuntimeException(net.robinfriedli.aiode.exceptions.CommandRuntimeException) ScriptCommandInterceptor(net.robinfriedli.aiode.command.interceptor.interceptors.ScriptCommandInterceptor) StoredScript(net.robinfriedli.aiode.entities.StoredScript) Preset(net.robinfriedli.aiode.entities.Preset) CommandContribution(net.robinfriedli.aiode.entities.xml.CommandContribution)

Example 4 with Preset

use of net.robinfriedli.aiode.entities.Preset in project aiode by robinfriedli.

the class AlertPresetCreationInterceptor method afterCommit.

@Override
public void afterCommit() {
    List<Preset> createdPresets = getCreatedEntities(Preset.class);
    List<Preset> deletedPresets = getDeletedEntities(Preset.class);
    if (!createdPresets.isEmpty()) {
        if (createdPresets.size() == 1) {
            Preset createdPreset = createdPresets.get(0);
            messageService.sendSuccess("Saved preset " + createdPreset.getName(), channel);
        } else {
            messageService.sendSuccess("Saved presets " + StringList.create(createdPresets, Preset::getName).toSeparatedString(", "), channel);
        }
    }
    if (!deletedPresets.isEmpty()) {
        if (deletedPresets.size() == 1) {
            Preset deletedPreset = deletedPresets.get(0);
            messageService.sendSuccess("Deleted preset " + deletedPreset.getName(), channel);
        } else {
            messageService.sendSuccess("Deleted presets " + StringList.create(deletedPresets, Preset::getName).toSeparatedString(", "), channel);
        }
    }
}
Also used : Preset(net.robinfriedli.aiode.entities.Preset)

Example 5 with Preset

use of net.robinfriedli.aiode.entities.Preset in project aiode by robinfriedli.

the class SearchEngine method searchPreset.

@Nullable
public static Preset searchPreset(Session session, String name) {
    QueryBuilderFactory queryBuilderFactory = Aiode.get().getQueryBuilderFactory();
    Optional<Preset> optionalPreset = queryBuilderFactory.find(Preset.class).where((cb, root) -> cb.equal(cb.lower(root.get("name")), Util.normalizeWhiteSpace(name).toLowerCase())).build(session).uniqueResultOptional();
    return optionalPreset.orElse(null);
}
Also used : QueryBuilderFactory(net.robinfriedli.aiode.persist.qb.QueryBuilderFactory) Preset(net.robinfriedli.aiode.entities.Preset) Nullable(javax.annotation.Nullable)

Aggregations

Preset (net.robinfriedli.aiode.entities.Preset)5 List (java.util.List)2 Aiode (net.robinfriedli.aiode.Aiode)2 AbstractCommand (net.robinfriedli.aiode.command.AbstractCommand)2 CommandParser (net.robinfriedli.aiode.command.parser.CommandParser)2 InvalidCommandException (net.robinfriedli.aiode.exceptions.InvalidCommandException)2 QueryBuilderFactory (net.robinfriedli.aiode.persist.qb.QueryBuilderFactory)2 Session (org.hibernate.Session)2 Lists (com.google.common.collect.Lists)1 IOException (java.io.IOException)1 Arrays (java.util.Arrays)1 Optional (java.util.Optional)1 Set (java.util.Set)1 Collectors (java.util.stream.Collectors)1 Nullable (javax.annotation.Nullable)1 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)1 CommandInterceptorChain (net.robinfriedli.aiode.command.interceptor.CommandInterceptorChain)1 ScriptCommandInterceptor (net.robinfriedli.aiode.command.interceptor.interceptors.ScriptCommandInterceptor)1 ArgumentBuildingMode (net.robinfriedli.aiode.command.parser.ArgumentBuildingMode)1 CommandParseListener (net.robinfriedli.aiode.command.parser.CommandParseListener)1