diff --git a/.gitignore b/.gitignore index 17b56e8..8c1d287 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,10 @@ target/ AdvancedKitsReloaded.iml +.classpath +.project +.settings/ + ### Java template # Compiled class file *.class diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/advancedkits.iml b/advancedkits.iml deleted file mode 100644 index 3e75064..0000000 --- a/advancedkits.iml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - BUKKIT - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/pom.xml b/pom.xml index c90212f..96f6375 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ hu.tryharddevs advancedkits - 1.1.14 + 1.1.16 AdvancedKitsReloaded @@ -22,16 +22,16 @@ placeholderapi-repo - http://repo.extendedclip.com/content/repositories/placeholderapi/ + https://repo.extendedclip.com/content/repositories/placeholderapi/ vault-repo - http://nexus.hc.to/content/repositories/pub_releases/ + https://nexus.hc.to/content/repositories/pub_releases/ aikar-repo - http://ci.emc.gs/nexus/content/groups/aikar/ + https://ci.emc.gs/nexus/content/groups/aikar/ jitpack.io @@ -46,7 +46,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.2 + 3.8.1 1.8 1.8 @@ -60,7 +60,7 @@ org.apache.maven.plugins maven-source-plugin - 3.0.1 + 3.2.1 attach-sources @@ -73,14 +73,13 @@ org.apache.maven.plugins maven-shade-plugin - 2.4.1 + 3.2.4 ${project.build.directory}/dependency-reduced-pom.xml co.aikar:acf-core co.aikar:minecraft-timings - com.github.TryHardDood:ReflectionHelper com.github.InventivetalentDev:ParticleAPI @@ -101,10 +100,6 @@ co.aikar.timings.lib hu.tryharddevs.advancedkits.utils.timings - - org.inventivetalent.reflection - hu.tryharddevs.advancedkits.utils.reflection - org.inventivetalent.particle hu.tryharddevs.advancedkits.utils.particle @@ -120,29 +115,6 @@ - - maven-antrun-plugin - 1.8 - - - copy - package - - - Copying AdvancedKitsReloaded.jar to localtest - - - - - - - - - run - - - - @@ -154,21 +126,27 @@ - org.bukkit - bukkit - 1.12-pre2-SNAPSHOT + org.spigotmc + spigot-api + 1.16.5-R0.1-SNAPSHOT provided me.clip placeholderapi - 2.7.1 + 2.10.10 net.milkbowl.vault VaultAPI - 1.6 + 1.7 + + + org.bukkit + bukkit + + @@ -179,13 +157,7 @@ co.aikar minecraft-timings - 1.0.3 - - - - com.github.TryHardDood - ReflectionHelper - -SNAPSHOT + 1.0.4 com.github.InventivetalentDev diff --git a/src/main/java/hu/tryharddevs/advancedkits/AdvancedKitsMain.java b/src/main/java/hu/tryharddevs/advancedkits/AdvancedKitsMain.java index 70bfc96..d564469 100644 --- a/src/main/java/hu/tryharddevs/advancedkits/AdvancedKitsMain.java +++ b/src/main/java/hu/tryharddevs/advancedkits/AdvancedKitsMain.java @@ -18,7 +18,6 @@ import org.bukkit.ChatColor; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; -import org.inventivetalent.reflection.minecraft.Minecraft; import java.util.ArrayList; import java.util.Arrays; @@ -43,12 +42,6 @@ public void onEnable() { this.log(ChatColor.GREEN + "Starting " + this.getDescription().getName() + " " + this.getDescription().getVersion()); advancedKits = this; - if (Minecraft.VERSION.olderThan(Minecraft.Version.v1_9_R1)) { - this.log(ChatColor.RED + "ERROR: Unsupported Minecraft version. (" + Minecraft.VERSION.toString() + ")"); - this.setEnabled(false); - return; - } - // Hooking vault this.log("Hooking to Vault."); Boolean vaultFound = this.getServer().getPluginManager().getPlugin("Vault") != null; @@ -81,7 +74,7 @@ public void onEnable() { // Register events this.log("Registering events"); this.getServer().getPluginManager().registerEvents(new PlayerListener(this), this); - this.getServer().getPluginManager().registerEvents(new CInventoryMain(this), this); + this.getServer().getPluginManager().registerEvents(new CInventoryMain(), this); // Register CommandManager and the Commands. this.log("Registering commands."); @@ -101,18 +94,6 @@ public void onEnable() { commandManager.registerCommand(new UseCommand(this)); commandManager.registerCommand(new MainCommand(this)); - // Check for update - if (Config.AUTOUPDATE_ENABLED) { - this.log("Checking for updates."); - new Updater(this, 91129, this.getFile(), Updater.UpdateType.DEFAULT, true); - } - - // Check if metrics is enabled - if (Config.METRICS_ENABLED) { - this.log("Enabling Plugin Metrics."); - new MetricsLite(this); - } - this.log(ChatColor.GREEN + "Finished loading " + this.getDescription().getName() + " " + this.getDescription().getVersion() + " by " + this.getDescription().getAuthors().stream().collect(Collectors.joining(","))); } diff --git a/src/main/java/hu/tryharddevs/advancedkits/Config.java b/src/main/java/hu/tryharddevs/advancedkits/Config.java index b7a2d1b..ba54b3f 100644 --- a/src/main/java/hu/tryharddevs/advancedkits/Config.java +++ b/src/main/java/hu/tryharddevs/advancedkits/Config.java @@ -13,8 +13,6 @@ public class Config { public static String CHAT_PREFIX = ChatColor.translateAlternateColorCodes('&', "&7[&6AdvancedKits&7]"); public static String LOCALE = "en"; public static Boolean COLORED_LOG = true; - public static Boolean METRICS_ENABLED = true; - public static Boolean AUTOUPDATE_ENABLED = true; public static Boolean TITLES_ENABLED = true; public static Boolean ACTIONBARS_ENABLED = true; public static List DISABLED_WORLDS = new ArrayList<>(); @@ -42,16 +40,6 @@ public static void loadConfigurationValues(AdvancedKitsMain instance) { oldConfig = true; } - if (!config.contains("MetricsEnabled")) { - config.addDefault("MetricsEnabled", true); - oldConfig = true; - } - - if (!config.contains("AutoUpdateEnabled")) { - config.addDefault("AutoUpdateEnabled", true); - oldConfig = true; - } - if (!config.contains("Messages.TitlesEnabled")) { config.addDefault("Messages.TitlesEnabled", true); oldConfig = true; @@ -83,8 +71,6 @@ public static void loadConfigurationValues(AdvancedKitsMain instance) { LOCALE = config.getString("Locale"); COLORED_LOG = config.getBoolean("Log.ColoredLog"); - METRICS_ENABLED = config.getBoolean("MetricsEnabled"); - AUTOUPDATE_ENABLED = config.getBoolean("AutoUpdateEnabled"); TITLES_ENABLED = config.getBoolean("Messages.TitlesEnabled", true); ACTIONBARS_ENABLED = config.getBoolean("Messages.ActionbarsEnabled", true); diff --git a/src/main/java/hu/tryharddevs/advancedkits/MetricsLite.java b/src/main/java/hu/tryharddevs/advancedkits/MetricsLite.java deleted file mode 100644 index 72aaa09..0000000 --- a/src/main/java/hu/tryharddevs/advancedkits/MetricsLite.java +++ /dev/null @@ -1,285 +0,0 @@ -package hu.tryharddevs.advancedkits; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.ServicePriority; -import org.bukkit.plugin.java.JavaPlugin; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -import javax.net.ssl.HttpsURLConnection; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.URL; -import java.util.Timer; -import java.util.TimerTask; -import java.util.UUID; -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! - */ -public class MetricsLite { - - // The version of this bStats class - public static final int B_STATS_VERSION = 1; - // The url to which the data is sent - private static final String URL = "https://bStats.org/submitData/bukkit"; - // Should failed requests be logged? - private static boolean logFailedRequests; - // The uuid of the server - private static String serverUUID; - - static { - // 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'}); - 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 (MetricsLite.class.getPackage().getName().equals(defaultPackage) || MetricsLite.class.getPackage().getName().equals(examplePackage)) { - throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); - } - } - - // The plugin - private final JavaPlugin plugin; - - /** - * Class constructor. - * - * @param plugin The plugin which stats should be submitted. - */ - public MetricsLite(JavaPlugin plugin) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null!"); - } - this.plugin = plugin; - - // Get the config file - File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); - File configFile = new File(bStatsFolder, "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - - // Check if the config file exists - if (!config.isSet("serverUuid")) { - - // 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); - - // 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 { - config.save(configFile); - } catch (IOException ignored) { - } - } - - // Load the data - serverUUID = config.getString("serverUuid"); - logFailedRequests = config.getBoolean("logFailedRequests", false); - if (config.getBoolean("enabled", true)) { - 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(MetricsLite.class, this, plugin, ServicePriority.Normal); - if (!found) { - // We are the first! - startSubmitting(); - } - } - } - - /** - * Sends the data to the bStats server. - * - * @param data The data to send. - * @throws Exception If the request failed. - */ - private static void sendData(JSONObject data) throws Exception { - if (data == null) { - throw new IllegalArgumentException("Data cannot be null!"); - } - if (Bukkit.isPrimaryThread()) { - throw new IllegalAccessException("This method must not be called from the main thread!"); - } - HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); - - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - - // 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(); - - connection.getInputStream().close(); // We don't care about the response - Just send our data :) - } - - /** - * 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("UTF-8")); - gzip.close(); - return outputStream.toByteArray(); - } - - /** - * 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; - } - // 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, new Runnable() { - @Override public void run() { - submitData(); - } - }); - } - }, 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.put("pluginName", pluginName); // Append the name of the plugin - data.put("pluginVersion", pluginVersion); // Append the version of the plugin - JSONArray customCharts = new JSONArray(); - data.put("customCharts", customCharts); - - return data; - } - - /** - * Gets the server specific data. - * - * @return The server specific data. - */ - private JSONObject getServerData() { - // Minecraft specific data - int playerAmount = Bukkit.getOnlinePlayers().size(); - int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; - String bukkitVersion = Bukkit.getVersion(); - bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1); - - // 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(); - - JSONObject data = new JSONObject(); - - data.put("serverUUID", serverUUID); - - data.put("playerAmount", playerAmount); - data.put("onlineMode", onlineMode); - data.put("bukkitVersion", bukkitVersion); - - data.put("javaVersion", javaVersion); - data.put("osName", osName); - data.put("osArch", osArch); - data.put("osVersion", osVersion); - data.put("coreCount", coreCount); - - return data; - } - - /** - * Collects the data and sends it afterwards. - */ - private void submitData() { - final JSONObject data = getServerData(); - - 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 :) - } catch (NoSuchFieldException ignored) { - continue; // Continue "searching" - } - // Found one! - try { - pluginData.add(service.getMethod("getPluginData").invoke(Bukkit.getServicesManager().load(service))); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { - } - } - - data.put("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(data); - } catch (Exception e) { - // Something went wrong! :( - if (logFailedRequests) { - plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); - } - } - } - }).start(); - } - -} \ No newline at end of file diff --git a/src/main/java/hu/tryharddevs/advancedkits/Updater.java b/src/main/java/hu/tryharddevs/advancedkits/Updater.java deleted file mode 100644 index 6be45d3..0000000 --- a/src/main/java/hu/tryharddevs/advancedkits/Updater.java +++ /dev/null @@ -1,780 +0,0 @@ -package hu.tryharddevs.advancedkits; - -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; -import org.bukkit.scheduler.BukkitRunnable; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.JSONValue; - -import java.io.*; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.util.Enumeration; -import java.util.logging.Level; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -/** - * Check for updates on BukkitDev for a given plugin, and download the updates if needed. - *

