Search in sources :

Example 11 with CommandContext

use of net.robinfriedli.aiode.command.CommandContext in project aiode by robinfriedli.

the class PlayCommand method doRun.

@Override
public void doRun() throws Exception {
    CommandContext context = getContext();
    Guild guild = context.getGuild();
    VoiceChannel channel = context.getVoiceChannel();
    AudioManager audioManager = Aiode.get().getAudioManager();
    MessageChannel messageChannel = getContext().getChannel();
    AudioPlayback playbackForGuild = audioManager.getPlaybackForGuild(guild);
    playbackForGuild.setCommunicationChannel(messageChannel);
    if (getCommandInput().isBlank()) {
        if (playbackForGuild.isPaused() || !audioManager.getQueue(guild).isEmpty()) {
            audioManager.startOrResumePlayback(guild, channel);
        } else {
            throw new InvalidCommandException("Queue is empty. Specify a song you want to play.");
        }
    } else {
        super.doRun();
    }
}
Also used : AudioManager(net.robinfriedli.aiode.audio.AudioManager) AudioPlayback(net.robinfriedli.aiode.audio.AudioPlayback) CommandContext(net.robinfriedli.aiode.command.CommandContext) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) VoiceChannel(net.dv8tion.jda.api.entities.VoiceChannel) Guild(net.dv8tion.jda.api.entities.Guild)

Example 12 with CommandContext

use of net.robinfriedli.aiode.command.CommandContext in project aiode by robinfriedli.

the class CommandExecutionInterceptor method postCommand.

/**
 * Finalize and persist the {@link CommandHistory} entry for this command execution.
 *
 * @param command               the executed command
 * @param completedSuccessfully whether the command completed sucessfully
 * @param failedManually        whether the command failed because {@link Command#isFailed()} returned true
 * @param errorMessage          the error message if an exception was thrown
 * @param unexpectedException   whether an unexpected exception was thrown, this excludes {@link UserException}
 * @param aborted               whether command execution was aborted
 */
private void postCommand(Command command, boolean completedSuccessfully, boolean failedManually, String errorMessage, boolean unexpectedException, boolean aborted) {
    CommandContext context = command.getContext();
    context.interruptMonitoring();
    HistoryPool.execute(() -> {
        CommandHistory history = context.getCommandHistory();
        if (history != null) {
            history.setDurationMs(System.currentTimeMillis() - history.getStartMillis());
            history.setCompletedSuccessfully(completedSuccessfully);
            history.setFailedManually(failedManually);
            history.setUnexpectedException(unexpectedException);
            history.setErrorMessage(errorMessage);
            history.setAborted(aborted);
            StaticSessionProvider.consumeSession(session -> session.persist(history));
        } else {
            logger.warn("Command " + command + " has no history");
        }
    });
}
Also used : CommandHistory(net.robinfriedli.aiode.entities.CommandHistory) CommandContext(net.robinfriedli.aiode.command.CommandContext)

Example 13 with CommandContext

use of net.robinfriedli.aiode.command.CommandContext 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 14 with CommandContext

use of net.robinfriedli.aiode.command.CommandContext in project aiode by robinfriedli.

the class PermissionCommand method grantPermissions.

private void grantPermissions() {
    SecurityManager securityManager = Aiode.get().getSecurityManager();
    CommandContext context = getContext();
    GuildSpecification specification = context.getGuildContext().getSpecification();
    Session session = context.getSession();
    Set<? extends PermissionTarget> selectedTargets = getSelectedTargets();
    Set<Role> selectedRoles = getSelectedRoles("to");
    boolean addedAnything = invoke(() -> {
        boolean takenAction = false;
        for (PermissionTarget permissionTarget : selectedTargets) {
            Optional<AccessConfiguration> existingConfiguration = securityManager.getAccessConfiguration(permissionTarget, context.getGuild());
            if (existingConfiguration.isPresent()) {
                AccessConfiguration accessConfiguration = existingConfiguration.get();
                Set<String> roleIds = accessConfiguration.getRoleIds();
                for (Role selectedRole : selectedRoles) {
                    if (roleIds.contains(selectedRole.getId())) {
                        continue;
                    }
                    GrantedRole role = new GrantedRole(selectedRole);
                    session.persist(role);
                    accessConfiguration.addRole(role);
                    takenAction = true;
                }
            } else {
                AccessConfiguration accessConfiguration = new AccessConfiguration(permissionTarget, session);
                for (Role selectedRole : selectedRoles) {
                    GrantedRole role = new GrantedRole(selectedRole);
                    session.persist(role);
                    accessConfiguration.addRole(role);
                }
                session.persist(accessConfiguration);
                specification.addAccessConfiguration(accessConfiguration);
                takenAction = true;
            }
        }
        return takenAction;
    });
    if (!addedAnything) {
        sendError("All selected roles have already been granted each selected permission. No changes needed.");
    }
}
Also used : SecurityManager(net.robinfriedli.aiode.command.SecurityManager) CommandContext(net.robinfriedli.aiode.command.CommandContext) PermissionTarget(net.robinfriedli.aiode.command.PermissionTarget) CustomPermissionTarget(net.robinfriedli.aiode.entities.CustomPermissionTarget) Role(net.dv8tion.jda.api.entities.Role) GrantedRole(net.robinfriedli.aiode.entities.GrantedRole) GrantedRole(net.robinfriedli.aiode.entities.GrantedRole) GuildSpecification(net.robinfriedli.aiode.entities.GuildSpecification) AccessConfiguration(net.robinfriedli.aiode.entities.AccessConfiguration) Session(org.hibernate.Session)

