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();
}
}
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");
}
});
}
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());
}
}
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.");
}
}
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.");
}
}
Aggregations