- * VERY, VERY IMPORTANT: Because there are no standards for adding auto-update toggles in your plugin's config, this system provides NO CHECK WITH YOUR CONFIG to make sure the user has allowed auto-updating. - *
- * It is a BUKKIT POLICY that you include a boolean value in your config that prevents the auto-updater from running AT ALL. - *
- * If you fail to include this option in your config, your plugin will be REJECTED when you attempt to submit it to dev.bukkit.org. - *

- * An example of a good configuration option would be something similar to 'auto-update: true' - if this value is set to false you may NOT run the auto-updater. - *
- * If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l - * - * @author Gravity - * @version 2.4 - */ - -public class Updater { - - /* Constants */ - - // Remote file's title - private static final String TITLE_VALUE = "name"; - // Remote file's download link - private static final String LINK_VALUE = "downloadUrl"; - // Remote file's release type - private static final String TYPE_VALUE = "releaseType"; - // Remote file's build version - private static final String VERSION_VALUE = "gameVersion"; - // Path to GET - private static final String QUERY = "/servermods/files?projectIds="; - // Slugs will be appended to this to get to the project's RSS feed - private static final String HOST = "https://api.curseforge.com"; - // User-agent when querying Curse - private static final String USER_AGENT = "Updater (by Gravity)"; - // Used for locating version numbers in file names - private static final String DELIMETER = "^v|[\\s_-]v"; - // If the version number contains one of these, don't update. - private static final String[] NO_UPDATE_TAG = {"-DEV", "-PRE", "-SNAPSHOT"}; - // Used for downloading files - private static final int BYTE_SIZE = 1024; - // Config key for api key - private static final String API_KEY_CONFIG_KEY = "api-key"; - // Config key for disabling Updater - private static final String DISABLE_CONFIG_KEY = "disable"; - // Default api key value in config - private static final String API_KEY_DEFAULT = "PUT_API_KEY_HERE"; - // Default disable value in config - private static final boolean DISABLE_DEFAULT = false; - - /* User-provided variables */ - - // Plugin running Updater - private final Plugin plugin; - // Type of update check to run - private final UpdateType type; - // Whether to announce file downloads - private final boolean announce; - // The plugin file (jar) - private final File file; - // The folder that downloads will be placed in - private final File updateFolder; - // The provided callback (if any) - private final UpdateCallback callback; - // Project's Curse ID - private int id = -1; - // BukkitDev ServerMods API key - private String apiKey = null; - - /* Collected from Curse API */ - - private String versionName; - private String versionLink; - private String versionType; - private String versionGameVersion; - - /* Update process variables */ - - // Connection to RSS - private URL url; - // Updater thread - private Thread thread; - // Used for determining the outcome of the update process - private Updater.UpdateResult result = Updater.UpdateResult.SUCCESS; - - /** - * Initialize the updater. - * - * @param plugin The plugin that is checking for an update. - * @param id The dev.bukkit.org id of the project. - * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class. - * @param type Specify the type of update this will be. See {@link UpdateType} - * @param announce True if the program should announce the progress of new updates in console. - */ - public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) { - this(plugin, id, file, type, null, announce); - } - - /** - * Initialize the updater with the provided callback. - * - * @param plugin The plugin that is checking for an update. - * @param id The dev.bukkit.org id of the project. - * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class. - * @param type Specify the type of update this will be. See {@link UpdateType} - * @param callback The callback instance to notify when the Updater has finished - */ - public Updater(Plugin plugin, int id, File file, UpdateType type, UpdateCallback callback) { - this(plugin, id, file, type, callback, false); - } - - /** - * Initialize the updater with the provided callback. - * - * @param plugin The plugin that is checking for an update. - * @param id The dev.bukkit.org id of the project. - * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class. - * @param type Specify the type of update this will be. See {@link UpdateType} - * @param callback The callback instance to notify when the Updater has finished - * @param announce True if the program should announce the progress of new updates in console. - */ - public Updater(Plugin plugin, int id, File file, UpdateType type, UpdateCallback callback, boolean announce) { - this.plugin = plugin; - this.type = type; - this.announce = announce; - this.file = file; - this.id = id; - this.updateFolder = this.plugin.getServer().getUpdateFolderFile(); - this.callback = callback; - - final File pluginFile = this.plugin.getDataFolder().getParentFile(); - final File updaterFile = new File(pluginFile, "Updater"); - final File updaterConfigFile = new File(updaterFile, "config.yml"); - - YamlConfiguration config = new YamlConfiguration(); - config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n' + "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n' + "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration."); - config.addDefault(API_KEY_CONFIG_KEY, API_KEY_DEFAULT); - config.addDefault(DISABLE_CONFIG_KEY, DISABLE_DEFAULT); - - if (!updaterFile.exists()) { - this.fileIOOrError(updaterFile, updaterFile.mkdir(), true); - } - - boolean createFile = !updaterConfigFile.exists(); - try { - if (createFile) { - this.fileIOOrError(updaterConfigFile, updaterConfigFile.createNewFile(), true); - config.options().copyDefaults(true); - config.save(updaterConfigFile); - } else { - config.load(updaterConfigFile); - } - } catch (final Exception e) { - final String message; - if (createFile) { - message = "The updater could not create configuration at " + updaterFile.getAbsolutePath(); - } else { - message = "The updater could not load configuration at " + updaterFile.getAbsolutePath(); - } - this.plugin.getLogger().log(Level.SEVERE, message, e); - } - - if (config.getBoolean(DISABLE_CONFIG_KEY)) { - this.result = UpdateResult.DISABLED; - return; - } - - String key = config.getString(API_KEY_CONFIG_KEY); - if (API_KEY_DEFAULT.equalsIgnoreCase(key) || "".equals(key)) { - key = null; - } - - this.apiKey = key; - - try { - this.url = new URL(Updater.HOST + Updater.QUERY + this.id); - } catch (final MalformedURLException e) { - this.plugin.getLogger().log(Level.SEVERE, "The project ID provided for updating, " + this.id + " is invalid.", e); - this.result = UpdateResult.FAIL_BADID; - } - - if (this.result != UpdateResult.FAIL_BADID) { - this.thread = new Thread(new UpdateRunnable()); - this.thread.start(); - } else { - runUpdater(); - } - } - - /** - * Get the result of the update process. - * - * @return result of the update process. - * - * @see UpdateResult - */ - public Updater.UpdateResult getResult() { - this.waitForThread(); - return this.result; - } - - /** - * Get the latest version's release type. - * - * @return latest version's release type. - * - * @see ReleaseType - */ - public ReleaseType getLatestType() { - this.waitForThread(); - if (this.versionType != null) { - for (ReleaseType type : ReleaseType.values()) { - if (this.versionType.equalsIgnoreCase(type.name())) { - return type; - } - } - } - return null; - } - - /** - * Get the latest version's game version (such as "CB 1.2.5-R1.0"). - * - * @return latest version's game version. - */ - public String getLatestGameVersion() { - this.waitForThread(); - return this.versionGameVersion; - } - - /** - * Get the latest version's name (such as "Project v1.0"). - * - * @return latest version's name. - */ - public String getLatestName() { - this.waitForThread(); - return this.versionName; - } - - /** - * Get the latest version's direct file link. - * - * @return latest version's file link. - */ - public String getLatestFileLink() { - this.waitForThread(); - return this.versionLink; - } - - /** - * As the result of Updater output depends on the thread's completion, it is necessary to wait for the thread to finish - * before allowing anyone to check the result. - */ - private void waitForThread() { - if ((this.thread != null) && this.thread.isAlive()) { - try { - this.thread.join(); - } catch (final InterruptedException e) { - this.plugin.getLogger().log(Level.SEVERE, null, e); - } - } - } - - /** - * Save an update from dev.bukkit.org into the server's update folder. - * - * @param file the name of the file to save it as. - */ - private void saveFile(String file) { - final File folder = this.updateFolder; - - deleteOldFiles(); - if (!folder.exists()) { - this.fileIOOrError(folder, folder.mkdir(), true); - } - downloadFile(); - - // Check to see if it's a zip file, if it is, unzip it. - final File dFile = new File(folder.getAbsolutePath(), file); - if (dFile.getName().endsWith(".zip")) { - // Unzip - this.unzip(dFile.getAbsolutePath()); - } - if (this.announce) { - this.plugin.getLogger().info("Finished updating."); - } - } - - /** - * Download a file and save it to the specified folder. - */ - private void downloadFile() { - BufferedInputStream in = null; - FileOutputStream fout = null; - try { - URL fileUrl = followRedirects(this.versionLink); - final int fileLength = fileUrl.openConnection().getContentLength(); - in = new BufferedInputStream(fileUrl.openStream()); - fout = new FileOutputStream(new File(this.updateFolder, file.getName())); - - final byte[] data = new byte[Updater.BYTE_SIZE]; - int count; - if (this.announce) { - this.plugin.getLogger().info("About to download a new update: " + this.versionName); - } - long downloaded = 0; - while ((count = in.read(data, 0, Updater.BYTE_SIZE)) != -1) { - downloaded += count; - fout.write(data, 0, count); - final int percent = (int) ((downloaded * 100) / fileLength); - if (this.announce && ((percent % 10) == 0)) { - this.plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes."); - } - } - } catch (Exception ex) { - this.plugin.getLogger().log(Level.WARNING, "The auto-updater tried to download a new update, but was unsuccessful.", ex); - this.result = Updater.UpdateResult.FAIL_DOWNLOAD; - } finally { - try { - if (in != null) { - in.close(); - } - } catch (final IOException ex) { - this.plugin.getLogger().log(Level.SEVERE, null, ex); - } - try { - if (fout != null) { - fout.close(); - } - } catch (final IOException ex) { - this.plugin.getLogger().log(Level.SEVERE, null, ex); - } - } - } - - private URL followRedirects(String location) throws IOException { - URL resourceUrl, base, next; - HttpURLConnection conn; - String redLoc; - while (true) { - resourceUrl = new URL(location); - conn = (HttpURLConnection) resourceUrl.openConnection(); - - conn.setConnectTimeout(15000); - conn.setReadTimeout(15000); - conn.setInstanceFollowRedirects(false); - conn.setRequestProperty("User-Agent", "Mozilla/5.0..."); - - switch (conn.getResponseCode()) { - case HttpURLConnection.HTTP_MOVED_PERM: - case HttpURLConnection.HTTP_MOVED_TEMP: - redLoc = conn.getHeaderField("Location"); - base = new URL(location); - next = new URL(base, redLoc); // Deal with relative URLs - location = next.toExternalForm(); - continue; - } - break; - } - return conn.getURL(); - } - - /** - * Remove possibly leftover files from the update folder. - */ - private void deleteOldFiles() { - //Just a quick check to make sure we didn't leave any files from last time... - File[] list = listFilesOrError(this.updateFolder); - for (final File xFile : list) { - if (xFile.getName().endsWith(".zip")) { - this.fileIOOrError(xFile, xFile.mkdir(), true); - } - } - } - - /** - * Part of Zip-File-Extractor, modified by Gravity for use with Updater. - * - * @param file the location of the file to extract. - */ - private void unzip(String file) { - final File fSourceZip = new File(file); - try { - final String zipPath = file.substring(0, file.length() - 4); - ZipFile zipFile = new ZipFile(fSourceZip); - Enumeration e = zipFile.entries(); - while (e.hasMoreElements()) { - ZipEntry entry = e.nextElement(); - File destinationFilePath = new File(zipPath, entry.getName()); - this.fileIOOrError(destinationFilePath.getParentFile(), destinationFilePath.getParentFile().mkdirs(), true); - if (!entry.isDirectory()) { - final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); - int b; - final byte[] buffer = new byte[Updater.BYTE_SIZE]; - final FileOutputStream fos = new FileOutputStream(destinationFilePath); - final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE); - while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) { - bos.write(buffer, 0, b); - } - bos.flush(); - bos.close(); - bis.close(); - final String name = destinationFilePath.getName(); - if (name.endsWith(".jar") && this.pluginExists(name)) { - File output = new File(this.updateFolder, name); - this.fileIOOrError(output, destinationFilePath.renameTo(output), true); - } - } - } - zipFile.close(); - - // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. - moveNewZipFiles(zipPath); - - } catch (final IOException e) { - this.plugin.getLogger().log(Level.SEVERE, "The auto-updater tried to unzip a new update file, but was unsuccessful.", e); - this.result = Updater.UpdateResult.FAIL_DOWNLOAD; - } finally { - this.fileIOOrError(fSourceZip, fSourceZip.delete(), false); - } - } - - /** - * Find any new files extracted from an update into the plugin's data directory. - * - * @param zipPath path of extracted files. - */ - private void moveNewZipFiles(String zipPath) { - File[] list = listFilesOrError(new File(zipPath)); - for (final File dFile : list) { - if (dFile.isDirectory() && this.pluginExists(dFile.getName())) { - // Current dir - final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName()); - // List of existing files in the new dir - final File[] dList = listFilesOrError(dFile); - // List of existing files in the current dir - final File[] oList = listFilesOrError(oFile); - for (File cFile : dList) { - // Loop through all the files in the new dir - boolean found = false; - for (final File xFile : oList) { - // Loop through all the contents in the current dir to see if it exists - if (xFile.getName().equals(cFile.getName())) { - found = true; - break; - } - } - if (!found) { - // Move the new file into the current dir - File output = new File(oFile, cFile.getName()); - this.fileIOOrError(output, cFile.renameTo(output), true); - } else { - // This file already exists, so we don't need it anymore. - this.fileIOOrError(cFile, cFile.delete(), false); - } - } - } - this.fileIOOrError(dFile, dFile.delete(), false); - } - File zip = new File(zipPath); - this.fileIOOrError(zip, zip.delete(), false); - } - - /** - * Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip. - * - * @param name a name to check for inside the plugins folder. - * @return true if a file inside the plugins folder is named this. - */ - private boolean pluginExists(String name) { - File[] plugins = listFilesOrError(new File("plugins")); - for (final File file : plugins) { - if (file.getName().equals(name)) { - return true; - } - } - return false; - } - - /** - * Check to see if the program should continue by evaluating whether the plugin is already updated, or shouldn't be updated. - * - * @return true if the version was located and is not the same as the remote's newest. - */ - private boolean versionCheck() { - final String title = this.versionName; - if (this.type != UpdateType.NO_VERSION_CHECK) { - final String localVersion = this.plugin.getDescription().getVersion(); - if (title.split(DELIMETER).length >= 2) { - // Get the newest file's version number - final String remoteVersion = title.split(DELIMETER)[title.split(DELIMETER).length - 1].split(" ")[0]; - - if (this.hasTag(localVersion) || !this.shouldUpdate(localVersion, remoteVersion)) { - // We already have the latest version, or this build is tagged for no-update - this.result = Updater.UpdateResult.NO_UPDATE; - return false; - } - } else { - // The file's name did not contain the string 'vVersion' - final String authorInfo = this.plugin.getDescription().getAuthors().isEmpty() ? "" : " (" + this.plugin.getDescription().getAuthors().get(0) + ")"; - this.plugin.getLogger().warning("The author of this plugin" + authorInfo + " has misconfigured their Auto Update system"); - this.plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'"); - this.plugin.getLogger().warning("Please notify the author of this error."); - this.result = Updater.UpdateResult.FAIL_NOVERSION; - return false; - } - } - return true; - } - - /** - * If you wish to run mathematical versioning checks, edit this method. - *

- * With default behavior, Updater will NOT verify that a remote version available on BukkitDev - * which is not this version is indeed an "update". - * If a version is present on BukkitDev that is not the version that is currently running, - * Updater will assume that it is a newer version. - * This is because there is no standard versioning scheme, and creating a calculation that can - * determine whether a new update is actually an update is sometimes extremely complicated. - *

- *

- * Updater will call this method from {@link #versionCheck()} before deciding whether - * the remote version is actually an update. - * If you have a specific versioning scheme with which a mathematical determination can - * be reliably made to decide whether one version is higher than another, you may - * revise this method, using the local and remote version parameters, to execute the - * appropriate check. - *

- *

- * Returning a value of false will tell the update process that this is NOT a new version. - * Without revision, this method will always consider a remote version at all different from - * that of the local version a new update. - *

- * - * @param localVersion the current version - * @param remoteVersion the remote version - * @return true if Updater should consider the remote version an update, false if not. - */ - public boolean shouldUpdate(String localVersion, String remoteVersion) { - Integer iLocal = Integer.valueOf(localVersion.replace(".", "")); - Integer iRemote = Integer.valueOf(remoteVersion.replace(".", "")); - return (iRemote > iLocal); - //return !localVersion.equalsIgnoreCase(remoteVersion); - } - - /** - * Evaluate whether the version number is marked showing that it should not be updated by this program. - * - * @param version a version number to check for tags in. - * @return true if updating should be disabled. - */ - private boolean hasTag(String version) { - for (final String string : Updater.NO_UPDATE_TAG) { - if (version.toUpperCase().contains(string)) { - return true; - } - } - return false; - } - - /** - * Make a connection to the BukkitDev API and request the newest file's details. - * - * @return true if successful. - */ - private boolean read() { - try { - final URLConnection conn = this.url.openConnection(); - conn.setConnectTimeout(5000); - - if (this.apiKey != null) { - conn.addRequestProperty("X-API-Key", this.apiKey); - } - conn.addRequestProperty("User-Agent", Updater.USER_AGENT); - - conn.setDoOutput(true); - - final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); - final String response = reader.readLine(); - - final JSONArray array = (JSONArray) JSONValue.parse(response); - - if (array.isEmpty()) { - this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id); - this.result = UpdateResult.FAIL_BADID; - return false; - } - - JSONObject latestUpdate = (JSONObject) array.get(array.size() - 1); - this.versionName = (String) latestUpdate.get(Updater.TITLE_VALUE); - this.versionLink = (String) latestUpdate.get(Updater.LINK_VALUE); - this.versionType = (String) latestUpdate.get(Updater.TYPE_VALUE); - this.versionGameVersion = (String) latestUpdate.get(Updater.VERSION_VALUE); - - return true; - } catch (final IOException e) { - if (e.getMessage().contains("HTTP response code: 403")) { - this.plugin.getLogger().severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); - this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct."); - this.result = UpdateResult.FAIL_APIKEY; - } else { - this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating."); - this.plugin.getLogger().severe("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); - this.result = UpdateResult.FAIL_DBO; - } - this.plugin.getLogger().log(Level.SEVERE, null, e); - return false; - } - } - - /** - * Perform a file operation and log any errors if it fails. - * - * @param file file operation is performed on. - * @param result result of file operation. - * @param create true if a file is being created, false if deleted. - */ - private void fileIOOrError(File file, boolean result, boolean create) { - if (!result) { - this.plugin.getLogger().severe("The updater could not " + (create ? "create" : "delete") + " file at: " + file.getAbsolutePath()); - } - } - - private File[] listFilesOrError(File folder) { - File[] contents = folder.listFiles(); - if (contents == null) { - this.plugin.getLogger().severe("The updater could not access files at: " + this.updateFolder.getAbsolutePath()); - return new File[0]; - } else { - return contents; - } - } - - private void runUpdater() { - if (this.url != null && (this.read() && this.versionCheck())) { - // Obtain the results of the project's file feed - if ((this.versionLink != null) && (this.type != UpdateType.NO_DOWNLOAD)) { - String name = this.file.getName(); - // If it's a zip file, it shouldn't be downloaded as the plugin's name - if (this.versionLink.endsWith(".zip")) { - name = this.versionLink.substring(this.versionLink.lastIndexOf("/") + 1); - } - this.saveFile(name); - } else { - this.result = UpdateResult.UPDATE_AVAILABLE; - } - } - - if (this.callback != null) { - new BukkitRunnable() { - @Override - public void run() { - runCallback(); - } - }.runTask(this.plugin); - } - } - - private void runCallback() { - this.callback.onFinish(this); - } - - /** - * Gives the developer the result of the update process. Can be obtained by called {@link #getResult()} - */ - public enum UpdateResult { - /** - * The updater found an update, and has readied it to be loaded the next time the server restarts/reloads. - */ - SUCCESS, - /** - * The updater did not find an update, and nothing was downloaded. - */ - NO_UPDATE, - /** - * The server administrator has disabled the updating system. - */ - DISABLED, - /** - * The updater found an update, but was unable to download it. - */ - FAIL_DOWNLOAD, - /** - * For some reason, the updater was unable to contact dev.bukkit.org to download the file. - */ - FAIL_DBO, - /** - * When running the version check, the file on DBO did not contain a recognizable version. - */ - FAIL_NOVERSION, - /** - * The id provided by the plugin running the updater was invalid and doesn't exist on DBO. - */ - FAIL_BADID, - /** - * The server administrator has improperly configured their API key in the configuration. - */ - FAIL_APIKEY, - /** - * The updater found an update, but because of the UpdateType being set to NO_DOWNLOAD, it wasn't downloaded. - */ - UPDATE_AVAILABLE - } - - /** - * Allows the developer to specify the type of update that will be run. - */ - public enum UpdateType { - /** - * Run a version check, and then if the file is out of date, download the newest version. - */ - DEFAULT, - /** - * Don't run a version check, just find the latest update and download it. - */ - NO_VERSION_CHECK, - /** - * Get information about the version and the download size, but don't actually download anything. - */ - NO_DOWNLOAD - } - - /** - * Represents the various release types of a file on BukkitDev. - */ - public enum ReleaseType { - /** - * An "alpha" file. - */ - ALPHA, - /** - * A "beta" file. - */ - BETA, - /** - * A "release" file. - */ - RELEASE - } - - /** - * Called on main thread when the Updater has finished working, regardless - * of result. - */ - public interface UpdateCallback { - /** - * Called when the updater has finished working. - * - * @param updater The updater instance - */ - void onFinish(Updater updater); - } - - private class UpdateRunnable implements Runnable { - @Override - public void run() { - runUpdater(); - } - } -} \ No newline at end of file diff --git a/src/main/java/hu/tryharddevs/advancedkits/cinventory/CInventoryMain.java b/src/main/java/hu/tryharddevs/advancedkits/cinventory/CInventoryMain.java index f37bf85..97c0aff 100644 --- a/src/main/java/hu/tryharddevs/advancedkits/cinventory/CInventoryMain.java +++ b/src/main/java/hu/tryharddevs/advancedkits/cinventory/CInventoryMain.java @@ -1,6 +1,5 @@ package hu.tryharddevs.advancedkits.cinventory; -import hu.tryharddevs.advancedkits.AdvancedKitsMain; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -14,14 +13,8 @@ public class CInventoryMain implements Listener { - private final AdvancedKitsMain instance; - private static final ArrayList cInventoryArrayList = new ArrayList<>(); - public CInventoryMain(AdvancedKitsMain instance) { - this.instance = instance; - } - public static void registerInventory(CInventory cInventory) { cInventoryArrayList.add(cInventory); } diff --git a/src/main/java/hu/tryharddevs/advancedkits/cinventory/inventories/CPageInventory.java b/src/main/java/hu/tryharddevs/advancedkits/cinventory/inventories/CPageInventory.java index de56a7d..cacf328 100644 --- a/src/main/java/hu/tryharddevs/advancedkits/cinventory/inventories/CPageInventory.java +++ b/src/main/java/hu/tryharddevs/advancedkits/cinventory/inventories/CPageInventory.java @@ -187,7 +187,7 @@ public void setExitInventory(ItemStack item) { public ItemStack getBackPage() { if (this.backAPage == null) { - this.backAPage = new ItemBuilder(new ItemStack(Material.SIGN)).setName(getMessage("guiBackpage")).setLore(getMessage("guiBackpageLore")).toItemStack(); + this.backAPage = new ItemBuilder(new ItemStack(Material.OAK_SIGN)).setName(getMessage("guiBackpage")).setLore(getMessage("guiBackpageLore")).toItemStack(); } return this.backAPage; } @@ -202,7 +202,7 @@ private int getCurrentPage() { public ItemStack getForwardsPage() { if (this.forwardsAPage == null) { - this.forwardsAPage = new ItemBuilder(new ItemStack(Material.SIGN)).setName(getMessage("guiNextpage")).setLore(getMessage("guiNextpageLore")).toItemStack(); + this.forwardsAPage = new ItemBuilder(new ItemStack(Material.OAK_SIGN)).setName(getMessage("guiNextpage")).setLore(getMessage("guiNextpageLore")).toItemStack(); } return this.forwardsAPage; } diff --git a/src/main/java/hu/tryharddevs/advancedkits/commands/CreateCommand.java b/src/main/java/hu/tryharddevs/advancedkits/commands/CreateCommand.java index 5ff215e..d64c5f9 100644 --- a/src/main/java/hu/tryharddevs/advancedkits/commands/CreateCommand.java +++ b/src/main/java/hu/tryharddevs/advancedkits/commands/CreateCommand.java @@ -16,7 +16,6 @@ import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.inventory.ItemStack; -import org.inventivetalent.reflection.minecraft.Minecraft; import java.util.ArrayList; import java.util.Arrays; @@ -54,16 +53,14 @@ public void onCreateCommand(Player player, String kitName) { cSimpleInventory.setItem(38, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorLeggings")).toItemStack()); cSimpleInventory.setItem(39, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorBoots")).toItemStack()); - if (Minecraft.VERSION.newerThan(Minecraft.Version.v1_9_R1)) { - cSimpleInventory.setItem(40, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorShield")).toItemStack()); - } + cSimpleInventory.setItem(40, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorShield")).toItemStack()); - cSimpleInventory.setItem(45, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 3).setName(getMessage("saveToSession")).toItemStack()); + cSimpleInventory.setItem(45, new ItemBuilder(Material.GREEN_STAINED_GLASS_PANE).setName(getMessage("saveToSession")).toItemStack()); if (!session.getKitItems().isEmpty() || !session.getKitArmors().isEmpty()) { - cSimpleInventory.setItem(46, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 3).setName(getMessage("loadFromSession")).toItemStack()); + cSimpleInventory.setItem(46, new ItemBuilder(Material.GREEN_STAINED_GLASS_PANE).setName(getMessage("loadFromSession")).toItemStack()); } - cSimpleInventory.setItem(53, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 13).setName(getMessage("guiCreateKit", kitName)).toItemStack()); + cSimpleInventory.setItem(53, new ItemBuilder(Material.BLUE_STAINED_GLASS_PANE).setName(getMessage("guiCreateKit", kitName)).toItemStack()); cSimpleInventory.openInventory(); @@ -144,8 +141,6 @@ public void onCreateCommand(Player player, String kitName) { // Shield case 40: { - if (!Minecraft.VERSION.newerThan(Minecraft.Version.v1_9_R1)) break; - if (Objects.isNull(itemOnCursor) || itemOnCursor.getType() == Material.AIR) { event.getInventory().setItem(clickedSlot, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorShield")).toItemStack()); } else if (ItemStackUtil.isShield(itemOnCursor)) { @@ -188,7 +183,7 @@ public void onCreateCommand(Player player, String kitName) { else if (ItemStackUtil.isChest(armor)) event.getInventory().setItem(37, armor); else if (ItemStackUtil.isLegs(armor)) event.getInventory().setItem(38, armor); else if (ItemStackUtil.isBoots(armor)) event.getInventory().setItem(39, armor); - else if (Minecraft.VERSION.newerThan(Minecraft.Version.v1_9_R1) && ItemStackUtil.isShield(armor)) + else if (ItemStackUtil.isShield(armor)) event.getInventory().setItem(40, armor); } diff --git a/src/main/java/hu/tryharddevs/advancedkits/commands/EditCommand.java b/src/main/java/hu/tryharddevs/advancedkits/commands/EditCommand.java index 63ec70d..8d6857c 100644 --- a/src/main/java/hu/tryharddevs/advancedkits/commands/EditCommand.java +++ b/src/main/java/hu/tryharddevs/advancedkits/commands/EditCommand.java @@ -86,16 +86,16 @@ public void onEditCommand(Player player, @Optional Kit kit) { else if (ItemStackUtil.isChest(armor)) cSimpleInventory.setItem(37, armor); else if (ItemStackUtil.isLegs(armor)) cSimpleInventory.setItem(38, armor); else if (ItemStackUtil.isBoots(armor)) cSimpleInventory.setItem(39, armor); - else if (Minecraft.VERSION.newerThan(Minecraft.Version.v1_9_R1) && ItemStackUtil.isShield(armor)) + else if (ItemStackUtil.isShield(armor)) cSimpleInventory.setItem(40, armor); } - cSimpleInventory.setItem(45, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 3).setName(getMessage("saveToSession")).toItemStack()); + cSimpleInventory.setItem(45, new ItemBuilder(Material.LIGHT_BLUE_STAINED_GLASS_PANE).setName(getMessage("saveToSession")).toItemStack()); if (!session.getKitItems().isEmpty() || !session.getKitArmors().isEmpty()) { - cSimpleInventory.setItem(46, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 3).setName(getMessage("loadFromSession")).setLore(getMessage("loadFromSessionWarning")).toItemStack()); + cSimpleInventory.setItem(46, new ItemBuilder(Material.LIGHT_BLUE_STAINED_GLASS_PANE).setName(getMessage("loadFromSession")).setLore(getMessage("loadFromSessionWarning")).toItemStack()); } - cSimpleInventory.setItem(53, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 13).setName(getMessage("guiEditKit", kit.getName())).toItemStack()); + cSimpleInventory.setItem(53, new ItemBuilder(Material.GREEN_STAINED_GLASS_PANE).setName(getMessage("guiEditKit", kit.getName())).toItemStack()); cSimpleInventory.openInventory(); //Check if there's a missing armor piece from the gui. If so replace it with the holder @@ -108,10 +108,8 @@ else if (Minecraft.VERSION.newerThan(Minecraft.Version.v1_9_R1) && ItemStackUtil if (Objects.isNull(cSimpleInventory.getItem(39))) cSimpleInventory.setItem(39, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorBoots")).toItemStack()); - if (Minecraft.VERSION.newerThan(Minecraft.Version.v1_9_R1)) { - if (Objects.isNull(cSimpleInventory.getItem(40))) - cSimpleInventory.setItem(40, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorShield")).toItemStack()); - } + if (Objects.isNull(cSimpleInventory.getItem(40))) + cSimpleInventory.setItem(40, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorShield")).toItemStack()); cSimpleInventory.onInventoryDragEvent(event -> { if (!Stream.of( diff --git a/src/main/java/hu/tryharddevs/advancedkits/commands/MainCommand.java b/src/main/java/hu/tryharddevs/advancedkits/commands/MainCommand.java index 1443144..95452f6 100644 --- a/src/main/java/hu/tryharddevs/advancedkits/commands/MainCommand.java +++ b/src/main/java/hu/tryharddevs/advancedkits/commands/MainCommand.java @@ -1,7 +1,13 @@ package hu.tryharddevs.advancedkits.commands; import co.aikar.commands.BaseCommand; -import co.aikar.commands.annotation.*; +import co.aikar.commands.annotation.CommandAlias; +import co.aikar.commands.annotation.CommandCompletion; +import co.aikar.commands.annotation.CommandPermission; +import co.aikar.commands.annotation.Default; +import co.aikar.commands.annotation.Optional; +import co.aikar.commands.annotation.Subcommand; +import co.aikar.commands.annotation.Syntax; import co.aikar.commands.contexts.OnlinePlayer; import hu.tryharddevs.advancedkits.AdvancedKitsMain; import hu.tryharddevs.advancedkits.Config; @@ -31,7 +37,6 @@ import static hu.tryharddevs.advancedkits.utils.MessagesApi.sendMessage; import static hu.tryharddevs.advancedkits.utils.localization.I18n.getMessage; -@SuppressWarnings("ConstantConditions") @CommandAlias("%rootcommand") public class MainCommand extends BaseCommand { private final AdvancedKitsMain instance; @@ -120,18 +125,18 @@ public void onDeleteCommand(CommandSender sender, @Optional Kit kit) { CSimpleInventory cSimpleInventory = new CSimpleInventory("AdvancedKits - Delete Kit", player); - cSimpleInventory.setItem(2, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 13).setName(getMessage("guiConfirm")).toItemStack()); - cSimpleInventory.setItem(6, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 14).setName(getMessage("guiCancel")).toItemStack()); + cSimpleInventory.setItem(2, new ItemBuilder(Material.GREEN_STAINED_GLASS_PANE).setName(getMessage("guiConfirm")).toItemStack()); + cSimpleInventory.setItem(6, new ItemBuilder(Material.RED_STAINED_GLASS_PANE).setName(getMessage("guiCancel")).toItemStack()); cSimpleInventory.openInventory(); cSimpleInventory.onInventoryClickEvent((_event) -> { if (_event.getCurrentItem() == null) return; - ItemStack item = _event.getCurrentItem(); - if (item.getDurability() == (short) 14) //Cancel + Material item = _event.getCurrentItem().getType(); + if (item == Material.RED_STAINED_GLASS_PANE) //Cancel { _event.getWhoClicked().closeInventory(); - } else if (item.getDurability() == (short) 13) //Delete + } else if (item == Material.GREEN_STAINED_GLASS_PANE) //Delete { _event.getWhoClicked().closeInventory(); instance.getKitManager().deleteKit(kit); @@ -261,8 +266,11 @@ public void onViewCommand(Player player, @Optional Kit kit) { } if (Objects.isNull(kit)) { - CPageInventory cPageInventory = new CPageInventory("AdvancedKits - View Kit", player); - cPageInventory.setPages(KitManager.getKits().stream().filter(_kit -> _kit.getFlag(VISIBLE, world)).sorted(Comparator.comparing(Kit::getName)).map(_kit -> new ItemBuilder(_kit.getFlag(ICON, world).clone()).setName(ChatColor.WHITE + _kit.getDisplayName(world)).setLore(KitManager.getKitDescription(player, _kit, world)).hideAttributes().toItemStack()).collect(Collectors.toCollection(ArrayList::new))); + CPageInventory cPageInventory = new CPageInventory("Kit Auswahl", player); + cPageInventory.setPages(KitManager.getKits().stream().filter(_kit -> _kit.getFlag(VISIBLE, world)) + .sorted(Comparator.comparing(Kit::getName)).map(_kit -> new ItemBuilder(_kit.getFlag(ICON, world).clone()) + .setName(ChatColor.WHITE + _kit.getDisplayName(world)).setLore(KitManager.getKitDescription(player, _kit, world)).hideAttributes() + .toItemStack()).collect(Collectors.toCollection(ArrayList::new))); cPageInventory.openInventory(); cPageInventory.onInventoryClickEvent((_event) -> { @@ -280,12 +288,19 @@ public void onViewCommand(Player player, @Optional Kit kit) { } _player.closeInventory(); - Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit view " + clickedKit.getName()); + if(_event.getClick().isRightClick()) { + Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit view " + clickedKit.getName()); + } else { + Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit use " + clickedKit.getName()); + if(clickedKit.getFlag(KEEPINVENTORYOPEN, world)) { + Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit view"); + } + } }); return; } - CSimpleInventory cSimpleInventory = new CSimpleInventory("AdvancedKits - View Kit", player, 54); + CSimpleInventory cSimpleInventory = new CSimpleInventory("Kit-Vorschau", player, 54); cSimpleInventory.addItems(kit.getItems()); int i = 36; @@ -297,12 +312,12 @@ public void onViewCommand(Player player, @Optional Kit kit) { cSimpleInventory.setItem(49, new ItemBuilder(Material.PAPER).setName(getMessage("informations")).setLore(KitManager.getKitDescription(player, kit, world)).toItemStack()); if (user.isUnlocked(kit) || kit.getFlag(FREE, world)) { - cSimpleInventory.setItem(53, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 13).setName(ChatColor.GREEN + getMessage("guiUse")).hideAttributes().toItemStack()); + cSimpleInventory.setItem(53, new ItemBuilder(Material.GREEN_STAINED_GLASS_PANE).setName(ChatColor.GREEN + getMessage("guiUse")).hideAttributes().toItemStack()); } else if (kit.getFlag(COST, world) > 0) { - cSimpleInventory.setItem(53, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 14).setName(ChatColor.GREEN + getMessage("guiBuy")).hideAttributes().toItemStack()); + cSimpleInventory.setItem(53, new ItemBuilder(Material.RED_STAINED_GLASS_PANE).setName(ChatColor.GREEN + getMessage("guiBuy")).hideAttributes().toItemStack()); } - cSimpleInventory.setItem(45, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 0).setName(ChatColor.GREEN + getMessage("guiBackToMenu")).hideAttributes().toItemStack()); + cSimpleInventory.setItem(45, new ItemBuilder(Material.WHITE_STAINED_GLASS_PANE).setName(ChatColor.GREEN + getMessage("guiBackToMenu")).hideAttributes().toItemStack()); cSimpleInventory.openInventory(); cSimpleInventory.onInventoryClickEvent((_event) -> { @@ -311,12 +326,15 @@ public void onViewCommand(Player player, @Optional Kit kit) { return; Player _player = (Player) _event.getWhoClicked(); - if (clickedItem.getType() == Material.STAINED_GLASS_PANE) { - if (clickedItem.getDurability() == (short) 13) { + if (clickedItem.getType() == Material.GREEN_STAINED_GLASS_PANE || clickedItem.getType() == Material.RED_STAINED_GLASS_PANE|| clickedItem.getType() == Material.WHITE_STAINED_GLASS_PANE) { + if (clickedItem.getType() == Material.GREEN_STAINED_GLASS_PANE) { Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit use " + kit.getName()); - } else if (clickedItem.getDurability() == (short) 14) { + if(kit.getFlag(KEEPINVENTORYOPEN, world)) { + Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit view"); + } + } else if (clickedItem.getType() == Material.RED_STAINED_GLASS_PANE) { Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit buy " + kit.getName()); - } else if (clickedItem.getDurability() == (short) 0) { + } else if (clickedItem.getType() == Material.WHITE_STAINED_GLASS_PANE) { Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit view"); } } @@ -328,7 +346,7 @@ public void onViewCommand(Player player, @Optional Kit kit) { @CommandPermission("advancedkits.flag") @CommandCompletion("@kits @flags") @Syntax(" [world]") - public void onFlagCommand(CommandSender sender, Kit kit, Flag flag, String value, @Optional String world) { + public void onFlagCommand(CommandSender sender, Kit kit, Flag flag, String value, @Optional String world) { String tempValue = String.join(" ", value, Objects.isNull(world) ? "" : world); String[] splittedValue = tempValue.split(" "); @@ -349,7 +367,7 @@ public void onFlagCommand(CommandSender sender, Kit kit, Flag flag, String value } if (flag.getName().equalsIgnoreCase("firework")) { - if (Objects.isNull(player.getInventory().getItemInMainHand()) || !player.getInventory().getItemInMainHand().getType().equals(Material.FIREWORK)) { + if (Objects.isNull(player.getInventory().getItemInMainHand()) || !player.getInventory().getItemInMainHand().getType().equals(Material.FIREWORK_ROCKET)) { sendMessage(player, getMessage("notFirework")); return; } diff --git a/src/main/java/hu/tryharddevs/advancedkits/commands/UseCommand.java b/src/main/java/hu/tryharddevs/advancedkits/commands/UseCommand.java index 5bbbbab..1b3ba1a 100644 --- a/src/main/java/hu/tryharddevs/advancedkits/commands/UseCommand.java +++ b/src/main/java/hu/tryharddevs/advancedkits/commands/UseCommand.java @@ -57,8 +57,11 @@ public void onUseCommand(Player player, @Optional Kit kit) { } if (Objects.isNull(kit)) { - CPageInventory cPageInventory = new CPageInventory("AdvancedKits - Use Kit", player); - cPageInventory.setPages(KitManager.getKits().stream().filter(_kit -> _kit.getFlag(VISIBLE, world) && (_kit.getFlag(FREE, world) && player.hasPermission(_kit.getPermission()) || user.isUnlocked(_kit))).sorted(Comparator.comparing(Kit::getName)).map(_kit -> new ItemBuilder(_kit.getFlag(ICON, world).clone()).setName(ChatColor.WHITE + _kit.getDisplayName(world)).setLore(KitManager.getKitDescription(player, _kit, world)).hideAttributes().toItemStack()).collect(Collectors.toCollection(ArrayList::new))); + CPageInventory cPageInventory = new CPageInventory("Kits", player); + cPageInventory.setPages(KitManager.getKits().stream() + .filter(_kit -> _kit.getFlag(VISIBLE, world) && (_kit.getFlag(FREE, world) && player.hasPermission(_kit.getPermission()) || user.isUnlocked(_kit))) + .sorted(Comparator.comparing(Kit::getName)).map(_kit -> new ItemBuilder(_kit.getFlag(ICON, world).clone()).setName(ChatColor.WHITE + _kit.getDisplayName(world)) + .setLore(KitManager.getKitDescription(player, _kit, world)).hideAttributes().toItemStack()).collect(Collectors.toCollection(ArrayList::new))); cPageInventory.openInventory(); cPageInventory.onInventoryClickEvent((_event) -> { @@ -77,7 +80,14 @@ public void onUseCommand(Player player, @Optional Kit kit) { } _player.closeInventory(); - Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit use " + clickedKit.getName()); + if(_event.getClick().isRightClick()) { + Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit view " + clickedKit.getName()); + } else { + Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit use " + clickedKit.getName()); + if(kit.getFlag(KEEPINVENTORYOPEN, world)) { + Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit use"); + } + } }); return; } @@ -123,7 +133,7 @@ public void onUseCommand(Player player, @Optional Kit kit) { if (kit.getFlag(MAXUSES, world) > 0) user.addUse(kit, world); } - sendMessage(player, getMessage("successfullyUsed", kit.getName())); + sendMessage(player, getMessage("successfullyUsed", kit.getDisplayName(world))); } private static boolean hasInventorySpace(Player player, ItemStack item) { diff --git a/src/main/java/hu/tryharddevs/advancedkits/kits/Kit.java b/src/main/java/hu/tryharddevs/advancedkits/kits/Kit.java index 1ccd3d8..5ee0548 100644 --- a/src/main/java/hu/tryharddevs/advancedkits/kits/Kit.java +++ b/src/main/java/hu/tryharddevs/advancedkits/kits/Kit.java @@ -164,7 +164,7 @@ public , V> V getFlag(T flag, String world) { return val; } - public boolean hasFlag(Flag flag, String world) { + public boolean hasFlag(Flag flag, String world) { if (this.flags.containsKey(world)) { if (this.flags.get(world).containsKey(flag)) { return true; diff --git a/src/main/java/hu/tryharddevs/advancedkits/kits/KitManager.java b/src/main/java/hu/tryharddevs/advancedkits/kits/KitManager.java index 1397806..78fce57 100644 --- a/src/main/java/hu/tryharddevs/advancedkits/kits/KitManager.java +++ b/src/main/java/hu/tryharddevs/advancedkits/kits/KitManager.java @@ -26,7 +26,6 @@ import static hu.tryharddevs.advancedkits.kits.flags.DefaultFlags.*; import static hu.tryharddevs.advancedkits.utils.localization.I18n.getMessage; -@SuppressWarnings("ALL") public class KitManager { private static final Pattern FILE_PATTERN = Pattern.compile("[^A-Za-z0-9_]+", Pattern.CASE_INSENSITIVE); private static ArrayList kitArrayList = new ArrayList<>(); diff --git a/src/main/java/hu/tryharddevs/advancedkits/kits/flags/DefaultFlags.java b/src/main/java/hu/tryharddevs/advancedkits/kits/flags/DefaultFlags.java index 1704d09..058ca4e 100644 --- a/src/main/java/hu/tryharddevs/advancedkits/kits/flags/DefaultFlags.java +++ b/src/main/java/hu/tryharddevs/advancedkits/kits/flags/DefaultFlags.java @@ -10,14 +10,16 @@ import java.util.List; public class DefaultFlags { - public static final BooleanFlag VISIBLE = new BooleanFlag("visible", true); - public static final BooleanFlag FIRSTJOIN = new BooleanFlag("firstjoin", false); - public static final BooleanFlag AUTOEQUIPARMOR = new BooleanFlag("autoequiparmor", false); - public static final BooleanFlag FREE = new BooleanFlag("free", false); - public static final BooleanFlag USEONBUY = new BooleanFlag("useonbuy", false); - public static final BooleanFlag CLEARINVENTORY = new BooleanFlag("clearinventory", false); - public static final BooleanFlag SPEWITEMS = new BooleanFlag("spewitems", false); - public static final BooleanFlag ITEMSINCONTAINER = new BooleanFlag("itemsincontainer", false); + public static final BooleanFlag VISIBLE = new BooleanFlag("visible", true); + public static final BooleanFlag FIRSTJOIN = new BooleanFlag("firstjoin", false); + public static final BooleanFlag RESPAWN = new BooleanFlag("respawn", false); + public static final BooleanFlag AUTOEQUIPARMOR = new BooleanFlag("autoequiparmor", false); + public static final BooleanFlag FREE = new BooleanFlag("free", false); + public static final BooleanFlag USEONBUY = new BooleanFlag("useonbuy", false); + public static final BooleanFlag CLEARINVENTORY = new BooleanFlag("clearinventory", false); + public static final BooleanFlag SPEWITEMS = new BooleanFlag("spewitems", false); + public static final BooleanFlag ITEMSINCONTAINER = new BooleanFlag("itemsincontainer", false); + public static final BooleanFlag KEEPINVENTORYOPEN = new BooleanFlag("keepinventoryopen", false); public static final StringFlag DISPLAYNAME = new StringFlag("displayname"); @@ -28,7 +30,7 @@ public class DefaultFlags { public static final DoubleFlag DELAY = new DoubleFlag("delay", 0.0); public static final ItemStackFlag ICON = new ItemStackFlag("icon", new ItemStack(Material.EMERALD_BLOCK)); - public static final ItemStackFlag FIREWORK = new ItemStackFlag("firework", new ItemStack(Material.FIREWORK)); + public static final ItemStackFlag FIREWORK = new ItemStackFlag("firework", new ItemStack(Material.FIREWORK_ROCKET)); public static final ListFlag CUSTOMDESCRIPTION = new ListFlag<>("customdescription", new StringFlag(null)); public static final ListFlag COMMANDS = new ListFlag<>("commands", new StringFlag(null)); @@ -38,7 +40,7 @@ public class DefaultFlags { public static final ListFlag PARTICLEEFFECTS = new ListFlag<>("particleeffects", new ParticleEffectFlag(null)); public static final ListFlag SOUNDEFFECTS = new ListFlag<>("soundeffects", new SoundEffectFlag(null)); - private static final Flag[] flagsList = new Flag[]{VISIBLE, FIRSTJOIN, AUTOEQUIPARMOR, FREE, USEONBUY, CLEARINVENTORY, SPEWITEMS, ITEMSINCONTAINER, DISPLAYNAME, PERUSECOST, COST, MAXUSES, DELAY, FIREWORK, ICON, CUSTOMDESCRIPTION, COMMANDS, MESSAGES, DISABLEDWORLDS, POTIONEFFECTS, PARTICLEEFFECTS, SOUNDEFFECTS}; + private static final Flag[] flagsList = new Flag[]{VISIBLE, FIRSTJOIN, RESPAWN, AUTOEQUIPARMOR, FREE, USEONBUY, CLEARINVENTORY, SPEWITEMS, ITEMSINCONTAINER, DISPLAYNAME, PERUSECOST, COST, MAXUSES, DELAY, FIREWORK, ICON, CUSTOMDESCRIPTION, COMMANDS, MESSAGES, DISABLEDWORLDS, POTIONEFFECTS, PARTICLEEFFECTS, SOUNDEFFECTS}; public static Flag[] getFlags() { return flagsList; diff --git a/src/main/java/hu/tryharddevs/advancedkits/kits/flags/Flag.java b/src/main/java/hu/tryharddevs/advancedkits/kits/flags/Flag.java index 18c5fe9..98c7861 100644 --- a/src/main/java/hu/tryharddevs/advancedkits/kits/flags/Flag.java +++ b/src/main/java/hu/tryharddevs/advancedkits/kits/flags/Flag.java @@ -35,9 +35,13 @@ private static boolean isValidName(String name) { public static ContextResolver getContextResolver() { return (c) -> { String flagName = c.popFirstArg(); - Flag flag = DefaultFlags.fuzzyMatchFlag(flagName); + Flag flag = DefaultFlags.fuzzyMatchFlag(flagName); if (Objects.isNull(flag)) { - throw new InvalidCommandArgument(getMessage("flagNotFound") + "\n" + Config.CHAT_PREFIX + " " + getMessage("availableFlags", Arrays.stream(DefaultFlags.getFlags()).map(Flag::getName).sorted(String::compareToIgnoreCase).collect(Collectors.joining(",")))); + throw new InvalidCommandArgument( + getMessage("flagNotFound") + "\n" + Config.CHAT_PREFIX + " " + getMessage("availableFlags", Arrays + .stream(DefaultFlags.getFlags()) + .map(Flag::getName).sorted(String::compareToIgnoreCase) + .collect(Collectors.joining(",")))); } return flag; }; diff --git a/src/main/java/hu/tryharddevs/advancedkits/kits/flags/ItemStackFlag.java b/src/main/java/hu/tryharddevs/advancedkits/kits/flags/ItemStackFlag.java index fed434d..438ab76 100644 --- a/src/main/java/hu/tryharddevs/advancedkits/kits/flags/ItemStackFlag.java +++ b/src/main/java/hu/tryharddevs/advancedkits/kits/flags/ItemStackFlag.java @@ -1,6 +1,9 @@ package hu.tryharddevs.advancedkits.kits.flags; import hu.tryharddevs.advancedkits.utils.ItemStackUtil; + +import java.util.Map; + import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -38,11 +41,11 @@ public ItemStackFlag(String name) { } @Override public ItemStack unmarshal(@Nullable Object o) { - try { - String material = String.valueOf(o); - return new ItemStack(Material.matchMaterial(material)); - } catch (ClassCastException | NullPointerException e) { - return ItemStackUtil.itemFromString(String.valueOf(o)); + Material material = Material.matchMaterial(String.valueOf(o)); + if(material != null) { + return new ItemStack(material); + } else { + return ItemStackUtil.itemFromString(String.valueOf(o)); } } diff --git a/src/main/java/hu/tryharddevs/advancedkits/listeners/PlayerListener.java b/src/main/java/hu/tryharddevs/advancedkits/listeners/PlayerListener.java index 25b86c0..ada3101 100644 --- a/src/main/java/hu/tryharddevs/advancedkits/listeners/PlayerListener.java +++ b/src/main/java/hu/tryharddevs/advancedkits/listeners/PlayerListener.java @@ -9,7 +9,11 @@ import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; -import org.bukkit.block.*; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Chest; +import org.bukkit.block.DoubleChest; +import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -21,6 +25,7 @@ import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; @@ -31,6 +36,7 @@ import java.util.Objects; import static hu.tryharddevs.advancedkits.kits.flags.DefaultFlags.FIRSTJOIN; +import static hu.tryharddevs.advancedkits.kits.flags.DefaultFlags.RESPAWN; import static hu.tryharddevs.advancedkits.utils.MessagesApi.sendMessage; import static hu.tryharddevs.advancedkits.utils.localization.I18n.getMessage; @@ -56,6 +62,14 @@ public void onPlayerJoin(PlayerLoginEvent event) { public void onPlayerLeave(PlayerQuitEvent event) { User.getUser(event.getPlayer().getUniqueId()).save(); } + + @EventHandler + public void onPlayerRespawn(PlayerRespawnEvent event) { + final Player player = event.getPlayer(); + this.instance.getServer().getScheduler().scheduleSyncDelayedTask(instance, () -> KitManager.getKits().stream().filter(kit -> kit.getFlag(RESPAWN, player.getWorld().getName())).forEach(kit -> { + Bukkit.dispatchCommand(player, "advancedkitsreloaded:kit use " + kit.getName()); + }), 2L); + } @EventHandler(priority = EventPriority.MONITOR) public void onBlockPlace(BlockPlaceEvent event) { @@ -104,36 +118,13 @@ public void onBlockPlace(BlockPlaceEvent event) { } } - @EventHandler(priority = EventPriority.MONITOR) - public void onBlockBreakEvent(BlockBreakEvent event) { - if (event.isCancelled()) return; - - if (!event.getBlock().getType().equals(Material.CHEST) || event.getBlock().getDrops().isEmpty()) return; - - event.setCancelled(true); - event.getBlock().setType(Material.AIR); - - Collection drops = event.getBlock().getDrops(); - drops.add(new ItemStack(Material.CHEST)); - drops.forEach(drop -> { - if (drop.getType().equals(Material.CHEST)) { - if (drop.hasItemMeta() && drop.getItemMeta().hasDisplayName()) { - if (Objects.nonNull(KitManager.getKit(drop.getItemMeta().getDisplayName(), event.getPlayer().getWorld().getName()))) { - drop = new ItemBuilder(drop).setName("Chest").toItemStack(); - } - } - } - event.getPlayer().getWorld().dropItemNaturally(event.getBlock().getLocation(), drop); - }); - } - @EventHandler public void onPlayerClickSignEvent(PlayerInteractEvent event) { Action action = event.getAction(); if (action == Action.RIGHT_CLICK_BLOCK) { if (event.getClickedBlock().getState() instanceof Sign) { Player player = event.getPlayer(); - Sign sign = (Sign) event.getClickedBlock().getState(); + Sign sign = (Sign) event.getClickedBlock().getState(); if (sign.getLine(0).equalsIgnoreCase(ChatColor.GRAY + "[" + ChatColor.DARK_BLUE + "Kits" + ChatColor.GRAY + "]")) { Kit kit = KitManager.getKit(ChatColor.stripColor(sign.getLine(1)), player.getWorld().getName()); diff --git a/src/main/java/hu/tryharddevs/advancedkits/utils/ItemBuilder.java b/src/main/java/hu/tryharddevs/advancedkits/utils/ItemBuilder.java index 8dc9ffc..7811b6b 100644 --- a/src/main/java/hu/tryharddevs/advancedkits/utils/ItemBuilder.java +++ b/src/main/java/hu/tryharddevs/advancedkits/utils/ItemBuilder.java @@ -1,19 +1,12 @@ package hu.tryharddevs.advancedkits.utils; -import org.bukkit.Color; -import org.bukkit.DyeColor; import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.LeatherArmorMeta; -import org.bukkit.inventory.meta.SkullMeta; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.Map; /** * Easily create itemstacks, without messing your hands. @@ -53,17 +46,6 @@ private ItemBuilder(Material m, int amount) { is = new ItemStack(m, amount); } - /** - * Create a new ItemBuilder from scratch. - * - * @param m The material of the item. - * @param amount The amount of the item. - * @param durability The durability of the item. - */ - public ItemBuilder(Material m, int amount, byte durability) { - is = new ItemStack(m, amount, durability); - } - /** * Clone the ItemBuilder into a new one. * @@ -73,16 +55,6 @@ public ItemBuilder clone() { return new ItemBuilder(is); } - /** - * Change the durability of the item. - * - * @param dur The durability to set it to. - */ - public ItemBuilder setDurability(short dur) { - is.setDurability(dur); - return this; - } - /** * Set the displayname of the item. * @@ -95,73 +67,6 @@ public ItemBuilder setName(String name) { return this; } - /** - * Add an unsafe enchantment. - * - * @param ench The enchantment to add. - * @param level The level to put the enchant on. - */ - public ItemBuilder addUnsafeEnchantment(Enchantment ench, int level) { - is.addUnsafeEnchantment(ench, level); - return this; - } - - /** - * Remove a certain enchant from the item. - * - * @param ench The enchantment to remove - */ - public ItemBuilder removeEnchantment(Enchantment ench) { - is.removeEnchantment(ench); - return this; - } - - /** - * Set the skull owner for the item. Works on skulls only. - * - * @param owner The name of the skull's owner. - */ - public ItemBuilder setSkullOwner(String owner) { - try { - SkullMeta im = (SkullMeta) is.getItemMeta(); - im.setOwner(owner); - is.setItemMeta(im); - } catch (ClassCastException ignored) { - } - return this; - } - - /** - * Add an enchant to the item. - * - * @param ench The enchant to add - * @param level The level - */ - public ItemBuilder addEnchant(Enchantment ench, int level) { - ItemMeta im = is.getItemMeta(); - im.addEnchant(ench, level, true); - is.setItemMeta(im); - return this; - } - - /** - * Add multiple enchants at once. - * - * @param enchantments The enchants to add. - */ - public ItemBuilder addEnchantments(Map enchantments) { - is.addEnchantments(enchantments); - return this; - } - - /** - * Sets infinity durability on the item by setting the durability to Short.MAX_VALUE. - */ - public ItemBuilder setInfinityDurability() { - is.setDurability(Short.MAX_VALUE); - return this; - } - /** * Re-sets the lore. * @@ -186,66 +91,6 @@ public ItemBuilder setLore(List lore) { return this; } - /** - * Remove a lore line. - * - * @param line The lore to remove. - */ - public ItemBuilder removeLoreLine(String line) { - ItemMeta im = is.getItemMeta(); - List lore = new ArrayList<>(im.getLore()); - if (!lore.contains(line)) return this; - lore.remove(line); - im.setLore(lore); - is.setItemMeta(im); - return this; - } - - /** - * Remove a lore line. - * - * @param index The index of the lore line to remove. - */ - public ItemBuilder removeLoreLine(int index) { - ItemMeta im = is.getItemMeta(); - List lore = new ArrayList<>(im.getLore()); - if (index < 0 || index > lore.size()) return this; - lore.remove(index); - im.setLore(lore); - is.setItemMeta(im); - return this; - } - - /** - * Add a lore line. - * - * @param line The lore line to add. - */ - public ItemBuilder addLoreLine(String line) { - ItemMeta im = is.getItemMeta(); - List lore = new ArrayList<>(); - if (im.hasLore()) lore = new ArrayList<>(im.getLore()); - lore.add(line); - im.setLore(lore); - is.setItemMeta(im); - return this; - } - - /** - * Add a lore line. - * - * @param line The lore line to add. - * @param pos The index of where to put it. - */ - public ItemBuilder addLoreLine(String line, int pos) { - ItemMeta im = is.getItemMeta(); - List lore = new ArrayList<>(im.getLore()); - lore.set(pos, line); - im.setLore(lore); - is.setItemMeta(im); - return this; - } - /** * Hides every attributes, and extra lores generated by Minecraft. */ @@ -256,46 +101,6 @@ public ItemBuilder hideAttributes() { return this; } - /** - * Sets the dye color on an item. - * * Notice that this doesn't check for item type, sets the literal data of the dyecolor as durability. - * - * @param color The color to put. - */ - @SuppressWarnings("deprecation") - public ItemBuilder setDyeColor(DyeColor color) { - this.is.setDurability(color.getDyeData()); - return this; - } - - /** - * Sets the dye color of a wool item. Works only on wool. - * - * @param color The DyeColor to set the wool item to. - * @see ItemBuilder@setDyeColor(DyeColor) - * @deprecated As of version 1.2 changed to setDyeColor. - */ - @Deprecated - public ItemBuilder setWoolColor(DyeColor color) { - if (!is.getType().equals(Material.WOOL)) return this; - this.is.setDurability(color.getDyeData()); - return this; - } - - /** - * Sets the armor color of a leather armor piece. Works only on leather armor pieces. - * - * @param color The color to set it to. - */ - public ItemBuilder setLeatherArmorColor(Color color) { - try { - LeatherArmorMeta im = (LeatherArmorMeta) is.getItemMeta(); - im.setColor(color); - is.setItemMeta(im); - } catch (ClassCastException ignored) { - } - return this; - } /** * Retrieves the itemstack from the ItemBuilder. @@ -305,4 +110,4 @@ public ItemBuilder setLeatherArmorColor(Color color) { public ItemStack toItemStack() { return is; } -} +} \ No newline at end of file diff --git a/src/main/java/hu/tryharddevs/advancedkits/utils/ItemStackUtil.java b/src/main/java/hu/tryharddevs/advancedkits/utils/ItemStackUtil.java index 6063d99..ba7a441 100644 --- a/src/main/java/hu/tryharddevs/advancedkits/utils/ItemStackUtil.java +++ b/src/main/java/hu/tryharddevs/advancedkits/utils/ItemStackUtil.java @@ -12,7 +12,6 @@ import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.util.io.BukkitObjectInputStream; import org.bukkit.util.io.BukkitObjectOutputStream; -import org.inventivetalent.reflection.minecraft.Minecraft; import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; import java.io.ByteArrayInputStream; @@ -44,10 +43,10 @@ private static JsonObject serializeItem(Object object) { * This is because some people are getting skulls with null owners, which causes Spigot to throw an error * when it tries to serialize the item. If this ever gets fixed in Spigot, this will be removed. */ - if (itemStack.getType() == Material.SKULL_ITEM) { + if (itemStack.getType() == Material.PLAYER_HEAD) { SkullMeta meta = (SkullMeta) itemStack.getItemMeta(); - if (meta.hasOwner() && (meta.getOwner() == null || meta.getOwner().isEmpty())) { - itemStack.setItemMeta(Bukkit.getServer().getItemFactory().getItemMeta(Material.SKULL_ITEM)); + if (meta.hasOwner() && meta.getOwningPlayer() == null) { + itemStack.setItemMeta(Bukkit.getServer().getItemFactory().getItemMeta(Material.PLAYER_HEAD)); } } } @@ -121,7 +120,7 @@ public static boolean isChest(ItemStack item) { } private static boolean isChest(Material material) { - return material.name().endsWith("CHESTPLATE") || Minecraft.VERSION.newerThan(Minecraft.Version.v1_9_R1) && material.name().endsWith("ELYTRA"); + return material.name().endsWith("CHESTPLATE") || material.name().endsWith("ELYTRA"); } public static boolean isHelmet(ItemStack item) { diff --git a/src/main/java/hu/tryharddevs/advancedkits/utils/MessagesApi.java b/src/main/java/hu/tryharddevs/advancedkits/utils/MessagesApi.java index 1f84006..bb50d03 100644 --- a/src/main/java/hu/tryharddevs/advancedkits/utils/MessagesApi.java +++ b/src/main/java/hu/tryharddevs/advancedkits/utils/MessagesApi.java @@ -7,7 +7,6 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; -import org.inventivetalent.reflection.minecraft.Minecraft; import org.inventivetalent.reflection.resolver.FieldResolver; import org.inventivetalent.reflection.resolver.MethodResolver; import org.inventivetalent.reflection.resolver.ResolverQuery; @@ -26,30 +25,9 @@ ** * ****************************************************/ -@SuppressWarnings("ALL") public class MessagesApi { private static final OBCClassResolver obcClassResolver = new OBCClassResolver(); private static final NMSClassResolver nmsClassResolver = new NMSClassResolver(); - private static final boolean useOldMethods = Minecraft.VERSION.olderThan(Minecraft.Version.v1_8_R1); - - @Deprecated - public static void sendTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String message) { - sendTitle(player, fadeIn, stay, fadeOut, message, null); - } - - @Deprecated - public static void sendSubtitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String message) { - sendTitle(player, fadeIn, stay, fadeOut, null, message); - } - - @Deprecated - public static void sendFullTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String title, String subtitle) { - sendTitle(player, fadeIn, stay, fadeOut, title, subtitle); - } - - @Deprecated public static Integer getPlayerProtocol(Player player) { - return 47; - } private static void sendPacket(Player player, Object packet) { try { @@ -147,18 +125,10 @@ public static void sendActionBar(Player player, String message) { Object ppoc; Class c4 = nmsClassResolver.resolveSilent("PacketPlayOutChat"); Class c5 = nmsClassResolver.resolveSilent("Packet"); - if (useOldMethods) { - Class c2 = nmsClassResolver.resolveSilent("ChatSerializer"); - Class c3 = nmsClassResolver.resolveSilent("IChatBaseComponent"); - Method m3 = c2.getDeclaredMethod("a", String.class); - Object cbc = c3.cast(m3.invoke(c2, "{\"text\": \"" + message + "\"}")); - ppoc = c4.getConstructor(new Class[]{c3, byte.class}).newInstance(cbc, (byte) 2); - } else { - Class c2 = nmsClassResolver.resolveSilent("ChatComponentText"); - Class c3 = nmsClassResolver.resolveSilent("IChatBaseComponent"); - Object o = c2.getConstructor(new Class[]{String.class}).newInstance(message); - ppoc = c4.getConstructor(new Class[]{c3, byte.class}).newInstance(o, (byte) 2); - } + Class c2 = nmsClassResolver.resolveSilent("ChatComponentText"); + Class c3 = nmsClassResolver.resolveSilent("IChatBaseComponent"); + Object o = c2.getConstructor(new Class[]{String.class}).newInstance(message); + ppoc = c4.getConstructor(new Class[]{c3, byte.class}).newInstance(o, (byte) 2); Method m1 = c1.getDeclaredMethod("getHandle"); Object h = m1.invoke(p); Field f1 = h.getClass().getDeclaredField("playerConnection"); diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 8643292..38d8e0a 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,12 +1,13 @@ name: AdvancedKitsReloaded version: ${project.version} main: hu.tryharddevs.advancedkits.AdvancedKitsMain +api-version: 1.13 prefix: AdvancedKits authors: [TryHardDood] description: AdvancedKitsReloaded is a Kit managing plugin for Minecraft servers which runs Spigot, Bukkit,CraftBukkit and Paper servers (Above 1.8). With this plugin you can easily create/edit/delete your kits and you can customize it as much as you'd like. website: https://tryharddood.github.io/ depends: [Vault] -softdepend: [PlaceholderAPI] +softdepend: [PlaceholderAPI, Pt] permissions: advancedkits.*: description: Gives access to all advancedkits commands