Search in sources :

Example 6 with StoredScript

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

the class AbstractScriptCommand method saveNewScript.

private void saveNewScript(QueryBuilderFactory queryBuilderFactory, Session session, CommandContext context) {
    String identifier = getArgumentValue("identifier");
    String script = getCommandInput();
    Optional<StoredScript> existingScript = SearchEngine.searchScript(identifier, scriptUsageId, session);
    if (existingScript.isPresent()) {
        throw new InvalidCommandException(String.format("%s with identifier '%s' already exists", scriptUsageId, identifier));
    }
    Aiode aiode = Aiode.get();
    GroovyVariableManager groovyVariableManager = aiode.getGroovyVariableManager();
    GroovyShell groovyShell;
    if (argumentSet("privileged")) {
        groovyShell = new GroovyShell();
    } else {
        groovyShell = new GroovyShell(aiode.getGroovySandboxComponent().getCompilerConfiguration());
    }
    groovyVariableManager.prepareShell(groovyShell);
    try {
        groovyShell.parse(script);
    } catch (MultipleCompilationErrorsException e) {
        throw new InvalidCommandException(String.format("Could not compile provided script:%s%s", System.lineSeparator(), ExceptionUtils.formatScriptCompilationError(e)));
    }
    StoredScript.ScriptUsage scriptUsage = queryBuilderFactory.find(StoredScript.ScriptUsage.class).where((cb, root) -> cb.equal(root.get("uniqueId"), scriptUsageId)).build(session).uniqueResult();
    StoredScript storedScript = new StoredScript();
    storedScript.setGuildId(context.getGuild().getIdLong());
    storedScript.setIdentifier(identifier);
    storedScript.setScript(script);
    storedScript.setScriptUsage(scriptUsage);
    storedScript.setActive(!argumentSet("deactivate"));
    invoke(() -> session.persist(storedScript));
}
Also used : InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) StoredScript(net.robinfriedli.aiode.entities.StoredScript) MultipleCompilationErrorsException(org.codehaus.groovy.control.MultipleCompilationErrorsException) Aiode(net.robinfriedli.aiode.Aiode) GroovyVariableManager(net.robinfriedli.aiode.scripting.GroovyVariableManager) GroovyShell(groovy.lang.GroovyShell)

Example 7 with StoredScript

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

the class AbstractScriptCommand method findScript.

private StoredScript findScript(Session session) {
    String identifier;
    if (argumentSet("identifier")) {
        identifier = getArgumentValue("identifier");
    } else if (!getCommandInput().isBlank()) {
        identifier = getCommandInput();
    } else {
        throw new InvalidCommandException("Expected either the command input or identifier argument to specify the target script.");
    }
    Optional<StoredScript> foundScript = SearchEngine.searchScript(identifier, scriptUsageId, session);
    if (foundScript.isPresent()) {
        return foundScript.get();
    } else {
        throw new InvalidCommandException(String.format("No saved %s found for '%s'", scriptUsageId, identifier));
    }
}
Also used : InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) StoredScript(net.robinfriedli.aiode.entities.StoredScript)

Example 8 with StoredScript

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

the class ScriptCommandInterceptor method performChained.

@Override
public void performChained(Command command) {
    if (command instanceof AbstractCommand) {
        AbstractCommand abstractCommand = (AbstractCommand) command;
        if (abstractCommand.getArgumentController().argumentSet("skipInterceptors") || abstractCommand.getCommandContribution().isDisableScriptInterceptors()) {
            return;
        }
    } else {
        return;
    }
    CommandContext context = command.getContext();
    Session session = context.getSession();
    GuildSpecification specification = context.getGuildContext().getSpecification(session);
    boolean enableScripting = guildPropertyManager.getPropertyValueOptional("enableScripting", Boolean.class, specification).orElse(true);
    if (!enableScripting) {
        return;
    }
    String usageId = getUsageId();
    List<StoredScript> scriptInterceptors = queryBuilderFactory.find(StoredScript.class).where((cb, root, subQueryFactory) -> cb.and(cb.isTrue(root.get("active")), cb.equal(root.get("scriptUsage"), subQueryFactory.createUncorrelatedSubQuery(StoredScript.ScriptUsage.class, "pk").where((cb1, root1) -> cb1.equal(root1.get("uniqueId"), usageId)).build(session)))).build(session).getResultList();
    if (scriptInterceptors.isEmpty()) {
        return;
    }
    Aiode aiode = Aiode.get();
    SafeGroovyScriptRunner scriptRunner = new SafeGroovyScriptRunner(context, groovySandboxComponent, aiode.getGroovyVariableManager(), aiode.getSecurityManager(), false);
    AtomicReference<StoredScript> currentScriptReference = new AtomicReference<>();
    try {
        scriptRunner.runScripts(scriptInterceptors, currentScriptReference, 5, TimeUnit.SECONDS);
    } catch (ExecutionException e) {
        Throwable error = e.getCause() != null ? e.getCause() : e;
        if (error instanceof CommandFailure) {
            messageService.sendError(String.format("Executing command %1$ss failed due to an error in %1$s '%2$s'", usageId, currentScriptReference.get().getIdentifier()), context.getChannel());
        } else {
            EmbedBuilder embedBuilder = ExceptionUtils.buildErrorEmbed(error);
            StoredScript currentScript = currentScriptReference.get();
            embedBuilder.setTitle(String.format("Error occurred while executing custom command %s%s", usageId, currentScript.getIdentifier() != null ? ": " + currentScript.getIdentifier() : ""));
            messageService.sendTemporary(embedBuilder.build(), context.getChannel());
        }
    } catch (TimeoutException e) {
        StoredScript currentScript = currentScriptReference.get();
        messageService.sendError(String.format("Execution of script command %ss stopped because script%s has run into a timeout", usageId, currentScript != null ? String.format(" '%s'", currentScript.getIdentifier()) : ""), context.getChannel());
    }
}
Also used : CommandContext(net.robinfriedli.aiode.command.CommandContext) AbstractCommand(net.robinfriedli.aiode.command.AbstractCommand) AtomicReference(java.util.concurrent.atomic.AtomicReference) Aiode(net.robinfriedli.aiode.Aiode) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) SafeGroovyScriptRunner(net.robinfriedli.aiode.scripting.SafeGroovyScriptRunner) StoredScript(net.robinfriedli.aiode.entities.StoredScript) GuildSpecification(net.robinfriedli.aiode.entities.GuildSpecification) CommandFailure(net.robinfriedli.aiode.exceptions.CommandFailure) ExecutionException(java.util.concurrent.ExecutionException) Session(org.hibernate.Session) TimeoutException(java.util.concurrent.TimeoutException)

