Plex-FAWE/worldedit-core/src/main/java/com/sk89q/worldedit/command/ScriptingCommands.java

239 lines
8.8 KiB
Java
Raw Normal View History

/*
2014-04-04 22:03:18 +00:00
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
2014-04-04 22:03:18 +00:00
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
2014-04-04 22:03:18 +00:00
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
2014-04-04 22:03:18 +00:00
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
2014-04-04 22:03:18 +00:00
*/
package com.sk89q.worldedit.command;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.sk89q.worldedit.command.util.Logging.LogMode.ALL;
import com.boydti.fawe.config.BBC;
import com.boydti.fawe.wrappers.LocationMaskedPlayerWrapper;
import org.enginehub.piston.inject.InjectedValueAccess;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.command.util.CommandPermissions;
import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
import com.sk89q.worldedit.command.util.Logging;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
2019-04-14 12:46:01 +00:00
import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
2019-04-14 12:46:01 +00:00
import com.sk89q.worldedit.scripting.CraftScriptContext;
import com.sk89q.worldedit.scripting.CraftScriptEngine;
import com.sk89q.worldedit.scripting.RhinoCraftScriptEngine;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import javax.script.ScriptException;
import org.enginehub.piston.annotation.Command;
import org.enginehub.piston.annotation.CommandContainer;
import org.enginehub.piston.annotation.param.Arg;
import org.mozilla.javascript.NativeJavaObject;
/**
* Commands related to scripting.
*/
@CommandContainer(superTypes = CommandPermissionsConditionGenerator.Registration.class)
public class ScriptingCommands {
private final WorldEdit worldEdit;
/**
* Create a new instance.
*
* @param worldEdit reference to WorldEdit
*/
public ScriptingCommands(WorldEdit worldEdit) {
checkNotNull(worldEdit);
this.worldEdit = worldEdit;
}
@Command(
name = "setupdispatcher",
desc = ""
)
@CommandPermissions("fawe.setupdispatcher")
public void setupdispatcher(Player player, LocalSession session, final InjectedValueAccess args) throws WorldEditException {
PlatformCommandManager.getInstance().setupDispatcher();
}
public static <T> T runScript(Player player, File f, String[] args) throws WorldEditException {
return runScript(player, f, args, null);
}
public static <T> T runScript(Actor actor, File f, String[] args, @Nullable Function<String, String> processor) throws WorldEditException {
String filename = f.getPath();
int index = filename.lastIndexOf(".");
String ext = filename.substring(index + 1, filename.length());
if (!ext.equalsIgnoreCase("js")) {
actor.printError("Only .js scripts are currently supported");
return null;
}
String script;
try {
InputStream file;
if (!f.exists()) {
file = WorldEdit.class.getResourceAsStream("craftscripts/" + filename);
if (file == null) {
actor.printError("Script does not exist: " + filename);
return null;
}
} else {
file = new FileInputStream(f);
}
DataInputStream in = new DataInputStream(file);
byte[] data = new byte[in.available()];
in.readFully(data);
in.close();
script = new String(data, 0, data.length, StandardCharsets.UTF_8);
} catch (IOException e) {
actor.printError("Script read error: " + e.getMessage());
return null;
}
if (processor != null) {
script = processor.apply(script);
}
WorldEdit worldEdit = WorldEdit.getInstance();
LocalSession session = worldEdit.getSessionManager().get(actor);
CraftScriptEngine engine = null;
Object result = null;
try {
engine = new RhinoCraftScriptEngine();
} catch (NoClassDefFoundError e) {
actor.printError("Failed to find an installed script engine.");
actor.printError("Download: https://github.com/downloads/mozilla/rhino/rhino1_7R4.zip");
actor.printError("Extract: `js.jar` to `plugins` or `mods` directory`");
actor.printError("More info: https://github.com/boy0001/CraftScripts/");
return null;
}
engine.setTimeLimit(worldEdit.getConfiguration().scriptTimeout);
Player player = actor instanceof Player ? (Player) actor : null;
CraftScriptContext scriptContext = new CraftScriptContext(worldEdit, WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.USER_COMMANDS),
WorldEdit.getInstance().getConfiguration(), session, player, args);
2019-04-14 12:46:01 +00:00
Map<String, Object> vars = new HashMap<>();
vars.put("argv", args);
2019-04-14 12:46:01 +00:00
vars.put("context", scriptContext);
vars.put("actor", actor);
2019-04-14 12:46:01 +00:00
vars.put("player", player);
try {
result = engine.evaluate(script, filename, vars);
} catch (ScriptException e) {
e.printStackTrace();
actor.printError("Failed to execute:");
actor.printRaw(e.getMessage());
} catch (NumberFormatException | WorldEditException e) {
throw e;
} catch (Throwable e) {
actor.printError("Failed to execute (see console):");
actor.printRaw(e.getClass().getCanonicalName());
2019-04-14 12:46:01 +00:00
e.printStackTrace();
}
if (result instanceof NativeJavaObject) {
return (T) ((NativeJavaObject) result).unwrap();
}
return (T) result;
}
@Command(
name = "cs",
desc = "Execute a CraftScript"
)
@CommandPermissions("worldedit.scripting.execute")
@Logging(ALL)
public void execute(Player player, LocalSession session, InjectedValueAccess args) throws WorldEditException {
final String[] scriptArgs = args.getSlice(1);
final String filename = args.getString(0);
if (!player.hasPermission("worldedit.scripting.execute." + filename)) {
BBC.SCRIPTING_NO_PERM.send(player);
return;
}
session.setLastScript(filename);
File dir = worldEdit.getWorkingDirectoryFile(worldEdit.getConfiguration().scriptsDir);
File f = worldEdit.getSafeOpenFile(player, dir, filename, "js", "js");
try {
new RhinoCraftScriptEngine();
} catch (NoClassDefFoundError e) {
player.printError("Failed to find an installed script engine.");
player.printError("Download: https://github.com/downloads/mozilla/rhino/rhino1_7R4.zip");
player.printError("Extract: `js.jar` to `plugins` or `mods` directory`");
player.printError("More info: https://github.com/boy0001/CraftScripts/");
return;
}
runScript(LocationMaskedPlayerWrapper.unwrap(player), f, scriptArgs);
}
@Command(
name = ".s",
desc = "Execute last CraftScript"
)
@CommandPermissions("worldedit.scripting.execute")
@Logging(ALL)
public void executeLast(Player player, LocalSession session,
@Arg(desc = "Arguments to the CraftScript", def = "", variable = true)
List<String> args) throws WorldEditException {
String lastScript = session.getLastScript();
if (!player.hasPermission("worldedit.scripting.execute." + lastScript)) {
BBC.SCRIPTING_NO_PERM.send(player);
return;
}
if (lastScript == null) {
BBC.SCRIPTING_CS.send(player);
return;
}
File dir = worldEdit.getWorkingDirectoryFile(worldEdit.getConfiguration().scriptsDir);
File f = worldEdit.getSafeOpenFile(player, dir, lastScript, "js", "js");
worldEdit.runScript(player, f, Stream.concat(Stream.of(lastScript), args.stream())
.toArray(String[]::new));
}
}