diff --git a/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptExpansionCommands.java b/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptExpansionCommands.java index bb5a5fe..c7b1b3b 100644 --- a/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptExpansionCommands.java +++ b/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptExpansionCommands.java @@ -1,164 +1,168 @@ -/* - * - * Javascript-Expansion - * Copyright (C) 2020 Ryan McCarthy - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - * - */ -package com.extendedclip.papi.expansion.javascript; - -import com.extendedclip.papi.expansion.javascript.cloud.GithubScript; -import com.extendedclip.papi.expansion.javascript.command.*; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.util.StringUtil; -import org.jetbrains.annotations.NotNull; - -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 { - - private final JavascriptExpansion expansion; - private final String PERMISSION = "placeholderapi.js.admin"; - private final String command; - private List subCommands; - - public JavascriptExpansionCommands(JavascriptExpansion expansion) { - super("jsexpansion"); - command = getName(); - this.expansion = expansion; - this.setDescription("Javascript expansion commands"); - this.setUsage("/" + command + " "); - 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 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 tabComplete(CommandSender sender, @NotNull String alias, String[] args) throws IllegalArgumentException { - if (!sender.hasPermission(PERMISSION)) { - return Collections.emptyList(); - } - - final List commands = new ArrayList<>(Arrays.asList("list", "parse", "reload")); - final List completion = new ArrayList<>(); - - if (expansion.getGithubScriptManager() != null) { - commands.add(0, "git"); - } - - if (args.length == 1) { - return StringUtil.copyPartialMatches(args[0], commands, completion); - } - - if (args[0].equalsIgnoreCase("git")) { - if (expansion.getGithubScriptManager() == null) { - return Collections.emptyList(); - } - - if (args.length == 2) { - return StringUtil.copyPartialMatches(args[1], Arrays.asList("download", "enable", "info", "list", "refresh"), completion); - } - - if (args.length == 3 && args[1].equalsIgnoreCase("download")) { - if (expansion.getGithubScriptManager().getAvailableScripts() == null) { - return Collections.emptyList(); - } - - return StringUtil.copyPartialMatches(args[2], expansion.getGithubScriptManager().getAvailableScripts().stream().map(GithubScript::getName).collect(Collectors.toList()), completion); - } - } - - return Collections.emptyList(); - } - - 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 + " debug [savedata/loaddata] [identifier] &7- &fTest JavaScript code in chat." - ); - - if (expansion.getGithubScriptManager() != null) { - 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." - ); - } - } - - public String[] sliceFirstArr(String[] args) { - return Arrays.stream(args).skip(1).toArray(String[]::new); - } - -} +/* + * + * Javascript-Expansion + * Copyright (C) 2020 Ryan McCarthy + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + */ +package com.extendedclip.papi.expansion.javascript; + +import com.extendedclip.papi.expansion.javascript.cloud.GithubScript; +import com.extendedclip.papi.expansion.javascript.command.*; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; +import org.jetbrains.annotations.NotNull; + +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 { + + private final JavascriptExpansion expansion; + private final String PERMISSION = "placeholderapi.js.admin"; + private final String command; + private List subCommands; + + public JavascriptExpansionCommands(JavascriptExpansion expansion) { + super("jsexpansion"); + command = getName(); + this.expansion = expansion; + this.setDescription("Javascript expansion commands"); + this.setUsage("/" + command + " "); + 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 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 tabComplete(CommandSender sender, @NotNull String alias, String[] args) throws IllegalArgumentException { + if (!sender.hasPermission(PERMISSION)) { + return Collections.emptyList(); + } + + final List commands = new ArrayList<>(Arrays.asList("list", "parse", "reload")); + final List completion = new ArrayList<>(); + + if (expansion.getGithubScriptManager() != null) { + commands.add(0, "git"); + } + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], commands, completion); + } + + if (args[0].equalsIgnoreCase("git")) { + if (expansion.getGithubScriptManager() == null) { + return Collections.emptyList(); + } + + if (args.length == 2) { + return StringUtil.copyPartialMatches(args[1], Arrays.asList("download", "enable", "info", "list", "refresh"), completion); + } + + if (args.length == 3 && args[1].equalsIgnoreCase("download")) { + if (expansion.getGithubScriptManager().getAvailableScripts() == null) { + return Collections.emptyList(); + } + + return StringUtil.copyPartialMatches(args[2], expansion.getGithubScriptManager().getAvailableScripts().stream().map(GithubScript::getName).collect(Collectors.toList()), completion); + } + } + + return Collections.emptyList(); + } + + 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 + " debug [savedata/loaddata] [identifier] &7- &fTest JavaScript code in chat." + ); + + if (expansion.getGithubScriptManager() != null) { + 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." + ); + } else { + ExpansionUtils.sendMsg(sender, + "&e/" + command + " git &7- &fGithub command &7(please enable in config)" + ); + } + } + + public String[] sliceFirstArr(String[] args) { + return Arrays.stream(args).skip(1).toArray(String[]::new); + } + +} diff --git a/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptPlaceholder.java b/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptPlaceholder.java index 336d3b0..5b8e053 100644 --- a/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptPlaceholder.java +++ b/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptPlaceholder.java @@ -1,212 +1,212 @@ -/* - * - * Javascript-Expansion - * Copyright (C) 2020 Ryan McCarthy - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - * - */ -package com.extendedclip.papi.expansion.javascript; - -import me.clip.placeholderapi.PlaceholderAPI; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import org.apache.commons.lang.Validate; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; - -import javax.script.ScriptEngine; -import javax.script.ScriptException; -import java.io.File; -import java.io.IOException; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class JavascriptPlaceholder { - - 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(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 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)); - } - - matcher.appendTail(buffer); - String exp = buffer.toString(); - - try { - String[] arguments = null; - - if (args != null && args.length > 0) { - arguments = new String[args.length]; - - for (int i = 0; i < args.length; i++) { - if (args[i] == null || args[i].isEmpty()) { - continue; - } - arguments[i] = PlaceholderAPI.setBracketPlaceholders(player, args[i]); - } - } - - if (arguments == null) { - arguments = new String[]{}; - } - - engine.put("args", arguments); - - if (player != null && player.isOnline()) { - engine.put("BukkitPlayer", player.getPlayer()); - engine.put("Player", player.getPlayer()); - } - - engine.put("OfflinePlayer", player); - Object result = engine.eval(exp); - return result != null ? PlaceholderAPI.setBracketPlaceholders(player, result.toString()) : ""; - - } catch (ScriptException 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)"; - } - - public String getScript() { - return script; - } - - public ScriptData getData() { - if (scriptData == null) { - scriptData = new ScriptData(); - } - return scriptData; - } - - public void setData(ScriptData data) { - this.scriptData = data; - } - - @SuppressWarnings("ResultOfMethodCallIgnored") - public boolean loadData() { - yaml = new YamlConfiguration(); - dataFile.getParentFile().mkdirs(); - - if (!dataFile.exists()) { - try { - dataFile.createNewFile(); - } catch (IOException e) { - ExpansionUtils.errorLog("An error occurred while creating data file for " + getIdentifier(), e); - return false; - } - } - - try { - yaml.load(dataFile); - } catch (IOException | InvalidConfigurationException e) { - ExpansionUtils.errorLog("An error occurred while loading for " + getIdentifier(), e); - return false; - } - - final Set keys = yaml.getKeys(true); - - if (keys.size() == 0) { - return false; - } - - if (scriptData == null) - scriptData = new ScriptData(); - else scriptData.clear(); - - keys.forEach(key -> scriptData.set(key, ExpansionUtils.ymlToJavaObj(yaml.get(key)))); - - if (!scriptData.isEmpty()) { - this.setData(scriptData); - return true; - } - return false; - } - - public void saveData() { - if (scriptData == null || scriptData.isEmpty() || yaml == null) { - return; - } - - // 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); - } catch (IOException e) { - ExpansionUtils.errorLog(ExpansionUtils.PREFIX + "An error occurred while saving data for " + getIdentifier(), e); - } - } - - public void cleanup() { - if (this.scriptData != null) { - this.scriptData.clear(); - this.scriptData = null; - } - this.yaml = null; - } -} +/* + * + * Javascript-Expansion + * Copyright (C) 2020 Ryan McCarthy + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + */ +package com.extendedclip.papi.expansion.javascript; + +import me.clip.placeholderapi.PlaceholderAPI; +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; + +import javax.script.ScriptEngine; +import javax.script.ScriptException; +import java.io.File; +import java.io.IOException; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class JavascriptPlaceholder { + + 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(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 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)); + } + + matcher.appendTail(buffer); + String exp = buffer.toString(); + + try { + String[] arguments = null; + + if (args != null && args.length > 0) { + arguments = new String[args.length]; + + for (int i = 0; i < args.length; i++) { + if (args[i] == null || args[i].isEmpty()) { + continue; + } + arguments[i] = PlaceholderAPI.setBracketPlaceholders(player, args[i]); + } + } + + if (arguments == null) { + arguments = new String[]{}; + } + + engine.put("args", arguments); + + if (player != null && player.isOnline()) { + engine.put("BukkitPlayer", player.getPlayer()); + engine.put("Player", player.getPlayer()); + } + + engine.put("OfflinePlayer", player); + Object result = engine.eval(exp); + return result != null ? PlaceholderAPI.setBracketPlaceholders(player, result.toString()) : ""; + + } catch (ScriptException 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)"; + } + + public String getScript() { + return script; + } + + public ScriptData getData() { + if (scriptData == null) { + scriptData = new ScriptData(); + } + return scriptData; + } + + public void setData(ScriptData data) { + this.scriptData = data; + } + + @SuppressWarnings("ResultOfMethodCallIgnored") + public boolean loadData() { + yaml = new YamlConfiguration(); + dataFile.getParentFile().mkdirs(); + + if (!dataFile.exists()) { + try { + dataFile.createNewFile(); + } catch (IOException e) { + ExpansionUtils.errorLog("An error occurred while creating data file for " + getIdentifier(), e); + return false; + } + } + + try { + yaml.load(dataFile); + } catch (IOException | InvalidConfigurationException e) { + ExpansionUtils.errorLog("An error occurred while loading for " + getIdentifier(), e); + return false; + } + + final Set keys = yaml.getKeys(true); + + if (keys.size() == 0) { + return false; + } + + if (scriptData == null) + scriptData = new ScriptData(); + else scriptData.clear(); + + keys.forEach(key -> scriptData.set(key, ExpansionUtils.ymlToJavaObj(yaml.get(key)))); + + if (!scriptData.isEmpty()) { + setData(scriptData); + return true; + } + return false; + } + + public void saveData() { + if (scriptData == null || scriptData.isEmpty() || yaml == null) { + return; + } + + // 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); + } catch (IOException e) { + ExpansionUtils.errorLog(ExpansionUtils.PREFIX + "An error occurred while saving data for " + getIdentifier(), e); + } + } + + public void cleanup() { + if (this.scriptData != null) { + this.scriptData.clear(); + this.scriptData = null; + } + this.yaml = null; + } +} diff --git a/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptPlaceholdersConfig.java b/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptPlaceholdersConfig.java index 02cbb38..508462c 100644 --- a/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptPlaceholdersConfig.java +++ b/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptPlaceholdersConfig.java @@ -1,199 +1,213 @@ -/* - * - * Javascript-Expansion - * Copyright (C) 2020 Ryan McCarthy - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - * - */ -package com.extendedclip.papi.expansion.javascript; - -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; - -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.List; - -public class JavascriptPlaceholdersConfig { - - private final JavascriptExpansion ex; - private final PlaceholderAPIPlugin plugin; - private FileConfiguration config; - private File file; - - public JavascriptPlaceholdersConfig(JavascriptExpansion ex) { - this.ex = ex; - plugin = ex.getPlaceholderAPI(); - reload(); - } - - public void reload() { - if (file == null) { - file = new File(plugin.getDataFolder(), "javascript_placeholders.yml"); - } - - config = YamlConfiguration.loadConfiguration(file); - config.options().header("Javascript Expansion: " + ex.getVersion() - + "\nThis is the main configuration file for the Javascript Expansion." - + "\n" - + "\nYou will define your javascript placeholders in this file." - + "\n" - + "\nJavascript files must be located in the:" - + "\n /plugins/placeholderapi/javascripts/ folder" - + "\n" - + "\nA detailed guide on how to create your own javascript placeholders" - + "\ncan be found here:" - + "\nhttps://github.com/PlaceholderAPI-Expansions/Javascript-Expansion/wiki" - + "\n" - + "\nYour javascript placeholders will be identified by: %javascript_%" - + "\n" - + "\nConfiguration format:" - + "\n" - + "\n:" - + "\n file: ." - + "\n engine: (name of script engine)" - + "\n" - + "\n" - + "\nExample:" - + "\n" - + "\n'my_placeholder':" - + "\n file: 'my_placeholder.js'" - + "\n engine: 'nashorn'"); - - if (config.getKeys(false).isEmpty()) { - config.set("example.file", "example.js"); - config.set("example.engine", ExpansionUtils.DEFAULT_ENGINE); - } - - save(); - } - - public FileConfiguration load() { - if (config == null) reload(); - return config; - } - - public void save() { - if (config == null || file == null) { - return; - } - - try { - load().save(file); - } catch (IOException ex) { - ExpansionUtils.warnLog("Could not save to " + file, ex); - } - } - - @SuppressWarnings("ResultOfMethodCallIgnored") - public int loadPlaceholders() { - if (config == null || config.getKeys(false).isEmpty()) { - return 0; - } - - final File directory = new File(plugin.getDataFolder(), "javascripts"); - - try { - if (!directory.exists()) { - directory.mkdirs(); - ExpansionUtils.infoLog("Creating directory: " + directory.getPath()); - } - } catch (SecurityException e) { - ExpansionUtils.errorLog("Could not create directory: " + directory.getPath(), e); - } - - for (String identifier : config.getKeys(false)) { - 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; - } - - final File scriptFile = new File(plugin.getDataFolder() + "/javascripts", fileName); - - if (!scriptFile.exists()) { - ExpansionUtils.infoLog(scriptFile.getName() + " does not exist. Creating one for you..."); - - try { - scriptFile.createNewFile(); - ExpansionUtils.infoLog(scriptFile.getName() + " created! Add your javascript to this file and use '/jsexpansion reload' to load it!"); - } catch (IOException e) { - ExpansionUtils.errorLog("An error occurred while creating " + scriptFile.getName(), e); - } - - continue; - } - - final String script = getContents(scriptFile); - - if (script == null || script.isEmpty()) { - 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) { - ExpansionUtils.warnLog("ScriptEngine type for javascript placeholder: " + identifier + " is invalid! Defaulting to global", null); - engine = ex.getGlobalEngine(); - } - } - - if (engine == null) { - ExpansionUtils.warnLog("Failed to set ScriptEngine for javascript placeholder: " + identifier, null); - continue; - } - - final JavascriptPlaceholder placeholder = new JavascriptPlaceholder(engine, identifier, script); - final boolean added = ex.addJSPlaceholder(placeholder); - - if (added) { - if (placeholder.loadData()) { - ExpansionUtils.infoLog("Data for placeholder &b" + identifier + "&r has been loaded"); - } - - ExpansionUtils.infoLog("Placeholder &b%javascript_" + identifier + "%&r has been loaded"); - } else { - ExpansionUtils.warnLog("Javascript placeholder %javascript_" + identifier + "% is duplicated!", null); - } - } - return ex.getAmountLoaded(); - } - - private String getContents(File file) { - final StringBuilder sb = new StringBuilder(); - - try { - List 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(); - } -} +/* + * + * Javascript-Expansion + * Copyright (C) 2020 Ryan McCarthy + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + */ +package com.extendedclip.papi.expansion.javascript; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.List; + +public class JavascriptPlaceholdersConfig { + + private final JavascriptExpansion ex; + private final PlaceholderAPIPlugin plugin; + private FileConfiguration config; + private File file; + + public JavascriptPlaceholdersConfig(JavascriptExpansion ex) { + this.ex = ex; + plugin = ex.getPlaceholderAPI(); + reload(); + } + + public void reload() { + if (file == null) { + file = new File(plugin.getDataFolder(), "javascript_placeholders.yml"); + } + + config = YamlConfiguration.loadConfiguration(file); + config.options().header("Javascript Expansion: " + ex.getVersion() + + "\nThis is the main configuration file for the Javascript Expansion." + + "\n" + + "\nYou will define your javascript placeholders in this file." + + "\n" + + "\nJavascript files must be located in the:" + + "\n /plugins/placeholderapi/javascripts/ folder" + + "\n" + + "\nA detailed guide on how to create your own javascript placeholders" + + "\ncan be found here:" + + "\nhttps://github.com/PlaceholderAPI-Expansions/Javascript-Expansion/wiki" + + "\n" + + "\nYour javascript placeholders will be identified by: %javascript_%" + + "\n" + + "\nConfiguration format:" + + "\n" + + "\n:" + + "\n file: ." + + "\n engine: (name of script engine)" + + "\n" + + "\n" + + "\nExample:" + + "\n" + + "\n'my_placeholder':" + + "\n file: 'my_placeholder.js'" + + "\n engine: 'nashorn'"); + + if (config.getKeys(false).isEmpty()) { + config.set("example.file", "example.js"); + config.set("example.engine", ExpansionUtils.DEFAULT_ENGINE); + } + + save(); + } + + public FileConfiguration load() { + if (config == null) reload(); + return config; + } + + public void save() { + if (config == null || file == null) { + return; + } + + try { + load().save(file); + } catch (IOException ex) { + ExpansionUtils.warnLog("Could not save to " + file, ex); + } + } + + @SuppressWarnings("ResultOfMethodCallIgnored") + public int loadPlaceholders() { + if (config == null || config.getKeys(false).isEmpty()) { + return 0; + } + + final File directory = new File(plugin.getDataFolder(), "javascripts"); + + try { + if (!directory.exists()) { + directory.mkdirs(); + ExpansionUtils.infoLog("Creating directory: " + directory.getPath()); + } + } catch (SecurityException e) { + ExpansionUtils.errorLog("Could not create directory: " + directory.getPath(), e); + } + + for (String identifier : config.getKeys(false)) { + 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; + } + + final File scriptFile = new File(plugin.getDataFolder() + "/javascripts", fileName); + + if (!scriptFile.exists()) { + ExpansionUtils.infoLog(scriptFile.getName() + " does not exist. Creating one for you..."); + + try { + scriptFile.createNewFile(); + ExpansionUtils.infoLog(scriptFile.getName() + " created! Add your javascript to this file and use '/jsexpansion reload' to load it!"); + } catch (IOException e) { + ExpansionUtils.errorLog("An error occurred while creating " + scriptFile.getName(), e); + } + + continue; + } + + final String script = getContents(scriptFile); + + if (script == null || script.isEmpty()) { + ExpansionUtils.warnLog("File: " + scriptFile.getName() + " for Javascript placeholder: " + identifier + " is empty", null); + continue; + } + + boolean debug = (boolean) ex.get("debug", false); + int errScriptEngine = 0; + + ScriptEngine engine; + if (!config.contains(identifier + ".engine")) { + engine = ex.getGlobalEngine(); + if (debug) { + ExpansionUtils.warnLog("ScriptEngine type for javascript placeholder: " + identifier + " is empty! Defaulting to global", null); + } else { + errScriptEngine++; + } + } else { + try { + engine = new ScriptEngineManager(null).getEngineByName(config.getString(identifier + ".engine", "nashorn")); + } catch (NullPointerException e) { + if (debug) { + ExpansionUtils.warnLog("ScriptEngine type for javascript placeholder: " + identifier + " is invalid! Defaulting to global", null); + } else { + errScriptEngine++; + } + engine = ex.getGlobalEngine(); + } + } + + if (errScriptEngine > 0) { + ExpansionUtils.warnLog("ScriptEngine type for " + errScriptEngine + " javascript placeholder" + ExpansionUtils.plural(errScriptEngine) + + " failed! Defaulting all to global. More information by enabling debug mode", null); + } + + if (engine == null) { + ExpansionUtils.warnLog("Failed to set ScriptEngine for javascript placeholder: " + identifier, null); + continue; + } + + final JavascriptPlaceholder placeholder = new JavascriptPlaceholder(engine, identifier, script); + final boolean added = ex.addJSPlaceholder(placeholder); + + if (added) { + if (placeholder.loadData()) { + ExpansionUtils.infoLog("Data for placeholder &b" + identifier + "&r has been loaded"); + } + + ExpansionUtils.infoLog("Placeholder &b%javascript_" + identifier + "%&r has been loaded"); + } else { + ExpansionUtils.warnLog("Javascript placeholder %javascript_" + identifier + "% is duplicated!", null); + } + } + return ex.getAmountLoaded(); + } + + private String getContents(File file) { + final StringBuilder sb = new StringBuilder(); + + try { + List lines = Files.readAllLines(file.toPath()); + lines.forEach((line) -> sb.append(line).append("\n")); + } catch (IOException e) { + return null; + } + + return sb.toString(); + } +}