Example 9 with StoredScript

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

the class ScriptCommand method executeScript.

private void executeScript(Aiode aiode, CommandContext context, Session session) {
    GroovySandboxComponent groovySandboxComponent = aiode.getGroovySandboxComponent();
    GroovyVariableManager groovyVariableManager = aiode.getGroovyVariableManager();
    SafeGroovyScriptRunner groovyScriptRunner = new SafeGroovyScriptRunner(context, groovySandboxComponent, groovyVariableManager, aiode.getSecurityManager(), argumentSet("privileged"));
    StoredScript script;
    if (this.script != null) {
        script = this.script;
    } else {
        String identifier = getArgumentValue("invoke");
        Optional<StoredScript> storedScript = SearchEngine.searchScript(identifier, "script", session);
        if (storedScript.isPresent()) {
            script = storedScript.get();
        } else {
            throw new InvalidCommandException(String.format("No such script '%s'", identifier));
        }
    }
    if (!script.isActive()) {
        throw new InvalidCommandException(String.format("Script '%s' has been deactivated. Use the active argument to reactivate the script.", script.getIdentifier()));
    }
    groovyScriptRunner.runAndSendResult(script.getScript(), 10, TimeUnit.SECONDS);
}
Also used : SafeGroovyScriptRunner(net.robinfriedli.aiode.scripting.SafeGroovyScriptRunner) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) StoredScript(net.robinfriedli.aiode.entities.StoredScript) GroovyVariableManager(net.robinfriedli.aiode.scripting.GroovyVariableManager) GroovySandboxComponent(net.robinfriedli.aiode.boot.configurations.GroovySandboxComponent)

Example 10 with StoredScript

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

the class AlertScriptModificationInterceptor method afterCommit.

@Override
public void afterCommit() {
    List<StoredScript> createdEntities = getCreatedEntities(StoredScript.class);
    List<StoredScript> deletedEntities = getDeletedEntities(StoredScript.class);
    List<StoredScript> updatedEntities = getUpdatedEntities(StoredScript.class);
    alertScriptModification("Created", createdEntities);
    alertScriptModification("Deleted", deletedEntities);
    List<StoredScript> activatedScripts = Lists.newArrayList();
    List<StoredScript> deactivatedScripts = Lists.newArrayList();
    for (StoredScript updatedEntity : updatedEntities) {
        if (isFieldTouched(updatedEntity, "active")) {
            Object prevVal = getOriginalValue(updatedEntity, "active");
            if (prevVal instanceof Boolean) {
                boolean wasActive = (boolean) prevVal;
                if (!wasActive && updatedEntity.isActive()) {
                    activatedScripts.add(updatedEntity);
                } else if (wasActive && !updatedEntity.isActive()) {
                    deactivatedScripts.add(updatedEntity);
                }
            }
        }
    }
    alertScriptModification("Activated", activatedScripts);
    alertScriptModification("Deactivated", deactivatedScripts);
}
Also used : StoredScript(net.robinfriedli.aiode.entities.StoredScript)

Aggregations

StoredScript (net.robinfriedli.aiode.entities.StoredScript)11 InvalidCommandException (net.robinfriedli.aiode.exceptions.InvalidCommandException)6 Aiode (net.robinfriedli.aiode.Aiode)4 Session (org.hibernate.Session)4 GroovyShell (groovy.lang.GroovyShell)3 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)3 CommandContext (net.robinfriedli.aiode.command.CommandContext)3 QueryBuilderFactory (net.robinfriedli.aiode.persist.qb.QueryBuilderFactory)3 GroovyVariableManager (net.robinfriedli.aiode.scripting.GroovyVariableManager)3 List (java.util.List)2 Optional (java.util.Optional)2 AbstractCommand (net.robinfriedli.aiode.command.AbstractCommand)2 CommandContribution (net.robinfriedli.aiode.entities.xml.CommandContribution)2 MultipleCompilationErrorsException (org.codehaus.groovy.control.MultipleCompilationErrorsException)2 Lists (com.google.common.collect.Lists)1 IOException (java.io.IOException)1 Arrays (java.util.Arrays)1 Set (java.util.Set)1 ExecutionException (java.util.concurrent.ExecutionException)1 TimeoutException (java.util.concurrent.TimeoutException)1