Dev Build

This commit is contained in:
LikeWhat 2020-11-19 01:42:03 +01:00
parent 03a9983a9e
commit 61fd882dc7
23 changed files with 516 additions and 255 deletions

View File

@ -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<String, String> 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<String> 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<String> 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,10 +357,12 @@ 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");
// 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")) {
@ -370,16 +373,20 @@ public class CustomHeads extends JavaPlugin {
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)");
}
// 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,14 +396,13 @@ public class CustomHeads extends JavaPlugin {
ScrollableInventory.clearCache();
PlayerWrapper.clearCache();
}
}.runTaskTimer(instance, 6000, 6000);
}.runTaskTimer(instance, 36000, 36000);
// Animation Timer
Utils.runAsyncTimer(
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())) {
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;
@ -421,16 +427,14 @@ public class CustomHeads extends JavaPlugin {
contentItem = nextIcon;
}
}
if(tagEditor.hasMyTags(contentItem)) {
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;
}

View File

@ -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);
}

View File

@ -122,6 +122,4 @@ public interface CustomHeadsPlayer {
SearchHistory getSearchHistory();
GetHistory getGetHistory();
// Im no professional Description Writer so shhhhhhhhhhhhh...
}

View File

@ -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<CustomHead> getHeads();
public String getPlainName() {
return ChatColor.stripColor(name);
}

View File

@ -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<SubCategory> 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<CustomHead> heads) {
Category setHeads(List<CustomHead> heads) {
this.heads = heads;
return this;
}
@ -83,7 +81,7 @@ public class Category extends BaseCategory {
return !heads.isEmpty();
}
public Category setSubCategories(List<SubCategory> subCategories) {
Category setSubCategories(List<SubCategory> subCategories) {
this.subCategories = subCategories;
return this;
}
@ -96,7 +94,7 @@ public class Category extends BaseCategory {
return subCategories != null && !subCategories.isEmpty();
}
public Category setIcons(List<ItemStack> icons) {
Category setIcons(List<ItemStack> icons) {
this.icons = icons;
iterator = icons.iterator();
return this;

View File

@ -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");
}

View File

@ -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<Boolean> 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);
}
}
}

View File

@ -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<Player, String> lastMenu = new HashMap<>();
private static HashMap<UUID, String> lastActiveMenu = new HashMap<>();
//private static HashMap<Player, String> 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<ItemStack> 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);
}
}

View File

@ -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<Player, Location> CACHED_LOCATIONS = new HashMap<>();
// public static final HashMap<Player, Location> CACHED_LOCATIONS = new HashMap<>();
public static final HashMap<UUID, CategorySetup> 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();

View File

@ -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);
}
}

View File

@ -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();
}

View File

@ -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();
}

View File

@ -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;

View File

@ -54,7 +54,6 @@ public class InteractiveDialog {
destroy();
}
}
};
Bukkit.getPluginManager().registerEvents(listener, CustomHeads.getInstance());
}

View File

@ -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,6 +107,8 @@ public class ScrollableInventory {
refreshContent();
Utils.runAsync(new BukkitRunnable() {
public void run() {
List<ItemStack> sublist = getContentFromPage(currentPage, true);
for (int i = 0; i < sublist.size(); i++) {
inventory.setItem(i, sublist.get(i));
@ -119,9 +122,11 @@ public class ScrollableInventory {
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));

View File

@ -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,16 +384,25 @@ public class Utils {
}
}
openPreloader(player);
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.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");
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) {
if (itemStack == null) return false;
@ -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;
}
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);
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;

View File

@ -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<Player> active_fireworks = new ArrayList<>();
public static final List<Location> 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;
public void onStart() {
CustomHeads.getApi().setSkull(location.getBlock(), "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOGEzZDVkNWIyY2YzMzEyOTllNjNkNzYxOGExNDI2NmU4Y2NjNjE1OGU5ZTMxZmNiMGJkOTExZTEyZmY3NzM2In19fQ==", faces[ran.nextInt(faces.length)]);
}
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 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<CustomHead> 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<Boolean>() {
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")) {

View File

@ -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);
}

View File

@ -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 {

View File

@ -12,11 +12,11 @@ import lombok.Getter;
@Getter
public class CachedResponse<T> {
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;
}
}

View File

@ -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() {

View File

@ -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,6 +52,7 @@ public class SpigetResourceFetcher {
}
public void fetchUpdates(FetchResult resultFetcher) {
Utils.runAsync(
new BukkitRunnable() {
public void run() {
try {
@ -95,7 +97,7 @@ public class SpigetResourceFetcher {
Bukkit.getLogger().log(Level.WARNING, "Failed to fetch Version List", e);
}
}
}.runTaskAsynchronously(CustomHeads.getInstance());
});
}
public void getLatestUpdate(Consumer<ResourceUpdate> consumer) {
@ -103,6 +105,7 @@ public class SpigetResourceFetcher {
}
public void getVersions(Consumer<List<ResourceUpdate>> consumer) {
Utils.runAsync(
new BukkitRunnable() {
public void run() {
try {
@ -135,7 +138,7 @@ public class SpigetResourceFetcher {
}
consumer.accept(null);
}
}.runTaskAsynchronously(CustomHeads.getInstance());
});
}
public interface FetchResult {

View File

@ -64,6 +64,8 @@ economy:
heads:
buyable: false
permanentBuy: true
get-command:
price-per-head: 0
update-notifications:
onJoin: true
console: true