diff --git a/README.md b/README.md index b2f825f..dfad8b1 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,9 @@ You must have gradle installed then run "gradle build". Once the build is comple [Bukkit Page](http://dev.bukkit.org/bukkit-plugins/advanced-portals/) # Usage Data -![Global Plugin Stats](http://i.mcstats.org/AdvancedPortals/Global+Statistics.borderless.png) +Usage stats can be found here https://bstats.org/plugin/bukkit/AdvancedPortals + +Were available here http://mcstats.org/plugin/AdvancedPortals but mcstats is no longer working. The api isn't implemented in this version, sorry for any inconvenience. Check the recode tree for possibly a working recode at some point. diff --git a/src/main/java/com/sekwah/advancedportals/AdvancedPortalsCommand.java b/src/main/java/com/sekwah/advancedportals/AdvancedPortalsCommand.java index 9a94f3f..5b976e8 100644 --- a/src/main/java/com/sekwah/advancedportals/AdvancedPortalsCommand.java +++ b/src/main/java/com/sekwah/advancedportals/AdvancedPortalsCommand.java @@ -27,6 +27,8 @@ public class AdvancedPortalsCommand implements CommandExecutor, TabCompleter { private int portalArgsStringLength = 0; + private HashSet ignoreExtras = new HashSet<>(Arrays.asList("command.1", "permission")); + // TODO recode the portal args to be put into a hashmap and use a string array // to store all possible portal arguments. Makes code shorter and possibly more efficient. //private HashMap portalArgs = new HashMap<>(); @@ -142,7 +144,6 @@ public class AdvancedPortalsCommand implements CommandExecutor, TabCompleter { boolean hasDestination = false; boolean isBungeePortal = false; boolean needsPermission = false; - boolean delayed = false; boolean executesCommand = false; String destination = null; String portalName = null; @@ -155,37 +156,50 @@ public class AdvancedPortalsCommand implements CommandExecutor, TabCompleter { // Is completely changed in the recode but for now im leaving it as this horrible mess... for (int i = 1; i < args.length; i++) { - if (args[i].toLowerCase().startsWith("name:") && args[i].length() > 5) { + if (startsWithPortalArg("name:", args[i])) { + portalName = args[i].replaceFirst("name:", ""); + if(portalName.equals("")) { + player.sendMessage(PluginMessages.customPrefixFail + " You must include a name for the portal that isnt nothing!"); + return true; + } hasName = true; portalName = args[i].replaceFirst("name:", ""); - } else if (args[i].toLowerCase().startsWith("name:")) { - player.sendMessage(PluginMessages.customPrefixFail + " You must include a name for the portal that isnt nothing!"); - return true; - } else if (args[i].toLowerCase().startsWith("destination:") && args[i].length() > 12) { + } else if (startsWithPortalArg("destination:", args[i])) { hasDestination = true; destination = args[i].toLowerCase().replaceFirst("destination:", ""); - } else if (args[i].toLowerCase().startsWith("desti:") && args[i].length() > 6) { + } else if (startsWithPortalArg("desti:", args[i])) { hasDestination = true; destination = args[i].toLowerCase().replaceFirst("desti:", ""); - } else if (args[i].toLowerCase().startsWith("triggerblock:") && args[i].length() > 13) { + } else if (startsWithPortalArg("triggerblock:", args[i])) { hasTriggerBlock = true; triggerBlock = args[i].toLowerCase().replaceFirst("triggerblock:", ""); - } else if (args[i].toLowerCase().startsWith("triggerblock:") && args[i].length() > 13) { + } else if (startsWithPortalArg("triggerblock:", args[i])) { hasTriggerBlock = true; triggerBlock = args[i].toLowerCase().replaceFirst("triggerblock:", ""); } else if (this.startsWithPortalArg("bungee:", args[i])) { isBungeePortal = true; serverName = args[i].substring("bungee:".length()); - } else if (args[i].toLowerCase().startsWith("permission:") && args[i].length() > 11) { + } else if (startsWithPortalArg("permission:", args[i])) { needsPermission = true; permission = args[i].toLowerCase().replaceFirst("permission:", ""); extraData.add(new PortalArg("permission", permission)); - } else if (args[i].toLowerCase().startsWith("delayed:") && args[i].length() > 8) { - delayed = Boolean.parseBoolean(args[i].toLowerCase().replaceFirst("delayed:", "")); - extraData.add(new PortalArg("delayed", Boolean.toString(delayed))); - } else if (args[i].toLowerCase().startsWith("command:") && args[i].length() > 8) { + } else if (startsWithPortalArg("delayed:", args[i])) { + boolean delayed = Boolean.parseBoolean(args[i].toLowerCase().replaceFirst("delayed:", "")); + extraData.add(new PortalArg("delayed", Boolean.toString(delayed))); + } else if(startsWithPortalArg("message:", args[i])) { + String message = parseArgVariable(args, i, "message:"); + if(message == null) { + player.sendMessage(PluginMessages.customPrefixFail + " Message quotes not closed!"); + return true; + } + extraData.add(new PortalArg("message", message )); + } else if (startsWithPortalArg("command:", args[i])) { executesCommand = true; portalCommand = parseArgVariable(args, i, "command:"); + if(portalCommand == null) { + player.sendMessage(PluginMessages.customPrefixFail + " Command quotes not closed!"); + return true; + } i += this.portalArgsStringLength - 1; if(portalCommand.startsWith("#") && !(this.plugin.getSettings().hasCommandLevel("c") && (sender.hasPermission("advancedportals.createportal.commandlevel.console")) @@ -248,7 +262,11 @@ public class AdvancedPortalsCommand implements CommandExecutor, TabCompleter { player.sendMessage("\u00A7apermission: \u00A7e(none needed)"); } - player.sendMessage("\u00A7adelayed: \u00A7e" + delayed); + for(PortalArg portalArg : extraData) { + if(!ignoreExtras.contains(portalArg.argName)) { + player.sendMessage("\u00A7a" + portalArg.argName + ": \u00A7e" + portalArg.value); + } + } if (executesCommand) { player.sendMessage("\u00A7acommand: \u00A7e" + portalCommand); @@ -577,10 +595,13 @@ public class AdvancedPortalsCommand implements CommandExecutor, TabCompleter { String variableString = args[currentArg].replaceFirst(argStarter, ""); this.portalArgsStringLength = 1; if (variableString.charAt(0) == '"') { - variableString = variableString.substring(1, variableString.length()); - if (variableString.charAt(variableString.length() - 1) != '"') { + variableString = variableString.substring(1); + if (variableString.length() == 0 || variableString.charAt(variableString.length() - 1) != '"') { currentArg++; - for (; currentArg < args.length; currentArg++) { + for (; currentArg <= args.length; currentArg++) { + if(currentArg == args.length) { + return null; + } variableString += " " + args[currentArg]; this.portalArgsStringLength += 1; if (variableString.charAt(variableString.length() - 1) == '"') { diff --git a/src/main/java/com/sekwah/advancedportals/AdvancedPortalsPlugin.java b/src/main/java/com/sekwah/advancedportals/AdvancedPortalsPlugin.java index f1facb6..31e5d4d 100644 --- a/src/main/java/com/sekwah/advancedportals/AdvancedPortalsPlugin.java +++ b/src/main/java/com/sekwah/advancedportals/AdvancedPortalsPlugin.java @@ -4,7 +4,6 @@ import com.sekwah.advancedportals.compat.CraftBukkit; import com.sekwah.advancedportals.destinations.Destination; import com.sekwah.advancedportals.destinations.DestinationCommand; import com.sekwah.advancedportals.effects.WarpEffects; -import com.sekwah.advancedportals.injector.PacketInjector; import com.sekwah.advancedportals.listeners.*; import com.sekwah.advancedportals.metrics.Metrics; import com.sekwah.advancedportals.portals.Portal; @@ -26,13 +25,7 @@ public class AdvancedPortalsPlugin extends JavaPlugin { saveDefaultConfig(); - try { - Metrics metrics = new Metrics(this); - - metrics.start(); - } catch (IOException e) { - // Failed to submit the stats :-( - } + Metrics metrics = new Metrics(this); try { diff --git a/src/main/java/com/sekwah/advancedportals/PluginMessages.java b/src/main/java/com/sekwah/advancedportals/PluginMessages.java index 780b5f7..27a6170 100644 --- a/src/main/java/com/sekwah/advancedportals/PluginMessages.java +++ b/src/main/java/com/sekwah/advancedportals/PluginMessages.java @@ -13,8 +13,8 @@ public class PluginMessages { ConfigAccessor config = new ConfigAccessor(this.plugin, "config.yml"); this.useCustomPrefix = config.getConfig().getBoolean("UseCustomPrefix"); if (useCustomPrefix) { - PluginMessages.customPrefix = config.getConfig().getString("CustomPrefix").replaceAll("&", "\u00A7"); - PluginMessages.customPrefixFail = config.getConfig().getString("CustomPrefixFail").replaceAll("&", "\u00A7"); + PluginMessages.customPrefix = config.getConfig().getString("CustomPrefix").replaceAll("&(?=[0-9a-fk-or])", "\u00A7"); + PluginMessages.customPrefixFail = config.getConfig().getString("CustomPrefixFail").replaceAll("&(?=[0-9a-fk-or])", "\u00A7"); } } diff --git a/src/main/java/com/sekwah/advancedportals/destinations/Destination.java b/src/main/java/com/sekwah/advancedportals/destinations/Destination.java index 388ded8..85db2a1 100644 --- a/src/main/java/com/sekwah/advancedportals/destinations/Destination.java +++ b/src/main/java/com/sekwah/advancedportals/destinations/Destination.java @@ -101,6 +101,10 @@ public class Destination { } public static boolean warp(Player player, String name) { + return warp(player, name, false); + } + + public static boolean warp(Player player, String name, boolean hideActionbar) { ConfigAccessor config = new ConfigAccessor(plugin, "destinations.yml"); if (config.getConfig().getString(name + ".world") != null) { Location loc = player.getLocation(); @@ -137,10 +141,8 @@ public class Destination { player.sendMessage(""); player.sendMessage(PluginMessages.customPrefixFail + "\u00A7a You have been warped to \u00A7e" + name.replaceAll("_", " ") + "\u00A7a."); player.sendMessage(""); - } else if (PORTAL_MESSAGE_DISPLAY == 2) { + } else if (PORTAL_MESSAGE_DISPLAY == 2 && !hideActionbar) { plugin.compat.sendActionBarMessage("\u00A7aYou have warped to \u00A7e" + name.replaceAll("_", " ") + "\u00A7a.", player); - /**plugin.nmsAccess.sendActionBarMessage("[{text:\"You have warped to \",color:green},{text:\"" + config.getConfig().getString(Portal.portals[portalId].portalName + ".destination").replaceAll("_", " ") - + "\",color:yellow},{\"text\":\".\",color:green}]", player);*/ } return true; diff --git a/src/main/java/com/sekwah/advancedportals/metrics/Metrics.java b/src/main/java/com/sekwah/advancedportals/metrics/Metrics.java index b41f33c..9a608b0 100644 --- a/src/main/java/com/sekwah/advancedportals/metrics/Metrics.java +++ b/src/main/java/com/sekwah/advancedportals/metrics/Metrics.java @@ -1,773 +1,718 @@ -/* - * Copyright 2011-2013 Tyler Blair. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are - * permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and contributors and should not be interpreted as representing official policies, - * either expressed or implied, of anybody else. - */ package com.sekwah.advancedportals.metrics; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; import org.bukkit.Bukkit; -import org.bukkit.Server; -import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.scheduler.BukkitTask; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.ServicePriority; +import javax.net.ssl.HttpsURLConnection; import java.io.*; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.net.Proxy; import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.*; +import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.zip.GZIPOutputStream; +/** + * bStats collects some data for plugin authors. + *

+ * Check out https://bStats.org/ to learn more about bStats! + */ +@SuppressWarnings({"WeakerAccess", "unused"}) public class Metrics { - /** - * The current revision number - */ - private final static int REVISION = 7; + static { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D + final String defaultPackage = new String( + new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); + final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure nobody just copy & pastes the example and use the wrong package names + if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } - /** - * The base url of the metrics domain - */ - private static final String BASE_URL = "http://report.mcstats.org"; + // The version of this bStats class + public static final int B_STATS_VERSION = 1; - /** - * The url used to report a server's status - */ - private static final String REPORT_URL = "/plugin/%s"; + // The url to which the data is sent + private static final String URL = "https://bStats.org/submitData/bukkit"; - /** - * Interval of time to ping (in minutes) - */ - private static final int PING_INTERVAL = 15; + // Is bStats enabled on this server? + private boolean enabled; - /** - * The plugin this metrics submits for - */ + // Should failed requests be logged? + private static boolean logFailedRequests; + + // Should the sent data be logged? + private static boolean logSentData; + + // Should the response text be logged? + private static boolean logResponseStatusText; + + // The uuid of the server + private static String serverUUID; + + // The plugin private final Plugin plugin; - /** - * All of the custom graphs to submit to metrics - */ - private final Set graphs = Collections.synchronizedSet(new HashSet()); + // A list with all custom charts + private final List charts = new ArrayList<>(); /** - * The plugin configuration file + * Class constructor. + * + * @param plugin The plugin which stats should be submitted. */ - private final YamlConfiguration configuration; - - /** - * The plugin configuration file - */ - private final File configurationFile; - - /** - * Unique server id - */ - private final String guid; - - /** - * Debug mode - */ - private final boolean debug; - - /** - * Lock for synchronization - */ - private final Object optOutLock = new Object(); - - /** - * The scheduled task - */ - private volatile BukkitTask task = null; - - public Metrics(final Plugin plugin) throws IOException { + public Metrics(Plugin plugin) { if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null"); + throw new IllegalArgumentException("Plugin cannot be null!"); } - this.plugin = plugin; - // load the config - configurationFile = getConfigFile(); - configuration = YamlConfiguration.loadConfiguration(configurationFile); + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - // add some defaults - configuration.addDefault("opt-out", false); - configuration.addDefault("guid", UUID.randomUUID().toString()); - configuration.addDefault("debug", false); + // Check if the config file exists + if (!config.isSet("serverUuid")) { - // Do we need to create the file? - if (configuration.get("guid", null) == null) { - configuration.options().header("http://mcstats.org").copyDefaults(true); - configuration.save(configurationFile); - } + // Add default values + config.addDefault("enabled", true); + // Every server gets it's unique random id. + config.addDefault("serverUuid", UUID.randomUUID().toString()); + // Should failed request be logged? + config.addDefault("logFailedRequests", false); + // Should the sent data be logged? + config.addDefault("logSentData", false); + // Should the response text be logged? + config.addDefault("logResponseStatusText", false); - // Load the guid then - guid = configuration.getString("guid"); - debug = configuration.getBoolean("debug", false); - } - - /** - * Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics - * website. Plotters can be added to the graph object returned. - * - * @param name The name of the graph - * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given - */ - public Graph createGraph(final String name) { - if (name == null) { - throw new IllegalArgumentException("Graph name cannot be null"); - } - - // Construct the graph object - final Graph graph = new Graph(name); - - // Now we can add our graph - graphs.add(graph); - - // and return back - return graph; - } - - /** - * Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend - * - * @param graph The name of the graph - */ - public void addGraph(final Graph graph) { - if (graph == null) { - throw new IllegalArgumentException("Graph cannot be null"); - } - - graphs.add(graph); - } - - /** - * Start measuring statistics. This will immediately create an async repeating task as the plugin and send the - * initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200 - * ticks. - * - * @return True if statistics measuring is running, otherwise false. - */ - public boolean start() { - synchronized (optOutLock) { - // Did we opt out? - if (isOptOut()) { - return false; - } - - // Is metrics already running? - if (task != null) { - return true; - } - - // Begin hitting the server with glorious data - task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() { - - private boolean firstPost = true; - - public void run() { - try { - // This has to be synchronized or it can collide with the disable method. - synchronized (optOutLock) { - // Disable Task, if it is running and the server owner decided to opt-out - if (isOptOut() && task != null) { - task.cancel(); - task = null; - // Tell all plotters to stop gathering information. - for (Graph graph : graphs) { - graph.onOptOut(); - } - } - } - - // We use the inverse of firstPost because if it is the first time we are posting, - // it is not a interval ping, so it evaluates to FALSE - // Each time thereafter it will evaluate to TRUE, i.e PING! - postPlugin(!firstPost); - - // After the first post we set firstPost to false - // Each post thereafter will be a ping - firstPost = false; - } catch (IOException e) { - if (debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); - } - } - } - }, 0, PING_INTERVAL * 1200); - - return true; - } - } - - /** - * Has the server owner denied plugin metrics? - * - * @return true if metrics should be opted out of it - */ - public boolean isOptOut() { - synchronized (optOutLock) { + // Inform the server owners about bStats + config.options().header( + "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + + "To honor their work, you should not disable it.\n" + + "This has nearly no effect on the server performance!\n" + + "Check out https://bStats.org/ to learn more :)" + ).copyDefaults(true); try { - // Reload the metrics file - configuration.load(getConfigFile()); - } catch (IOException ex) { - if (debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); + config.save(configFile); + } catch (IOException ignored) { } + } + + // Load the data + enabled = config.getBoolean("enabled", true); + serverUUID = config.getString("serverUuid"); + logFailedRequests = config.getBoolean("logFailedRequests", false); + logSentData = config.getBoolean("logSentData", false); + logResponseStatusText = config.getBoolean("logResponseStatusText", false); + + if (enabled) { + boolean found = false; + // Search for all other bStats Metrics classes to see if we are the first one + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + found = true; // We aren't the first + break; + } catch (NoSuchFieldException ignored) { } + } + // Register our service + Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); + if (!found) { + // We are the first! + startSubmitting(); + } + } + } + + /** + * Checks if bStats is enabled. + * + * @return Whether bStats is enabled or not. + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + if (chart == null) { + throw new IllegalArgumentException("Chart cannot be null!"); + } + charts.add(chart); + } + + /** + * Starts the Scheduler which submits our data every 30 minutes. + */ + private void startSubmitting() { + final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + if (!plugin.isEnabled()) { // Plugin was disabled + timer.cancel(); + return; } - return true; - } catch (InvalidConfigurationException ex) { - if (debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - } - return true; + // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler + // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) + Bukkit.getScheduler().runTask(plugin, () -> submitData()); } - return configuration.getBoolean("opt-out", false); + }, 1000 * 60 * 5, 1000 * 60 * 30); + // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start + // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! + // WARNING: Just don't do it! + } + + /** + * Gets the plugin specific data. + * This method is called using Reflection. + * + * @return The plugin specific data. + */ + public JsonObject getPluginData() { + JsonObject data = new JsonObject(); + + String pluginName = plugin.getDescription().getName(); + String pluginVersion = plugin.getDescription().getVersion(); + + data.addProperty("pluginName", pluginName); // Append the name of the plugin + data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin + JsonArray customCharts = new JsonArray(); + for (CustomChart customChart : charts) { + // Add the data of the custom charts + JsonObject chart = customChart.getRequestJsonObject(); + if (chart == null) { // If the chart is null, we skip it + continue; + } + customCharts.add(chart); } + data.add("customCharts", customCharts); + + return data; } /** - * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. + * Gets the server specific data. * - * @throws java.io.IOException + * @return The server specific data. */ - public void enable() throws IOException { - // This has to be synchronized or it can collide with the check in the task. - synchronized (optOutLock) { - // Check if the server owner has already set opt-out, if not, set it. - if (isOptOut()) { - configuration.set("opt-out", false); - configuration.save(configurationFile); - } - - // Enable Task, if it is not running - if (task == null) { - start(); - } - } - } - - /** - * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. - * - * @throws java.io.IOException - */ - public void disable() throws IOException { - // This has to be synchronized or it can collide with the check in the task. - synchronized (optOutLock) { - // Check if the server owner has already set opt-out, if not, set it. - if (!isOptOut()) { - configuration.set("opt-out", true); - configuration.save(configurationFile); - } - - // Disable Task, if it is running - if (task != null) { - task.cancel(); - task = null; - } - } - } - - /** - * Gets the File object of the config file that should be used to store data such as the GUID and opt-out status - * - * @return the File object for the config file - */ - public File getConfigFile() { - // I believe the easiest way to get the base folder (e.g craftbukkit set via -P) for plugins to use - // is to abuse the plugin object we already have - // plugin.getDataFolder() => base/plugins/PluginA/ - // pluginsFolder => base/plugins/ - // The base is not necessarily relative to the startup directory. - File pluginsFolder = plugin.getDataFolder().getParentFile(); - - // return => base/plugins/PluginMetrics/config.yml - return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); - } - - /** - * Gets the online player (backwards compatibility) - * - * @return online player amount - */ - private int getOnlinePlayers() { + private JsonObject getServerData() { + // Minecraft specific data + int playerAmount; try { - Method onlinePlayerMethod = Server.class.getMethod("getOnlinePlayers"); - if(onlinePlayerMethod.getReturnType().equals(Collection.class)) { - return ((Collection)onlinePlayerMethod.invoke(Bukkit.getServer())).size(); - } else { - return ((Player[])onlinePlayerMethod.invoke(Bukkit.getServer())).length; - } - } catch (Exception ex) { - if (debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - } + // Around MC 1.8 the return type was changed to a collection from an array, + // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed } + int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; + String bukkitVersion = Bukkit.getVersion(); + String bukkitName = Bukkit.getName(); - return 0; - } - - /** - * Generic method that posts a plugin to the metrics website - */ - private void postPlugin(final boolean isPing) throws IOException { - // Server software specific section - PluginDescriptionFile description = plugin.getDescription(); - String pluginName = description.getName(); - boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled - String pluginVersion = description.getVersion(); - String serverVersion = Bukkit.getVersion(); - int playersOnline = this.getOnlinePlayers(); - - // END server software specific section -- all code below does not use any code outside of this class / Java - - // Construct the post data - StringBuilder json = new StringBuilder(1024); - json.append('{'); - - // The plugin's description file containg all of the plugin data such as name, version, author, etc - appendJSONPair(json, "guid", guid); - appendJSONPair(json, "plugin_version", pluginVersion); - appendJSONPair(json, "server_version", serverVersion); - appendJSONPair(json, "players_online", Integer.toString(playersOnline)); - - // New data as of R6 - String osname = System.getProperty("os.name"); - String osarch = System.getProperty("os.arch"); - String osversion = System.getProperty("os.version"); - String java_version = System.getProperty("java.version"); + // OS/Java specific data + String javaVersion = System.getProperty("java.version"); + String osName = System.getProperty("os.name"); + String osArch = System.getProperty("os.arch"); + String osVersion = System.getProperty("os.version"); int coreCount = Runtime.getRuntime().availableProcessors(); - // normalize os arch .. amd64 -> x86_64 - if (osarch.equals("amd64")) { - osarch = "x86_64"; - } + JsonObject data = new JsonObject(); - appendJSONPair(json, "osname", osname); - appendJSONPair(json, "osarch", osarch); - appendJSONPair(json, "osversion", osversion); - appendJSONPair(json, "cores", Integer.toString(coreCount)); - appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); - appendJSONPair(json, "java_version", java_version); + data.addProperty("serverUUID", serverUUID); - // If we're pinging, append it - if (isPing) { - appendJSONPair(json, "ping", "1"); - } + data.addProperty("playerAmount", playerAmount); + data.addProperty("onlineMode", onlineMode); + data.addProperty("bukkitVersion", bukkitVersion); + data.addProperty("bukkitName", bukkitName); - if (graphs.size() > 0) { - synchronized (graphs) { - json.append(','); - json.append('"'); - json.append("graphs"); - json.append('"'); - json.append(':'); - json.append('{'); + data.addProperty("javaVersion", javaVersion); + data.addProperty("osName", osName); + data.addProperty("osArch", osArch); + data.addProperty("osVersion", osVersion); + data.addProperty("coreCount", coreCount); - boolean firstGraph = true; + return data; + } - final Iterator iter = graphs.iterator(); + /** + * Collects the data and sends it afterwards. + */ + private void submitData() { + final JsonObject data = getServerData(); - while (iter.hasNext()) { - Graph graph = iter.next(); + JsonArray pluginData = new JsonArray(); + // Search for all other bStats Metrics classes to get their plugin data + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) - StringBuilder graphJson = new StringBuilder(); - graphJson.append('{'); - - for (Plotter plotter : graph.getPlotters()) { - appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); - } - - graphJson.append('}'); - - if (!firstGraph) { - json.append(','); - } - - json.append(escapeJSON(graph.getName())); - json.append(':'); - json.append(graphJson); - - firstGraph = false; + for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { + try { + Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); + if (plugin instanceof JsonObject) { + pluginData.add((JsonObject) plugin); + } else { // old bstats version compatibility + try { + Class jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); + if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { + Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); + jsonStringGetter.setAccessible(true); + String jsonString = (String) jsonStringGetter.invoke(plugin); + JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); + pluginData.add(object); + } + } catch (ClassNotFoundException e) { + // minecraft version 1.14+ + if (logFailedRequests) { + this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e); + } + continue; // continue looping since we cannot do any other thing. + } + } + } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } } + } catch (NoSuchFieldException ignored) { } + } - json.append('}'); + data.add("plugins", pluginData); + + // Create a new thread for the connection to the bStats server + new Thread(new Runnable() { + @Override + public void run() { + try { + // Send the data + sendData(plugin, data); + } catch (Exception e) { + // Something went wrong! :( + if (logFailedRequests) { + plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); + } + } } + }).start(); + } + + /** + * Sends the data to the bStats server. + * + * @param plugin Any plugin. It's just used to get a logger instance. + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(Plugin plugin, JsonObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null!"); } - - // close json - json.append('}'); - - // Create the url - URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); - - // Connect to the website - URLConnection connection; - - // Mineshafter creates a socks proxy, so we can safely bypass it - // It does not reroute POST requests so we need to go around it - if (isMineshafterPresent()) { - connection = url.openConnection(Proxy.NO_PROXY); - } else { - connection = url.openConnection(); + if (Bukkit.isPrimaryThread()) { + throw new IllegalAccessException("This method must not be called from the main thread!"); } + if (logSentData) { + plugin.getLogger().info("Sending data to bStats: " + data.toString()); + } + HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); - byte[] uncompressed = json.toString().getBytes(); - byte[] compressed = gzip(json.toString()); - - // Headers - connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); - connection.addRequestProperty("Content-Type", "application/json"); - connection.addRequestProperty("Content-Encoding", "gzip"); - connection.addRequestProperty("Content-Length", Integer.toString(compressed.length)); + // Add headers + connection.setRequestMethod("POST"); connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format + connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); + // Send data connection.setDoOutput(true); + DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); + outputStream.write(compressedData); + outputStream.flush(); + outputStream.close(); - if (debug) { - System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length); + InputStream inputStream = connection.getInputStream(); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + + StringBuilder builder = new StringBuilder(); + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + bufferedReader.close(); + if (logResponseStatusText) { + plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString()); + } + } + + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + GZIPOutputStream gzip = new GZIPOutputStream(outputStream); + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + gzip.close(); + return outputStream.toByteArray(); + } + + /** + * Represents a custom chart. + */ + public static abstract class CustomChart { + + // The id of the chart + final String chartId; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + CustomChart(String chartId) { + if (chartId == null || chartId.isEmpty()) { + throw new IllegalArgumentException("ChartId cannot be null or empty!"); + } + this.chartId = chartId; } - // Write the data - OutputStream os = connection.getOutputStream(); - os.write(compressed); - os.flush(); - - // Now read the response - final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String response = reader.readLine(); - - // close resources - os.close(); - reader.close(); - - if (response == null || response.startsWith("ERR") || response.startsWith("7")) { - if (response == null) { - response = "null"; - } else if (response.startsWith("7")) { - response = response.substring(response.startsWith("7,") ? 2 : 1); + private JsonObject getRequestJsonObject() { + JsonObject chart = new JsonObject(); + chart.addProperty("chartId", chartId); + try { + JsonObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + chart.add("data", data); + } catch (Throwable t) { + if (logFailedRequests) { + Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); + } + return null; } + return chart; + } - throw new IOException(response); - } else { - // Is this the first update this hour? - if (response.equals("1") || response.contains("This is your first update this hour")) { - synchronized (graphs) { - final Iterator iter = graphs.iterator(); + protected abstract JsonObject getChartData() throws Exception; - while (iter.hasNext()) { - final Graph graph = iter.next(); + } - for (Plotter plotter : graph.getPlotters()) { - plotter.reset(); - } - } + /** + * Represents a custom simple pie. + */ + public static class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + data.addProperty("value", value); + return data; + } + } + + /** + * Represents a custom advanced pie. + */ + public static class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.addProperty(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + + /** + * Represents a custom drilldown pie. + */ + public static class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JsonObject value = new JsonObject(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + value.addProperty(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + values.add(entryValues.getKey(), value); } } - } - } - - /** - * GZip compress a string of bytes - * - * @param input - * @return - */ - public static byte[] gzip(String input) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - GZIPOutputStream gzos = null; - - try { - gzos = new GZIPOutputStream(baos); - gzos.write(input.getBytes("UTF-8")); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (gzos != null) try { - gzos.close(); - } catch (IOException ignore) { + if (reallyAllSkipped) { + // Null = skip the chart + return null; } - } - - return baos.toByteArray(); - } - - /** - * Check if mineshafter is present. If it is, we need to bypass it to send POST requests - * - * @return true if mineshafter is installed on the server - */ - private boolean isMineshafterPresent() { - try { - Class.forName("mineshafter.MineServer"); - return true; - } catch (Exception e) { - return false; + data.add("values", values); + return data; } } /** - * Appends a json encoded key/value pair to the given string builder. - * - * @param json - * @param key - * @param value - * @throws UnsupportedEncodingException + * Represents a custom single line chart. */ - private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException { - boolean isValueNumeric = false; + public static class SingleLineChart extends CustomChart { - try { - if (value.equals("0") || !value.endsWith("0")) { - Double.parseDouble(value); - isValueNumeric = true; - } - } catch (NumberFormatException e) { - isValueNumeric = false; - } - - if (json.charAt(json.length() - 1) != '{') { - json.append(','); - } - - json.append(escapeJSON(key)); - json.append(':'); - - if (isValueNumeric) { - json.append(value); - } else { - json.append(escapeJSON(value)); - } - } - - /** - * Escape a string to create a valid JSON string - * - * @param text - * @return - */ - private static String escapeJSON(String text) { - StringBuilder builder = new StringBuilder(); - - builder.append('"'); - for (int index = 0; index < text.length(); index++) { - char chr = text.charAt(index); - - switch (chr) { - case '"': - case '\\': - builder.append('\\'); - builder.append(chr); - break; - case '\b': - builder.append("\\b"); - break; - case '\t': - builder.append("\\t"); - break; - case '\n': - builder.append("\\n"); - break; - case '\r': - builder.append("\\r"); - break; - default: - if (chr < ' ') { - String t = "000" + Integer.toHexString(chr); - builder.append("\\u" + t.substring(t.length() - 4)); - } else { - builder.append(chr); - } - break; - } - } - builder.append('"'); - - return builder.toString(); - } - - /** - * Encode text as UTF-8 - * - * @param text the text to encode - * @return the encoded text, as UTF-8 - */ - private static String urlEncode(final String text) throws UnsupportedEncodingException { - return URLEncoder.encode(text, "UTF-8"); - } - - /** - * Represents a custom graph on the website - */ - public static class Graph { + private final Callable callable; /** - * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is - * rejected - */ - private final String name; - - /** - * The set of plotters that are contained within this graph - */ - private final Set plotters = new LinkedHashSet(); - - private Graph(final String name) { - this.name = name; - } - - /** - * Gets the graph's name + * Class constructor. * - * @return the Graph's name + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. */ - public String getName() { - return name; - } - - /** - * Add a plotter to the graph, which will be used to plot entries - * - * @param plotter the plotter to add to the graph - */ - public void addPlotter(final Plotter plotter) { - plotters.add(plotter); - } - - /** - * Remove a plotter from the graph - * - * @param plotter the plotter to remove from the graph - */ - public void removePlotter(final Plotter plotter) { - plotters.remove(plotter); - } - - /** - * Gets an unmodifiable set of the plotter objects in the graph - * - * @return an unmodifiable {@link java.util.Set} of the plotter objects - */ - public Set getPlotters() { - return Collections.unmodifiableSet(plotters); + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; } @Override - public int hashCode() { - return name.hashCode(); - } - - @Override - public boolean equals(final Object object) { - if (!(object instanceof Graph)) { - return false; + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; } - - final Graph graph = (Graph) object; - return graph.name.equals(name); + data.addProperty("value", value); + return data; } - /** - * Called when the server owner decides to opt-out of BukkitMetrics while the server is running. - */ - protected void onOptOut() { - } } /** - * Interface used to collect custom data for a plugin + * Represents a custom multi line chart. */ - public static abstract class Plotter { + public static class MultiLineChart extends CustomChart { + + private final Callable> callable; /** - * The plot's name - */ - private final String name; - - /** - * Construct a plotter with the default plot name - */ - public Plotter() { - this("Default"); - } - - /** - * Construct a plotter with a specific plot name + * Class constructor. * - * @param name the name of the plotter to use, which will show up on the website + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. */ - public Plotter(final String name) { - this.name = name; - } - - /** - * Get the current value for the plotted point. Since this function defers to an external function it may or may - * not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called - * from any thread so care should be taken when accessing resources that need to be synchronized. - * - * @return the current value for the point to be plotted. - */ - public abstract int getValue(); - - /** - * Get the column name for the plotted point - * - * @return the plotted point's column name - */ - public String getColumnName() { - return name; - } - - /** - * Called after the website graphs have been updated - */ - public void reset() { + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; } @Override - public int hashCode() { - return getColumnName().hashCode(); - } - - @Override - public boolean equals(final Object object) { - if (!(object instanceof Plotter)) { - return false; + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.addProperty(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } - final Plotter plotter = (Plotter) object; - return plotter.name.equals(name) && plotter.getValue() == getValue(); + } + + /** + * Represents a custom simple bar chart. + */ + public static class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + JsonArray categoryValues = new JsonArray(); + categoryValues.add(entry.getValue()); + values.add(entry.getKey(), categoryValues); + } + data.add("values", values); + return data; + } + + } + + /** + * Represents a custom advanced bar chart. + */ + public static class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + continue; // Skip this invalid + } + allSkipped = false; + JsonArray categoryValues = new JsonArray(); + for (int categoryValue : entry.getValue()) { + categoryValues.add(categoryValue); + } + values.add(entry.getKey(), categoryValues); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; } } -} + +} \ No newline at end of file diff --git a/src/main/java/com/sekwah/advancedportals/portals/Portal.java b/src/main/java/com/sekwah/advancedportals/portals/Portal.java index 07846e7..2ea187a 100644 --- a/src/main/java/com/sekwah/advancedportals/portals/Portal.java +++ b/src/main/java/com/sekwah/advancedportals/portals/Portal.java @@ -391,6 +391,8 @@ public class Portal { cooldown.put(player.getName(), System.currentTimeMillis()); boolean showFailMessage = !portal.hasArg("command.1"); + boolean hasMessage = portal.getArg("message") != null; + //plugin.getLogger().info(portal.getName() + ":" + portal.getDestiation()); boolean warped = false; if (portal.getBungee() != null) { @@ -409,7 +411,7 @@ public class Portal { else if (portal.getDestiation() != null) { ConfigAccessor configDesti = new ConfigAccessor(plugin, "destinations.yml"); if (configDesti.getConfig().getString(portal.getDestiation() + ".world") != null) { - warped = Destination.warp(player, portal.getDestiation()); + warped = Destination.warp(player, portal.getDestiation(), hasMessage); if(!warped){ throwPlayerBack(player); } @@ -469,6 +471,12 @@ public class Portal { } while (command != null); } + if(warped) { + if(hasMessage) { + plugin.compat.sendActionBarMessage(portal.getArg("message").replaceAll("&(?=[0-9a-fk-or])", "\u00A7"), player); + } + } + return warped; } diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 6121325..1af1772 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,6 +1,6 @@ main: com.sekwah.advancedportals.AdvancedPortalsPlugin name: AdvancedPortals -version: 0.1.0 +version: 0.2.0 author: sekwah41 description: An advanced portals plugin for bukkit. api-version: 1.13