diff --git a/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptExpansion.java b/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptExpansion.java index f38847b..5e9dc1e 100644 --- a/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptExpansion.java +++ b/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptExpansion.java @@ -20,10 +20,9 @@ */ package com.extendedclip.papi.expansion.javascript; -import com.extendedclip.papi.expansion.javascript.cloud.GithubScript; import com.extendedclip.papi.expansion.javascript.cloud.GithubScriptManager; +import java.lang.reflect.Field; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -39,14 +38,11 @@ import me.clip.placeholderapi.expansion.Configurable; import me.clip.placeholderapi.expansion.PlaceholderExpansion; import org.bukkit.Bukkit; -import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.command.Command; +import org.bukkit.command.CommandMap; -public class JavascriptExpansion extends PlaceholderExpansion implements Cacheable, Configurable, Listener { +public class JavascriptExpansion extends PlaceholderExpansion implements Cacheable, Configurable { private ScriptEngine globalEngine = null; @@ -54,123 +50,21 @@ public class JavascriptExpansion extends PlaceholderExpansion implements Cacheab private final Set scripts = new HashSet<>(); private final String VERSION = getClass().getPackage().getImplementationVersion(); private static JavascriptExpansion instance; - private boolean debug = false; - private GithubScriptManager githubScripts = null; + private boolean debug; + private GithubScriptManager githubScripts; + private JavascriptExpansionCommands commands; + private CommandMap commandMap; + public JavascriptExpansion() { instance = this; - } - - /* - * I am just testing the waters here because there is no command system for expansions... - */ - @EventHandler - public void onCmdExecute(PlayerCommandPreprocessEvent event) { - - String msg = event.getMessage(); - - if (!msg.startsWith("/papijsp")) { - return; + try { + final Field f = Bukkit.getServer().getClass().getDeclaredField("commandMap"); + f.setAccessible(true); + commandMap = (CommandMap) f.get(Bukkit.getServer()); + } catch (Exception e) { + e.printStackTrace(); } - - if (!event.getPlayer().hasPermission("placeholderapi.admin")) { - return; - } - - event.setCancelled(true); - - Player p = event.getPlayer(); - - // default command - if (!msg.contains(" ")) { - msg(p, "&7Javascript expansion v: &f" + getVersion()); - msg(p, "&7Created by: &f" + getAuthor()); - msg(p, "&fWiki: &ahttps://github.com/PlaceholderAPI-Expansions/Javascript-Expansion/wiki"); - msg(p, "&r"); - msg(p, "&7/papijsp reload &7- &fReload your javascripts without reloading PlaceholderAPI"); - msg(p, "&7/papijsp list &7- &fList loaded script identifiers."); - msg(p, "&7/papijsp git download &7- &fDownload a script from the js expansion github."); - msg(p, "&7/papijsp git list &7- &fList available scripts in the js expansion github."); - msg(p, "&7/papijsp git info (name) &7- &fGet the description and url of a specific script."); - return; - } - - if (msg.equals("/papijsp reload")) { - msg(p, "&aReloading..."); - int l = this.reloadScripts(); - msg(p, l + " &7script" + (l == 1 ? "" : "s")+ " loaded"); - return; - } - - if (msg.equals("/papijsp list")) { - List loaded = this.getLoadedIdentifiers(); - msg(p, loaded.size() + " &7script" + (loaded.size() == 1 ? "" : "s")+ " loaded"); - msg(p, String.join(", ", loaded)); - return; - } - - if (msg.equals("/papijsp git list")) { - msg(p, GithubScript.values().length + " &7script" - + (GithubScript.values().length == 1 ? "" : "s") + " available on Github."); - msg(p, String.join(", ", GithubScript.getAllScriptNames())); - return; - } - - if (msg.startsWith("/papijsp git info ")) { - - if (this.githubScripts == null) { - msg(p, "This feature is disabled in the PAPI config!"); - return; - } - - msg = msg.replace("/papijsp git info ", ""); - - GithubScript script = GithubScript.getScript(msg); - - if (script == null) { - msg(p, "&cThe script &7" + msg + " &cdoes not exist!"); - return; - } - - msg(p, "&7Name: &f" + script.getName(), - "&7Version: &f" + script.getVersion(), - "&7Description: &f" + script.getDescription(), - "&7Url: &f" + script.getUrl()); - - return; - } - - if (msg.startsWith("/papijsp git download ")) { - - if (this.githubScripts == null) { - msg(p, "This feature is disabled in the PAPI config!"); - return; - } - - msg = msg.replace("/papijsp git download ", ""); - - GithubScript script = GithubScript.getScript(msg); - - if (script == null) { - msg(p, "&cThe script &7" + msg + " &cdoes not exist!"); - return; - } - - Bukkit.getScheduler().runTaskAsynchronously(getPlaceholderAPI(), new Runnable() { - @Override - public void run() { - githubScripts.downloadScript(script); - } - }); - msg(p, "&aDownload initiated... Check the scripts folder in a moment..."); - return; - } - - msg(p, "&cIncorrect usage &7- &f/papijsp"); - } - - public void msg(Player p, String... text) { - Arrays.stream(text).forEach(line -> p.sendMessage(ChatColor.translateAlternateColorCodes('&', line))); } @Override @@ -224,16 +118,22 @@ public class JavascriptExpansion extends PlaceholderExpansion implements Cacheab } if ((Boolean) get("github_script_downloads", false)) { githubScripts = new GithubScriptManager(this); + githubScripts.fetch(); } + + registerCommand(); return super.register(); } @Override public void clear() { + unregisterCommand(); scripts.forEach(s -> { s.saveData(); s.cleanup(); }); + githubScripts.clear(); + githubScripts = null; scripts.clear(); globalEngine = null; instance = null; @@ -315,7 +215,7 @@ public class JavascriptExpansion extends PlaceholderExpansion implements Cacheab return def; } - private int reloadScripts() { + protected int reloadScripts() { scripts.forEach(s -> { s.saveData(); s.cleanup(); @@ -328,4 +228,22 @@ public class JavascriptExpansion extends PlaceholderExpansion implements Cacheab public static JavascriptExpansion getInstance() { return instance; } + + public GithubScriptManager getGithubScriptManager() { + return githubScripts; + } + + private boolean unregisterCommand() { + if (commandMap == null || commands == null) return false; + Command c = commandMap.getCommand(commands.getName()); + if (c == null) return false; + return c.unregister(commandMap); + } + + private boolean registerCommand() { + if (commandMap == null) return false; + commands = new JavascriptExpansionCommands(this); + commandMap.register(commands.getName(), commands); + return commands.isRegistered(); + } } diff --git a/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptExpansionCommands.java b/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptExpansionCommands.java new file mode 100644 index 0000000..379cdb2 --- /dev/null +++ b/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptExpansionCommands.java @@ -0,0 +1,128 @@ +package com.extendedclip.papi.expansion.javascript; + +import com.extendedclip.papi.expansion.javascript.cloud.GithubScript; +import com.extendedclip.papi.expansion.javascript.cloud.GithubScriptManager; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +public class JavascriptExpansionCommands extends Command { + + private JavascriptExpansion expansion; + + public JavascriptExpansionCommands(JavascriptExpansion expansion) { + super("jsexpansion"); + this.expansion = expansion; + this.setDescription("Javascript expansion commands"); + this.setUsage("/jsexpansion "); + this.setPermission("placeholderapi.js.admin"); + } + + @Override + public boolean execute(CommandSender s, String label, String[] args) { + if (!s.hasPermission(this.getPermission())) { + msg(s, "&cYou don't have permission to do that!"); + return true; + } + + if (args.length == 0) { + msg(s, "&7Javascript expansion v: &f" + expansion.getVersion(), + "&7Created by: &f" + expansion.getAuthor(), + "&fWiki: &ahttps://github.com/PlaceholderAPI-Expansions/Javascript-Expansion/wiki", + "&r", + "&7/jsexpansion reload &7- &fReload your javascripts without reloading PlaceholderAPI", + "&7/jsexpansion list &7- &fList loaded script identifiers."); + if (expansion.getGithubScriptManager() != null) { + msg(s, + "&7/jsexpansion git download &7- &fDownload a script from the js expansion github."); + msg(s, "&7/jsexpansion git list &7- &fList available scripts in the js expansion github."); + msg(s, + "&7/jsexpansion git info (name) &7- &fGet the description and url of a specific script."); + } + return true; + } + + if (args[0].equalsIgnoreCase("reload")) { + msg(s, "&aJavascriptExpansion reloading..."); + int l = expansion.reloadScripts(); + msg(s, l + " &7script" + (l == 1 ? "" : "s") + " loaded"); + return true; + } + + if (args[0].equalsIgnoreCase("list")) { + List loaded = expansion.getLoadedIdentifiers(); + msg(s, loaded.size() + " &7script" + (loaded.size() == 1 ? "" : "s") + " loaded"); + msg(s, String.join(", ", loaded)); + return true; + } + + if (args[0].equalsIgnoreCase("git")) { + if (expansion.getGithubScriptManager() == null) { + msg(s, "&8This feature is disabled in the PlaceholderAPI config."); + return true; + } + + if (args.length < 2) { + msg(s, "&cIncorrect usage!"); + return true; + } + + GithubScriptManager manager = expansion.getGithubScriptManager(); + + if (args[1].equalsIgnoreCase("list")) { + msg(s, manager.getAvailableScripts().size() + " &escript" + + (manager.getAvailableScripts().size() == 1 ? "" : "s") + " available on Github."); + msg(s, String.join(", ", manager.getAvailableScripts().stream() + .map(GithubScript::getName) + .collect(Collectors.toSet()))); + return true; + } + + if (args[1].equalsIgnoreCase("info")) { + if (args.length < 3) { + msg(s, "&4Incorrect usage! &f" + this.getName() + " git info "); + return true; + } + GithubScript script = manager.getScript(args[2]); + if (script == null) { + msg(s, "&4The script &f" + args[2] + " &4does not exist!"); + return true; + } + msg(s, "&eName: &f" + script.getName(), + "&eVersion: &f" + script.getVersion(), + "&eDescription: &f" + script.getDescription(), + "&eAuthor: &f" + script.getAuthor(), + "&eUrl: &f" + script.getUrl()); + return true; + } + if (args[1].equalsIgnoreCase("download")) { + if (args.length < 3) { + msg(s, "&4Incorrect usage! &f" + this.getName() + " git download "); + return true; + } + GithubScript script = manager.getScript(args[2]); + + if (script == null) { + msg(s, "&4The script &f" + args[2] + " &4does not exist!"); + return true; + } + + manager.downloadScript(script); + msg(s, "&aDownload initiated... &eCheck the scripts folder in a moment..."); + return true; + } + msg(s, "&4Incorrect usage! &f" + this.getName() + " &7for more help."); + return true; + } + + return true; + } + + public void msg(CommandSender s, String... text) { + Arrays.stream(text) + .forEach(line -> s.sendMessage(ChatColor.translateAlternateColorCodes('&', line))); + } +} 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 01a7952..53e3899 100644 --- a/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptPlaceholder.java +++ b/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptPlaceholder.java @@ -36,6 +36,9 @@ import org.bukkit.configuration.file.YamlConfiguration; public class JavascriptPlaceholder { + private final String FILEDIR = + PlaceholderAPIPlugin.getInstance().getDataFolder() + File.separator + "javascripts" + + File.separator + "javascript_data"; private ScriptEngine engine = null; private String identifier; private String script; @@ -43,8 +46,6 @@ public class JavascriptPlaceholder { private File dataFile; private FileConfiguration cfg; - private final String FILEDIR = PlaceholderAPIPlugin.getInstance().getDataFolder() + File.separator + "javascripts"+ File.separator + "javascript_data"; - public JavascriptPlaceholder(ScriptEngine engine, String identifier, String script) { Validate.notNull(engine, "ScriptEngine can not be null"); Validate.notNull(identifier, "Identifier can not be 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 38817e7..0f0e99b 100644 --- a/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptPlaceholdersConfig.java +++ b/src/main/java/com/extendedclip/papi/expansion/javascript/JavascriptPlaceholdersConfig.java @@ -1,222 +1,233 @@ -/* - * - * Javascript-Expansion - * Copyright (C) 2018 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 java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Scanner; -import java.util.logging.Level; - -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; - -import me.clip.placeholderapi.PlaceholderAPIPlugin; - -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; - -public class JavascriptPlaceholdersConfig { - - private JavascriptExpansion ex; - - private 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) == null || config.getKeys(false).isEmpty()) { - config.set("example.file", "example.js"); - config.set("example.engine", "nashorn"); - } - 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) { - plugin.getLogger().log(Level.SEVERE, "Could not save to " + file, ex); - } - } - - public int loadPlaceholders() { - if (config == null || config.getKeys(false) == null || config.getKeys(false).isEmpty()) { - return 0; - } - - File dir = new File(plugin.getDataFolder() + File.separator + "javascripts"); - - try { - if (!dir.exists()) { - dir.mkdirs(); - plugin.getLogger().info("Creating directory: plugins" + File.separator + "PlaceholderAPI" + File.separator + "javascripts"); - } else { - } - } catch (SecurityException e) { - plugin.getLogger().severe("Could not create directory: plugins" + File.separator + "PlaceholderAPI" + File.separator + "javascripts"); - } - - for (String identifier : config.getKeys(false)) { - if (!config.contains(identifier + ".file") || config.getString(identifier + ".file", null) == null) { - plugin.getLogger().warning("Javascript placeholder: " + identifier + " does not have a file specified"); - continue; - } - - File scriptFile = new File(plugin.getDataFolder() + File.separator + "javascripts", config.getString(identifier + ".file")); - - if (!scriptFile.exists()) { - plugin.getLogger().info(scriptFile.getName() + " does not exist. Creating file..."); - - try { - scriptFile.createNewFile(); - plugin.getLogger().info(scriptFile.getName() + " created! Add your javascript to this file and use /placeholderapi reload to load it!"); - } catch (IOException e) { - e.printStackTrace(); - } - continue; - } - - String script = getContents(scriptFile); - - if (script == null || script.isEmpty()) { - plugin.getLogger().warning("File: " + scriptFile.getName() + " for javascript placeholder: " + identifier + " is empty"); - continue; - } - - ScriptEngine engine = null; - - if (!config.contains(identifier + ".engine")) { - engine = ex.getGlobalEngine(); - } else { - try { - engine = new ScriptEngineManager().getEngineByName(config.getString(identifier + ".engine", "nashorn")); - } catch (NullPointerException e) { - plugin.getLogger().warning("ScriptEngine type for javascript placeholder: " + identifier + " is invalid! Defaulting to global"); - engine = ex.getGlobalEngine(); - } - } - - if (engine == null) { - plugin.getLogger().warning("Failed to set ScriptEngine for javascript placeholder: " + identifier); - continue; - } - - JavascriptPlaceholder pl = new JavascriptPlaceholder(engine, identifier, script); - - boolean added = ex.addJSPlaceholder(pl); - - if (added) { - - if (pl.loadData()) { - plugin.getLogger().info("Loaded data for javascript placeholder: " + identifier); - } - plugin.getLogger().info("%javascript_" + identifier + "% has been loaded!"); - } else { - plugin.getLogger().warning("Javascript placeholder %javascript_" + identifier + "% is a duplicate!"); - } - } - return ex.getAmountLoaded(); - } - - private String getContents(File f) { - StringBuilder sb = new StringBuilder(); - - try { - Scanner scanner = new Scanner(f); - - 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 + " "); - } - scanner.close(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - return null; - } - return sb.toString(); - } -} +/* + * + * Javascript-Expansion + * Copyright (C) 2018 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 java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Scanner; +import java.util.logging.Level; +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +public class JavascriptPlaceholdersConfig { + + private JavascriptExpansion ex; + + private 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) == null || config.getKeys(false).isEmpty()) { + config.set("example.file", "example.js"); + config.set("example.engine", "nashorn"); + } + 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) { + plugin.getLogger().log(Level.SEVERE, "Could not save to " + file, ex); + } + } + + public int loadPlaceholders() { + if (config == null || config.getKeys(false) == null || config.getKeys(false).isEmpty()) { + return 0; + } + + File dir = new File(plugin.getDataFolder() + File.separator + "javascripts"); + + try { + if (!dir.exists()) { + dir.mkdirs(); + plugin.getLogger().info( + "Creating directory: plugins" + File.separator + "PlaceholderAPI" + File.separator + + "javascripts"); + } else { + } + } catch (SecurityException e) { + plugin.getLogger().severe( + "Could not create directory: plugins" + File.separator + "PlaceholderAPI" + File.separator + + "javascripts"); + } + + for (String identifier : config.getKeys(false)) { + if (!config.contains(identifier + ".file") + || config.getString(identifier + ".file", null) == null) { + plugin.getLogger() + .warning("Javascript placeholder: " + identifier + " does not have a file specified"); + continue; + } + + File scriptFile = new File(plugin.getDataFolder() + File.separator + "javascripts", + config.getString(identifier + ".file")); + + if (!scriptFile.exists()) { + plugin.getLogger().info(scriptFile.getName() + " does not exist. Creating file..."); + + try { + scriptFile.createNewFile(); + plugin.getLogger().info(scriptFile.getName() + + " created! Add your javascript to this file and use /placeholderapi reload to load it!"); + } catch (IOException e) { + e.printStackTrace(); + } + continue; + } + + String script = getContents(scriptFile); + + if (script == null || script.isEmpty()) { + plugin.getLogger().warning( + "File: " + scriptFile.getName() + " for javascript placeholder: " + identifier + + " is empty"); + continue; + } + + ScriptEngine engine = null; + + if (!config.contains(identifier + ".engine")) { + engine = ex.getGlobalEngine(); + } else { + try { + engine = new ScriptEngineManager() + .getEngineByName(config.getString(identifier + ".engine", "nashorn")); + } catch (NullPointerException e) { + plugin.getLogger().warning("ScriptEngine type for javascript placeholder: " + identifier + + " is invalid! Defaulting to global"); + engine = ex.getGlobalEngine(); + } + } + + if (engine == null) { + plugin.getLogger() + .warning("Failed to set ScriptEngine for javascript placeholder: " + identifier); + continue; + } + + JavascriptPlaceholder pl = new JavascriptPlaceholder(engine, identifier, script); + + boolean added = ex.addJSPlaceholder(pl); + + if (added) { + + if (pl.loadData()) { + plugin.getLogger().info("Loaded data for javascript placeholder: " + identifier); + } + plugin.getLogger().info("%javascript_" + identifier + "% has been loaded!"); + } else { + plugin.getLogger() + .warning("Javascript placeholder %javascript_" + identifier + "% is a duplicate!"); + } + } + return ex.getAmountLoaded(); + } + + private String getContents(File f) { + StringBuilder sb = new StringBuilder(); + + try { + Scanner scanner = new Scanner(f); + + 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 + " "); + } + scanner.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + return null; + } + return sb.toString(); + } +} diff --git a/src/main/java/com/extendedclip/papi/expansion/javascript/ScriptData.java b/src/main/java/com/extendedclip/papi/expansion/javascript/ScriptData.java index 761edea..c00b286 100644 --- a/src/main/java/com/extendedclip/papi/expansion/javascript/ScriptData.java +++ b/src/main/java/com/extendedclip/papi/expansion/javascript/ScriptData.java @@ -1,65 +1,65 @@ -/* - * - * Javascript-Expansion - * Copyright (C) 2018 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 java.util.HashMap; -import java.util.Map; - -public class ScriptData { - - private Map map; - - public ScriptData(Map data) { - this.map = data; - } - - public ScriptData() { - this.map = new HashMap<>(); - } - - public Map getData() { - return map; - } - - public void clear() { - map.clear(); - } - - public boolean exists(String key) { - return map.containsKey(key) && map.get(key) != null; - } - - public Object get(String key) { - return map.get(key); - } - - public void remove(String key) { - map.put(key, null); - } - - public void set(String key, Object value) { - map.put(key, value); - } - - public boolean isEmpty() { - return map.isEmpty(); - } -} +/* + * + * Javascript-Expansion + * Copyright (C) 2018 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 java.util.HashMap; +import java.util.Map; + +public class ScriptData { + + private Map map; + + public ScriptData(Map data) { + this.map = data; + } + + public ScriptData() { + this.map = new HashMap<>(); + } + + public Map getData() { + return map; + } + + public void clear() { + map.clear(); + } + + public boolean exists(String key) { + return map.containsKey(key) && map.get(key) != null; + } + + public Object get(String key) { + return map.get(key); + } + + public void remove(String key) { + map.put(key, null); + } + + public void set(String key, Object value) { + map.put(key, value); + } + + public boolean isEmpty() { + return map.isEmpty(); + } +} diff --git a/src/main/java/com/extendedclip/papi/expansion/javascript/cloud/GithubScript.java b/src/main/java/com/extendedclip/papi/expansion/javascript/cloud/GithubScript.java index 3ce407d..46bdce4 100644 --- a/src/main/java/com/extendedclip/papi/expansion/javascript/cloud/GithubScript.java +++ b/src/main/java/com/extendedclip/papi/expansion/javascript/cloud/GithubScript.java @@ -1,20 +1,11 @@ package com.extendedclip.papi.expansion.javascript.cloud; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; -public enum GithubScript { - HAS_PERMISSION("has_permission", - "1.0.0", - "aBooDyy", - "Check if player have \"permission.test\" permission and send a custom message.", - "https://raw.githubusercontent.com/PlaceholderAPI/Javascript-Expansion/master/scripts/has_permission.js"), - ; +public class GithubScript { private String name, version, author, description, url; - private GithubScript(String name, String version, String author, String description, String url) { + public GithubScript(String name, String version, String author, String description, String url) { this.name = name; this.version = version; this.author = author; @@ -41,12 +32,4 @@ public enum GithubScript { public String getUrl() { return url; } - - public static List getAllScriptNames() { - return Arrays.stream(values()).map(GithubScript::getName).collect(Collectors.toList()); - } - - public static GithubScript getScript(String name) { - return Arrays.stream(values()).filter(s -> { return s.getName().equalsIgnoreCase(name); } ).findFirst().orElse(null); - } } diff --git a/src/main/java/com/extendedclip/papi/expansion/javascript/cloud/GithubScriptManager.java b/src/main/java/com/extendedclip/papi/expansion/javascript/cloud/GithubScriptManager.java index 5bb3069..d0820df 100644 --- a/src/main/java/com/extendedclip/papi/expansion/javascript/cloud/GithubScriptManager.java +++ b/src/main/java/com/extendedclip/papi/expansion/javascript/cloud/GithubScriptManager.java @@ -1,6 +1,8 @@ package com.extendedclip.papi.expansion.javascript.cloud; import com.extendedclip.papi.expansion.javascript.JavascriptExpansion; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; @@ -10,34 +12,72 @@ import java.io.PrintStream; import java.net.URL; import java.util.ArrayList; import java.util.List; +import org.bukkit.Bukkit; public class GithubScriptManager { private JavascriptExpansion expansion; - private String path; + private String javascriptsFolder; + private List availableScripts; + private final String MASTER_LIST_URL = "https://raw.githubusercontent.com/PlaceholderAPI/Javascript-Expansion/master/scripts/master_list.json"; + private final Gson GSON = new Gson(); public GithubScriptManager(JavascriptExpansion expansion) { this.expansion = expansion; - path = expansion.getPlaceholderAPI().getDataFolder() + javascriptsFolder = expansion.getPlaceholderAPI().getDataFolder() + File.separator + "javascripts" + File.separator; } + public void clear() { + availableScripts = null; + } + + public void fetch() { + Bukkit.getScheduler().runTaskAsynchronously(expansion.getPlaceholderAPI(), new Runnable() { + @Override + public void run() { + String json = getContents(MASTER_LIST_URL); + + if (json.isEmpty()) { + return; + } + System.out.println(json); + availableScripts = GSON.fromJson(json, new TypeToken>() { + }.getType()); + } + }); + } + public void downloadScript(GithubScript script) { - List contents = read(script.getUrl()); - if (contents == null || contents.isEmpty()) { - return; - } - File f = new File(path, script.getName() + ".js"); - try (PrintStream out = new PrintStream(new FileOutputStream(f))) { - contents.forEach(l -> out.println(l)); - } catch (FileNotFoundException e) { - e.printStackTrace(); - return; - } - expansion.getConfig().load().set(script.getName() + ".file", script.getName() +".js"); - expansion.getConfig().save(); + Bukkit.getScheduler().runTaskAsynchronously(expansion.getPlaceholderAPI(), new Runnable() { + @Override + public void run() { + List contents = read(script.getUrl()); + if (contents == null || contents.isEmpty()) { + return; + } + File f = new File(javascriptsFolder, script.getName() + ".js"); + try (PrintStream out = new PrintStream(new FileOutputStream(f))) { + contents.forEach(l -> out.println(l)); + } catch (FileNotFoundException e) { + e.printStackTrace(); + return; + } + Bukkit.getScheduler().runTask(expansion.getPlaceholderAPI(), new Runnable() { + @Override + public void run() { + expansion.getConfig().load().set(script.getName() + ".file", script.getName() + ".js"); + expansion.getConfig().save(); + } + }); + } + }); + } + + private String getContents(String url) { + return String.join("", read(url)); } private List read(String url) { @@ -57,4 +97,13 @@ public class GithubScriptManager { return lines; } + + public List getAvailableScripts() { + return availableScripts; + } + + public GithubScript getScript(String name) { + if (availableScripts == null) return null; + return availableScripts.stream().filter(s -> {return s.getName().equalsIgnoreCase(name);}).findFirst().orElse(null); + } }