Example 15 with CommandContext

use of net.robinfriedli.aiode.command.CommandContext in project aiode by robinfriedli.

the class PermissionCommand method denyPermissions.

private void denyPermissions() {
    SecurityManager securityManager = Aiode.get().getSecurityManager();
    CommandContext context = getContext();
    Set<? extends PermissionTarget> selectedCommands = getSelectedTargets();
    Set<Role> selectedRoles = getSelectedRoles("for");
    Session session = context.getSession();
    boolean removedAnything = invoke(() -> {
        boolean takenAction = false;
        for (PermissionTarget permissionTarget : selectedCommands) {
            Optional<AccessConfiguration> existingAccessConfiguration = securityManager.getAccessConfiguration(permissionTarget, context.getGuild());
            if (existingAccessConfiguration.isPresent()) {
                AccessConfiguration accessConfiguration = existingAccessConfiguration.get();
                for (Role selectedRole : selectedRoles) {
                    Optional<GrantedRole> setRole = accessConfiguration.getRole(selectedRole.getId());
                    if (setRole.isPresent()) {
                        GrantedRole grantedRole = setRole.get();
                        accessConfiguration.removeRole(grantedRole);
                        session.delete(grantedRole);
                        takenAction = true;
                    }
                }
            }
        }
        return takenAction;
    });
    if (!removedAnything) {
        sendError("None of the selected roles were granted any of the selected permissions. The deny argument is used " + "to remove granted roles from permissions. If there currently aren't any restrictions for the selected permissions " + "use the grant argument to limit the permission to certain roles.");
    }
}
Also used : Role(net.dv8tion.jda.api.entities.Role) GrantedRole(net.robinfriedli.aiode.entities.GrantedRole) SecurityManager(net.robinfriedli.aiode.command.SecurityManager) CommandContext(net.robinfriedli.aiode.command.CommandContext) GrantedRole(net.robinfriedli.aiode.entities.GrantedRole) AccessConfiguration(net.robinfriedli.aiode.entities.AccessConfiguration) Session(org.hibernate.Session) PermissionTarget(net.robinfriedli.aiode.command.PermissionTarget) CustomPermissionTarget(net.robinfriedli.aiode.entities.CustomPermissionTarget)

Aggregations

CommandContext (net.robinfriedli.aiode.command.CommandContext)21 Session (org.hibernate.Session)9 InvalidCommandException (net.robinfriedli.aiode.exceptions.InvalidCommandException)8 Guild (net.dv8tion.jda.api.entities.Guild)7 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)6 Aiode (net.robinfriedli.aiode.Aiode)6 SecurityManager (net.robinfriedli.aiode.command.SecurityManager)6 AbstractCommand (net.robinfriedli.aiode.command.AbstractCommand)5 PermissionTarget (net.robinfriedli.aiode.command.PermissionTarget)5 CustomPermissionTarget (net.robinfriedli.aiode.entities.CustomPermissionTarget)5 StoredScript (net.robinfriedli.aiode.entities.StoredScript)3 List (java.util.List)2 MessageChannel (net.dv8tion.jda.api.entities.MessageChannel)2 Role (net.dv8tion.jda.api.entities.Role)2 User (net.dv8tion.jda.api.entities.User)2 InsufficientPermissionException (net.dv8tion.jda.api.exceptions.InsufficientPermissionException)2 AudioManager (net.robinfriedli.aiode.audio.AudioManager)2 ThreadExecutionQueue (net.robinfriedli.aiode.concurrent.ThreadExecutionQueue)2 AccessConfiguration (net.robinfriedli.aiode.entities.AccessConfiguration)2 GrantedRole (net.robinfriedli.aiode.entities.GrantedRole)2