mirror of
https://github.com/PlaceholderAPI/Javascript-Expansion.git
synced 2025-05-23 02:19:04 +00:00
1.6.0-SNAPSHOT update codes (#28)
* Code format Revamp * Update JavascriptExpansionCommands.java * Get out of here, regex... * Updated to ver. 1.6.0-SNAPSHOT * Update JavascriptExpansion.java * Forgot to manage for setIfNull, sorry * Fix wrong args from CMD Manager migration * Fix error on 1.13+
This commit is contained in:
parent
4e4ff336b2
commit
772111dc6c
10
pom.xml
10
pom.xml
@ -2,7 +2,7 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.extendedclip.papi.expansion.javascript</groupId>
|
||||
<artifactId>javascript-expansion</artifactId>
|
||||
<version>1.5.4</version>
|
||||
<version>1.6.0-SNAPSHOT</version>
|
||||
<name>PAPI-Expansion-Javascript</name>
|
||||
<description>PlaceholderAPI expansion for javascript placeholders</description>
|
||||
|
||||
@ -21,13 +21,13 @@
|
||||
<dependency>
|
||||
<groupId>org.spigotmc</groupId>
|
||||
<artifactId>spigot-api</artifactId>
|
||||
<version>1.15.2-R0.1-SNAPSHOT</version>
|
||||
<version>1.16.1-R0.1-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>me.clip</groupId>
|
||||
<artifactId>placeholderapi</artifactId>
|
||||
<version>2.10.5</version>
|
||||
<version>2.10.9</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
@ -37,7 +37,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.0.2</version>
|
||||
<version>3.2.0</version>
|
||||
<configuration>
|
||||
<finalName>${name}</finalName>
|
||||
<archive>
|
||||
@ -51,7 +51,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.7.0</version>
|
||||
<version>3.8.1</version>
|
||||
<configuration>
|
||||
<target>1.8</target>
|
||||
<source>1.8</source>
|
||||
|
@ -4,5 +4,4 @@ function randomLetter() {
|
||||
|
||||
return String.fromCharCode(start + Math.floor(random));
|
||||
}
|
||||
|
||||
randomLetter();
|
@ -0,0 +1,108 @@
|
||||
package com.extendedclip.papi.expansion.javascript;
|
||||
|
||||
import jdk.nashorn.api.scripting.ScriptObjectMirror;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.configuration.MemorySection;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class ExpansionUtils {
|
||||
|
||||
public static final String DEFAULT_ENGINE = "nashorn";
|
||||
public static final String PREFIX = "[PAPI] [Javascript-Expansion] ";
|
||||
private static final Logger logger = Bukkit.getLogger();
|
||||
|
||||
public static @NotNull String colorize(String s) {
|
||||
return ChatColor.translateAlternateColorCodes('&', s);
|
||||
}
|
||||
|
||||
public static void sendMsg(CommandSender sender, String... msg) {
|
||||
sender.sendMessage(colorize(Arrays.stream(msg).filter(Objects::nonNull).collect(Collectors.joining("\n"))));
|
||||
}
|
||||
|
||||
public static void warnLog(String log, Throwable throwable) {
|
||||
warnLog(log, throwable, true);
|
||||
}
|
||||
|
||||
public static void infoLog(final String log) {
|
||||
infoLog(log, true);
|
||||
}
|
||||
|
||||
public static void infoLog(String log, boolean canPrefix) {
|
||||
String prefix = "";
|
||||
if (canPrefix) prefix = PREFIX;
|
||||
logger.info(colorize(prefix + log));
|
||||
}
|
||||
|
||||
public static void warnLog(String log, Throwable throwable, boolean canPrefix) {
|
||||
String prefix = "";
|
||||
if (canPrefix) prefix = PREFIX;
|
||||
if (throwable == null) {
|
||||
logger.log(Level.WARNING, prefix + log);
|
||||
} else logger.log(Level.WARNING, prefix + log, throwable);
|
||||
}
|
||||
|
||||
public static void errorLog(String log, Throwable throwable) {
|
||||
errorLog(log, throwable, true);
|
||||
}
|
||||
|
||||
public static void errorLog(String log, Throwable throwable, boolean canPrefix) {
|
||||
String prefix = "";
|
||||
if (canPrefix) prefix = PREFIX;
|
||||
if (throwable == null) {
|
||||
logger.log(Level.SEVERE, prefix + log);
|
||||
} else {
|
||||
logger.log(Level.SEVERE, prefix + log, throwable);
|
||||
}
|
||||
}
|
||||
|
||||
// Only support for Nashorn engine!
|
||||
protected static Object jsonToJava(Object jsObj) {
|
||||
if (jsObj instanceof ScriptObjectMirror) {
|
||||
ScriptObjectMirror jsObjectMirror = (ScriptObjectMirror) jsObj;
|
||||
if (jsObjectMirror.isArray()) {
|
||||
List<Object> list = new ArrayList<>();
|
||||
for (Map.Entry<String, Object> entry : jsObjectMirror.entrySet()) {
|
||||
list.add(jsonToJava(entry.getValue()));
|
||||
}
|
||||
return list;
|
||||
} else {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
for (Map.Entry<String, Object> entry : jsObjectMirror.entrySet()) {
|
||||
map.put(entry.getKey(), jsonToJava(entry.getValue()));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
} else {
|
||||
return jsObj;
|
||||
}
|
||||
}
|
||||
|
||||
protected static Object ymlToJavaObj(Object obj) {
|
||||
if (obj instanceof MemorySection) {
|
||||
MemorySection ymlMem = (MemorySection) obj;
|
||||
if (ymlMem.isList(ymlMem.getCurrentPath())) {
|
||||
ArrayList<Object> list = new ArrayList<>();
|
||||
for (String entry : ymlMem.getKeys(true)) {
|
||||
list.add(ymlToJavaObj(ymlMem.get(entry)));
|
||||
}
|
||||
return list;
|
||||
} else {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
for (String entry : ymlMem.getKeys(true)) {
|
||||
map.put(entry, ymlToJavaObj(ymlMem.get(entry)));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
} else {
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -26,14 +26,16 @@ import me.clip.placeholderapi.expansion.Configurable;
|
||||
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandMap;
|
||||
import org.bukkit.command.SimpleCommandMap;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import javax.script.ScriptEngine;
|
||||
import javax.script.ScriptEngineFactory;
|
||||
import javax.script.ScriptEngineManager;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.*;
|
||||
import java.util.logging.Level;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class JavascriptExpansion extends PlaceholderExpansion implements Cacheable, Configurable {
|
||||
@ -41,22 +43,26 @@ public class JavascriptExpansion extends PlaceholderExpansion implements Cacheab
|
||||
private ScriptEngine globalEngine = null;
|
||||
|
||||
private JavascriptPlaceholdersConfig config;
|
||||
private final Set<JavascriptPlaceholder> scripts = new HashSet<>();
|
||||
private final String VERSION = getClass().getPackage().getImplementationVersion();
|
||||
private final Set<JavascriptPlaceholder> scripts;
|
||||
private final String VERSION;
|
||||
private static JavascriptExpansion instance;
|
||||
private boolean debug;
|
||||
private GithubScriptManager githubManager;
|
||||
private JavascriptExpansionCommands commands;
|
||||
private CommandMap commandMap;
|
||||
private String argument_split;
|
||||
|
||||
public JavascriptExpansion() {
|
||||
instance = this;
|
||||
this.VERSION = getClass().getPackage().getImplementationVersion();
|
||||
this.scripts = new HashSet<>();
|
||||
|
||||
try {
|
||||
final Field field = Bukkit.getServer().getClass().getDeclaredField("commandMap");
|
||||
field.setAccessible(true);
|
||||
commandMap = (CommandMap) field.get(Bukkit.getServer());
|
||||
} catch (NoSuchFieldException | IllegalAccessException e) {
|
||||
getPlaceholderAPI().getLogger().log(Level.SEVERE, "[JavaScript Expansion] An error occurred while accessing CommandMap.", e);
|
||||
ExpansionUtils.errorLog("An error occurred while accessing CommandMap.", e, true);
|
||||
}
|
||||
}
|
||||
|
||||
@ -77,24 +83,36 @@ public class JavascriptExpansion extends PlaceholderExpansion implements Cacheab
|
||||
|
||||
@Override
|
||||
public boolean register() {
|
||||
String defaultEngine = ExpansionUtils.DEFAULT_ENGINE;
|
||||
|
||||
if (globalEngine == null) {
|
||||
try {
|
||||
globalEngine = new ScriptEngineManager(null).getEngineByName(getString("engine", "nashorn"));
|
||||
globalEngine = new ScriptEngineManager(null).getEngineByName(getString("engine", defaultEngine));
|
||||
} catch (NullPointerException ex) {
|
||||
getPlaceholderAPI().getLogger().warning("[JavaScript Expansion] Javascript engine type was invalid! Defaulting to 'nashorn'");
|
||||
globalEngine = new ScriptEngineManager(null).getEngineByName("nashorn");
|
||||
ExpansionUtils.warnLog("Javascript engine type was invalid! Defaulting to '" + defaultEngine + "'", null);
|
||||
globalEngine = new ScriptEngineManager(null).getEngineByName(defaultEngine);
|
||||
}
|
||||
}
|
||||
|
||||
argument_split = getString("argument_split", ",");
|
||||
if (argument_split.equals("_")) {
|
||||
argument_split = ",";
|
||||
ExpansionUtils.warnLog("Underscore character will not be allowed for splitting. Defaulting to ',' for this", null);
|
||||
}
|
||||
|
||||
debug = (boolean) get("debug", false);
|
||||
config = new JavascriptPlaceholdersConfig(this);
|
||||
config.loadPlaceholders();
|
||||
|
||||
int amountLoaded = config.loadPlaceholders();
|
||||
ExpansionUtils.infoLog(amountLoaded + " script" + plural(amountLoaded) + " loaded!");
|
||||
|
||||
|
||||
if (debug) {
|
||||
getPlaceholderAPI().getLogger().info("[JavaScript Expansion] Java version: " + System.getProperty("java.version"));
|
||||
ExpansionUtils.infoLog("Java version: " + System.getProperty("java.version"));
|
||||
|
||||
final ScriptEngineManager manager = new ScriptEngineManager(null);
|
||||
final List<ScriptEngineFactory> factories = manager.getEngineFactories();
|
||||
getPlaceholderAPI().getLogger().info("Displaying all script engine factories.");
|
||||
ExpansionUtils.infoLog("Displaying all script engine factories.", false);
|
||||
|
||||
for (ScriptEngineFactory factory : factories) {
|
||||
System.out.println(factory.getEngineName());
|
||||
@ -107,7 +125,7 @@ public class JavascriptExpansion extends PlaceholderExpansion implements Cacheab
|
||||
}
|
||||
}
|
||||
|
||||
if ((Boolean) get("github_script_downloads", false)) {
|
||||
if ((boolean) get("github_script_downloads", false)) {
|
||||
githubManager = new GithubScriptManager(this);
|
||||
githubManager.fetch();
|
||||
}
|
||||
@ -136,16 +154,16 @@ public class JavascriptExpansion extends PlaceholderExpansion implements Cacheab
|
||||
}
|
||||
|
||||
@Override
|
||||
public String onRequest(OfflinePlayer player, String identifier) {
|
||||
public String onRequest(OfflinePlayer player, @NotNull String identifier) {
|
||||
if (player == null || scripts.size() == 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
for (JavascriptPlaceholder script : scripts) {
|
||||
if (identifier.startsWith(script.getIdentifier() + "_")) {
|
||||
identifier = identifier.replace(script.getIdentifier() + "_", "");
|
||||
identifier = identifier.replaceFirst(script.getIdentifier() + "_", "");
|
||||
|
||||
return !identifier.contains(",") ? script.evaluate(player, identifier) : script.evaluate(player, identifier.split(","));
|
||||
return !identifier.contains(argument_split) ? script.evaluate(player, identifier) : script.evaluate(player, identifier.split(argument_split));
|
||||
}
|
||||
|
||||
if (identifier.equalsIgnoreCase(script.getIdentifier())) {
|
||||
@ -174,9 +192,9 @@ public class JavascriptExpansion extends PlaceholderExpansion implements Cacheab
|
||||
return true;
|
||||
}
|
||||
|
||||
public Set<JavascriptPlaceholder> getJSPlaceholders() {
|
||||
return scripts;
|
||||
}
|
||||
// public Set<JavascriptPlaceholder> getJSPlaceholders() {
|
||||
// return scripts;
|
||||
// }
|
||||
|
||||
public List<String> getLoadedIdentifiers() {
|
||||
return scripts.stream()
|
||||
@ -208,12 +226,13 @@ public class JavascriptExpansion extends PlaceholderExpansion implements Cacheab
|
||||
final Map<String, Object> defaults = new HashMap<>();
|
||||
defaults.put("engine", "javascript");
|
||||
defaults.put("debug", false);
|
||||
defaults.put("argument_split", ",");
|
||||
defaults.put("github_script_downloads", false);
|
||||
|
||||
return defaults;
|
||||
}
|
||||
|
||||
protected int reloadScripts() {
|
||||
public int reloadScripts() {
|
||||
scripts.forEach(script -> {
|
||||
script.saveData();
|
||||
script.cleanup();
|
||||
@ -236,19 +255,48 @@ public class JavascriptExpansion extends PlaceholderExpansion implements Cacheab
|
||||
this.githubManager = manager;
|
||||
}
|
||||
|
||||
@SuppressWarnings("UnusedReturnValue")
|
||||
private boolean unregisterCommand() {
|
||||
return commandMap != null && commands != null && commands.unregister(commandMap);
|
||||
private void unregisterCommand() {
|
||||
if (commandMap != null && commands != null) {
|
||||
|
||||
try {
|
||||
Class<? extends CommandMap> cmdMapClass = commandMap.getClass();
|
||||
final Field f;
|
||||
|
||||
//Check if the server's in 1.13+
|
||||
if (cmdMapClass.getSimpleName().equals("CraftCommandMap")) {
|
||||
f = cmdMapClass.getSuperclass().getDeclaredField("knownCommands");
|
||||
} else {
|
||||
f = cmdMapClass.getDeclaredField("knownCommands");
|
||||
}
|
||||
|
||||
@SuppressWarnings("UnusedReturnValue")
|
||||
private boolean registerCommand() {
|
||||
f.setAccessible(true);
|
||||
Map<String, Command> knownCmds = (Map<String, Command>) f.get(commandMap);
|
||||
knownCmds.remove(commands.getName());
|
||||
for (String alias : commands.getAliases()) {
|
||||
if (knownCmds.containsKey(alias) && knownCmds.get(alias).toString().contains(commands.getName())) {
|
||||
knownCmds.remove(alias);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (NoSuchFieldException | IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
commands.unregister(commandMap);
|
||||
}
|
||||
}
|
||||
|
||||
private void registerCommand() {
|
||||
if (commandMap == null) {
|
||||
return false;
|
||||
return;
|
||||
}
|
||||
|
||||
commands = new JavascriptExpansionCommands(this);
|
||||
commandMap.register("papi" + commands.getName(), commands);
|
||||
return commands.isRegistered();
|
||||
commands.isRegistered();
|
||||
}
|
||||
|
||||
private String plural(final int amount) {
|
||||
return amount > 1 ? "s" : "";
|
||||
}
|
||||
}
|
||||
|
@ -21,18 +21,16 @@
|
||||
package com.extendedclip.papi.expansion.javascript;
|
||||
|
||||
import com.extendedclip.papi.expansion.javascript.cloud.GithubScript;
|
||||
import com.extendedclip.papi.expansion.javascript.cloud.GithubScriptManager;
|
||||
import me.clip.placeholderapi.PlaceholderAPIPlugin;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import com.extendedclip.papi.expansion.javascript.command.*;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.util.StringUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class JavascriptExpansionCommands extends Command {
|
||||
@ -40,6 +38,7 @@ public class JavascriptExpansionCommands extends Command {
|
||||
private final JavascriptExpansion expansion;
|
||||
private final String PERMISSION = "placeholderapi.js.admin";
|
||||
private final String command;
|
||||
private List<ICommand> subCommands;
|
||||
|
||||
public JavascriptExpansionCommands(JavascriptExpansion expansion) {
|
||||
super("jsexpansion");
|
||||
@ -47,11 +46,59 @@ public class JavascriptExpansionCommands extends Command {
|
||||
this.expansion = expansion;
|
||||
this.setDescription("Javascript expansion commands");
|
||||
this.setUsage("/" + command + " <args>");
|
||||
this.setAliases(new ArrayList<>(Arrays.asList("javascriptexpansion", "jsexp")));
|
||||
this.setPermission(PERMISSION);
|
||||
initCommands();
|
||||
}
|
||||
|
||||
public void initCommands() {
|
||||
if (subCommands != null) {
|
||||
subCommands.clear();
|
||||
}
|
||||
subCommands = new ArrayList<>(Arrays.asList(
|
||||
new GitCommand(expansion),
|
||||
new ListCommand(expansion),
|
||||
new ParseCommand(expansion),
|
||||
new ReloadCommand(expansion),
|
||||
new DebugCommand(expansion))
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException {
|
||||
public boolean execute(CommandSender sender, @NotNull String label, String[] args) {
|
||||
|
||||
if (!sender.hasPermission(PERMISSION)) {
|
||||
ExpansionUtils.sendMsg(sender, "&cYou don't have permission to do that!");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (args.length == 0) {
|
||||
sendHelp(sender);
|
||||
return true;
|
||||
}
|
||||
|
||||
ICommand command = null;
|
||||
for (ICommand icmd : subCommands) {
|
||||
if (icmd.getAlias().equalsIgnoreCase(args[0])) {
|
||||
command = icmd;
|
||||
command.command = getName();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (command == null) {
|
||||
ExpansionUtils.sendMsg(sender, "&cInvalid expansion sub-command! Type&f /" + getName() + " &cfor help");
|
||||
return true;
|
||||
}
|
||||
|
||||
command.execute(sender, sliceFirstArr(args));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//TODO: This thing here has to be organized thoroughly later...
|
||||
@Override
|
||||
public List<String> tabComplete(CommandSender sender, @NotNull String alias, String[] args) throws IllegalArgumentException {
|
||||
if (!sender.hasPermission(PERMISSION)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
@ -88,207 +135,30 @@ public class JavascriptExpansionCommands extends Command {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean execute(CommandSender sender, String label, String[] args) {
|
||||
if (!sender.hasPermission(PERMISSION)) {
|
||||
msg(sender, "&cYou don't have permission to do that!");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (args.length == 0) {
|
||||
msg(sender,
|
||||
private void sendHelp(CommandSender sender) {
|
||||
ExpansionUtils.sendMsg(sender,
|
||||
"&eJavascript expansion &7v: &f" + expansion.getVersion(),
|
||||
"&eCreated by: &f" + expansion.getAuthor(),
|
||||
"&eWiki: &fhttps://github.com/PlaceholderAPI/Javascript-Expansion/wiki",
|
||||
"&r",
|
||||
"&e/" + command + " reload &7- &fReload your javascripts without reloading PlaceholderAPI.",
|
||||
"&e/" + command + " list &7- &fList loaded script identifiers.",
|
||||
"&e/" + command + " parse [me/player] [code] &7- &fTest JavaScript code in chat."
|
||||
"&e/" + command + " parse [me/player] [code] &7- &fTest JavaScript code in chat.",
|
||||
"&e/" + command + " debug [savedata/loaddata] [identifier] &7- &fTest JavaScript code in chat."
|
||||
);
|
||||
|
||||
if (expansion.getGithubScriptManager() != null) {
|
||||
msg(sender,
|
||||
ExpansionUtils.sendMsg(sender,
|
||||
"&e/" + command + " git refresh &7- &fRefresh available Github scripts",
|
||||
"&e/" + command + " git download [name] &7- &fDownload a script from the js expansion github.",
|
||||
"&e/" + command + " git list &7- &fList available scripts in the js expansion github.",
|
||||
"&e/" + command + " git info [name] &7- &fGet the description and url of a specific script."
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
switch (args[0].toLowerCase()) {
|
||||
case "git": {
|
||||
if (expansion.getGithubScriptManager() == null) {
|
||||
msg(sender, "&cThis feature is disabled in the PlaceholderAPI config.");
|
||||
return true;
|
||||
public String[] sliceFirstArr(String[] args) {
|
||||
return Arrays.stream(args).skip(1).toArray(String[]::new);
|
||||
}
|
||||
|
||||
if (args.length < 2) {
|
||||
msg(sender, "&cIncorrect usage! Type '&f/" + command + "&c' for more help.");
|
||||
return true;
|
||||
}
|
||||
|
||||
final GithubScriptManager manager = expansion.getGithubScriptManager();
|
||||
|
||||
switch (args[1].toLowerCase()) {
|
||||
case "refresh": {
|
||||
expansion.getGithubScriptManager().fetch();
|
||||
msg(sender, "&aFetching available scripts... Check back in a sec!");
|
||||
return true;
|
||||
}
|
||||
|
||||
case "list": {
|
||||
final List<GithubScript> availableScripts = manager.getAvailableScripts();
|
||||
final Set<String> scripts = availableScripts.stream().map(GithubScript::getName).collect(Collectors.toSet());
|
||||
|
||||
msg(sender, availableScripts.size() + " &escript" + plural(availableScripts.size()) + " available on Github.", String.join(", ", scripts));
|
||||
return true;
|
||||
}
|
||||
|
||||
case "info": {
|
||||
if (args.length < 3) {
|
||||
msg(sender, "&cIncorrect usage! &f/" + command + " git info [name]");
|
||||
return true;
|
||||
}
|
||||
|
||||
final GithubScript script = manager.getScript(args[2]);
|
||||
|
||||
if (script == null) {
|
||||
msg(sender, "&cThe script &f" + args[2] + " &cdoes not exist!");
|
||||
return true;
|
||||
}
|
||||
|
||||
msg(sender,
|
||||
"&eName: &f" + script.getName(),
|
||||
"&eVersion: &f" + script.getVersion(),
|
||||
"&eDescription: &f" + script.getDescription(),
|
||||
"&eAuthor: &f" + script.getAuthor(),
|
||||
"&eSource URL: &f" + script.getUrl()
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
case "download": {
|
||||
if (args.length < 3) {
|
||||
msg(sender, "&cIncorrect usage! &f/" + command + " git download [name]");
|
||||
return true;
|
||||
}
|
||||
|
||||
final GithubScript script = manager.getScript(args[2]);
|
||||
|
||||
if (script == null) {
|
||||
msg(sender, "&cThe script &f" + args[2] + " &cdoes not exist!");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (new File(expansion.getGithubScriptManager().getJavascriptsFolder(), script.getName() + ".js").exists()) {
|
||||
msg(sender, "&cCould not download " + script.getName() + " because a file with the same name already exist in the javascripts folder.");
|
||||
return true;
|
||||
}
|
||||
|
||||
manager.downloadScript(script);
|
||||
msg(sender, "&aDownload started. &eCheck the scripts folder in a moment...");
|
||||
return true;
|
||||
}
|
||||
|
||||
case "enabled":
|
||||
if (args.length < 3) {
|
||||
msg(sender, "&cIncorrect usage! &f/" + command + " git enabled [true/false]");
|
||||
return true;
|
||||
}
|
||||
|
||||
final boolean enabled = Boolean.parseBoolean(args[2]);
|
||||
final PlaceholderAPIPlugin papi = expansion.getPlaceholderAPI();
|
||||
|
||||
papi.getConfig().set("expansions." + this.getName() + ".github_script_downloads", enabled);
|
||||
papi.saveConfig();
|
||||
papi.reloadConfig();
|
||||
|
||||
if (!enabled) {
|
||||
if (expansion.getGithubScriptManager() != null) {
|
||||
expansion.getGithubScriptManager().clear();
|
||||
expansion.setGithubScriptManager(null);
|
||||
}
|
||||
} else {
|
||||
if (expansion.getGithubScriptManager() == null) {
|
||||
expansion.setGithubScriptManager(new GithubScriptManager(expansion));
|
||||
}
|
||||
expansion.getGithubScriptManager().fetch();
|
||||
}
|
||||
|
||||
msg(sender, "&6Git script downloads set to: &e" + enabled);
|
||||
return true;
|
||||
|
||||
default: {
|
||||
msg(sender, "&cIncorrect usage! Type '&f/" + command + "&c' for more help.");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case "list": {
|
||||
final List<String> loaded = expansion.getLoadedIdentifiers();
|
||||
msg(sender,
|
||||
loaded.size() + " &7script" + plural(loaded.size()) + " loaded.",
|
||||
String.join(", ", loaded)
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
case "parse": {
|
||||
if (args.length < 3) {
|
||||
msg(sender, "&cIncorrect usage! &f/" + command + " parse [me/player] [code]");
|
||||
return true;
|
||||
}
|
||||
|
||||
final String script = String.join(" ", Arrays.copyOfRange(args, 2, args.length));
|
||||
final JavascriptPlaceholder placeholder = new JavascriptPlaceholder(expansion.getGlobalEngine(), "parse-command", String.join(" ", script));
|
||||
|
||||
if ("me".equalsIgnoreCase(args[1])) {
|
||||
if (!(sender instanceof Player)) {
|
||||
msg(sender, "&cOnly players can run this command!");
|
||||
return true;
|
||||
}
|
||||
|
||||
sender.sendMessage(placeholder.evaluate((Player) sender));
|
||||
return true;
|
||||
}
|
||||
|
||||
final OfflinePlayer player = Bukkit.getOfflinePlayer(args[1]);
|
||||
|
||||
if (!player.hasPlayedBefore() || player.getName() == null) {
|
||||
msg(sender, "&cUnknown player " + args[1]);
|
||||
return true;
|
||||
}
|
||||
|
||||
sender.sendMessage(placeholder.evaluate(player));
|
||||
return true;
|
||||
}
|
||||
|
||||
case "reload": {
|
||||
msg(sender, "&aJavascriptExpansion reloading...");
|
||||
final int scripts = expansion.reloadScripts();
|
||||
msg(sender, scripts + " &7script" + plural(scripts) + " loaded");
|
||||
return true;
|
||||
}
|
||||
|
||||
default: {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String plural(final int amount) {
|
||||
return amount > 1 ? "s" : "";
|
||||
}
|
||||
|
||||
public void msg(CommandSender sender, String... text) {
|
||||
if (text == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', Arrays.stream(text).filter(Objects::nonNull).collect(Collectors.joining("\n"))));
|
||||
}
|
||||
}
|
||||
|
@ -33,51 +33,66 @@ import javax.script.ScriptException;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class JavascriptPlaceholder {
|
||||
|
||||
private final String DIRECTORY = PlaceholderAPIPlugin.getInstance().getDataFolder() + "/javascripts/javascript_data";
|
||||
private final ScriptEngine engine;
|
||||
private final String identifier;
|
||||
private final String script;
|
||||
private ScriptData scriptData;
|
||||
private final File dataFile;
|
||||
private YamlConfiguration yaml;
|
||||
private final Pattern pattern;
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored")
|
||||
public JavascriptPlaceholder(ScriptEngine engine, String identifier, String script) {
|
||||
Validate.notNull(engine, "ScriptEngine can not be null");
|
||||
Validate.notNull(identifier, "Identifier can not be null");
|
||||
Validate.notNull(script, "Script can not be null");
|
||||
|
||||
String dir = PlaceholderAPIPlugin.getInstance().getDataFolder() + "/javascripts/javascript_data";
|
||||
this.engine = engine;
|
||||
this.identifier = identifier;
|
||||
this.script = script;
|
||||
final File directory = new File(DIRECTORY);
|
||||
final File directory = new File(dir);
|
||||
|
||||
if (!directory.exists()) {
|
||||
directory.mkdirs();
|
||||
}
|
||||
|
||||
pattern = Pattern.compile("//.*|/\\*[\\S\\s]*?\\*/|%([^%]+)%");
|
||||
scriptData = new ScriptData();
|
||||
dataFile = new File(directory, identifier + "_data.yml");
|
||||
engine.put("Data", scriptData);
|
||||
engine.put("DataVar", scriptData.getData());
|
||||
engine.put("BukkitServer", Bukkit.getServer());
|
||||
engine.put("Expansion", JavascriptExpansion.getInstance());
|
||||
engine.put("Placeholder", this);
|
||||
engine.put("PlaceholderAPI", PlaceholderAPI.class);
|
||||
|
||||
}
|
||||
|
||||
public String getIdentifier() {
|
||||
return identifier;
|
||||
}
|
||||
|
||||
public String getScript() {
|
||||
return script;
|
||||
public String evaluate(OfflinePlayer player, String... args) {
|
||||
|
||||
// A checker to deny all placeholders inside comment codes
|
||||
Matcher matcher = pattern.matcher(script);
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
|
||||
while (matcher.find()) {
|
||||
String matched = matcher.group(0);
|
||||
if (!matched.startsWith("%") || matched.startsWith("/*") || matched.startsWith("//")) continue;
|
||||
|
||||
matcher.appendReplacement(buffer, PlaceholderAPI.setPlaceholders(player, matched));
|
||||
}
|
||||
|
||||
public String evaluate(OfflinePlayer player, String... args) {
|
||||
String exp = PlaceholderAPI.setPlaceholders(player, script);
|
||||
matcher.appendTail(buffer);
|
||||
String exp = buffer.toString();
|
||||
|
||||
try {
|
||||
String[] arguments = null;
|
||||
@ -89,7 +104,6 @@ public class JavascriptPlaceholder {
|
||||
if (args[i] == null || args[i].isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
arguments[i] = PlaceholderAPI.setBracketPlaceholders(player, args[i]);
|
||||
}
|
||||
}
|
||||
@ -108,15 +122,20 @@ public class JavascriptPlaceholder {
|
||||
engine.put("OfflinePlayer", player);
|
||||
Object result = engine.eval(exp);
|
||||
return result != null ? PlaceholderAPI.setBracketPlaceholders(player, result.toString()) : "";
|
||||
|
||||
} catch (ScriptException ex) {
|
||||
PlaceholderAPIPlugin.getInstance().getLogger().log(Level.SEVERE, "[JavaScript] An error occurred while executing the script '" + identifier + "'", ex);
|
||||
ExpansionUtils.errorLog("An error occurred while executing the script '" + identifier + "':\n\t" + ex.getMessage(), null);
|
||||
} catch (ArrayIndexOutOfBoundsException ex) {
|
||||
ExpansionUtils.errorLog("Argument out of bound while executing script '" + identifier + "':\n\t" + ex.getMessage(), null);
|
||||
}
|
||||
return "Script error (check console)";
|
||||
}
|
||||
|
||||
return "Script error! (check console)";
|
||||
public String getScript() {
|
||||
return script;
|
||||
}
|
||||
|
||||
public ScriptData getData() {
|
||||
// this should never be null but just in case setData(null) is called
|
||||
if (scriptData == null) {
|
||||
scriptData = new ScriptData();
|
||||
}
|
||||
@ -127,6 +146,7 @@ public class JavascriptPlaceholder {
|
||||
this.scriptData = data;
|
||||
}
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored")
|
||||
public boolean loadData() {
|
||||
yaml = new YamlConfiguration();
|
||||
dataFile.getParentFile().mkdirs();
|
||||
@ -135,7 +155,7 @@ public class JavascriptPlaceholder {
|
||||
try {
|
||||
dataFile.createNewFile();
|
||||
} catch (IOException e) {
|
||||
PlaceholderAPIPlugin.getInstance().getLogger().log(Level.SEVERE, "[JavaScript Expansion] An error occurred while creating data file for " + getIdentifier(), e);
|
||||
ExpansionUtils.errorLog("An error occurred while creating data file for " + getIdentifier(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@ -143,7 +163,7 @@ public class JavascriptPlaceholder {
|
||||
try {
|
||||
yaml.load(dataFile);
|
||||
} catch (IOException | InvalidConfigurationException e) {
|
||||
PlaceholderAPIPlugin.getInstance().getLogger().log(Level.SEVERE, "[JavaScript Expansion] An error occurred while loading for " + getIdentifier(), e);
|
||||
ExpansionUtils.errorLog("An error occurred while loading for " + getIdentifier(), e);
|
||||
return false;
|
||||
}
|
||||
|
||||
@ -153,35 +173,32 @@ public class JavascriptPlaceholder {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (scriptData == null) {
|
||||
if (scriptData == null)
|
||||
scriptData = new ScriptData();
|
||||
} else {
|
||||
scriptData.clear();
|
||||
}
|
||||
else scriptData.clear();
|
||||
|
||||
keys.forEach(key -> scriptData.set(key, yaml.get(key)));
|
||||
keys.forEach(key -> scriptData.set(key, ExpansionUtils.ymlToJavaObj(yaml.get(key))));
|
||||
|
||||
if (!scriptData.isEmpty()) {
|
||||
this.setData(scriptData);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean saveData() {
|
||||
public void saveData() {
|
||||
if (scriptData == null || scriptData.isEmpty() || yaml == null) {
|
||||
return false;
|
||||
return;
|
||||
}
|
||||
|
||||
scriptData.getData().forEach((key, value) -> yaml.set(key, value));
|
||||
// Function for merging JSON.
|
||||
// TODO: This will be removed along with Nashorn in a later future
|
||||
scriptData.getData().forEach((key, value) -> yaml.set(key, ExpansionUtils.jsonToJava(value)));
|
||||
|
||||
try {
|
||||
yaml.save(dataFile);
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
PlaceholderAPIPlugin.getInstance().getLogger().log(Level.SEVERE, "[JavaScript Expansion] An error occurred while saving data for " + getIdentifier(), e);
|
||||
return false;
|
||||
ExpansionUtils.errorLog(ExpansionUtils.PREFIX + "An error occurred while saving data for " + getIdentifier(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@ -190,7 +207,6 @@ public class JavascriptPlaceholder {
|
||||
this.scriptData.clear();
|
||||
this.scriptData = null;
|
||||
}
|
||||
|
||||
this.yaml = null;
|
||||
}
|
||||
}
|
||||
|
@ -27,19 +27,15 @@ import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import javax.script.ScriptEngine;
|
||||
import javax.script.ScriptEngineManager;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.util.Scanner;
|
||||
import java.util.logging.Level;
|
||||
import java.nio.file.Files;
|
||||
import java.util.List;
|
||||
|
||||
public class JavascriptPlaceholdersConfig {
|
||||
|
||||
private JavascriptExpansion ex;
|
||||
|
||||
private PlaceholderAPIPlugin plugin;
|
||||
|
||||
private final JavascriptExpansion ex;
|
||||
private final PlaceholderAPIPlugin plugin;
|
||||
private FileConfiguration config;
|
||||
|
||||
private File file;
|
||||
|
||||
public JavascriptPlaceholdersConfig(JavascriptExpansion ex) {
|
||||
@ -83,31 +79,30 @@ public class JavascriptPlaceholdersConfig {
|
||||
|
||||
if (config.getKeys(false).isEmpty()) {
|
||||
config.set("example.file", "example.js");
|
||||
config.set("example.engine", "nashorn");
|
||||
config.set("example.engine", ExpansionUtils.DEFAULT_ENGINE);
|
||||
}
|
||||
|
||||
save();
|
||||
}
|
||||
|
||||
public FileConfiguration load() {
|
||||
if (config == null) {
|
||||
reload();
|
||||
}
|
||||
if (config == null) reload();
|
||||
return config;
|
||||
}
|
||||
|
||||
public void save() {
|
||||
if ((config == null) || (file == null)) {
|
||||
if (config == null || file == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
load().save(file);
|
||||
} catch (IOException ex) {
|
||||
plugin.getLogger().log(Level.SEVERE, "Could not save to " + file, ex);
|
||||
ExpansionUtils.warnLog("Could not save to " + file, ex);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored")
|
||||
public int loadPlaceholders() {
|
||||
if (config == null || config.getKeys(false).isEmpty()) {
|
||||
return 0;
|
||||
@ -118,55 +113,56 @@ public class JavascriptPlaceholdersConfig {
|
||||
try {
|
||||
if (!directory.exists()) {
|
||||
directory.mkdirs();
|
||||
plugin.getLogger().info("[JavaScript Expansion] Creating directory: " + directory.getPath());
|
||||
ExpansionUtils.infoLog("Creating directory: " + directory.getPath());
|
||||
}
|
||||
} catch (SecurityException e) {
|
||||
plugin.getLogger().log(Level.SEVERE, "[JavaScript Expansion] Could not create directory: " + directory.getPath(), e);
|
||||
ExpansionUtils.errorLog("Could not create directory: " + directory.getPath(), e);
|
||||
}
|
||||
|
||||
for (String identifier : config.getKeys(false)) {
|
||||
if (!config.contains(identifier + ".file") || config.getString(identifier + ".file") == null) {
|
||||
plugin.getLogger().warning("[JavaScript Expansion] Javascript placeholder: " + identifier + " does not have a file specified");
|
||||
final String fileName = config.getString(identifier + ".file");
|
||||
if (!config.contains(identifier + ".file") || fileName == null) {
|
||||
ExpansionUtils.warnLog("Javascript placeholder: " + identifier + " does not have a file specified", null);
|
||||
continue;
|
||||
}
|
||||
|
||||
File scriptFile = new File(plugin.getDataFolder() + "/javascripts", config.getString(identifier + ".file"));
|
||||
final File scriptFile = new File(plugin.getDataFolder() + "/javascripts", fileName);
|
||||
|
||||
if (!scriptFile.exists()) {
|
||||
plugin.getLogger().info("[JavaScript Expansion] " +scriptFile.getName() + " does not exist. Creating file...");
|
||||
ExpansionUtils.infoLog(scriptFile.getName() + " does not exist. Creating one for you...");
|
||||
|
||||
try {
|
||||
scriptFile.createNewFile();
|
||||
plugin.getLogger().info("[JavaScript Expansion] " + scriptFile.getName() + " created! Add your javascript to this file and use '/jsexpansion reload' to load it!");
|
||||
ExpansionUtils.infoLog(scriptFile.getName() + " created! Add your javascript to this file and use '/jsexpansion reload' to load it!");
|
||||
} catch (IOException e) {
|
||||
plugin.getLogger().log(Level.SEVERE, "[JavaScript Expansion] An error occurred while creating " + scriptFile.getName(), e);
|
||||
ExpansionUtils.errorLog("An error occurred while creating " + scriptFile.getName(), e);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
String script = getContents(scriptFile);
|
||||
final String script = getContents(scriptFile);
|
||||
|
||||
if (script == null || script.isEmpty()) {
|
||||
plugin.getLogger().warning("[JavaScript Expansion] File: " + scriptFile.getName() + " for javascript placeholder: " + identifier + " is empty");
|
||||
ExpansionUtils.warnLog("File: " + scriptFile.getName() + " for Javascript placeholder: " + identifier + " is empty", null);
|
||||
continue;
|
||||
}
|
||||
|
||||
ScriptEngine engine;
|
||||
|
||||
if (!config.contains(identifier + ".engine")) {
|
||||
engine = ex.getGlobalEngine();
|
||||
ExpansionUtils.warnLog("ScriptEngine type for javascript placeholder " + identifier + " isn't initialized! Defaulting to global", null);
|
||||
} else {
|
||||
try {
|
||||
engine = new ScriptEngineManager(null).getEngineByName(config.getString(identifier + ".engine", "nashorn"));
|
||||
} catch (NullPointerException e) {
|
||||
plugin.getLogger().warning("[JavaScript Expansion] ScriptEngine type for javascript placeholder: " + identifier + " is invalid! Defaulting to global");
|
||||
ExpansionUtils.warnLog("ScriptEngine type for javascript placeholder: " + identifier + " is invalid! Defaulting to global", null);
|
||||
engine = ex.getGlobalEngine();
|
||||
}
|
||||
}
|
||||
|
||||
if (engine == null) {
|
||||
plugin.getLogger().warning("[JavaScript Expansion] Failed to set ScriptEngine for javascript placeholder: " + identifier);
|
||||
ExpansionUtils.warnLog("Failed to set ScriptEngine for javascript placeholder: " + identifier, null);
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -175,15 +171,14 @@ public class JavascriptPlaceholdersConfig {
|
||||
|
||||
if (added) {
|
||||
if (placeholder.loadData()) {
|
||||
plugin.getLogger().info("[JavaScript Expansion] Loaded data for javascript placeholder: " + identifier);
|
||||
ExpansionUtils.infoLog("Data for placeholder &b" + identifier + "&r has been loaded");
|
||||
}
|
||||
|
||||
plugin.getLogger().info("[JavaScript Expansion] %javascript_" + identifier + "% has been loaded!");
|
||||
ExpansionUtils.infoLog("Placeholder &b%javascript_" + identifier + "%&r has been loaded");
|
||||
} else {
|
||||
plugin.getLogger().warning("[JavaScript Expansion] Javascript placeholder %javascript_" + identifier + "% is a duplicate!");
|
||||
ExpansionUtils.warnLog("Javascript placeholder %javascript_" + identifier + "% is duplicated!", null);
|
||||
}
|
||||
}
|
||||
|
||||
return ex.getAmountLoaded();
|
||||
}
|
||||
|
||||
@ -191,31 +186,14 @@ public class JavascriptPlaceholdersConfig {
|
||||
final StringBuilder sb = new StringBuilder();
|
||||
|
||||
try {
|
||||
Scanner scanner = new Scanner(file);
|
||||
|
||||
while (scanner.hasNextLine()) {
|
||||
String line = scanner.nextLine();
|
||||
|
||||
if (line == null || line.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
line = line.trim();
|
||||
|
||||
/* temp fix for single line comments
|
||||
* doesnt solve every case though..
|
||||
* lines that start with code and may have a comment afterward still screw stuff up...
|
||||
*/
|
||||
if (line.startsWith("//")) {
|
||||
continue;
|
||||
}
|
||||
sb.append(line).append(" ");
|
||||
}
|
||||
scanner.close();
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
List<String> lines = Files.readAllLines(file.toPath());
|
||||
lines.forEach((line) -> sb.append(line).append("\n"));
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// This thing is just in case, who needs it now..
|
||||
// return sb.toString().replaceAll("//.*|/\\*(?:[^/*|*/]|\\\\.|\\n\\*)*\\*/", "");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
@ -56,7 +56,11 @@ public class ScriptData {
|
||||
}
|
||||
|
||||
public void set(String key, Object value) {
|
||||
map.put(key, value);
|
||||
map.put(key, ExpansionUtils.jsonToJava(value));
|
||||
}
|
||||
|
||||
public void setIfNull(String key, Object value) {
|
||||
map.putIfAbsent(key, ExpansionUtils.jsonToJava(value));
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
|
@ -20,9 +20,12 @@
|
||||
*/
|
||||
package com.extendedclip.papi.expansion.javascript.cloud;
|
||||
|
||||
import com.extendedclip.papi.expansion.javascript.ExpansionUtils;
|
||||
import com.extendedclip.papi.expansion.javascript.JavascriptExpansion;
|
||||
import com.extendedclip.papi.expansion.javascript.JavascriptPlaceholdersConfig;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import jdk.nashorn.api.scripting.ScriptUtils;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import java.io.*;
|
||||
@ -35,7 +38,7 @@ import java.util.stream.Collectors;
|
||||
|
||||
public class GithubScriptManager {
|
||||
|
||||
private JavascriptExpansion expansion;
|
||||
private final JavascriptExpansion expansion;
|
||||
private final String JAVASCRIPTS_FOLDER;
|
||||
private List<GithubScript> availableScripts;
|
||||
private final String MASTER_LIST_URL = "https://raw.githubusercontent.com/PlaceholderAPI/Javascript-Expansion/master/scripts/master_list.json";
|
||||
@ -65,7 +68,6 @@ public class GithubScriptManager {
|
||||
});
|
||||
}
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored")
|
||||
public void downloadScript(GithubScript script) {
|
||||
Bukkit.getScheduler().runTaskAsynchronously(expansion.getPlaceholderAPI(), () -> {
|
||||
final List<String> contents = read(script.getUrl());
|
||||
@ -77,13 +79,16 @@ public class GithubScriptManager {
|
||||
try (final PrintStream out = new PrintStream(new FileOutputStream(new File(JAVASCRIPTS_FOLDER, script.getName() + ".js")))) {
|
||||
contents.forEach(out::println);
|
||||
} catch (FileNotFoundException e) {
|
||||
expansion.getPlaceholderAPI().getLogger().log(Level.SEVERE, "An error occurred while downloading " + script.getName(), e);
|
||||
ExpansionUtils.errorLog("An error occurred while downloading " + script.getName(), e);
|
||||
return;
|
||||
}
|
||||
|
||||
Bukkit.getScheduler().runTask(expansion.getPlaceholderAPI(), () -> {
|
||||
expansion.getConfig().load().set(script.getName() + ".file", script.getName() + ".js");
|
||||
expansion.getConfig().save();
|
||||
JavascriptPlaceholdersConfig config = expansion.getConfig();
|
||||
config.load().set(script.getName() + ".file", script.getName() + ".js");
|
||||
config.load().set(script.getName() + ".engine", "javascript");
|
||||
|
||||
config.save();
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -97,14 +102,6 @@ public class GithubScriptManager {
|
||||
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()))) {
|
||||
lines.addAll(reader.lines().filter(Objects::nonNull).collect(Collectors.toList()));
|
||||
/*
|
||||
String inputLine;
|
||||
|
||||
while ((inputLine = reader.readLine()) != null) {
|
||||
lines.add(inputLine);
|
||||
}
|
||||
|
||||
*/
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
|
@ -0,0 +1,50 @@
|
||||
package com.extendedclip.papi.expansion.javascript.command;
|
||||
|
||||
import com.extendedclip.papi.expansion.javascript.ExpansionUtils;
|
||||
import com.extendedclip.papi.expansion.javascript.JavascriptExpansion;
|
||||
import com.extendedclip.papi.expansion.javascript.JavascriptPlaceholder;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class DebugCommand extends ICommand {
|
||||
|
||||
private final JavascriptExpansion expansion;
|
||||
|
||||
public DebugCommand(JavascriptExpansion expansion) {
|
||||
this.expansion = expansion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandSender sender, String[] args) {
|
||||
if (args.length < 2) {
|
||||
ExpansionUtils.sendMsg(sender, "&cIncorrect usage! Type '&f/" + command + "&c' for more help.");
|
||||
return;
|
||||
}
|
||||
|
||||
JavascriptPlaceholder jsp = expansion.getJSPlaceholder(getIdentifier(args));
|
||||
if (jsp == null) {
|
||||
ExpansionUtils.sendMsg(sender, "&cInvalid javascript identifier! Please re-check your typo");
|
||||
return;
|
||||
}
|
||||
|
||||
if (args[0].equals("savedata")) {
|
||||
jsp.saveData();
|
||||
ExpansionUtils.sendMsg(sender, "&aJavascript data '" + args[1] + "' successfully saved");
|
||||
} else if (args[0].equals("loaddata")) {
|
||||
jsp.loadData();
|
||||
ExpansionUtils.sendMsg(sender, "&aJavascript data '" + args[1] + "' successfully loaded");
|
||||
}
|
||||
}
|
||||
|
||||
public String getIdentifier(String[] args) {
|
||||
return Arrays.stream(args).skip(1).collect(Collectors.joining(" "));
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getAlias() {
|
||||
return "debug";
|
||||
}
|
||||
}
|
@ -0,0 +1,142 @@
|
||||
package com.extendedclip.papi.expansion.javascript.command;
|
||||
|
||||
import com.extendedclip.papi.expansion.javascript.ExpansionUtils;
|
||||
import com.extendedclip.papi.expansion.javascript.JavascriptExpansion;
|
||||
import com.extendedclip.papi.expansion.javascript.cloud.GithubScript;
|
||||
import com.extendedclip.papi.expansion.javascript.cloud.GithubScriptManager;
|
||||
import me.clip.placeholderapi.PlaceholderAPIPlugin;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class GitCommand extends ICommand {
|
||||
|
||||
private final JavascriptExpansion expansion;
|
||||
|
||||
public GitCommand(JavascriptExpansion expansion) {
|
||||
this.expansion = expansion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandSender sender, String[] args) {
|
||||
|
||||
if (expansion.getGithubScriptManager() == null) {
|
||||
ExpansionUtils.sendMsg(sender, "&cThis feature is disabled in the PlaceholderAPI config.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (args.length < 1) {
|
||||
ExpansionUtils.sendMsg(sender, "&cIncorrect usage! Type '&f/" + command + "&c' for more help.");
|
||||
return;
|
||||
}
|
||||
|
||||
final GithubScriptManager manager = expansion.getGithubScriptManager();
|
||||
|
||||
switch (args[0].toLowerCase()) {
|
||||
case "refresh": {
|
||||
expansion.getGithubScriptManager().fetch();
|
||||
ExpansionUtils.sendMsg(sender, "&aFetching available scripts... Check back in a sec!");
|
||||
return;
|
||||
}
|
||||
|
||||
case "list": {
|
||||
final List<GithubScript> availableScripts = manager.getAvailableScripts();
|
||||
final Set<String> scripts = availableScripts.stream().map(GithubScript::getName).collect(Collectors.toSet());
|
||||
|
||||
ExpansionUtils.sendMsg(sender, availableScripts.size() + " &escript" + plural(availableScripts.size()) + " available on Github.", String.join(", ", scripts));
|
||||
return;
|
||||
}
|
||||
|
||||
case "info": {
|
||||
if (args.length < 2) {
|
||||
ExpansionUtils.sendMsg(sender, "&cIncorrect usage! &f/" + command + " git info [name]");
|
||||
return;
|
||||
}
|
||||
|
||||
final GithubScript script = manager.getScript(args[1]);
|
||||
|
||||
if (script == null) {
|
||||
ExpansionUtils.sendMsg(sender, "&cThe script &f" + args[1] + " &cdoes not exist!");
|
||||
return;
|
||||
}
|
||||
|
||||
ExpansionUtils.sendMsg(sender,
|
||||
"&eName: &f" + script.getName(),
|
||||
"&eVersion: &f" + script.getVersion(),
|
||||
"&eDescription: &f" + script.getDescription(),
|
||||
"&eAuthor: &f" + script.getAuthor(),
|
||||
"&eSource URL: &f" + script.getUrl()
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
case "download": {
|
||||
if (args.length < 2) {
|
||||
ExpansionUtils.sendMsg(sender, "&cIncorrect usage! &f/" + command + " git download [name]");
|
||||
return;
|
||||
}
|
||||
|
||||
final GithubScript script = manager.getScript(args[1]);
|
||||
|
||||
if (script == null) {
|
||||
ExpansionUtils.sendMsg(sender, "&cThe script &f" + args[1] + " &cdoes not exist!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (new File(expansion.getGithubScriptManager().getJavascriptsFolder(), script.getName() + ".js").exists()) {
|
||||
ExpansionUtils.sendMsg(sender, "&cCould not download " + script.getName() + " because a file with the same name already exist in the javascripts folder.");
|
||||
return;
|
||||
}
|
||||
|
||||
manager.downloadScript(script);
|
||||
ExpansionUtils.sendMsg(sender, "&aDownload started. &eCheck the scripts folder in a moment...");
|
||||
return;
|
||||
}
|
||||
|
||||
case "enabled":
|
||||
if (args.length < 2) {
|
||||
ExpansionUtils.sendMsg(sender, "&cIncorrect usage! &f/jsexpansion git enabled [true/false]");
|
||||
return;
|
||||
}
|
||||
|
||||
final boolean enabled = Boolean.parseBoolean(args[1]);
|
||||
final PlaceholderAPIPlugin papi = expansion.getPlaceholderAPI();
|
||||
|
||||
papi.getConfig().set("expansions." + command + ".github_script_downloads", enabled);
|
||||
papi.saveConfig();
|
||||
papi.reloadConfig();
|
||||
|
||||
if (!enabled) {
|
||||
if (expansion.getGithubScriptManager() != null) {
|
||||
expansion.getGithubScriptManager().clear();
|
||||
expansion.setGithubScriptManager(null);
|
||||
}
|
||||
} else {
|
||||
if (expansion.getGithubScriptManager() == null) {
|
||||
expansion.setGithubScriptManager(new GithubScriptManager(expansion));
|
||||
}
|
||||
expansion.getGithubScriptManager().fetch();
|
||||
}
|
||||
|
||||
ExpansionUtils.sendMsg(sender, "&6Git script downloads set to: &e" + enabled);
|
||||
return;
|
||||
|
||||
default: {
|
||||
ExpansionUtils.sendMsg(sender, "&cIncorrect usage! Type '&f/" + command + "&c' for more help.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getAlias() {
|
||||
return "git";
|
||||
}
|
||||
|
||||
private String plural(final int amount) {
|
||||
return amount > 1 ? "s" : "";
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.extendedclip.papi.expansion.javascript.command;
|
||||
|
||||
import com.extendedclip.papi.expansion.javascript.ExpansionUtils;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public abstract class ICommand {
|
||||
|
||||
public String command;
|
||||
|
||||
public abstract void execute(CommandSender sender, String[] args);
|
||||
|
||||
public abstract @NotNull String getAlias();
|
||||
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.extendedclip.papi.expansion.javascript.command;
|
||||
|
||||
import com.extendedclip.papi.expansion.javascript.ExpansionUtils;
|
||||
import com.extendedclip.papi.expansion.javascript.JavascriptExpansion;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ListCommand extends ICommand {
|
||||
|
||||
private final JavascriptExpansion expansion;
|
||||
|
||||
public ListCommand(JavascriptExpansion expansion) {
|
||||
this.expansion = expansion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandSender sender, String[] args) {
|
||||
|
||||
final List<String> loaded = expansion.getLoadedIdentifiers();
|
||||
ExpansionUtils.sendMsg(sender,loaded.size() + " &7script" + plural(loaded.size()) + " loaded.",
|
||||
String.join(", ", loaded));
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getAlias() {
|
||||
return "list";
|
||||
}
|
||||
|
||||
private String plural(final int amount) {
|
||||
return amount > 1 ? "s" : "";
|
||||
}
|
||||
}
|
@ -0,0 +1,57 @@
|
||||
package com.extendedclip.papi.expansion.javascript.command;
|
||||
|
||||
import com.extendedclip.papi.expansion.javascript.ExpansionUtils;
|
||||
import com.extendedclip.papi.expansion.javascript.JavascriptExpansion;
|
||||
import com.extendedclip.papi.expansion.javascript.JavascriptPlaceholder;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class ParseCommand extends ICommand {
|
||||
|
||||
private final JavascriptExpansion expansion;
|
||||
|
||||
public ParseCommand(JavascriptExpansion expansion) {
|
||||
this.expansion = expansion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandSender sender, String[] args) {
|
||||
if (args.length < 2) {
|
||||
ExpansionUtils.sendMsg(sender, "&cIncorrect usage! &f/" + command + " parse [me/player] [code]");
|
||||
return;
|
||||
}
|
||||
|
||||
final String script = String.join(" ", Arrays.copyOfRange(args, 1, args.length));
|
||||
final JavascriptPlaceholder placeholder = new JavascriptPlaceholder(expansion.getGlobalEngine(), "parse-command", String.join(" ", script));
|
||||
|
||||
if ("me".equalsIgnoreCase(args[0])) {
|
||||
if (!(sender instanceof Player)) {
|
||||
ExpansionUtils.sendMsg(sender, "&cOnly players can run this command!");
|
||||
return;
|
||||
}
|
||||
|
||||
sender.sendMessage(placeholder.evaluate((Player) sender));
|
||||
return;
|
||||
}
|
||||
|
||||
final OfflinePlayer player = Bukkit.getOfflinePlayer(args[1]);
|
||||
|
||||
if (!player.hasPlayedBefore() || player.getName() == null) {
|
||||
ExpansionUtils.sendMsg(sender, "&cUnknown player " + args[1]);
|
||||
return;
|
||||
}
|
||||
|
||||
sender.sendMessage(placeholder.evaluate(player));
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getAlias() {
|
||||
return "parse";
|
||||
}
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package com.extendedclip.papi.expansion.javascript.command;
|
||||
|
||||
import com.extendedclip.papi.expansion.javascript.ExpansionUtils;
|
||||
import com.extendedclip.papi.expansion.javascript.JavascriptExpansion;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class ReloadCommand extends ICommand {
|
||||
|
||||
private final JavascriptExpansion expansion;
|
||||
|
||||
public ReloadCommand(JavascriptExpansion expansion) {
|
||||
this.expansion = expansion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandSender sender, String[] args) {
|
||||
|
||||
ExpansionUtils.sendMsg(sender, "&aJavascriptExpansion reloading...");
|
||||
final int scripts = expansion.reloadScripts();
|
||||
ExpansionUtils.sendMsg(sender, scripts + " &7script" + plural(scripts) + " loaded");
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getAlias() {
|
||||
return "reload";
|
||||
}
|
||||
|
||||
private String plural(final int amount) {
|
||||
return amount > 1 ? "s" : "";
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user