From 61fd882dc724bf9195dd4b141118f3b0ab62cebd Mon Sep 17 00:00:00 2001 From: LikeWhat Date: Thu, 19 Nov 2020 01:42:03 +0100 Subject: [PATCH] Dev Build --- .../de/likewhat/customheads/CustomHeads.java | 116 +++++++------ .../customheads/api/CustomHeadsAPI.java | 22 +++ .../customheads/api/CustomHeadsPlayer.java | 2 - .../customheads/category/BaseCategory.java | 6 +- .../customheads/category/Category.java | 10 +- .../customheads/category/CategorySetup.java | 2 +- .../customheads/economy/EconomyManager.java | 13 ++ .../listener/InventoryListener.java | 44 +++-- .../customheads/listener/OtherListeners.java | 16 +- .../customheads/utils/APIHandler.java | 72 ++++++++ .../customheads/utils/EmptyCallback.java | 14 ++ .../utils/FireworksBatteryHandler.java | 21 +++ .../customheads/utils/GameProfileBuilder.java | 2 +- .../customheads/utils/InteractiveDialog.java | 1 - .../utils/ScrollableInventory.java | 27 +-- .../de/likewhat/customheads/utils/Utils.java | 68 ++++++-- .../customheads/utils/stuff/CHCommand.java | 162 +++++++++++++----- .../utils/stuff/CHSearchQuery.java | 8 +- .../utils/updaters/AsyncFileDownloader.java | 8 +- .../utils/updaters/CachedResponse.java | 6 +- .../utils/updaters/GitHubDownloader.java | 4 +- .../utils/updaters/SpigetResourceFetcher.java | 145 ++++++++-------- src/main/resources/config.yml | 2 + 23 files changed, 516 insertions(+), 255 deletions(-) create mode 100644 src/main/java/de/likewhat/customheads/utils/EmptyCallback.java create mode 100644 src/main/java/de/likewhat/customheads/utils/FireworksBatteryHandler.java diff --git a/src/main/java/de/likewhat/customheads/CustomHeads.java b/src/main/java/de/likewhat/customheads/CustomHeads.java index fac8861..3cb0c78 100644 --- a/src/main/java/de/likewhat/customheads/CustomHeads.java +++ b/src/main/java/de/likewhat/customheads/CustomHeads.java @@ -26,7 +26,6 @@ import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.PluginManager; @@ -36,6 +35,7 @@ import org.bukkit.scheduler.BukkitRunnable; import java.io.File; import java.util.*; import java.util.logging.Level; +import java.util.stream.Collectors; import static de.likewhat.customheads.utils.Utils.hasPermission; @@ -47,7 +47,7 @@ import static de.likewhat.customheads.utils.Utils.hasPermission; @Getter public class CustomHeads extends JavaPlugin { - private static final boolean DEV_BUILD = false; + private static final boolean DEV_BUILD = true; public static final HashMap uuidCache = new HashMap<>(); public static final String chPrefix = "§7[§eCustomHeads§7] "; @@ -65,9 +65,10 @@ public class CustomHeads extends JavaPlugin { @Getter private static SpigetResourceFetcher spigetFetcher; @Getter private static EconomyManager economyManager; @Getter private static CategoryManager categoryManager; - private static List versions = Arrays.asList("v1_8_R1", "v1_8_R2", "v1_8_R3", "v1_9_R1", "v1_9_R2", "v1_10_R1", "v1_11_R1", "v1_12_R1", "v1_13_R1", "v1_13_R2", "v1_14_R1", "v1_15_R1"); + private static List versions = Arrays.asList("v1_8_R1", "v1_8_R2", "v1_8_R3", "v1_9_R1", "v1_9_R2", "v1_10_R1", "v1_11_R1", "v1_12_R1", "v1_13_R1", "v1_13_R2", "v1_14_R1", "v1_15_R1", "v1_16_R1"); private static String packet = Bukkit.getServer().getClass().getPackage().getName(); public static String version = packet.substring(packet.lastIndexOf('.') + 1); + @Getter private static int getCommandPrice = 0; public static final boolean USE_TEXTURES = versions.contains(version); private static boolean keepCategoryPermissions = false; @@ -171,13 +172,14 @@ public class CustomHeads extends JavaPlugin { return true; } - public static boolean reload() { + public static boolean silentReload() { headsConfig.reload(); reducedDebug = headsConfig.get().getBoolean("reducedDebug"); categoriesBuyable = headsConfig.get().getBoolean("economy.category.buyable"); headsBuyable = headsConfig.get().getBoolean("economy.heads.buyable"); headsPermanentBuy = headsConfig.get().getBoolean("economy.heads.permanentBuy"); keepCategoryPermissions = headsConfig.get().getBoolean("economy.category.keepPermissions"); + reloadHistoryData(); reloadEconomy(); PlayerWrapper.clearCache(); @@ -190,7 +192,7 @@ public class CustomHeads extends JavaPlugin { public void onDisable() { if (isInit) { - OtherListeners.CACHED_LOCATIONS.values().forEach(loc -> loc.getBlock().setType(Material.AIR)); + CHCommand.CACHED_FIREWORKS.forEach(loc -> loc.getBlock().setType(Material.AIR)); PlayerWrapper.clearCache(); } } @@ -213,9 +215,9 @@ public class CustomHeads extends JavaPlugin { playerDataFile.saveJson(); headsConfig.get().set("heads", null); headsConfig.save(); - getServer().getConsoleSender().sendMessage(chPrefix + "Successfully converted Head Data"); + getServer().getConsoleSender().sendMessage(chPrefix + "Successfully converted old Head Data"); } catch (Exception e) { - getLogger().log(Level.WARNING, "Failed to convertFromJson Head Data...", e); + getLogger().log(Level.WARNING, "Failed to convert old Head Data...", e); } } @@ -276,12 +278,9 @@ public class CustomHeads extends JavaPlugin { } } }); - - } else { loadRest(); } - } private void downloadDefaultLanguage() { @@ -296,7 +295,7 @@ public class CustomHeads extends JavaPlugin { file.delete(); } } - getServer().getConsoleSender().sendMessage(chWarning + "I wasn't able to find the Default Languge File on your Server..."); + getServer().getConsoleSender().sendMessage(chWarning + "I wasn't able to find the Default Language File on your Server..."); getServer().getConsoleSender().sendMessage(chPrefix + "§7Downloading necessary Files..."); GitHubDownloader gitHubDownloader = new GitHubDownloader("IHasName", "CustomHeads").enableAutoUnzipping(); gitHubDownloader.download(getDescription().getVersion(), "en_EN.zip", new File(getDataFolder(), "language"), () -> { @@ -318,6 +317,8 @@ public class CustomHeads extends JavaPlugin { headsBuyable = headsConfig.get().getBoolean("economy.heads.buyable"); headsPermanentBuy = headsConfig.get().getBoolean("economy.heads.permanentBuy"); + getCommandPrice = headsConfig.get().getInt("economy.get-command.price-per-head"); + // Setting up APIHandler api = new APIHandler(); @@ -356,30 +357,36 @@ public class CustomHeads extends JavaPlugin { getCommand("heads").setExecutor(new CHCommand()); getCommand("heads").setTabCompleter(new CHTabCompleter()); - // Check for updates spigetFetcher = new SpigetResourceFetcher(29057); SpigetResourceFetcher.setUserAgent("UC-CustomHeads"); - spigetFetcher.fetchUpdates(new SpigetResourceFetcher.FetchResult() { - public void updateAvailable(SpigetResourceFetcher.ResourceRelease release, SpigetResourceFetcher.ResourceUpdate update) { - if (headsConfig.get().getBoolean("update-notifications.console")) { - getServer().getConsoleSender().sendMessage(chPrefix + "§bNew Update for CustomHeads found! v" + release.getReleaseName() + " (Running on v" + getDescription().getVersion() + ") - You can Download it here https://www.spigotmc.org/resources/29057"); + // Don't check for updates if the Plugin is a Dev Build + if(!DEV_BUILD) { + // Check for updates + spigetFetcher.fetchUpdates(new SpigetResourceFetcher.FetchResult() { + public void updateAvailable(SpigetResourceFetcher.ResourceRelease release, SpigetResourceFetcher.ResourceUpdate update) { + if (headsConfig.get().getBoolean("update-notifications.console")) { + getServer().getConsoleSender().sendMessage(chPrefix + "§bNew Update for CustomHeads found! v" + release.getReleaseName() + " (Running on v" + getDescription().getVersion() + ") - You can Download it here https://www.spigotmc.org/resources/29057"); + } } - } - public void noUpdate() { - } - }); + public void noUpdate() { + } + }); + } if (!USE_TEXTURES) { getServer().getConsoleSender().sendMessage(chWarning + "Hrm. Seems like CustomHeads wasn't tested on this Minecraft Version yet..."); getServer().getConsoleSender().sendMessage(chWarning + "Please report this to me on Discord (Link's on the Spigot Page)"); } - initMetrics(); + // No need to report Metrics for Dev Builds + if(!DEV_BUILD) { + initMetrics(); + } // -- Timers - // Clear Cache every 5 Minutes + // Clear Cache every 30 Minutes new BukkitRunnable() { public void run() { uuidCache.clear(); @@ -389,48 +396,45 @@ public class CustomHeads extends JavaPlugin { ScrollableInventory.clearCache(); PlayerWrapper.clearCache(); } - }.runTaskTimer(instance, 6000, 6000); + }.runTaskTimer(instance, 36000, 36000); // Animation Timer - new BukkitRunnable() { - public void run() { - for (Player player : getServer().getOnlinePlayers()) { - if (player.getOpenInventory() != null && player.getOpenInventory().getType() == InventoryType.CHEST) { - if (CustomHeads.getLooks().getMenuTitles().contains(player.getOpenInventory().getTitle())) { - ItemStack[] inventoryContent = player.getOpenInventory().getTopInventory().getContents(); - for (int i = 0; i < inventoryContent.length; i++) { - if (inventoryContent[i] == null) continue; - ItemStack contentItem = inventoryContent[i]; - if (CustomHeads.getTagEditor().getTags(contentItem).contains("openCategory") && CustomHeads.getTagEditor().getTags(contentItem).contains("icon-loop")) { - String[] categoryArgs = CustomHeads.getTagEditor().getTags(contentItem).get(CustomHeads.getTagEditor().indexOf(contentItem, "openCategory") + 1).split("#>"); - if (categoryArgs[0].equals("category")) { - CustomHeadsPlayer customHeadsPlayer = api.wrapPlayer(player); - Category category = CustomHeads.getCategoryManager().getCategory(categoryArgs[1]); - ItemStack nextIcon = category.nextIcon(); - boolean bought = customHeadsPlayer.getUnlockedCategories(true).contains(category); - nextIcon = new ItemEditor(nextIcon) - .setDisplayName(customHeadsPlayer.getUnlockedCategories(CustomHeads.hasEconomy() && !CustomHeads.keepCategoryPermissions()).contains(category) ? "§a" + nextIcon.getItemMeta().getDisplayName() : "§7" + ChatColor.stripColor(nextIcon.getItemMeta().getDisplayName()) + " " + CustomHeads.getLanguageManager().LOCKED) - .addLoreLine(CustomHeads.hasEconomy() && CustomHeads.categoriesBuyable() ? bought ? CustomHeads.getLanguageManager().ECONOMY_BOUGHT : Utils.getCategoryPriceFormatted(category, true) + "\n" + CustomHeads.getLanguageManager().ECONOMY_BUY_PROMPT : null) - .addLoreLines(hasPermission(player, "heads.view.permissions") ? Arrays.asList(" ", "§7§oPermission: " + category.getPermission()) : null) - .getItem(); - if (CustomHeads.hasEconomy() && !CustomHeads.keepCategoryPermissions()) { - if (!bought) { - nextIcon = CustomHeads.getTagEditor().addTags(nextIcon, "buyCategory", category.getId()); - } + Utils.runAsyncTimer( + new BukkitRunnable() { + public void run() { + getServer().getOnlinePlayers().stream().filter(player -> player.getOpenInventory() != null && player.getOpenInventory().getType() == InventoryType.CHEST && CustomHeads.getLooks().getMenuTitles().contains(player.getOpenInventory().getTitle())).collect(Collectors.toList()).forEach(player -> { + ItemStack[] inventoryContent = player.getOpenInventory().getTopInventory().getContents(); + for (int i = 0; i < inventoryContent.length; i++) { + if (inventoryContent[i] == null) continue; + ItemStack contentItem = inventoryContent[i]; + if (CustomHeads.getTagEditor().getTags(contentItem).contains("openCategory") && CustomHeads.getTagEditor().getTags(contentItem).contains("icon-loop")) { + String[] categoryArgs = CustomHeads.getTagEditor().getTags(contentItem).get(CustomHeads.getTagEditor().indexOf(contentItem, "openCategory") + 1).split("#>"); + if (categoryArgs[0].equals("category")) { + CustomHeadsPlayer customHeadsPlayer = api.wrapPlayer(player); + Category category = CustomHeads.getCategoryManager().getCategory(categoryArgs[1]); + ItemStack nextIcon = category.nextIcon(); + boolean bought = customHeadsPlayer.getUnlockedCategories(true).contains(category); + nextIcon = new ItemEditor(nextIcon) + .setDisplayName(customHeadsPlayer.getUnlockedCategories(CustomHeads.hasEconomy() && !CustomHeads.keepCategoryPermissions()).contains(category) ? "§a" + nextIcon.getItemMeta().getDisplayName() : "§7" + ChatColor.stripColor(nextIcon.getItemMeta().getDisplayName()) + " " + CustomHeads.getLanguageManager().LOCKED) + .addLoreLine(CustomHeads.hasEconomy() && CustomHeads.categoriesBuyable() ? bought ? CustomHeads.getLanguageManager().ECONOMY_BOUGHT : Utils.getCategoryPriceFormatted(category, true) + "\n" + CustomHeads.getLanguageManager().ECONOMY_BUY_PROMPT : null) + .addLoreLines(hasPermission(player, "heads.view.permissions") ? Arrays.asList(" ", "§7§oPermission: " + category.getPermission()) : null) + .getItem(); + if (CustomHeads.hasEconomy() && !CustomHeads.keepCategoryPermissions()) { + if (!bought) { + nextIcon = CustomHeads.getTagEditor().addTags(nextIcon, "buyCategory", category.getId()); } - contentItem = nextIcon; } - } - if(tagEditor.hasMyTags(contentItem)) { - inventoryContent[i] = CustomHeads.getTagEditor().addTags(contentItem, "menuID", CustomHeads.getLooks().getIDbyTitle(player.getOpenInventory().getTitle())); + contentItem = nextIcon; } } - player.getOpenInventory().getTopInventory().setContents(inventoryContent); + if (tagEditor.hasMyTags(contentItem)) { + inventoryContent[i] = CustomHeads.getTagEditor().addTags(contentItem, "menuID", CustomHeads.getLooks().getIDbyTitle(player.getOpenInventory().getTitle())); + } } - } + player.getOpenInventory().getTopInventory().setContents(inventoryContent); + }); } - } - }.runTaskTimer(instance, 0, 20); + }, 0, 20); isInit = true; } diff --git a/src/main/java/de/likewhat/customheads/api/CustomHeadsAPI.java b/src/main/java/de/likewhat/customheads/api/CustomHeadsAPI.java index cb9686f..d5d66fa 100644 --- a/src/main/java/de/likewhat/customheads/api/CustomHeadsAPI.java +++ b/src/main/java/de/likewhat/customheads/api/CustomHeadsAPI.java @@ -10,6 +10,7 @@ package de.likewhat.customheads.api; import de.likewhat.customheads.category.Category; import de.likewhat.customheads.category.CustomHead; import de.likewhat.customheads.headwriter.HeadFontType; +import de.likewhat.customheads.utils.FireworksBatteryHandler; import org.bukkit.Location; import org.bukkit.OfflinePlayer; import org.bukkit.block.Block; @@ -93,4 +94,25 @@ public interface CustomHeadsAPI { */ CustomHead getHead(Category category, int id); + /** + * Starts a Firework in the world + * + * @param location Location where to start the Firework + * @param shots Sets how many shots the Battery has + * @param delay Delay between the shots (Ticks) + */ + void createFireworkBattery(Location location, int shots, int delay); + + /** + * Starts a Firework in the world + * Has a Callback + * @see FireworksBatteryHandler + * + * @param location Location where to start the Firework + * @param shots Sets how many shots the Battery has + * @param delay Delay between the shots (Ticks) + * @param handler Contains callables for when the Firework starts, ends and when the next Firework is launched + */ + void createFireworkBattery(Location location, int shots, int delay, FireworksBatteryHandler handler); + } diff --git a/src/main/java/de/likewhat/customheads/api/CustomHeadsPlayer.java b/src/main/java/de/likewhat/customheads/api/CustomHeadsPlayer.java index f9ba77f..f7dfdd5 100644 --- a/src/main/java/de/likewhat/customheads/api/CustomHeadsPlayer.java +++ b/src/main/java/de/likewhat/customheads/api/CustomHeadsPlayer.java @@ -122,6 +122,4 @@ public interface CustomHeadsPlayer { SearchHistory getSearchHistory(); GetHistory getGetHistory(); - - // Im no professional Description Writer so shhhhhhhhhhhhh... } diff --git a/src/main/java/de/likewhat/customheads/category/BaseCategory.java b/src/main/java/de/likewhat/customheads/category/BaseCategory.java index f700c8d..f82298a 100644 --- a/src/main/java/de/likewhat/customheads/category/BaseCategory.java +++ b/src/main/java/de/likewhat/customheads/category/BaseCategory.java @@ -5,6 +5,8 @@ import lombok.Getter; import lombok.Setter; import org.bukkit.ChatColor; +import java.util.List; + /* * Project: CustomHeads in BaseCategory * by LikeWhat @@ -12,7 +14,7 @@ import org.bukkit.ChatColor; @Getter @Setter -public class BaseCategory { +public abstract class BaseCategory { private String permission; private String name; @@ -24,6 +26,8 @@ public class BaseCategory { this.permission = permission; } + public abstract List getHeads(); + public String getPlainName() { return ChatColor.stripColor(name); } diff --git a/src/main/java/de/likewhat/customheads/category/Category.java b/src/main/java/de/likewhat/customheads/category/Category.java index 53ed75f..6b47cf1 100644 --- a/src/main/java/de/likewhat/customheads/category/Category.java +++ b/src/main/java/de/likewhat/customheads/category/Category.java @@ -28,7 +28,6 @@ import java.util.stream.Collectors; public class Category extends BaseCategory { private static final Gson CATEGORY_TO_JSON = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().registerTypeAdapter(Category.class, new Serializer()).registerTypeAdapter(SubCategory.class, new SubCategory.Serializer()).create(); -// public static int counter = 0; private int lastID = 1; private List subCategories; @@ -54,12 +53,11 @@ public class Category extends BaseCategory { return CATEGORY_TO_JSON; } - //Public Methods public boolean hasCategoryIcon() { return categoryIcon != null; } - private Category setCategoryIcon(ItemStack icon) { + Category setCategoryIcon(ItemStack icon) { categoryIcon = icon; return this; } @@ -74,7 +72,7 @@ public class Category extends BaseCategory { return heads; } - public Category setHeads(List heads) { + Category setHeads(List heads) { this.heads = heads; return this; } @@ -83,7 +81,7 @@ public class Category extends BaseCategory { return !heads.isEmpty(); } - public Category setSubCategories(List subCategories) { + Category setSubCategories(List subCategories) { this.subCategories = subCategories; return this; } @@ -96,7 +94,7 @@ public class Category extends BaseCategory { return subCategories != null && !subCategories.isEmpty(); } - public Category setIcons(List icons) { + Category setIcons(List icons) { this.icons = icons; iterator = icons.iterator(); return this; diff --git a/src/main/java/de/likewhat/customheads/category/CategorySetup.java b/src/main/java/de/likewhat/customheads/category/CategorySetup.java index afdcfc0..545cd68 100644 --- a/src/main/java/de/likewhat/customheads/category/CategorySetup.java +++ b/src/main/java/de/likewhat/customheads/category/CategorySetup.java @@ -142,7 +142,7 @@ public class CategorySetup { category.setPrice(price); category.setIcons(Arrays.asList(new ItemEditor(icon).setDisplayName(name).setLore(description).getItem())); CustomHeads.getCategoryManager().updateCategory(category, CustomHeads.getLanguageManager().getCurrentLanguage()); - CustomHeads.reload(); + CustomHeads.silentReload(); player.closeInventory(); player.sendMessage("Successfully created Category"); } diff --git a/src/main/java/de/likewhat/customheads/economy/EconomyManager.java b/src/main/java/de/likewhat/customheads/economy/EconomyManager.java index f44a47d..5660b39 100644 --- a/src/main/java/de/likewhat/customheads/economy/EconomyManager.java +++ b/src/main/java/de/likewhat/customheads/economy/EconomyManager.java @@ -4,9 +4,11 @@ import de.likewhat.customheads.CustomHeads; import de.likewhat.customheads.api.CustomHeadsPlayer; import de.likewhat.customheads.category.Category; import de.likewhat.customheads.category.CustomHead; +import de.likewhat.customheads.utils.SimpleCallback; import lombok.Getter; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.EconomyResponse; +import org.bukkit.entity.Player; import org.bukkit.plugin.RegisteredServiceProvider; import static de.likewhat.customheads.utils.Utils.openCategory; @@ -60,4 +62,15 @@ public class EconomyManager { } } + public void buyItem(Player player, int price, String itemName, SimpleCallback successCallback) { + EconomyResponse economyResponse = economyPlugin.withdrawPlayer(player, price); + if (economyResponse.transactionSuccess()) { + player.sendMessage(CustomHeads.getLanguageManager().ECONOMY_BUY_SUCCESSFUL.replace("{ITEM}", itemName)); + successCallback.call(true); + } else { + player.sendMessage(CustomHeads.getLanguageManager().ECONOMY_BUY_FAILED.replace("{REASON}", economyResponse.errorMessage).replace("{ITEM}", itemName)); + successCallback.call(false); + } + } + } diff --git a/src/main/java/de/likewhat/customheads/listener/InventoryListener.java b/src/main/java/de/likewhat/customheads/listener/InventoryListener.java index 59a4faa..91a5a5d 100644 --- a/src/main/java/de/likewhat/customheads/listener/InventoryListener.java +++ b/src/main/java/de/likewhat/customheads/listener/InventoryListener.java @@ -28,7 +28,6 @@ import org.bukkit.inventory.meta.SkullMeta; import java.io.File; import java.util.*; -import java.util.logging.Level; import java.util.stream.Collectors; import static de.likewhat.customheads.utils.Utils.*; @@ -40,13 +39,14 @@ import static de.likewhat.customheads.utils.Utils.*; public class InventoryListener implements Listener { - private static HashMap lastMenu = new HashMap<>(); + private static HashMap lastActiveMenu = new HashMap<>(); //private static HashMap lastInventory = new HashMap<>(); - public static String getLastMenu(Player player, boolean remove) { - String last = lastMenu.get(player); - if (remove) - lastMenu.remove(player); + public static String getLastMenu(UUID uuid, boolean remove) { + String last = lastActiveMenu.get(uuid); + if (remove) { + lastActiveMenu.remove(uuid); + } return last; } @@ -132,11 +132,16 @@ public class InventoryListener implements Listener { @EventHandler public void onInvClick(InventoryClickEvent event) { Player player = (Player) event.getWhoClicked(); + if(event.getRawSlot() >= event.getInventory().getSize() && event.isShiftClick()) { + handleInventoryAction(event); + return; + } + if (event.getInventory() == null || event.getRawSlot() >= event.getInventory().getSize() || event.getInventory().getType() != InventoryType.CHEST || !hasPermission(player, "heads.use")) { return; } -// player.sendMessage("§7[CHTags Tags] §r" + CustomHeads.getTagEditor().getTags(event.getCurrentItem())); // Yeah debug at its finest + player.sendMessage("§7[CHTags Tags] §r" + CustomHeads.getTagEditor().getTags(event.getCurrentItem()) + " lastActiveMenu: " + lastActiveMenu.getOrDefault(player.getUniqueId(), "none")); // Yeah debug at its finest if (event.getView().getTitle().equals(CustomHeads.getLanguageManager().LOADING)) { event.setCancelled(true); @@ -150,7 +155,7 @@ public class InventoryListener implements Listener { event.setCancelled(true); String name = toConfigString(ChatColor.stripColor(event.getCurrentItem().getItemMeta().getDisplayName())); if (customHeadsPlayer.hasHead(name)) { - player.openInventory(getDialog(CustomHeads.getLanguageManager().REMOVE_CONFIRMATION.replace("{HEAD}", name), new String[]{"confirmDelete", "head#>" + name, "chItem", "saved_heads", "menuID", InventoryListener.getLastMenu(player, false)}, new String[]{""}, new String[]{"chItem", "saved_heads", "menuID", getLastMenu(player, true)}, null, customHeadsPlayer.getHead(name))); + player.openInventory(getDialog(CustomHeads.getLanguageManager().REMOVE_CONFIRMATION.replace("{HEAD}", name), new String[]{"confirmDelete", "head#>" + name, "chItem", "saved_heads", "menuID", getLastMenu(player.getUniqueId(), false)}, new String[]{""}, new String[]{"chItem", "saved_heads", "menuID", getLastMenu(player.getUniqueId(), true)}, null, customHeadsPlayer.getHead(name))); } return; } @@ -192,8 +197,8 @@ public class InventoryListener implements Listener { String menuID = null; if (itemTags.contains("menuID")) { menuID = itemTags.get(itemTags.indexOf("menuID") + 1).toLowerCase(); - lastMenu.put(player, menuID); - + player.sendMessage("menuID present: " + menuID); + lastActiveMenu.put(player.getUniqueId(), menuID); } if (itemTags.contains("blockMoving")) { @@ -241,7 +246,7 @@ public class InventoryListener implements Listener { for (int line = 0; line < lines; line++) { int start = line * 8; int end = (line + 1) * 8; - String listString = splitter.subList(start, splitter.size() > end ? end : splitter.size()).toString(); + String listString = splitter.subList(start, Math.min(splitter.size(), end)).toString(); listString = listString.substring(1, listString.length() - 1); loreInfo.add("&7" + listString); } @@ -298,8 +303,8 @@ public class InventoryListener implements Listener { if (itemTags.contains("openScInv")) { ScrollableInventory inv = ScrollableInventory.getInventoryByID(itemTags.get(itemTags.indexOf("openScInv") + 1)); List characterList = new ArrayList<>(); - characterList.sort(Comparator.comparing(itemStack -> itemStack.getItemMeta().getDisplayName())); font.getCharacters().forEach((character, customHead) -> characterList.add(CustomHeads.getTagEditor().addTags(new ItemEditor(customHead).setDisplayName("§b" + (character.equals(' ') ? "BLANK" : character)).getItem(), "fontName", font.getFontName(), "character", "" + character, "editFont", "select"))); + characterList.sort(Comparator.comparing(itemStack -> itemStack.getItemMeta().getDisplayName())); inv.setContent(characterList); inv.refreshCurrentPage(); } @@ -336,10 +341,11 @@ public class InventoryListener implements Listener { openCategory(category, player, new String[]{"openMenu", menuID}); } else { if (category.hasSubCategories()) { - // Last null because it'll only open the SubCategory Menu openCategory(category, player, new String[] {"openCategory", "subCategory#>" + category.getId()}); + } else if (lastActiveMenu.containsKey(player.getUniqueId())){ + openCategory(category, player, new String[]{"openMenu", lastActiveMenu.get(player.getUniqueId())}); } else { - Bukkit.getLogger().log(Level.WARNING, "If this Error is thrown... uhm please report it to me on my Discord"); + player.closeInventory(); } } } @@ -414,7 +420,9 @@ public class InventoryListener implements Listener { if (!hasPermission(player, CustomHeads.getLooks().getMenuInfo(itemTags.get(itemTags.indexOf("openMenu") + 1).toLowerCase())[1])) { return; } - Inventory menu = CustomHeads.getLooks().getMenu(itemTags.get(itemTags.indexOf("openMenu") + 1).toLowerCase()); + String mId = itemTags.get(itemTags.indexOf("openMenu") + 1).toLowerCase(); + Inventory menu = CustomHeads.getLooks().getMenu(mId); + lastActiveMenu.put(player.getUniqueId(), mId); if (menu != null) player.openInventory(menu); } @@ -472,7 +480,7 @@ public class InventoryListener implements Listener { event.setCancelled(true); if (!hasPermission(player, "heads.use") || !hasPermission(player, "heads.use.more")) return; ScrollableInventory savedHeads = new ScrollableInventory(CustomHeads.getLanguageManager().SAVED_HEADS_TITLE.replace("{PLAYER}", player.getName()), customHeadsPlayer.getSavedHeads()).setContentsClonable(true); - lastMenu.put(player, menuID); + lastActiveMenu.put(player.getUniqueId(), menuID); savedHeads.setBarItem(1, getBackButton("openMenu", menuID)); savedHeads.setBarItem(3, CustomHeads.getTagEditor().setTags(new ItemEditor(Material.PAPER).setDisplayName(CustomHeads.getLanguageManager().ITEMS_INFO).setLore(CustomHeads.getLanguageManager().ITEMS_INFO_LORE).getItem(), "dec", "info-item", "blockMoving")); player.openInventory(savedHeads.getAsInventory()); @@ -614,9 +622,9 @@ public class InventoryListener implements Listener { @EventHandler public void onEvent(InventoryCloseEvent event) { Player player = (Player) event.getPlayer(); - if(lastMenu.containsKey(player)) { + if(lastActiveMenu.containsKey(player)) { // player.sendMessage("Clearing Last Menu"); - lastMenu.remove(player); + lastActiveMenu.remove(player); } } diff --git a/src/main/java/de/likewhat/customheads/listener/OtherListeners.java b/src/main/java/de/likewhat/customheads/listener/OtherListeners.java index e92a8a5..24f95b2 100644 --- a/src/main/java/de/likewhat/customheads/listener/OtherListeners.java +++ b/src/main/java/de/likewhat/customheads/listener/OtherListeners.java @@ -3,16 +3,14 @@ package de.likewhat.customheads.listener; import de.likewhat.customheads.CustomHeads; import de.likewhat.customheads.category.CategorySetup; import de.likewhat.customheads.utils.Utils; +import de.likewhat.customheads.utils.stuff.CHCommand; import de.likewhat.customheads.utils.updaters.SpigetResourceFetcher; -import org.bukkit.Location; -import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerQuitEvent; import java.util.HashMap; import java.util.UUID; @@ -26,24 +24,16 @@ import static de.likewhat.customheads.utils.Utils.sendJSONMessage; public class OtherListeners implements Listener { - public static final HashMap CACHED_LOCATIONS = new HashMap<>(); +// public static final HashMap CACHED_LOCATIONS = new HashMap<>(); public static final HashMap CACHED_CATEGORYSETUPS = new HashMap<>(); @EventHandler public void fireworkbreak(BlockBreakEvent event) { - if (CACHED_LOCATIONS.containsValue(event.getBlock().getLocation().add(.5, .5, .5))) { + if (CHCommand.CACHED_FIREWORKS.contains(event.getBlock().getLocation().add(.5, .5, .5))) { event.setCancelled(true); } } - @EventHandler - public void onQuit(PlayerQuitEvent event) { - if (CACHED_LOCATIONS.containsKey(event.getPlayer())) { - CACHED_LOCATIONS.get(event.getPlayer()).getBlock().setType(Material.AIR); - CACHED_LOCATIONS.remove(event.getPlayer()); - } - } - @EventHandler public void notifyUpdate(PlayerJoinEvent event) { final Player player = event.getPlayer(); diff --git a/src/main/java/de/likewhat/customheads/utils/APIHandler.java b/src/main/java/de/likewhat/customheads/utils/APIHandler.java index 289c783..f99e312 100644 --- a/src/main/java/de/likewhat/customheads/utils/APIHandler.java +++ b/src/main/java/de/likewhat/customheads/utils/APIHandler.java @@ -21,15 +21,23 @@ import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.Skull; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Firework; import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.FireworkMeta; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; import java.lang.reflect.Constructor; +import java.util.Random; import java.util.logging.Level; public class APIHandler implements CustomHeadsAPI { private static Class tileEntitySkullClass, blockPositionClass; private static Constructor blockPositionConstructor; + private FireworkEffect.Type[] fxTypes = {FireworkEffect.Type.BALL, FireworkEffect.Type.BALL_LARGE, FireworkEffect.Type.BURST, FireworkEffect.Type.STAR}; + static { tileEntitySkullClass = Utils.getMCServerClassByName("TileEntitySkull"); @@ -140,4 +148,68 @@ public class APIHandler implements CustomHeadsAPI { return PlayerWrapper.wrapPlayer(player); } + public void createFireworkBattery(Location location, int shots, int delay) { + createFireworkBattery(location, shots, delay, new FireworksBatteryHandler() { + public void onStart() {} + public void onNext() {} + public void onEnd() {} + }); + } + + public void createFireworkBattery(Location location, int shots, int delay, FireworksBatteryHandler handler) { + Random random = new Random(); + +// if(placeBlock) { +// CustomHeads.getApi().setSkull(location.getBlock(), "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOGEzZDVkNWIyY2YzMzEyOTllNjNkNzYxOGExNDI2NmU4Y2NjNjE1OGU5ZTMxZmNiMGJkOTExZTEyZmY3NzM2In19fQ==", faces[random.nextInt(faces.length)]); +// } + handler.onStart(); + new BukkitRunnable() { + int counter = shots; + + public void run() { + if (counter == 0) { +// if(placeBlock) { +// location.getWorld().playEffect(location.getBlock().getLocation(), Effect.STEP_SOUND, 17); +// location.getBlock().setType(Material.AIR); +// } + handler.onEnd(); +// callback.call(location); + cancel(); + return; + } + Firework f = (Firework) location.getWorld().spawnEntity(location, EntityType.FIREWORK); + FireworkMeta fm = f.getFireworkMeta(); + FireworkEffect.Builder fx = FireworkEffect.builder(); + fx.flicker(random.nextBoolean()).trail(random.nextBoolean()).with(fxTypes[random.nextInt(fxTypes.length)]); + int c = random.nextInt(2) + 2; + for (int i = 0; i < c; i++) { + fx.withColor(Color.fromRGB(random.nextInt(200) + 50, random.nextInt(200) + 50, random.nextInt(200) + 50)); + if (random.nextBoolean()) { + fx.withFade(Color.fromRGB(random.nextInt(200) + 50, random.nextInt(200) + 50, random.nextInt(200) + 50)); + } + } + fm.addEffect(fx.build()); + fm.setPower(random.nextInt(2) + 1); + f.setFireworkMeta(fm); + f.setVelocity(new Vector(random.nextDouble() * (random.nextBoolean() ? .01 : -.01), .2, random.nextDouble() * (random.nextBoolean() ? .01 : -.01))); +// World world = location.getWorld(); + handler.onNext(); +// if(placeBlock) { +// if (NBTTagUtils.MC_VERSION > 13) { +// try { +// Class particleClass = Utils.getClassByName("org.bukkit.Particle"); +// World.class.getMethod("spawnParticle", particleClass, Location.class, int.class).invoke(world, NMSUtils.getEnumFromClass(particleClass, "LAVA"), location, 6); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } else { +// for (int i = 0; i < 6; i++) { +// world.playEffect(location, Effect.LAVA_POP, 0); +// } +// } +// } + counter--; + } + }.runTaskTimer(CustomHeads.getInstance(), 10, delay); + } } diff --git a/src/main/java/de/likewhat/customheads/utils/EmptyCallback.java b/src/main/java/de/likewhat/customheads/utils/EmptyCallback.java new file mode 100644 index 0000000..fffd7eb --- /dev/null +++ b/src/main/java/de/likewhat/customheads/utils/EmptyCallback.java @@ -0,0 +1,14 @@ +package de.likewhat.customheads.utils; + +/* + * Project: CustomHeads in EmptyCallback + * by LikeWhat + * + * created on 04.08.2020 at 01:57 + */ + +public interface EmptyCallback { + + void call(); + +} diff --git a/src/main/java/de/likewhat/customheads/utils/FireworksBatteryHandler.java b/src/main/java/de/likewhat/customheads/utils/FireworksBatteryHandler.java new file mode 100644 index 0000000..6517a30 --- /dev/null +++ b/src/main/java/de/likewhat/customheads/utils/FireworksBatteryHandler.java @@ -0,0 +1,21 @@ +package de.likewhat.customheads.utils; + +/* + * Project: CustomHeads in FireworksBatteryHandler + * by LikeWhat + * + * created on 04.08.2020 at 02:14 + */ + +/** + * Handler for Firework Batteries + */ +public interface FireworksBatteryHandler { + + void onStart(); + + void onNext(); + + void onEnd(); + +} diff --git a/src/main/java/de/likewhat/customheads/utils/GameProfileBuilder.java b/src/main/java/de/likewhat/customheads/utils/GameProfileBuilder.java index 12bb538..0b5a89b 100644 --- a/src/main/java/de/likewhat/customheads/utils/GameProfileBuilder.java +++ b/src/main/java/de/likewhat/customheads/utils/GameProfileBuilder.java @@ -85,7 +85,7 @@ public class GameProfileBuilder { } public static GameProfile createProfileWithTexture(String texture) { - GameProfile profile = new GameProfile(UUID.randomUUID(), null); + GameProfile profile = new GameProfile(UUID.randomUUID(), "0"); PropertyMap propertyMap = profile.getProperties(); propertyMap.put("textures", new Property("textures", texture)); return profile; diff --git a/src/main/java/de/likewhat/customheads/utils/InteractiveDialog.java b/src/main/java/de/likewhat/customheads/utils/InteractiveDialog.java index 787791e..aa1bae4 100644 --- a/src/main/java/de/likewhat/customheads/utils/InteractiveDialog.java +++ b/src/main/java/de/likewhat/customheads/utils/InteractiveDialog.java @@ -54,7 +54,6 @@ public class InteractiveDialog { destroy(); } } - }; Bukkit.getPluginManager().registerEvents(listener, CustomHeads.getInstance()); } diff --git a/src/main/java/de/likewhat/customheads/utils/ScrollableInventory.java b/src/main/java/de/likewhat/customheads/utils/ScrollableInventory.java index 14c46cb..de633b2 100644 --- a/src/main/java/de/likewhat/customheads/utils/ScrollableInventory.java +++ b/src/main/java/de/likewhat/customheads/utils/ScrollableInventory.java @@ -8,6 +8,7 @@ import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitRunnable; import java.util.*; @@ -106,22 +107,26 @@ public class ScrollableInventory { refreshContent(); - List sublist = getContentFromPage(currentPage, true); - for (int i = 0; i < sublist.size(); i++) { - inventory.setItem(i, sublist.get(i)); - } + Utils.runAsync(new BukkitRunnable() { + public void run() { + List sublist = getContentFromPage(currentPage, true); + for (int i = 0; i < sublist.size(); i++) { + inventory.setItem(i, sublist.get(i)); + } - for (int index : buttons.keySet()) - inventory.setItem(index + 47, CustomHeads.getTagEditor().addTags(buttons.get(index), "scInvID", uid)); + for (int index : buttons.keySet()) + inventory.setItem(index + 47, CustomHeads.getTagEditor().addTags(buttons.get(index), "scInvID", uid)); - if (page < getPages()) - inventory.setItem(53, CustomHeads.getTagEditor().setTags(new ItemEditor(Material.SKULL_ITEM, 3).setDisplayName(language.NEXT_PAGE).setLore(language.PAGE_GENERAL_PREFIX + " " + (page + 1)).setTexture("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMWI2ZjFhMjViNmJjMTk5OTQ2NDcyYWVkYjM3MDUyMjU4NGZmNmY0ZTgzMjIxZTU5NDZiZDJlNDFiNWNhMTNiIn19fQ==").getItem(), "scInvID", uid, "scrollInv", "slidePage#>next")); - if (page > 1) - inventory.setItem(45, CustomHeads.getTagEditor().setTags(new ItemEditor(Material.SKULL_ITEM, 3).setDisplayName(language.PREVIOUS_PAGE).setLore(language.PAGE_GENERAL_PREFIX + " " + (page - 1)).setTexture("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNzM3NjQ4YWU3YTU2NGE1Mjg3NzkyYjA1ZmFjNzljNmI2YmQ0N2Y2MTZhNTU5Y2U4YjU0M2U2OTQ3MjM1YmNlIn19fQ==").getItem(), "scInvID", uid, "scrollInv", "slidePage#>previous")); + if (page < getPages()) + inventory.setItem(53, CustomHeads.getTagEditor().setTags(new ItemEditor(Material.SKULL_ITEM, 3).setDisplayName(language.NEXT_PAGE).setLore(language.PAGE_GENERAL_PREFIX + " " + (page + 1)).setTexture("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMWI2ZjFhMjViNmJjMTk5OTQ2NDcyYWVkYjM3MDUyMjU4NGZmNmY0ZTgzMjIxZTU5NDZiZDJlNDFiNWNhMTNiIn19fQ==").getItem(), "scInvID", uid, "scrollInv", "slidePage#>next")); + if (page > 1) + inventory.setItem(45, CustomHeads.getTagEditor().setTags(new ItemEditor(Material.SKULL_ITEM, 3).setDisplayName(language.PREVIOUS_PAGE).setLore(language.PAGE_GENERAL_PREFIX + " " + (page - 1)).setTexture("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNzM3NjQ4YWU3YTU2NGE1Mjg3NzkyYjA1ZmFjNzljNmI2YmQ0N2Y2MTZhNTU5Y2U4YjU0M2U2OTQ3MjM1YmNlIn19fQ==").getItem(), "scInvID", uid, "scrollInv", "slidePage#>previous")); + } + }); } public int reArrangeContents(int method) { - if ((currentArrangement = method < 1 ? 1 : method > (sorting.size() + 1) ? (sorting.size() + 1) : method) == 1) { + if ((currentArrangement = method < 1 ? 1 : Math.min(method, (sorting.size() + 1))) == 1) { content = new ArrayList<>(defContent); } else { content.sort(sorting.get(currentArrangement - 1)); diff --git a/src/main/java/de/likewhat/customheads/utils/Utils.java b/src/main/java/de/likewhat/customheads/utils/Utils.java index fb44ffc..805acf5 100644 --- a/src/main/java/de/likewhat/customheads/utils/Utils.java +++ b/src/main/java/de/likewhat/customheads/utils/Utils.java @@ -285,7 +285,7 @@ public class Utils { } public static Inventory getDialog(String title, String[] yesAction, String[] yesActionLore, String[] noAction, String[] noActionLore, ItemStack middleItem) { - System.out.println("title: " + title + "\nyesAction: " + Utils.GSON.toJson(yesAction) + " noAction: " + Utils.GSON.toJson(noAction)); + //System.out.println("title: " + title + "\nyesAction: " + Utils.GSON.toJson(yesAction) + " noAction: " + Utils.GSON.toJson(noAction)); Inventory dialog = Bukkit.createInventory(null, 9 * 3, title.length() > 32 ? title.substring(0, 29) + "..." : title); dialog.setItem(11, CustomHeads.getTagEditor().setTags(new ItemEditor(Material.SKULL_ITEM, 3).setTexture("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMzYxZTViMzMzYzJhMzg2OGJiNmE1OGI2Njc0YTI2MzkzMjM4MTU3MzhlNzdlMDUzOTc3NDE5YWYzZjc3In19fQ==").setDisplayName("§a" + CustomHeads.getLanguageManager().YES).setLore(yesActionLore).getItem(), yesAction)); dialog.setItem(13, CustomHeads.getTagEditor().setTags(middleItem, "blockMoving")); @@ -384,15 +384,24 @@ public class Utils { } } openPreloader(player); - ScrollableInventory inventory = new ScrollableInventory(baseCategory.getName()); - inventory.setContent(categoryHeads.stream().map(customHead -> { - boolean bought = customHeadsPlayer.getUnlockedHeads().contains(customHead); - ItemEditor itemEditor = new ItemEditor(customHead); - return CustomHeads.hasEconomy() && CustomHeads.headsBuyable() ? (bought || hasPermission(player, "heads.viewCategory." + baseCategory.getPermission().replaceFirst("heads.viewCategory.", "") + ".allheads")) ? CustomHeads.getTagEditor().addTags(itemEditor.addLoreLine(CustomHeads.getLanguageManager().ECONOMY_BOUGHT).getItem(), "wearable", "clonable") : CustomHeads.getTagEditor().addTags(itemEditor.addLoreLine(formatPrice(customHead.getPrice(), true)).getItem(), "buyHead", "buyHead#>" + customHead.getOriginCategory().getId() + ":" + customHead.getId()) : CustomHeads.getTagEditor().addTags(itemEditor.getItem(), "wearable", "clonable"); - }).collect(Collectors.toList())); - inventory.setBarItem(1, Utils.getBackButton(backAction)); - inventory.setBarItem(3, CustomHeads.getTagEditor().setTags(new ItemEditor(Material.PAPER).setDisplayName(CustomHeads.getLanguageManager().ITEMS_INFO).setLore(CustomHeads.getLanguageManager().ITEMS_INFO_LORE).getItem(), "dec", "info-item", "blockMoving")); - player.openInventory(inventory.getAsInventory()); + + runAsync(new BukkitRunnable() { + public void run() { + ScrollableInventory inventory = new ScrollableInventory(baseCategory.getName()); + inventory.setContent(categoryHeads.stream().map(customHead -> { + boolean bought = customHeadsPlayer.getUnlockedHeads().contains(customHead); + ItemEditor itemEditor = new ItemEditor(customHead); + return CustomHeads.hasEconomy() && CustomHeads.headsBuyable() ? (bought || hasPermission(player, "heads.unlockAllHeads." + baseCategory.getPermission().replaceFirst("heads.viewCategory.", ""))) ? CustomHeads.getTagEditor().addTags(itemEditor.addLoreLine(CustomHeads.getLanguageManager().ECONOMY_BOUGHT).getItem(), "wearable", "clonable") : CustomHeads.getTagEditor().addTags(itemEditor.addLoreLine(formatPrice(customHead.getPrice(), true)).getItem(), "buyHead", "buyHead#>" + customHead.getOriginCategory().getId() + ":" + customHead.getId()) : CustomHeads.getTagEditor().addTags(itemEditor.getItem(), "wearable", "clonable"); + }).collect(Collectors.toList())); + inventory.setBarItem(1, Utils.getBackButton(backAction)); + inventory.setBarItem(3, CustomHeads.getTagEditor().setTags(new ItemEditor(Material.PAPER).setDisplayName(CustomHeads.getLanguageManager().ITEMS_INFO).setLore(CustomHeads.getLanguageManager().ITEMS_INFO_LORE).getItem(), "dec", "info-item", "blockMoving")); + runSyncedLater(new BukkitRunnable() { + public void run() { + player.openInventory(inventory.getAsInventory()); + } + }, 10); + } + }); } public static boolean hasCustomTexture(ItemStack itemStack) { @@ -414,6 +423,27 @@ public class Utils { runnable.runTask(CustomHeads.getInstance()); } + public static void runSyncedLater(BukkitRunnable runnable, long delay) { + runnable.runTaskLater(CustomHeads.getInstance(), delay); + } + + public static void runSyncedTimer(BukkitRunnable runnable, long delay, long time) { + runnable.runTaskTimer(CustomHeads.getInstance(), delay, time); + } + + public static void runAsync(BukkitRunnable runnable) { + runnable.runTaskAsynchronously(CustomHeads.getInstance()); + } + + public static void runAsyncLater(BukkitRunnable runnable, long delay) { + runnable.runTaskLaterAsynchronously(CustomHeads.getInstance(), delay); + } + + public static void runAsyncTimer(BukkitRunnable runnable, long delay, long time) { + runnable.runTaskTimerAsynchronously(CustomHeads.getInstance(), delay, time); + } + + // I created this Code at Random just to Split Text public static String[] splitEvery(String string, String regex, int index) { if (index <= 0) throw new IllegalArgumentException("Index must be higher than 0"); @@ -471,7 +501,7 @@ public class Utils { consumer.accept(CustomHeads.uuidCache.get(name)); return; } - new BukkitRunnable() { + Utils.runAsync(new BukkitRunnable() { public void run() { try { HttpURLConnection connection = (HttpURLConnection) new URL(String.format("https://api.mojang.com/users/profiles/minecraft/%s", name)).openConnection(); @@ -489,14 +519,22 @@ public class Utils { consumer.accept(null); return; } - consumer.accept(new JsonParser().parse(json).getAsJsonObject().get("id").getAsString()); + Utils.runSynced(new BukkitRunnable() { + public void run() { + consumer.accept(new JsonParser().parse(json).getAsJsonObject().get("id").getAsString()); + } + }); } } catch (Exception whoops) { Bukkit.getLogger().log(Level.WARNING, "Couldn't get UUID from " + name, whoops); - consumer.accept(null); + Utils.runSynced(new BukkitRunnable() { + public void run() { + consumer.accept(null); + } + }); } } - }.runTaskAsynchronously(CustomHeads.getInstance()); + }); } public static void unzipFile(File zipFile, File outputDir) { @@ -564,7 +602,7 @@ public class Utils { sender.sendMessage((console ? CustomHeads.chPrefix : "") + CustomHeads.getLanguageManager().LANGUAGE_REDOWNLOAD_DOWNLOADING); GitHubDownloader gitGetter = new GitHubDownloader("IHasName", "CustomHeads").enableAutoUnzipping(); gitGetter.download(CustomHeads.getInstance().getDescription().getVersion(), "en_EN.zip", new File("plugins/CustomHeads/language"), (AsyncFileDownloader.AfterTask) () -> { - CustomHeads.reload(); + CustomHeads.silentReload(); sender.sendMessage((console ? CustomHeads.chPrefix : "") + CustomHeads.getLanguageManager().LANGUAGE_REDOWNLOAD_DONE); }); return true; diff --git a/src/main/java/de/likewhat/customheads/utils/stuff/CHCommand.java b/src/main/java/de/likewhat/customheads/utils/stuff/CHCommand.java index e59f38a..ac99d21 100644 --- a/src/main/java/de/likewhat/customheads/utils/stuff/CHCommand.java +++ b/src/main/java/de/likewhat/customheads/utils/stuff/CHCommand.java @@ -8,7 +8,6 @@ import de.likewhat.customheads.category.CustomHead; import de.likewhat.customheads.category.SubCategory; import de.likewhat.customheads.headwriter.HeadFontType; import de.likewhat.customheads.headwriter.HeadWriter; -import de.likewhat.customheads.listener.OtherListeners; import de.likewhat.customheads.utils.*; import de.likewhat.customheads.utils.reflection.NBTTagUtils; import de.likewhat.customheads.utils.updaters.FetchResult; @@ -17,15 +16,11 @@ import org.bukkit.block.BlockFace; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Firework; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.FireworkMeta; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; -import org.bukkit.util.Vector; import java.io.File; import java.util.*; @@ -47,6 +42,8 @@ public class CHCommand implements CommandExecutor { private FireworkEffect.Type[] fxTypes = {FireworkEffect.Type.BALL, FireworkEffect.Type.BALL_LARGE, FireworkEffect.Type.BURST, FireworkEffect.Type.STAR}; private BlockFace[] faces = {BlockFace.NORTH, BlockFace.NORTH_EAST, BlockFace.NORTH_NORTH_EAST}; private Random ran = new Random(); + private List active_fireworks = new ArrayList<>(); + public static final List CACHED_FIREWORKS = new ArrayList<>(); public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (!(sender instanceof Player)) { @@ -443,51 +440,33 @@ public class CHCommand implements CommandExecutor { player.sendMessage(CustomHeads.getLanguageManager().CANNOT_PLACE_IN_AIR); return true; } - if (OtherListeners.CACHED_LOCATIONS.containsKey(player)) { + if (active_fireworks.contains(player)) { player.sendMessage(CustomHeads.getLanguageManager().ALREADY_IN_USE); return true; } player.sendMessage(CustomHeads.getLanguageManager().STARTING); - CustomHeads.getApi().setSkull(player.getLocation().getBlock(), "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOGEzZDVkNWIyY2YzMzEyOTllNjNkNzYxOGExNDI2NmU4Y2NjNjE1OGU5ZTMxZmNiMGJkOTExZTEyZmY3NzM2In19fQ==", faces[ran.nextInt(faces.length)]); - OtherListeners.CACHED_LOCATIONS.put(player, player.getLocation().getBlock().getLocation().add(.5, .5, .5)); - new BukkitRunnable() { - Player cPlayer = player; - int counter = 10; + active_fireworks.add(player); + Location startLocation = player.getLocation().getBlock().getLocation().add(.5, .5, .5); + CACHED_FIREWORKS.add(startLocation); +// OtherListeners.CACHED_LOCATIONS.put(player, player.getLocation().getBlock().getLocation().add(.5, .5, .5)); +// CustomHeads.getApi().createFireworkBattery(startLocation, 10, 20, location -> { +// location.getWorld().playEffect(location.getBlock().getLocation(), Effect.STEP_SOUND, 17); +// location.getBlock().setType(Material.AIR); +// }); + CustomHeads.getApi().createFireworkBattery(startLocation, 10, 20, new FireworksBatteryHandler() { + Location location = startLocation.clone(); - public void run() { - if (!OtherListeners.CACHED_LOCATIONS.containsKey(cPlayer)) { - cancel(); - return; - } - if (counter <= 0) { - OtherListeners.CACHED_LOCATIONS.get(cPlayer).getWorld().playEffect(OtherListeners.CACHED_LOCATIONS.get(cPlayer).getBlock().getLocation(), Effect.STEP_SOUND, 17); - OtherListeners.CACHED_LOCATIONS.get(cPlayer).getBlock().setType(Material.AIR); - OtherListeners.CACHED_LOCATIONS.remove(cPlayer); - cancel(); - return; - } - Firework f = (Firework) OtherListeners.CACHED_LOCATIONS.get(cPlayer).getWorld().spawnEntity(OtherListeners.CACHED_LOCATIONS.get(cPlayer), EntityType.FIREWORK); - FireworkMeta fm = f.getFireworkMeta(); - FireworkEffect.Builder fx = FireworkEffect.builder(); - fx.flicker(ran.nextBoolean()).trail(ran.nextBoolean()).with(fxTypes[ran.nextInt(fxTypes.length)]); - int c = ran.nextInt(2) + 2; - for (int i = 0; i < c; i++) { - fx.withColor(Color.fromRGB(ran.nextInt(200) + 50, ran.nextInt(200) + 50, ran.nextInt(200) + 50)); - if (ran.nextBoolean()) { - fx.withFade(Color.fromRGB(ran.nextInt(200) + 50, ran.nextInt(200) + 50, ran.nextInt(200) + 50)); - } - } - fm.addEffect(fx.build()); - fm.setPower(ran.nextInt(2) + 1); - f.setFireworkMeta(fm); - f.setVelocity(new Vector(ran.nextDouble() * (ran.nextBoolean() ? .01 : -.01), .2, ran.nextDouble() * (ran.nextBoolean() ? .01 : -.01))); - Location location = OtherListeners.CACHED_LOCATIONS.get(cPlayer); + public void onStart() { + CustomHeads.getApi().setSkull(location.getBlock(), "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOGEzZDVkNWIyY2YzMzEyOTllNjNkNzYxOGExNDI2NmU4Y2NjNjE1OGU5ZTMxZmNiMGJkOTExZTEyZmY3NzM2In19fQ==", faces[ran.nextInt(faces.length)]); + } + + public void onNext() { World world = location.getWorld(); - if(NBTTagUtils.MC_VERSION > 13) { + if (NBTTagUtils.MC_VERSION > 13) { try { Class particleClass = Utils.getClassByName("org.bukkit.Particle"); World.class.getMethod("spawnParticle", particleClass, Location.class, int.class).invoke(world, NMSUtils.getEnumFromClass(particleClass, "LAVA"), location, 6); - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); } } else { @@ -495,9 +474,61 @@ public class CHCommand implements CommandExecutor { world.playEffect(location, Effect.LAVA_POP, 0); } } - counter--; } - }.runTaskTimer(CustomHeads.getInstance(), 10, 20); + + public void onEnd() { + location.getWorld().playEffect(location.getBlock().getLocation(), Effect.STEP_SOUND, 17); + location.getBlock().setType(Material.AIR); + } + }); +// new BukkitRunnable() { +// Player cPlayer = player; +// int counter = 10; +// +// public void run() { +// if (!OtherListeners.CACHED_LOCATIONS.containsKey(cPlayer)) { +// cancel(); +// return; +// } +// if (counter <= 0) { +// OtherListeners.CACHED_LOCATIONS.get(cPlayer).getWorld().playEffect(OtherListeners.CACHED_LOCATIONS.get(cPlayer).getBlock().getLocation(), Effect.STEP_SOUND, 17); +// OtherListeners.CACHED_LOCATIONS.get(cPlayer).getBlock().setType(Material.AIR); +// OtherListeners.CACHED_LOCATIONS.remove(cPlayer); +// cancel(); +// return; +// } +// Firework f = (Firework) OtherListeners.CACHED_LOCATIONS.get(cPlayer).getWorld().spawnEntity(OtherListeners.CACHED_LOCATIONS.get(cPlayer), EntityType.FIREWORK); +// FireworkMeta fm = f.getFireworkMeta(); +// FireworkEffect.Builder fx = FireworkEffect.builder(); +// fx.flicker(ran.nextBoolean()).trail(ran.nextBoolean()).with(fxTypes[ran.nextInt(fxTypes.length)]); +// int c = ran.nextInt(2) + 2; +// for (int i = 0; i < c; i++) { +// fx.withColor(Color.fromRGB(ran.nextInt(200) + 50, ran.nextInt(200) + 50, ran.nextInt(200) + 50)); +// if (ran.nextBoolean()) { +// fx.withFade(Color.fromRGB(ran.nextInt(200) + 50, ran.nextInt(200) + 50, ran.nextInt(200) + 50)); +// } +// } +// fm.addEffect(fx.build()); +// fm.setPower(ran.nextInt(2) + 1); +// f.setFireworkMeta(fm); +// f.setVelocity(new Vector(ran.nextDouble() * (ran.nextBoolean() ? .01 : -.01), .2, ran.nextDouble() * (ran.nextBoolean() ? .01 : -.01))); +// Location location = OtherListeners.CACHED_LOCATIONS.get(cPlayer); +// World world = location.getWorld(); +// if(NBTTagUtils.MC_VERSION > 13) { +// try { +// Class particleClass = Utils.getClassByName("org.bukkit.Particle"); +// World.class.getMethod("spawnParticle", particleClass, Location.class, int.class).invoke(world, NMSUtils.getEnumFromClass(particleClass, "LAVA"), location, 6); +// } catch(Exception e) { +// e.printStackTrace(); +// } +// } else { +// for (int i = 0; i < 6; i++) { +// world.playEffect(location, Effect.LAVA_POP, 0); +// } +// } +// counter--; +// } +// }.runTaskTimer(CustomHeads.getInstance(), 10, 20); return true; } player.sendMessage(CustomHeads.getLanguageManager().NO_PERMISSION); @@ -578,8 +609,27 @@ public class CHCommand implements CommandExecutor { player.sendMessage(CustomHeads.getLanguageManager().GET_INVALID.replace("{PLAYER}", args[1])); return true; } - CustomHeads.getApi().wrapPlayer(player).getGetHistory().addEntry(args[1]); - player.getInventory().addItem(new ItemEditor(Material.SKULL_ITEM, 3).setDisplayName(CustomHeads.getLanguageManager().GET_HEAD_NAME.replace("{PLAYER}", args[1])).setOwner(args[1]).getItem()); + ItemStack playerHead = new ItemEditor(Material.SKULL_ITEM, 3).setDisplayName(CustomHeads.getLanguageManager().GET_HEAD_NAME.replace("{PLAYER}", args[1])).setOwner(args[1]).getItem(); + + if(CustomHeads.getGetCommandPrice() > 0 && CustomHeads.hasEconomy()) { + Utils.showInteractiveDialog(player, CustomHeads.getLanguageManager().ECONOMY_BUY_CONFIRM.replace("{ITEM}", args[1]).replace("{PRICE}", Utils.formatPrice(CustomHeads.getGetCommandPrice(), false)), yesPressed -> { + if(yesPressed) { + CustomHeads.getEconomyManager().buyItem(player, CustomHeads.getGetCommandPrice(), playerHead.getItemMeta().getDisplayName(), successful -> { + if(successful) { + player.getInventory().addItem(playerHead); + } + }); + } else { + player.closeInventory(); + } + }, null, null, playerHead); + return true; + } + CustomHeads.getApi() + .wrapPlayer(player) + .getGetHistory() + .addEntry(args[1]); + player.getInventory().addItem(playerHead); return true; } player.sendMessage(CustomHeads.getLanguageManager().NO_PERMISSION); @@ -653,6 +703,28 @@ public class CHCommand implements CommandExecutor { player.sendMessage(CustomHeads.getLanguageManager().NO_PERMISSION); return true; } + if(args[0].equalsIgnoreCase("random")) { + List heads = CustomHeads.getCategoryManager().getAllHeads(); + CustomHead randomHead = heads.get(RANDOM.nextInt(heads.size())); + if(randomHead.isFree()) { + player.getInventory().addItem(randomHead); + } else { +// Category category = randomHead.getOriginCategory(); + Utils.showInteractiveDialog(player, CustomHeads.getLanguageManager().ECONOMY_BUY_CONFIRM.replace("{ITEM}", ChatColor.stripColor(randomHead.getItemMeta().getDisplayName())).replace("{PRICE}", getHeadPriceFormatted(randomHead, false)), new SimpleCallback() { + CustomHead head = randomHead; + CustomHeadsPlayer p = CustomHeads.getApi().wrapPlayer(player); + public void call(Boolean buySuccessful) { + if(buySuccessful) { + CustomHeads.getEconomyManager().buyHead(p, head.getOriginCategory(), head.getId(), CustomHeads.headsPermanentBuy()); + p.unwrap().getInventory().addItem(head.getPlainItem()); + } else { + p.unwrap().closeInventory(); + } + + } + }, null, null, randomHead.getPlainItem()); + } + } if (args.length > 1) { CustomHeadsPlayer customHeadsPlayer = CustomHeads.getApi().wrapPlayer(player); if (args[0].equalsIgnoreCase("add") || args[0].equalsIgnoreCase("save")) { diff --git a/src/main/java/de/likewhat/customheads/utils/stuff/CHSearchQuery.java b/src/main/java/de/likewhat/customheads/utils/stuff/CHSearchQuery.java index 8e4da92..44fbb5e 100644 --- a/src/main/java/de/likewhat/customheads/utils/stuff/CHSearchQuery.java +++ b/src/main/java/de/likewhat/customheads/utils/stuff/CHSearchQuery.java @@ -39,10 +39,10 @@ public class CHSearchQuery { results = new ArrayList<>(); return; } - results = CustomHeads.getCategoryManager().getAllHeads().stream().filter(head -> { - String nameStripped = ChatColor.stripColor(head.getItemMeta().getDisplayName().toLowerCase()); - return Arrays.stream(search.split(" ")).anyMatch(s -> s.equalsIgnoreCase(nameStripped)); - }).collect(Collectors.toList()); + results = CustomHeads.getCategoryManager().getAllHeads().stream().filter(head -> ChatColor.stripColor(head.getItemMeta().getDisplayName().toLowerCase()).contains(search.toLowerCase()) + //String nameStripped = ChatColor.stripColor(head.getItemMeta().getDisplayName().toLowerCase()); + //return Arrays.stream(search.split(" ")).anyMatch(s -> s.contains(nameStripped)); + ).collect(Collectors.toList()); Collections.reverse(results); } diff --git a/src/main/java/de/likewhat/customheads/utils/updaters/AsyncFileDownloader.java b/src/main/java/de/likewhat/customheads/utils/updaters/AsyncFileDownloader.java index 367d8ec..34d28b7 100644 --- a/src/main/java/de/likewhat/customheads/utils/updaters/AsyncFileDownloader.java +++ b/src/main/java/de/likewhat/customheads/utils/updaters/AsyncFileDownloader.java @@ -1,7 +1,7 @@ package de.likewhat.customheads.utils.updaters; import com.google.common.io.Files; -import de.likewhat.customheads.CustomHeads; +import de.likewhat.customheads.utils.Utils; import org.bukkit.scheduler.BukkitRunnable; import java.io.File; @@ -36,7 +36,7 @@ public class AsyncFileDownloader { public void startDownload(FileDownloaderCallback callback) { System.out.println("Downloading " + fileName + "..."); - new BukkitRunnable() { + Utils.runAsync(new BukkitRunnable() { public void run() { try { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); @@ -59,7 +59,7 @@ public class AsyncFileDownloader { callback.failed(DownloaderStatus.ERROR.setDescription("Failed to download File").setException(e)); } } - }.runTaskAsynchronously(CustomHeads.getInstance()); + }); } public enum DownloaderStatus { @@ -95,11 +95,9 @@ public class AsyncFileDownloader { } public interface FileDownloaderCallback { - void complete(); void failed(AsyncFileDownloader.DownloaderStatus status); - } public interface AfterTask { diff --git a/src/main/java/de/likewhat/customheads/utils/updaters/CachedResponse.java b/src/main/java/de/likewhat/customheads/utils/updaters/CachedResponse.java index 540fa0b..211e202 100644 --- a/src/main/java/de/likewhat/customheads/utils/updaters/CachedResponse.java +++ b/src/main/java/de/likewhat/customheads/utils/updaters/CachedResponse.java @@ -12,11 +12,11 @@ import lombok.Getter; @Getter public class CachedResponse { - private final long time; + private final long cacheTime; private final T data; - public CachedResponse(long time, T data) { - this.time = time; + public CachedResponse(long cacheTime, T data) { + this.cacheTime = cacheTime; this.data = data; } } diff --git a/src/main/java/de/likewhat/customheads/utils/updaters/GitHubDownloader.java b/src/main/java/de/likewhat/customheads/utils/updaters/GitHubDownloader.java index c7e470e..d3708c9 100644 --- a/src/main/java/de/likewhat/customheads/utils/updaters/GitHubDownloader.java +++ b/src/main/java/de/likewhat/customheads/utils/updaters/GitHubDownloader.java @@ -42,7 +42,7 @@ public class GitHubDownloader { } public static void clearCache() { - responseCache.values().removeIf(cachedResponse -> cachedResponse.getTime() - System.currentTimeMillis() > 600000); + responseCache.values().removeIf(cachedResponse -> cachedResponse.getCacheTime() - System.currentTimeMillis() > 600000); } public GitHubDownloader enableAutoUnzipping() { @@ -202,7 +202,7 @@ public class GitHubDownloader { } timeLeft /= 1000; long time = timeLeft % 86400; - return (int) Math.floor((time % 86400) / 3600) + "h " + (int) Math.floor((time % 3600) / 60) + "m " + (int) Math.floor((time % 60)) + "s"; + return (int) Math.floor((time % 86400f) / 3600f) + "h " + (int) Math.floor((time % 3600f) / 60f) + "m " + (int) Math.floor((time % 60)) + "s"; } public String getMessage() { diff --git a/src/main/java/de/likewhat/customheads/utils/updaters/SpigetResourceFetcher.java b/src/main/java/de/likewhat/customheads/utils/updaters/SpigetResourceFetcher.java index b7d1de8..d248273 100644 --- a/src/main/java/de/likewhat/customheads/utils/updaters/SpigetResourceFetcher.java +++ b/src/main/java/de/likewhat/customheads/utils/updaters/SpigetResourceFetcher.java @@ -3,6 +3,7 @@ package de.likewhat.customheads.utils.updaters; import com.google.gson.*; import de.likewhat.customheads.CustomHeads; import de.likewhat.customheads.utils.Configs; +import de.likewhat.customheads.utils.Utils; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @@ -51,51 +52,52 @@ public class SpigetResourceFetcher { } public void fetchUpdates(FetchResult resultFetcher) { - new BukkitRunnable() { - public void run() { - try { - Configs updateFile = CustomHeads.getUpdateFile(); - long lastFetch = updateFile.get().getLong("lastUpdateCheck"); - JsonArray versionArray; - boolean fromCache = false; - if (updateFile.get().isSet("lastVersionFetch") && TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis() - lastFetch) <= 0) { - versionArray = jsonParser.parse(new String(Base64.getDecoder().decode(updateFile.get().getString("lastVersionFetch").getBytes()))).getAsJsonArray(); - fromCache = true; - } else { - HttpURLConnection connection = (HttpURLConnection) new URL(versionUrlFormatted).openConnection(); - connection.addRequestProperty("User-Agent", userAgent); - connection.setReadTimeout(5000); - versionArray = jsonParser.parse(new InputStreamReader(connection.getInputStream())).getAsJsonArray(); - } - - List releaseList = new ArrayList<>(); - for (JsonElement resourceRaw : versionArray) { - releaseList.add(GSON.fromJson(resourceRaw, ResourceRelease.class)); - } - if (!fromCache) { - updateFile.get().set("lastUpdateCheck", System.currentTimeMillis()); - updateFile.get().set("lastVersionFetch", new String(Base64.getEncoder().encode(GSON.toJson(releaseList).getBytes()))); - updateFile.save(); - } - - ResourceRelease latestRelease = releaseList.get(0); - String[] latestVersionString = latestRelease.getReleaseName().split("."); - String[] currentVersionString = CustomHeads.getInstance().getDescription().getVersion().split("."); - for(int i = 0; i < Math.max(latestVersionString.length, currentVersionString.length); i++) { - int latestVersion = i < latestVersionString.length ? Integer.parseInt(latestVersionString[i]) : 0; - int currentVersion = i < currentVersionString.length ? Integer.parseInt(currentVersionString[i]) : 0; - - if(latestVersion < currentVersion) { - getVersions(updateList -> resultFetcher.updateAvailable(latestRelease, updateList.get(0))); + Utils.runAsync( + new BukkitRunnable() { + public void run() { + try { + Configs updateFile = CustomHeads.getUpdateFile(); + long lastFetch = updateFile.get().getLong("lastUpdateCheck"); + JsonArray versionArray; + boolean fromCache = false; + if (updateFile.get().isSet("lastVersionFetch") && TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis() - lastFetch) <= 0) { + versionArray = jsonParser.parse(new String(Base64.getDecoder().decode(updateFile.get().getString("lastVersionFetch").getBytes()))).getAsJsonArray(); + fromCache = true; } else { - resultFetcher.noUpdate(); + HttpURLConnection connection = (HttpURLConnection) new URL(versionUrlFormatted).openConnection(); + connection.addRequestProperty("User-Agent", userAgent); + connection.setReadTimeout(5000); + versionArray = jsonParser.parse(new InputStreamReader(connection.getInputStream())).getAsJsonArray(); } + + List releaseList = new ArrayList<>(); + for (JsonElement resourceRaw : versionArray) { + releaseList.add(GSON.fromJson(resourceRaw, ResourceRelease.class)); + } + if (!fromCache) { + updateFile.get().set("lastUpdateCheck", System.currentTimeMillis()); + updateFile.get().set("lastVersionFetch", new String(Base64.getEncoder().encode(GSON.toJson(releaseList).getBytes()))); + updateFile.save(); + } + + ResourceRelease latestRelease = releaseList.get(0); + String[] latestVersionString = latestRelease.getReleaseName().split("."); + String[] currentVersionString = CustomHeads.getInstance().getDescription().getVersion().split("."); + for(int i = 0; i < Math.max(latestVersionString.length, currentVersionString.length); i++) { + int latestVersion = i < latestVersionString.length ? Integer.parseInt(latestVersionString[i]) : 0; + int currentVersion = i < currentVersionString.length ? Integer.parseInt(currentVersionString[i]) : 0; + + if(latestVersion < currentVersion) { + getVersions(updateList -> resultFetcher.updateAvailable(latestRelease, updateList.get(0))); + } else { + resultFetcher.noUpdate(); + } + } + } catch (Exception e) { + Bukkit.getLogger().log(Level.WARNING, "Failed to fetch Version List", e); } - } catch (Exception e) { - Bukkit.getLogger().log(Level.WARNING, "Failed to fetch Version List", e); } - } - }.runTaskAsynchronously(CustomHeads.getInstance()); + }); } public void getLatestUpdate(Consumer consumer) { @@ -103,39 +105,40 @@ public class SpigetResourceFetcher { } public void getVersions(Consumer> consumer) { - new BukkitRunnable() { - public void run() { - try { - Configs updateFile = CustomHeads.getUpdateFile(); - long lastFetch = updateFile.get().getLong("lastUpdateCheck"); - JsonArray descriptionArray; - boolean fromCache = false; - if (updateFile.get().isSet("lastDescriptionFetch") && TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis() - lastFetch) == 0) { - descriptionArray = jsonParser.parse(new String(Base64.getDecoder().decode(updateFile.get().getString("lastDescriptionFetch")))).getAsJsonArray(); - fromCache = true; - } else { - HttpURLConnection descriptionConnection = (HttpURLConnection) new URL(descriptionUrlFormatted).openConnection(); - descriptionConnection.addRequestProperty("User-Agent", userAgent); - descriptionConnection.setReadTimeout(5000); - descriptionArray = jsonParser.parse(new InputStreamReader(descriptionConnection.getInputStream())).getAsJsonArray(); - } + Utils.runAsync( + new BukkitRunnable() { + public void run() { + try { + Configs updateFile = CustomHeads.getUpdateFile(); + long lastFetch = updateFile.get().getLong("lastUpdateCheck"); + JsonArray descriptionArray; + boolean fromCache = false; + if (updateFile.get().isSet("lastDescriptionFetch") && TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis() - lastFetch) == 0) { + descriptionArray = jsonParser.parse(new String(Base64.getDecoder().decode(updateFile.get().getString("lastDescriptionFetch")))).getAsJsonArray(); + fromCache = true; + } else { + HttpURLConnection descriptionConnection = (HttpURLConnection) new URL(descriptionUrlFormatted).openConnection(); + descriptionConnection.addRequestProperty("User-Agent", userAgent); + descriptionConnection.setReadTimeout(5000); + descriptionArray = jsonParser.parse(new InputStreamReader(descriptionConnection.getInputStream())).getAsJsonArray(); + } - List updateList = new ArrayList<>(); - for (JsonElement updateRaw : descriptionArray) { - updateList.add(GSON.fromJson(updateRaw, ResourceUpdate.class)); + List updateList = new ArrayList<>(); + for (JsonElement updateRaw : descriptionArray) { + updateList.add(GSON.fromJson(updateRaw, ResourceUpdate.class)); + } + if (!fromCache) { + updateFile.get().set("lastDescriptionFetch", new String(Base64.getEncoder().encode(GSON.toJson(updateList).getBytes()))); + updateFile.save(); + } + consumer.accept(updateList); + return; + } catch (Exception e) { + Bukkit.getLogger().log(Level.WARNING, "Failed to fetch Update List", e); } - if (!fromCache) { - updateFile.get().set("lastDescriptionFetch", new String(Base64.getEncoder().encode(GSON.toJson(updateList).getBytes()))); - updateFile.save(); - } - consumer.accept(updateList); - return; - } catch (Exception e) { - Bukkit.getLogger().log(Level.WARNING, "Failed to fetch Update List", e); + consumer.accept(null); } - consumer.accept(null); - } - }.runTaskAsynchronously(CustomHeads.getInstance()); + }); } public interface FetchResult { diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 2d3385a..be461a4 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -64,6 +64,8 @@ economy: heads: buyable: false permanentBuy: true + get-command: + price-per-head: 0 update-notifications: onJoin: true console: true