diff --git a/Core.iml b/Core.iml index 07cf8c4..9e1f47a 100644 --- a/Core.iml +++ b/Core.iml @@ -12,36 +12,23 @@ - - - - - - - - + + - - + + + + + + - - - - - - - - - - - - + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 9c1b146..3baded1 100644 --- a/pom.xml +++ b/pom.xml @@ -12,6 +12,7 @@ Univento.eu Core System http://univento.eu + @@ -54,56 +55,47 @@ spigot-repo https://hub.spigotmc.org/nexus/content/repositories/snapshots/ - - inventive-repo - https://repo.inventivetalent.org/content/groups/public/ - - - org.mongodb - mongo-java-driver - LATEST - - - org.mongodb - mongodb-driver-async - LATEST - - - io.netty - netty-all - LATEST - - - org.projectlombok - lombok - LATEST - org.bukkit craftbukkit - 1.9.2-R0.1-SNAPSHOT + 1.10-R0.1-SNAPSHOT provided org.bukkit bukkit - 1.9.2-R0.1-SNAPSHOT + 1.10-R0.1-SNAPSHOT provided + + org.mongodb + mongo-java-driver + 3.2.2 + + + org.mongodb + mongodb-driver-async + 3.2.2 + + + io.netty + netty-all + 4.0.36.Final + org.spigotmc spigot-api - 1.9.2-R0.1-SNAPSHOT + 1.10-R0.1-SNAPSHOT provided - org.inventivetalent.npclib - api - RELEASE + com.google.code.gson + gson + 2.3.1 - + \ No newline at end of file diff --git a/src/main/java/eu/univento/core/Core.java b/src/main/java/eu/univento/core/Core.java index bd71458..32edc74 100644 --- a/src/main/java/eu/univento/core/Core.java +++ b/src/main/java/eu/univento/core/Core.java @@ -7,6 +7,7 @@ import eu.univento.core.api.database.MongoDB; import eu.univento.core.api.database.MySQL; import eu.univento.core.api.events.MoveEventFilter; import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.server.NetworkData; import eu.univento.core.api.server.ServerSettings; import eu.univento.core.commands.*; import eu.univento.core.listeners.*; @@ -111,34 +112,103 @@ public class Core extends JavaPlugin{ new GameMode(this, "gamemode" , "gamemode", "gm"); new SetRank(this, "setrank" , "setrank", "sr"); new GlobalMute(this, "globalmute", "globalmute"); - new TS(this, "ts", "ts"); - new Ban(this, "ban", "ban"); new ChatClear(this, "chatclear", "chatclear", "cc"); log(Level.INFO, "registered all commands"); PluginMessenger pluginMessenger = new PluginMessenger(); + NetworkData networkData = new NetworkData(); + Bukkit.getMessenger().registerOutgoingPluginChannel(this, "5zig_Set"); + Bukkit.getMessenger().registerIncomingPluginChannel(this, "5zig_Set", pluginMessenger); Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); + Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", networkData); Bukkit.getMessenger().registerOutgoingPluginChannel(this, "LABYMOD"); Bukkit.getMessenger().registerIncomingPluginChannel(this, "WDL|INIT", pluginMessenger); Bukkit.getMessenger().registerOutgoingPluginChannel(this, "WDL|CONTROL"); + Bukkit.getMessenger().registerIncomingPluginChannel(this, "WDL|REQUEST", pluginMessenger); Bukkit.getMessenger().registerIncomingPluginChannel(this, "PERMISSIONSREPL", pluginMessenger); + Bukkit.getMessenger().registerOutgoingPluginChannel(this, "schematica"); Blackscreen.setupUtil(getInstance()); mongoDB = new MongoDB(Config.readString("MongoDB.Host"), Config.readInt("MongoDB.Port"), Config.readString("MongoDB.User"), Config.readString("MongoDB.Password"), Config.readString("MongoDB.Database")); - log(Level.INFO, "Plugin ver. " + getDescription().getVersion() + " started"); + log(Level.INFO, "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " _ _ _ \n" + + " | | | | (_) \n" + + " ___ ___ _ ____ _____ _ __ ___| |_ __ _ _ __| |_ _ _ __ __ _ \n" + + "/ __|/ _ \\ '__\\ \\ / / _ \\ '__| / __| __/ _` | '__| __| | '_ \\ / _` |\n" + + "\\__ \\ __/ | \\ V / __/ | \\__ \\ || (_| | | | |_| | | | | (_| |\n" + + "|___/\\___|_| \\_/ \\___|_| |___/\\__\\__,_|_| \\__|_|_| |_|\\__, |\n" + + " __/ |\n" + + " |___/ \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"); + Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> log(Level.INFO, "\n" + + "\n" + + "\n" + + " _ _ \n" + + " | (_) \n" + + " ___ ___ _ ____ _____ _ __ ___ _ __ | |_ _ __ ___ \n" + + "/ __|/ _ \\ '__\\ \\ / / _ \\ '__| / _ \\| '_ \\| | | '_ \\ / _ \\\n" + + "\\__ \\ __/ | \\ V / __/ | | (_) | | | | | | | | | __/\n" + + "|___/\\___|_| \\_/ \\___|_| \\___/|_| |_|_|_|_| |_|\\___|\n" + + " \n" + + " \n" + + "\n"), 0L); } @Override public void onDisable() { mongoDB.getClient().close(); Bukkit.getMessenger().unregisterOutgoingPluginChannel(this, "BungeeCord"); + Bukkit.getMessenger().unregisterIncomingPluginChannel(this, "BungeeCord"); Bukkit.getMessenger().unregisterOutgoingPluginChannel(this, "LABYMOD"); Bukkit.getMessenger().unregisterIncomingPluginChannel(this, "WDL_INIT"); Bukkit.getMessenger().unregisterOutgoingPluginChannel(this, "WDL|CONTROL"); - log(Level.INFO, "Plugin stoped"); + log(Level.INFO, "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " _ _ _ \n" + + " | | | | | | \n" + + " ___ ___ _ ____ _____ _ __ ___| |__ _ _| |_ __| | _____ ___ __ \n" + + "/ __|/ _ \\ '__\\ \\ / / _ \\ '__| / __| '_ \\| | | | __/ _` |/ _ \\ \\ /\\ / / '_ \\ \n" + + "\\__ \\ __/ | \\ V / __/ | \\__ \\ | | | |_| | || (_| | (_) \\ V V /| | | |\n" + + "|___/\\___|_| \\_/ \\___|_| |___/_| |_|\\__,_|\\__\\__,_|\\___/ \\_/\\_/ |_| |_|\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\nd"); } } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/antihack/utils/PacketReader.java b/src/main/java/eu/univento/core/antihack/utils/PacketReader.java index aab388f..2ab1044 100644 --- a/src/main/java/eu/univento/core/antihack/utils/PacketReader.java +++ b/src/main/java/eu/univento/core/antihack/utils/PacketReader.java @@ -4,8 +4,8 @@ import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageDecoder; -import net.minecraft.server.v1_9_R1.Packet; -import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer; +import net.minecraft.server.v1_10_R1.Packet; +import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer; import org.bukkit.entity.Player; import java.util.List; diff --git a/src/main/java/eu/univento/core/api/Actionbar.java b/src/main/java/eu/univento/core/api/Actionbar.java index 3f71ce6..3bf28ea 100644 --- a/src/main/java/eu/univento/core/api/Actionbar.java +++ b/src/main/java/eu/univento/core/api/Actionbar.java @@ -1,9 +1,9 @@ package eu.univento.core.api; -import net.minecraft.server.v1_9_R1.IChatBaseComponent; -import net.minecraft.server.v1_9_R1.IChatBaseComponent.ChatSerializer; -import net.minecraft.server.v1_9_R1.PacketPlayOutChat; -import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer; +import net.minecraft.server.v1_10_R1.IChatBaseComponent; +import net.minecraft.server.v1_10_R1.IChatBaseComponent.ChatSerializer; +import net.minecraft.server.v1_10_R1.PacketPlayOutChat; +import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer; import org.bukkit.entity.Player; public class Actionbar { diff --git a/src/main/java/eu/univento/core/api/AutoCommand.java b/src/main/java/eu/univento/core/api/AutoCommand.java index 6ce34b9..c36f742 100644 --- a/src/main/java/eu/univento/core/api/AutoCommand.java +++ b/src/main/java/eu/univento/core/api/AutoCommand.java @@ -9,12 +9,13 @@ import org.bukkit.plugin.java.JavaPlugin; import java.lang.reflect.Field; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.logging.Level; /** * @author PostCrafter - * @see href http://postcrafter.de/viewtopic.php?f=15&t=143 + * @see //http://postcrafter.de/viewtopic.php?f=15&t=143 * @param

main class */ public abstract class AutoCommand

extends Command { @@ -37,9 +38,7 @@ public abstract class AutoCommand

extends Command { super.setDescription(description); List aliasList = new ArrayList<>(); - for (String alias : aliases) { - aliasList.add(alias); - } + Collections.addAll(aliasList, aliases); super.setAliases(aliasList); this.register(); } diff --git a/src/main/java/eu/univento/core/api/Hologram.java b/src/main/java/eu/univento/core/api/Hologram.java index 5fcf3bc..306471e 100644 --- a/src/main/java/eu/univento/core/api/Hologram.java +++ b/src/main/java/eu/univento/core/api/Hologram.java @@ -1,14 +1,11 @@ package eu.univento.core.api; import eu.univento.core.Core; -import net.minecraft.server.v1_9_R1.EntityArmorStand; -import net.minecraft.server.v1_9_R1.PacketPlayOutEntityDestroy; -import net.minecraft.server.v1_9_R1.PacketPlayOutSpawnEntityLiving; +import eu.univento.core.api.player.CustomPlayer; +import net.minecraft.server.v1_10_R1.*; import org.bukkit.Bukkit; import org.bukkit.Location; -import org.bukkit.craftbukkit.v1_9_R1.CraftWorld; -import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer; -import org.bukkit.entity.Player; +import org.bukkit.craftbukkit.v1_10_R1.CraftWorld; import java.util.ArrayList; import java.util.List; @@ -16,69 +13,69 @@ import java.util.List; public class Hologram { private List entitylist = new ArrayList<>(); - private String[] Text; + private String[] text; private Location location; - double DISTANCE = 0.25D; - int count; + private double DISTANCE = 0.25D; + private int count; - public Hologram(String[] Text, Location location) { - this.Text = Text; + public Hologram(String[] text, Location location) { + this.text = text; this.location = location; create(); } - public void showPlayerTemp(final Player p,int Time){ + public void showPlayerTemp(final CustomPlayer p, int Time){ showPlayer(p); Bukkit.getScheduler().runTaskLater(Core.getInstance(), () -> hidePlayer(p), Time); } - public void showAllTemp(final Player p,int Time){ + public void showAllTemp(int Time){ showAll(); - Bukkit.getScheduler().runTaskLater(Core.getInstance(), () -> hideAll(), Time); + Bukkit.getScheduler().runTaskLater(Core.getInstance(), this::hideAll, Time); } - public void showPlayer(Player p) { + public void showPlayer(CustomPlayer p) { for (EntityArmorStand armor : entitylist) { PacketPlayOutSpawnEntityLiving packet = new PacketPlayOutSpawnEntityLiving(armor); - ((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet); + p.sendPacket(packet); } } - public void hidePlayer(Player p) { + public void hidePlayer(CustomPlayer p) { for (EntityArmorStand armor : entitylist) { PacketPlayOutEntityDestroy packet = new PacketPlayOutEntityDestroy(armor.getId()); - ((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet); + p.sendPacket(packet); } } public void showAll() { - for (Player player : Bukkit.getOnlinePlayers()) { + for (CustomPlayer player : Core.getOnlinePlayers()) { for (EntityArmorStand armor : entitylist) { PacketPlayOutSpawnEntityLiving packet = new PacketPlayOutSpawnEntityLiving(armor); - ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); + player.sendPacket(packet); } } } public void hideAll() { - for (Player player : Bukkit.getOnlinePlayers()) { + for (CustomPlayer player : Core.getOnlinePlayers()) { for (EntityArmorStand armor : entitylist) { PacketPlayOutEntityDestroy packet = new PacketPlayOutEntityDestroy(armor.getId()); - ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); + player.sendPacket(packet); } } } private void create() { - for (String Text : this.Text) { + for (String text : this.text) { EntityArmorStand entity = new EntityArmorStand(((CraftWorld) this.location.getWorld()).getHandle(),this.location.getX(), this.location.getY(),this.location.getZ()); - entity.setCustomName(Text); + entity.setCustomName(text); entity.setCustomNameVisible(true); entity.setInvisible(true); - entity.setGravity(false); + entity.setNoGravity(true); entitylist.add(entity); this.location.subtract(0, this.DISTANCE, 0); count++; diff --git a/src/main/java/eu/univento/core/api/Title.java b/src/main/java/eu/univento/core/api/Title.java index 81f9db1..a56f295 100644 --- a/src/main/java/eu/univento/core/api/Title.java +++ b/src/main/java/eu/univento/core/api/Title.java @@ -1,11 +1,11 @@ package eu.univento.core.api; -import net.minecraft.server.v1_9_R1.IChatBaseComponent; -import net.minecraft.server.v1_9_R1.PacketPlayOutPlayerListHeaderFooter; -import net.minecraft.server.v1_9_R1.PacketPlayOutTitle; -import net.minecraft.server.v1_9_R1.PlayerConnection; +import net.minecraft.server.v1_10_R1.IChatBaseComponent; +import net.minecraft.server.v1_10_R1.PacketPlayOutPlayerListHeaderFooter; +import net.minecraft.server.v1_10_R1.PacketPlayOutTitle; +import net.minecraft.server.v1_10_R1.PlayerConnection; import org.bukkit.ChatColor; -import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer; +import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer; import org.bukkit.entity.Player; import java.lang.reflect.Field; diff --git a/src/main/java/eu/univento/core/api/blocks/MiniBlock.java b/src/main/java/eu/univento/core/api/blocks/MiniBlock.java new file mode 100644 index 0000000..8356d72 --- /dev/null +++ b/src/main/java/eu/univento/core/api/blocks/MiniBlock.java @@ -0,0 +1,223 @@ +package eu.univento.core.api.blocks; + +import org.bukkit.*; +import org.bukkit.entity.*; +import org.bukkit.inventory.*; +import org.bukkit.util.*; + +/** + * MiniBlock + * @version 1.3.5 + * @author _Ug + */ + +public class MiniBlock { + + + private Location location; + + private ItemStack item; + + private int size; + + private ArmorStand stand; + + private boolean isRemoved; + + /** + * Create a MiniBlock + * + * @param location Location to spawn MiniBlock at + * @param item Item for the MiniBlock + * @param size Size of MiniBlock (1-3 for blocks, 1-2 for items) + */ + public MiniBlock(Location location, ItemStack item, int size) { + + this.location = location; + + this.item = item; + + if (!isSizeValid(item, size)) size = 2; + + this.size = size; + + this.isRemoved = false; + + spawnMiniBlock(location, item, size); + + } + + /** + * Teleport MiniBlock + * + * @param location Location to teleport to + */ + public void teleport(Location location) { + + this.location = location; + + if (!this.isRemoved) { + + stand.remove(); + + spawnMiniBlock(this.location, this.item, this.size); + + } + + } + + /** + * Set MiniBlock item + * + * @param item Item to insert to MiniBlock + */ + public void setItem(ItemStack item) { + + this.item = item; + + stand.setItemInHand(item); + + } + + /** + * Set MiniBlock size + * + * @param size Size of MiniBlock (1-3 for blocks, 1-2 for items) + */ + public void setSize(int size) { + + this.size = size; + + if (!this.isRemoved) { + + stand.remove(); + + spawnMiniBlock(this.location, this.item, this.size); + + } + + } + + /** + * Remove MiniBlock + */ + public void remove() { + + if (!this.isRemoved) { + + stand.remove(); + + this.isRemoved = true; + + } + + } + + /* + * Getters + */ + + /** + * Get MiniBlock location + * + * @return MiniBlock location + */ + public Location getLocation() { + return this.location; + } + + /** + * Get MiniBlock item + * + * @return MiniBlock item + */ + public ItemStack getItem() { + return this.item; + } + + /** + * Get MiniBlock size + * + * @return MiniBlock size + */ + public int getSize() { + return this.size; + } + + /** + * Get removed status + * + * @return true if MiniBlock is removed + */ + public boolean isRemoved() { + return this.isRemoved; + } + + /* + * Private + */ + + private void spawnMiniBlock(Location location, ItemStack item, int size) { + + if (!isSizeValid(item, size)) return; + + boolean isBlock = item.getType().isBlock(); + + EulerAngle angle = new EulerAngle(0, 0, 0); + + boolean small = false; + + if (isBlock) { + if (size == 1) { + location.add(.2, -.445, 0); + location.setPitch(45); + angle = new EulerAngle(-.6, 0, 0); + small = true; + } else if (size == 2) { + location.add(.6, -.65, 0); + location.setPitch(45); + angle = new EulerAngle(-.25, 0, 0); + } else if (size == 3) { + location.add(0, -.7, 0); + } + } else { + if (size == 1) { + location.add(.2, -.5, -.1); + angle = new EulerAngle(-.35, 0, 0); + small = true; + } else if (size == 2) { + location.add(.7, -.8, -.1); + angle = new EulerAngle(0, 1, 0); + } + } + + ArmorStand stand = (ArmorStand) location.getWorld().spawnEntity(location, EntityType.ARMOR_STAND); + + fixup(stand); + + stand.setSmall(small); + + stand.setRightArmPose(angle); + + stand.setItemInHand(item); + + this.stand = stand; + + } + + private boolean isSizeValid(ItemStack item, int size) { + if (item.getType().isBlock()) { + return size == 1 || size == 2 || size == 3; + } else { + return size == 1 || size == 2; + } + } + + private void fixup(ArmorStand stand) { + stand.setVisible(false); + stand.setArms(true); + stand.setGravity(false); + stand.setCanPickupItems(false); + } + +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/database/MongoDB.java b/src/main/java/eu/univento/core/api/database/MongoDB.java index 3077702..6191278 100644 --- a/src/main/java/eu/univento/core/api/database/MongoDB.java +++ b/src/main/java/eu/univento/core/api/database/MongoDB.java @@ -13,17 +13,17 @@ public class MongoDB { private MongoClient client; private MongoDatabase database; + public MongoDB(String host, int port, String username, String password, String database) { + MongoCredential credential = MongoCredential.createCredential(username, database, password.toCharArray()); + client = new MongoClient(new ServerAddress(host, port), Collections.singletonList(credential)); + } + public MongoClient getClient() { if(client == null) new MongoDB(Config.readString("MongoDB.Host"), Config.readInt("MongoDB.Port"), Config.readString("MongoDB.User"), Config.readString("MongoDB.Password"), Config.readString("MongoDB.Database")); return client; } - public MongoDB(String host, int port, String username, String password, String database) { - MongoCredential credential = MongoCredential.createCredential(username, database, password.toCharArray()); - client = new MongoClient(new ServerAddress(host, port), Collections.singletonList(credential)); - } - public MongoDatabase getDatabase() { if(database == null) database = getClient().getDatabase(Config.readString("MongoDB.Database")); diff --git a/src/main/java/eu/univento/core/api/effects/Effects.java b/src/main/java/eu/univento/core/api/effects/Effects.java index d5fb373..1d7605c 100644 --- a/src/main/java/eu/univento/core/api/effects/Effects.java +++ b/src/main/java/eu/univento/core/api/effects/Effects.java @@ -1,10 +1,11 @@ package eu.univento.core.api.effects; +import eu.univento.core.api.player.CustomPlayer; import eu.univento.core.api.player.PlayerSettings; -import net.minecraft.server.v1_9_R1.EnumParticle; -import net.minecraft.server.v1_9_R1.PacketPlayOutWorldParticles; +import net.minecraft.server.v1_10_R1.EnumParticle; +import net.minecraft.server.v1_10_R1.PacketPlayOutWorldParticles; import org.bukkit.Location; -import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer; +import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer; import org.bukkit.entity.Player; /** @@ -23,8 +24,8 @@ public class Effects { */ public static void playEffect(Location loc, EnumParticle ep, float f, int count) { PacketPlayOutWorldParticles packet = new PacketPlayOutWorldParticles(ep, true, (float) loc.getX(), (float) loc.getY(), (float) loc.getZ(), f, f, f, 0.0F, count, 0, 0); - for(Player p : PlayerSettings.getAllPlayersWithEffectsEnabled()) { - ((CraftPlayer)p).getHandle().playerConnection.sendPacket(packet); + for(CustomPlayer p : PlayerSettings.getAllPlayersWithEffectsEnabled()) { + p.getHandle().playerConnection.sendPacket(packet); } } diff --git a/src/main/java/eu/univento/core/api/entity/EntityModifier.java b/src/main/java/eu/univento/core/api/entity/EntityModifier.java index a2beed0..07b6c41 100644 --- a/src/main/java/eu/univento/core/api/entity/EntityModifier.java +++ b/src/main/java/eu/univento/core/api/entity/EntityModifier.java @@ -1,12 +1,12 @@ package eu.univento.core.api.entity; -import net.minecraft.server.v1_9_R1.EntityLiving; -import net.minecraft.server.v1_9_R1.NBTTagCompound; +import net.minecraft.server.v1_10_R1.EntityLiving; +import net.minecraft.server.v1_10_R1.NBTTagCompound; import org.bukkit.Bukkit; import org.bukkit.EntityEffect; import org.bukkit.Location; -import org.bukkit.craftbukkit.v1_9_R1.entity.CraftCreature; -import org.bukkit.craftbukkit.v1_9_R1.entity.CraftEntity; +import org.bukkit.craftbukkit.v1_10_R1.entity.CraftCreature; +import org.bukkit.craftbukkit.v1_10_R1.entity.CraftEntity; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; @@ -19,7 +19,7 @@ import java.lang.reflect.Field; public class EntityModifier { static org.bukkit.entity.Entity entity; static CraftEntity craftentity; - static net.minecraft.server.v1_9_R1.Entity entityS; + static net.minecraft.server.v1_10_R1.Entity entityS; static int scheduler; static Plugin plugin; static Player player = null; @@ -103,7 +103,7 @@ public class EntityModifier { public Builder setInvulnerable(boolean invulnerable) { try { - Field invulnerableField = net.minecraft.server.v1_9_R1.Entity.class + Field invulnerableField = net.minecraft.server.v1_10_R1.Entity.class .getDeclaredField("invulnerable"); invulnerableField.setAccessible(true); invulnerableField.setBoolean(EntityModifier.entityS, invulnerable); diff --git a/src/main/java/eu/univento/core/api/fakeplayer/FakePlayer.java b/src/main/java/eu/univento/core/api/fakeplayer/FakePlayer.java index cc839bb..60f0964 100644 --- a/src/main/java/eu/univento/core/api/fakeplayer/FakePlayer.java +++ b/src/main/java/eu/univento/core/api/fakeplayer/FakePlayer.java @@ -2,9 +2,9 @@ package eu.univento.core.api.fakeplayer; import com.mojang.authlib.GameProfile; import eu.univento.core.Core; -import net.minecraft.server.v1_9_R1.*; +import net.minecraft.server.v1_10_R1.*; import org.bukkit.Location; -import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer; +import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; @@ -13,8 +13,6 @@ import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; import java.lang.reflect.Field; -import java.util.Arrays; -import java.util.Collections; /** * @author joethei @@ -159,8 +157,9 @@ public class FakePlayer { set(playerSpawn, "h", 0); set(playerSpawn, "i", this.dataWatcher); + //XXX: cannot acess PlayerInfoData PacketPlayOutPlayerInfo playerInfo = new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER); - set(playerInfo, "b", Collections.singletonList(playerInfo.new PlayerInfoData(this.gameProfile, 0, WorldSettings.EnumGamemode.NOT_SET, new ChatComponentText(this.gameProfile.getName())))); + //set(playerInfo, "b", Collections.singletonList(playerInfo.new PlayerInfoData(this.gameProfile, 0, WorldSettings.EnumGamemode.NOT_SET, new ChatComponentText(this.gameProfile.getName())))); sendPackets(playerInfo, playerSpawn); this.location = location; @@ -170,10 +169,10 @@ public class FakePlayer { this.task = tickTask.runTaskTimer(Core.getInstance(), 0L, 1L); } - + //XXX: cannot acess PlayerInfoData public void despawn() { PacketPlayOutPlayerInfo playerInfo = new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER); - set(playerInfo, "b", Collections.singletonList(playerInfo.new PlayerInfoData(this.gameProfile, 0, null, null))); + //set(playerInfo, "b", Collections.singletonList(playerInfo.new PlayerInfoData(this.gameProfile, 0, null, null))); sendPackets(new PacketPlayOutEntityDestroy(this.entityId), playerInfo); this.armorStand.remove(); @@ -181,9 +180,10 @@ public class FakePlayer { this.task.cancel(); } + //XXX: cannot acess PlayerInfoData public void removeTablist() { PacketPlayOutPlayerInfo playerInfo = new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER); - set(playerInfo, "b", Arrays.asList(playerInfo.new PlayerInfoData(this.gameProfile, 0, null, null))); + //set(playerInfo, "b", Arrays.asList(playerInfo.new PlayerInfoData(this.gameProfile, 0, null, null))); sendPackets(new PacketPlayOutEntityDestroy(this.entityId), playerInfo); } @@ -224,10 +224,6 @@ public class FakePlayer { } } - private Object get(Object instance, String name) { - return get(instance.getClass(), instance, name); - } - private Object get(Class clazz, Object instance, String name) { try{ Field field = clazz.getDeclaredField(name); diff --git a/src/main/java/eu/univento/core/api/gui/AnvilGUI.java b/src/main/java/eu/univento/core/api/gui/AnvilGUI.java index ad824a0..08741b5 100644 --- a/src/main/java/eu/univento/core/api/gui/AnvilGUI.java +++ b/src/main/java/eu/univento/core/api/gui/AnvilGUI.java @@ -1,9 +1,9 @@ package eu.univento.core.api.gui; import eu.univento.core.Core; -import net.minecraft.server.v1_9_R1.*; +import net.minecraft.server.v1_10_R1.*; import org.bukkit.Bukkit; -import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer; +import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; diff --git a/src/main/java/eu/univento/core/api/gui/SignInput.java b/src/main/java/eu/univento/core/api/gui/SignInput.java index 9bf1d4b..71c938b 100644 --- a/src/main/java/eu/univento/core/api/gui/SignInput.java +++ b/src/main/java/eu/univento/core/api/gui/SignInput.java @@ -1,9 +1,9 @@ package eu.univento.core.api.gui; import eu.univento.core.api.player.CustomPlayer; -import net.minecraft.server.v1_9_R1.BlockPosition; -import net.minecraft.server.v1_9_R1.EntityPlayer; -import net.minecraft.server.v1_9_R1.PacketPlayOutOpenSignEditor; +import net.minecraft.server.v1_10_R1.BlockPosition; +import net.minecraft.server.v1_10_R1.EntityPlayer; +import net.minecraft.server.v1_10_R1.PacketPlayOutOpenSignEditor; /** * @author joethei diff --git a/src/main/java/eu/univento/core/api/gui/SignInputHandler.java b/src/main/java/eu/univento/core/api/gui/SignInputHandler.java index dd2b700..9e9fc7f 100644 --- a/src/main/java/eu/univento/core/api/gui/SignInputHandler.java +++ b/src/main/java/eu/univento/core/api/gui/SignInputHandler.java @@ -3,11 +3,11 @@ package eu.univento.core.api.gui; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageDecoder; -import net.minecraft.server.v1_9_R1.NetworkManager; -import net.minecraft.server.v1_9_R1.Packet; -import net.minecraft.server.v1_9_R1.PacketPlayInUpdateSign; +import net.minecraft.server.v1_10_R1.NetworkManager; +import net.minecraft.server.v1_10_R1.Packet; +import net.minecraft.server.v1_10_R1.PacketPlayInUpdateSign; import org.bukkit.Bukkit; -import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer; +import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer; import org.bukkit.entity.Player; import java.lang.reflect.Field; diff --git a/src/main/java/eu/univento/core/api/items/ScrollingInventory.java b/src/main/java/eu/univento/core/api/items/ScrollingInventory.java new file mode 100644 index 0000000..3a93320 --- /dev/null +++ b/src/main/java/eu/univento/core/api/items/ScrollingInventory.java @@ -0,0 +1,121 @@ +package eu.univento.core.api.items; + +import eu.univento.core.Core; +import eu.univento.core.api.player.CustomPlayer; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.PotionMeta; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.logging.Level; + +public class ScrollingInventory implements Listener{ + + private Inventory inv; + private ArrayList items = new ArrayList<>(); + private ItemStack next; + private ItemStack back; + private int side = 0; + private int rows = 4; + private CustomPlayer player; + public ScrollingInventory(CustomPlayer player, String name, int rows){ + this.player = player; + int var = 1; + for(int i = 0; i> rows * 9; i = i + 9) + var++; + inv = Bukkit.createInventory(player, var * 9 + 9, name); + Bukkit.getPluginManager().registerEvents(this, Core.getInstance()); + this.rows = rows; + side = 0; + } + public void addItem(ItemStack item){ + items.add(item); + } + public void removeItem(ItemStack item){ + items.remove(item); + } + private void clearItems(){ + for(ItemStack is : inv.getContents()){ + inv.remove(is); + } + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent e){ + if(e.getInventory().equals(inv)){ + if(inv.getViewers().size() == 0) + HandlerList.unregisterAll(this); + } + } + + @EventHandler + public void onInventoryClick(InventoryClickEvent e){ + if(e.getInventory().equals(inv)){ + e.setCancelled(true); + if(e.getCurrentItem() != null){ + if(e.getCurrentItem().equals(back)) { + setDisplaySide(side - 1); + } + else if(e.getCurrentItem().equals(next)) { + setDisplaySide(side + 1); + } + } + } + } + + private void setDisplaySide(int i) { + clearItems(); + if(items.size() - side * rows > (side + 1) * rows) + setNext(); + if(side > 0) + setBack(); + int from = side * rows; + int to = (side + 1) * rows; + int a = 0; + for(ItemStack is : items.subList(from, (to > items.size() ? items.size() : to))){ + inv.setItem(a, is); + a++; + } + } + private void setNext(){ + if(next == null){ + next = new ItemStack(Material.TIPPED_ARROW); + PotionMeta nextMeta = (PotionMeta) next.getItemMeta(); + nextMeta.addCustomEffect(new PotionEffect(PotionEffectType.LUCK, 5 * 20, 1), true); + nextMeta.setDisplayName("§aVor"); + next.setItemMeta(nextMeta); + } + inv.setItem(inv.getSize()-2, next); + } + private void setBack(){ + if(back == null){ + back = new ItemStack(Material.TIPPED_ARROW); + PotionMeta backMeta = (PotionMeta) back.getItemMeta(); + backMeta.addCustomEffect(new PotionEffect(PotionEffectType.HEAL, 5 * 20, 1), true); + backMeta.setDisplayName("§cZurück"); + back.setItemMeta(backMeta); + } + inv.setItem(inv.getSize()-8, next); + } + public void openInventory(){ + setDisplaySide(0); + player.openInventory(inv); + } + public void setNextItem(ItemStack item){ + next = item; + setNext(); + } + public void setBackItem(ItemStack item){ + back = item; + setBack(); + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/map/Cuboid.java b/src/main/java/eu/univento/core/api/map/Cuboid.java index f61c422..5cb454f 100644 --- a/src/main/java/eu/univento/core/api/map/Cuboid.java +++ b/src/main/java/eu/univento/core/api/map/Cuboid.java @@ -1,14 +1,13 @@ package eu.univento.core.api.map; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; +import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.entity.LivingEntity; import org.bukkit.util.Vector; import java.util.*; +import java.util.stream.Collectors; /** * @author desht (Original code), KingFaris10 (Editor of code) @@ -150,6 +149,10 @@ public class Cuboid implements Cloneable, ConfigurationSerializable, Iterable getEntities() { + return getWorld().getLivingEntities().stream().filter(entity -> containsLocation(entity.getLocation())).collect(Collectors.toCollection(ArrayList::new)); + } + @Override public Cuboid clone() { return new Cuboid(this); diff --git a/src/main/java/eu/univento/core/api/player/BanSystem.java b/src/main/java/eu/univento/core/api/player/BanSystem.java index bbde5e0..5b45284 100644 --- a/src/main/java/eu/univento/core/api/player/BanSystem.java +++ b/src/main/java/eu/univento/core/api/player/BanSystem.java @@ -2,7 +2,7 @@ package eu.univento.core.api.player; import eu.univento.core.Core; import eu.univento.core.api.database.MySQL; -import eu.univento.core.api.utils.NameFetcher; +import eu.univento.core.api.utils.UUIDFetcher; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -138,11 +138,7 @@ static String getWhoBanned(CustomPlayer p)throws SQLException, ClassNotFoundExce return null; } String whouuid = rs.getString("who"); - UUID who = UUID.fromString(whouuid); - List list = new ArrayList<>(); - list.add(who); - NameFetcher name = new NameFetcher(list); sql.closeConnection(); - return name.toString(); + return UUIDFetcher.getName(UUID.fromString(whouuid)); } } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/player/CustomPlayer.java b/src/main/java/eu/univento/core/api/player/CustomPlayer.java index e745670..1813834 100644 --- a/src/main/java/eu/univento/core/api/player/CustomPlayer.java +++ b/src/main/java/eu/univento/core/api/player/CustomPlayer.java @@ -1,5 +1,7 @@ package eu.univento.core.api.player; +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; import com.mongodb.BasicDBObject; import com.mongodb.CursorType; import com.mongodb.client.FindIterable; @@ -15,17 +17,22 @@ import eu.univento.core.api.languages.Messages; import eu.univento.core.api.server.Game; import eu.univento.core.api.server.ServerSettings; import eu.univento.core.api.server.Servers; +import eu.univento.core.api.utils.GameProfileBuilder; +import eu.univento.core.api.utils.UUIDFetcher; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; -import net.minecraft.server.v1_9_R1.*; +import net.minecraft.server.v1_10_R1.*; +import net.minecraft.server.v1_10_R1.World; import org.bson.Document; import org.bukkit.*; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.attribute.AttributeModifier; -import org.bukkit.craftbukkit.v1_9_R1.CraftServer; -import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer; +import org.bukkit.craftbukkit.v1_10_R1.CraftServer; +import org.bukkit.craftbukkit.v1_10_R1.CraftWorld; +import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer; import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.Team; @@ -34,6 +41,7 @@ import java.io.IOException; import java.io.ObjectOutputStream; import java.lang.reflect.Field; import java.util.*; +import java.util.logging.Level; public class CustomPlayer extends CraftPlayer { @@ -48,9 +56,9 @@ public class CustomPlayer extends CraftPlayer { private boolean openInventory; - private MongoCollection playerCollection; - private MongoCollection friendCollection; - private MongoCollection onlinePlayerCollection; + private MongoCollection playerCollection; + private MongoCollection friendCollection; + private MongoCollection onlinePlayerCollection; private CustomPlayer(Player player) { super((CraftServer) Bukkit.getServer(), ((CraftPlayer) player).getHandle()); @@ -60,6 +68,7 @@ public class CustomPlayer extends CraftPlayer { playerCollection = mongoDB.getDatabase().getCollection("players"); friendCollection = mongoDB.getDatabase().getCollection("friends"); onlinePlayerCollection = mongoDB.getDatabase().getCollection("online-players"); + } public void onLeave() { @@ -73,9 +82,7 @@ public class CustomPlayer extends CraftPlayer { location.put("Yaw", getLocation().getYaw()); location.put("Pitch", getLocation().getPitch()); - if(ServerSettings.isLobby()) setInDatabase("Pos", new BasicDBObject(location)); - - onlinePlayerCollection.deleteOne(new Document("uuid", getUniqueId().toString())); + if (ServerSettings.isLobby()) setInDatabase("Pos", new BasicDBObject(location)); if (PLAYERS.containsKey(getName().toLowerCase())) PLAYERS.remove(getName().toLowerCase()); } @@ -94,6 +101,10 @@ public class CustomPlayer extends CraftPlayer { return getPlayer(player.getName()); } + public static CustomPlayer getPlayer(UUID uuid) { + return getPlayer(UUIDFetcher.getName(uuid)); + } + public Player getPLAYER() { return PLAYER; @@ -101,37 +112,6 @@ public class CustomPlayer extends CraftPlayer { public void insertToDatabase() { Document doc = new Document("uuid", getUniqueId().toString()); - Date date = new Date(); - - doc.put("lastName", getName()); - doc.put("rank", "Player"); - doc.put("firstLogin", date); - doc.put("lastLogin", date); - doc.put("lastOnline", date); - doc.put("lastIP", getAddress().getHostName()); - doc.put("tsid", 0); - doc.put("timesJoined", 1); - doc.put("coins", 0); - doc.put("experience", 0); - doc.put("foundSecrets", new ArrayList()); - doc.put("foundEggs", new ArrayList()); - - HashMap settings = new HashMap<>(); - settings.put("playerVisibility", "all"); - settings.put("inventoryAnimation", true); - settings.put("teleportAnimation", true); - settings.put("partyRequests", true); - settings.put("friendRequests", true); - settings.put("friendJump", true); - settings.put("chatSounds", true); - settings.put("tsMove", false); - settings.put("scoreboard", true); - settings.put("effects", true); - settings.put("storyMode", true); - settings.put("nicked", false); - settings.put("language", "DE"); - - doc.put("Settings", new BasicDBObject(settings)); HashMap location = new HashMap<>(); location.put("X", getLocation().getX()); @@ -144,31 +124,18 @@ public class CustomPlayer extends CraftPlayer { playerCollection.insertOne(doc); } + @Override public boolean hasPlayedBefore() { - FindIterable cursor = playerCollection.find(new Document("uuid", getUniqueId().toString())); + FindIterable cursor = playerCollection.find(new Document("uuid", getUniqueId().toString())); cursor.cursorType(CursorType.NonTailable); - Object obj = cursor.first(); + Document obj = cursor.first(); if (obj == null) return false; return true; } - public void updateDatabaseEntry() { - setInDatabase("lastName", getName()); - setInDatabase("lastLogin", new Date()); - setInDatabase("lastIP", getAddress().getHostName()); - setInDatabase("timesJoined", getTimesJoined() + 1); - - Document doc = new Document("uuid", getUniqueId().toString()); - - doc.put("name", getName()); - doc.put("server", getServer().getServerName()); - - onlinePlayerCollection.insertOne(doc); - } - public void setRank(Ranks rank) { setInDatabase("rank", rank.toString()); } @@ -209,7 +176,7 @@ public class CustomPlayer extends CraftPlayer { setInDatabase("Settings", settings); } - private void setSetting(String name, Object setting) { + private void setSetting(String name, java.io.Serializable setting) { Map list = getSettings(); list.put(name, setting); setSettings(list); @@ -240,7 +207,7 @@ public class CustomPlayer extends CraftPlayer { } private int getTimesJoined() { - return getIntegerFromDatabase("timesJoined"); + return getIntegerFromDatabase("timesJoined"); } public int getCoins() { @@ -251,13 +218,17 @@ public class CustomPlayer extends CraftPlayer { return getIntegerFromDatabase("experience"); } - public int getSecrets() { return getFoundSecrets().size();} + public int getSecrets() { + return getFoundSecrets().size(); + } public ArrayList getFoundSecrets() { return getArrayListFromDatabase("foundSecrets"); } - public int getEggs() { return getFoundEggs().size();} + public int getEggs() { + return getFoundEggs().size(); + } private ArrayList getFoundEggs() { return getArrayListFromDatabase("foundEggs"); @@ -269,7 +240,7 @@ public class CustomPlayer extends CraftPlayer { public Location getLastLocation() { Map map = getMapFromDatabase("Pos"); - return new Location(Bukkit.getWorld("world"), (double)map.get("X"), (double)map.get("Y"), (double)map.get("Z"), (float)map.get("Yaw"), (float)map.get("Pitch")); + return new Location(Bukkit.getWorld("world"), (double) map.get("X"), (double) map.get("Y"), (double) map.get("Z"), (float) map.get("Yaw"), (float) map.get("Pitch")); } public String getPlayerVisibility() { @@ -368,9 +339,9 @@ public class CustomPlayer extends CraftPlayer { setSetting("scoreboard", scoreboard); } - public void connectToServer(String server) { - Servers.connectServer(PLAYER, server); - } + public void connectToServer(String server) { + Servers.connectServer(PLAYER, server); + } public boolean isAllowed(Ranks rank) { return getRank().value >= rank.value; @@ -405,87 +376,92 @@ public class CustomPlayer extends CraftPlayer { //TODO: add actual function } - public String getPrefix() { - if(customPrefix != null) return customPrefix; - if(isNicked()) return getPrefix(Ranks.Premium); + public String getPrefix() { + if (customPrefix != null) return customPrefix; + if (isNicked()) return getPrefix(Ranks.Premium); return getPrefix(getRank()); - } + } - public String getSuffix() { - if(customSuffix != null) return customSuffix; - if(isNicked()) return getSuffix(Ranks.Premium); - return getSuffix(getRank()); - } + public String getSuffix() { + if (customSuffix != null) return customSuffix; + if (isNicked()) return getSuffix(Ranks.Premium); + return getSuffix(getRank()); + } - public String getColor() { - if(customColor != null) return customColor; - if(isNicked()) return getColor(Ranks.Premium); - return getColor(getRank()); - } + public String getChatColor() { + if(isNicked()) return getChatColor(Ranks.Premium); + return getChatColor(getRank()); + } + + public String getColor() { + if (customColor != null) return customColor; + if (isNicked()) return getColor(Ranks.Premium); + return getColor(getRank()); + } public Team getTeam() { - if(isNicked()) return getTeam(Ranks.Premium); + if (isNicked()) return getTeam(Ranks.Premium); return getTeam(getRank()); } - public Color getArmorColor() { + public Color getArmorColor() { return getArmorColor(getRank()); } - public void setCustomPrefix(String prefix) { - customPrefix = prefix; - } + public void setCustomPrefix(String prefix) { + customPrefix = prefix; + } - public void setCustomSuffix(String suffix) { - customSuffix = suffix; - } + public void setCustomSuffix(String suffix) { + customSuffix = suffix; + } - public void setCustomColor(String color) { - customColor = color; - } + public void setCustomColor(String color) { + customColor = color; + } - public boolean hasEmptyInventory() { - return Utils.hasEmptyInventory(PLAYER); - } + public boolean hasEmptyInventory() { + return Utils.hasEmptyInventory(PLAYER); + } - public void clearPotionEffects() { - Utils.clearPotionEffects(PLAYER); - } + public void clearPotionEffects() { + Utils.clearPotionEffects(PLAYER); + } - public boolean hasOpenInventory() { - return openInventory; - } - + public boolean hasOpenInventory() { + return openInventory; + } - public void setOpenInventory(boolean openInventory) { - this.openInventory = openInventory; - } - public void addCoins(int coins) { - setCoins(getCoins() + coins); - } + public void setOpenInventory(boolean openInventory) { + this.openInventory = openInventory; + } - public void substractCoins(int coins) { - setCoins(getCoins() - coins); - } - + public void addCoins(int coins) { + setCoins(getCoins() + coins); + } - public void sendActionBar(String text) { - Actionbar.send(PLAYER, text); - } + public void substractCoins(int coins) { + setCoins(getCoins() - coins); + } - public void addExperience(int experience) { - setExperience(getExperience() + experience); - setExp(0F); - giveExp(getExperience()); - playSound(getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1.0F, 1.0F); - } - public void substractExperience(int experience) { - setExperience(getExperience() - experience); - setExp(0F); - giveExp(getExperience()); - } + public void sendActionBar(String text) { + Actionbar.send(PLAYER, text); + } + + public void addExperience(int experience) { + setExperience(getExperience() + experience); + setExp(0F); + giveExp(getExperience()); + playSound(getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1.0F, 1.0F); + } + + public void substractExperience(int experience) { + setExperience(getExperience() - experience); + setExp(0F); + giveExp(getExperience()); + } public void refreshExperience() { setLevel(0); @@ -494,7 +470,7 @@ public class CustomPlayer extends CraftPlayer { } public void playParticle(Location loc, EnumParticle ep, float f, int count) { - if(hasEffects()) Effects.playEffectToPlayer(PLAYER, loc, ep, f, count); + if (hasEffects()) Effects.playEffectToPlayer(PLAYER, loc, ep, f, count); } public void setAttackSpeed(double speed) { @@ -534,21 +510,77 @@ public class CustomPlayer extends CraftPlayer { setSetting("nicked", nicked); } + private void loadSkin(String name) { + //Skin skin = new Skin(UUIDFetcher.getUUID(name).toString()); + GameProfile skin; + GameProfile gp = getProfile(); + try { + skin = GameProfileBuilder.fetch(UUIDFetcher.getUUID(name)); + Collection properties = skin.getProperties().get("textures"); + gp.getProperties().removeAll("textures"); + gp.getProperties().putAll("textures", properties); + PacketPlayOutEntityDestroy destroy = new PacketPlayOutEntityDestroy(getEntityId()); + sendPacket(destroy); + PacketPlayOutPlayerInfo remove = new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER, getHandle()); + sendPacket(remove); + setHealth(0.0D); + new BukkitRunnable() { + @Override + public void run() { + PacketPlayOutPlayerInfo add = new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, getHandle()); + sendPacket(add); + PacketPlayOutNamedEntitySpawn spawn = new PacketPlayOutNamedEntitySpawn(getHandle()); + Core.getOnlinePlayers().stream().filter(player -> !player.getName().equals(getName())).forEach(player -> sendPacket(spawn)); + } + }.runTaskLater(Core.getInstance(), 4); + } catch (IOException e) { + e.printStackTrace(); + Core.log(Level.SEVERE, "Mojang Skin Server offline"); + sendMessage("§cSkin Server sind offline"); + } + } + public void removeNick() { - //NickNamerAPI.getNickManager().removeNick(getUniqueId()); - //NickNamerAPI.getNickManager().removeSkin(getUniqueId()); - //NickNamerAPI.getNickManager().refreshPlayer(this); + setNick(getName()); } public String getNick() { - if(nickname != null) return nickname; - return ""; + if (nickname != null) return nickname; + return null; } public void setNick(String name) { - //NickNamerAPI.getNickManager().setNick(getUniqueId(), name); - //NickNamerAPI.getNickManager().setSkin(getUniqueId(), "md_5"); - //NickNamerAPI.getNickManager().refreshPlayer(this); + setDisplayName(name); + Field nameField = getField(GameProfile.class, "name"); + try { + nameField.set(getProfile(), name); + PacketPlayOutEntityDestroy destroy = new PacketPlayOutEntityDestroy(getEntityId()); + sendPacket(destroy); + PacketPlayOutPlayerInfo remove = new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER, getHandle()); + sendPacket(remove); + + new BukkitRunnable() { + @Override + public void run() { + PacketPlayOutPlayerInfo add = new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, getHandle()); + sendPacket(add); + PacketPlayOutNamedEntitySpawn spawn = new PacketPlayOutNamedEntitySpawn(getHandle()); + Core.getOnlinePlayers().stream().filter(players -> !players.equals(this)).forEach(players -> players.sendPacket(spawn)); + } + }.runTaskLater(Core.getInstance(), 4); + + loadSkin(name); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + + public void strikeLightning(Location loc) { + World nmsWorld = ((CraftWorld)loc.getWorld()).getHandle(); + EntityLightning lightning = new EntityLightning(nmsWorld, loc.getX(), loc.getY(), loc.getZ(), true); + sendPacket(new PacketPlayOutSpawnEntityWeather(lightning)); + playSound(loc, Sound.ENTITY_LIGHTNING_IMPACT, 20.0F, 1.0F); + playSound(loc, Sound.ENTITY_LIGHTNING_THUNDER, 20.0F, 1.0F); } @Override @@ -612,85 +644,171 @@ public class CustomPlayer extends CraftPlayer { } private String getPrefix(Ranks r) { - switch(r) { - case Admin: return "§8[§4Admin§8]§4 "; - case SrDeveloper: return "§8[§3SrDev§8]§3 "; - case Developer: return "§8[§3Dev§8]§3 "; - case SrModerator: return "§8[§cSrMod§8]§c "; - case HeadBuilder: return "§8[§aHead-Builder§8]§a "; - case Moderator: return "§8[§cMod§8]§c "; - case Builder: return "§8[§2Builder§8]§2 "; - case Supporter: return "§8[§9Supporter§8]§9 "; - case Youtuber: return "§5"; - case Premium: return "§6"; - case Player: return "§e"; - default: return "§cFehler "; + switch (r) { + case Admin: + return "§8[§4Admin§8]§4 "; + case SrDeveloper: + return "§8[§3SrDev§8]§3 "; + case Developer: + return "§8[§3Dev§8]§3 "; + case SrModerator: + return "§8[§cSrMod§8]§c "; + case HeadBuilder: + return "§8[§aHead-Builder§8]§a "; + case Moderator: + return "§8[§cMod§8]§c "; + case Builder: + return "§8[§2Builder§8]§2 "; + case Supporter: + return "§8[§9Supporter§8]§9 "; + case Youtuber: + return "§5"; + case Premium: + return "§6"; + case Player: + return "§e"; + default: + return "§cFehler "; } } private String getSuffix(Ranks r) { - switch(r) { - case Admin: return "§8 »§7 "; - case SrDeveloper: return "§8 »§7 "; - case Developer: return "§8 »§7 "; - case SrModerator: return "§8 »§7 "; - case HeadBuilder: return "§8 »§7 "; - case Moderator: return "§8 »§7 "; - case Builder: return "§8 »§7 "; - case Supporter: return "§8 »§7 "; - case Youtuber: return "§8 »§7 "; - case Premium: return "§8 »§7 "; - case Player: return "§8 »§7 "; - default: return "§cFehler"; + switch (r) { + case Admin: + return "§8 »§7 "; + case SrDeveloper: + return "§8 »§7 "; + case Developer: + return "§8 »§7 "; + case SrModerator: + return "§8 »§7 "; + case HeadBuilder: + return "§8 »§7 "; + case Moderator: + return "§8 »§7 "; + case Builder: + return "§8 »§7 "; + case Supporter: + return "§8 »§7 "; + case Youtuber: + return "§8 »§7 "; + case Premium: + return "§8 »§7 "; + case Player: + return "§8 »§7 "; + default: + return "§cFehler"; + } + } + + private String getChatColor(Ranks r) { + switch (r) { + case Admin: + return "§4"; + case SrDeveloper: + return "§3"; + case Developer: + return "§3"; + case SrModerator: + return "§c"; + case HeadBuilder: + return "§a"; + case Moderator: + return "§c"; + case Builder: + return "§2"; + case Supporter: + return "§9"; + case Youtuber: + return "§5"; + case Premium: + return "§6"; + case Player: + return "§e"; + default: + return "§cFehler"; } } private String getColor(Ranks r) { - switch(r) { - case Admin: return "§4"; - case SrDeveloper: return "§3"; - case Developer: return "§3"; - case SrModerator: return "§c"; - case HeadBuilder: return "§a"; - case Moderator: return "§c"; - case Builder: return "§2"; - case Supporter: return "§9"; - case Youtuber: return "§5"; - case Premium: return "§6"; - case Player: return "§e"; - default: return "§cFehler"; + switch (r) { + case Admin: + return "§4[Admin] "; + case SrDeveloper: + return "§3[SrDev] "; + case Developer: + return "§3[Dev]"; + case SrModerator: + return "§c[SrMod]"; + case HeadBuilder: + return "§a[HeadBuilder] "; + case Moderator: + return "§c[Mod] "; + case Builder: + return "§2[Builder] "; + case Supporter: + return "§9[Supp] "; + case Youtuber: + return "§5"; + case Premium: + return "§6"; + case Player: + return "§e"; + default: + return "§cFehler"; } } private Color getArmorColor(Ranks r) { switch (r) { - case Admin: return Color.MAROON; - case SrDeveloper: return Color.TEAL; - case Developer: return Color.TEAL; - case SrModerator: return Color.RED; - case HeadBuilder: return Color.LIME; - case Moderator: return Color.RED; - case Builder: return Color.GREEN; - case Supporter: return Color.PURPLE; - default: return null; + case Admin: + return Color.MAROON; + case SrDeveloper: + return Color.TEAL; + case Developer: + return Color.TEAL; + case SrModerator: + return Color.RED; + case HeadBuilder: + return Color.LIME; + case Moderator: + return Color.RED; + case Builder: + return Color.GREEN; + case Supporter: + return Color.PURPLE; + default: + return null; } } public Team getTeam(Ranks r) { Scoreboard board = getScoreboard(); switch (r) { - case Admin: return board.getTeam("a"); - case SrDeveloper: return board.getTeam("b"); - case Developer: return board.getTeam("c"); - case SrModerator: return board.getTeam("d"); - case HeadBuilder: return board.getTeam("e"); - case Moderator: return board.getTeam("f"); - case Builder: return board.getTeam("g"); - case Supporter: return board.getTeam("h"); - case Youtuber: return board.getTeam("i"); - case Premium: return board.getTeam("j"); - case Player: return board.getTeam("k"); - default: return board.getTeam("k"); + case Admin: + return board.getTeam("a"); + case SrDeveloper: + return board.getTeam("b"); + case Developer: + return board.getTeam("c"); + case SrModerator: + return board.getTeam("d"); + case HeadBuilder: + return board.getTeam("e"); + case Moderator: + return board.getTeam("f"); + case Builder: + return board.getTeam("g"); + case Supporter: + return board.getTeam("h"); + case Youtuber: + return board.getTeam("i"); + case Premium: + return board.getTeam("j"); + case Player: + return board.getTeam("k"); + default: + return board.getTeam("k"); } } @@ -734,12 +852,22 @@ public class CustomPlayer extends CraftPlayer { Premium.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.ALWAYS); Player.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.ALWAYS); - + Admin.setOption(Team.Option.COLLISION_RULE, Team.OptionStatus.NEVER); + SrDeveloper.setOption(Team.Option.COLLISION_RULE, Team.OptionStatus.NEVER); + Developer.setOption(Team.Option.COLLISION_RULE, Team.OptionStatus.NEVER); + SrModerator.setOption(Team.Option.COLLISION_RULE, Team.OptionStatus.NEVER); + HeadBuilder.setOption(Team.Option.COLLISION_RULE, Team.OptionStatus.NEVER); + Moderator.setOption(Team.Option.COLLISION_RULE, Team.OptionStatus.NEVER); + Builder.setOption(Team.Option.COLLISION_RULE, Team.OptionStatus.NEVER); + Supporter.setOption(Team.Option.COLLISION_RULE, Team.OptionStatus.NEVER); + Youtuber.setOption(Team.Option.COLLISION_RULE, Team.OptionStatus.NEVER); + Premium.setOption(Team.Option.COLLISION_RULE, Team.OptionStatus.NEVER); + Player.setOption(Team.Option.COLLISION_RULE, Team.OptionStatus.NEVER); } public void setLabyModFeatures(HashMap list) { HashMap temp = new HashMap<>(); - for(LabyMod feature : list.keySet()) { + for (LabyMod feature : list.keySet()) { temp.put(feature.name(), list.get(feature)); } ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); @@ -758,7 +886,7 @@ public class CustomPlayer extends CraftPlayer { } public void crashClient() { - getHandle().playerConnection.sendPacket(new PacketPlayOutExplosion(9999999999D, + sendPacket(new PacketPlayOutExplosion(9999999999D, 9999999999D, 9999999999D, 9999999999F, new ArrayList<>(), new Vec3D(9999999999D, 9999999999D, 9999999999D))); @@ -779,4 +907,11 @@ public class CustomPlayer extends CraftPlayer { return null; } + public void refreshTablist() { + for (CustomPlayer player : Core.getOnlinePlayers()) { + setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); + getScoreboard().getTeam(player.getTeam().getName()).addEntry(player.getDisplayName()); + } + } + } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/player/NickName.java b/src/main/java/eu/univento/core/api/player/NickName.java index 5c52453..94fa65a 100644 --- a/src/main/java/eu/univento/core/api/player/NickName.java +++ b/src/main/java/eu/univento/core/api/player/NickName.java @@ -3,12 +3,12 @@ package eu.univento.core.api.player; import com.mojang.authlib.GameProfile; import eu.univento.core.Core; import eu.univento.core.api.database.MySQL; -import net.minecraft.server.v1_9_R1.Packet; -import net.minecraft.server.v1_9_R1.PacketPlayOutEntityDestroy; -import net.minecraft.server.v1_9_R1.PacketPlayOutNamedEntitySpawn; -import net.minecraft.server.v1_9_R1.PacketPlayOutPlayerInfo; +import net.minecraft.server.v1_10_R1.Packet; +import net.minecraft.server.v1_10_R1.PacketPlayOutEntityDestroy; +import net.minecraft.server.v1_10_R1.PacketPlayOutNamedEntitySpawn; +import net.minecraft.server.v1_10_R1.PacketPlayOutPlayerInfo; import org.bukkit.Bukkit; -import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer; +import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; @@ -138,9 +138,186 @@ public class NickName { names.add("Einstellung"); names.add("Verbindung"); names.add("WarAFKWasWar"); + names.add("Messy_Turkey"); + names.add("SpatenLP"); + names.add("DragonEvil68"); + names.add("Hashtagger"); + names.add("NotchHD"); + names.add("MCproYT"); + names.add("CookiePlayz"); + names.add("eZplayer"); + names.add("AdminHD"); + names.add("Rexey"); + names.add("R3l04D"); + names.add("xCrasherHD"); + names.add("2012derFilm"); + names.add("CaptainMine"); + names.add("CaveGamerYT"); + names.add("Herobrine1O1"); + names.add("Dschungelcamper"); + names.add("FrauKalble"); + names.add("torupto12"); + names.add("MmeCarbonne"); + names.add("blobfisch12"); + names.add("MelizzlHD"); + names.add("ProExeCution"); + names.add("karen12345"); + names.add("TakaTukaLand"); + names.add("La_Bomba123"); + names.add("wiaMaria"); + names.add("JonniiiHD"); + names.add("PDizzle784"); + names.add("GoldenPrayerHD"); + names.add("ungenudeltHd"); + names.add("GomminaHD"); + names.add("blobfisch12"); + names.add("B4ckpf3ife"); + names.add("Bratko87"); + names.add("danitcrafterLp"); + names.add("ZetinCraftHD"); + names.add("MonsterElii"); + names.add("NicolaiFTW"); + names.add("SpoKaPHy"); + names.add("xXDschegiXxT"); + names.add("McPvP_01"); + names.add("gamerzocker_1"); + names.add("GraumannHQ"); + names.add("Flcokengamer"); + names.add("BigMChd"); + names.add("SuperJonny"); + names.add("iTz_PvP"); + names.add("WoW_Crafter"); + names.add("Eddior_LP"); + names.add("catmisu"); + names.add("YourCrash"); + names.add("XxYourDeathxX"); + names.add("Piccio"); + names.add("ElderSwordetT"); + names.add("rewincube"); + names.add("cubixx"); + names.add("SilentPlayer"); + names.add("Palurensohn"); + names.add("TimTimolian"); + names.add("HesligerBoy"); + names.add("theGulasch"); + names.add("VaroPlaxer"); + names.add("JumpLeager"); + names.add("SplexxCraxer"); + names.add("EnderCraftLEL"); + names.add("Doriboy"); + names.add("MettrioxX"); + names.add("xPrayerr"); + names.add("PingPlayerHD"); + names.add("JaNilo"); + names.add("BigMChd"); + names.add("SuperJonny"); + names.add("iTz_PvP"); + names.add("WoW_Crafter"); + names.add("Eddior_LP"); + names.add("catmisu"); + names.add("YourCrash"); + names.add("XxYourDeathxX"); + names.add("Piccio"); + names.add("ElderSwordetT"); + names.add("rewincube"); + names.add("cubixx"); + names.add("SilentPlayer"); + names.add("Palurensohn"); + names.add("TimTimolian"); + names.add("HesligerBoy"); + names.add("theGulasch"); + names.add("VaroPlaxer"); + names.add("JumpLeager"); + names.add("SplexxCraxer"); + names.add("CapureHD"); + names.add("GermanCraftBukkit"); + names.add("AngelH73"); + names.add("EnderGamer_01"); + names.add("marox0Lp"); + names.add("ShuffelPlays"); + names.add("TimePvP"); + names.add("MCCHecker1000"); + names.add("Kalbinator4000"); + names.add("Maddiaren"); + names.add("LoL_PlayerHD"); + names.add("Rukkie"); + names.add("Shokkie"); + names.add("XxTNTLäuferxX"); + names.add("DiPlayz"); + names.add("getWRECKED"); + names.add("Radio"); + names.add("xSlain"); + names.add("MrGum01"); + names.add("Siprent"); + names.add("GonnerZ"); + names.add("geburEk"); + names.add("Nudel2015"); + names.add("dangerTV"); + names.add("FrontCrafter"); + names.add("litte_chimp"); + names.add("UdoGamingHD"); + names.add("M1lchbub1"); + names.add("Sagacious_Zed"); + names.add("BVBSosa"); + names.add("Tyzrael"); + names.add("Stralekilian"); + names.add("DeeJayy"); + names.add("fronfran55"); + names.add("stassenbahnfan"); + names.add("mcspeedy2"); + names.add("alexcraft4"); + names.add("FIST_67843"); + names.add("jaxbox2"); + names.add("xCora"); + names.add("MixTipp"); + names.add("Wenzala"); + names.add("Siber14"); + names.add("streuner0772"); + names.add("xXBioSalatXx"); + names.add("ScrealmXL"); + names.add("TheCrealn"); + names.add("LivingFr3akzLP"); + names.add("SuperPlay3r"); + names.add("Chiggings"); + names.add("EcriLP"); + names.add("windelrocker991"); + names.add("11/88/0"); + names.add("LiLeyXx"); + names.add("ricardinatkr"); + names.add("tuyan3224"); + names.add("Thadoro"); + names.add("TitanicPlayer"); + names.add("0smara"); + names.add("Skillminer009"); + names.add("DiamondDefender"); + names.add("VaceVace"); + names.add("kann0905"); + names.add("MinenMiner"); + names.add("TwinOn"); + names.add("Lara7823863"); + names.add("86Maximilian68"); + names.add("zZStegiZz"); + names.add("iTzSkiLLA"); + names.add("iTzBunnY"); + names.add("MilliBanilli"); + names.add("MCExpertiDE"); + names.add("SpeedyGames"); + names.add("Manokko"); + names.add("blow_basti"); + names.add("ninja32"); + names.add("dasSpieler_Lp"); + names.add("EvionLP"); + names.add("yolo_swagi_boy"); + names.add("_NikoLP_"); + names.add("Playgames"); + names.add("spiderjanik"); + names.add("xICooki"); + names.add("Drekken123001"); + names.add("Zohan1416"); + names.add("CrasCrafter"); + names.add("maik12002"); - Random r = new Random(); - int i = r.nextInt(names.size()); + int i = new Random().nextInt(names.size()); return names.get(i); } diff --git a/src/main/java/eu/univento/core/api/player/Ranks.java b/src/main/java/eu/univento/core/api/player/Ranks.java index d8fe0fb..009deaa 100644 --- a/src/main/java/eu/univento/core/api/player/Ranks.java +++ b/src/main/java/eu/univento/core/api/player/Ranks.java @@ -3,11 +3,11 @@ package eu.univento.core.api.player; public enum Ranks { Admin(11), SrDeveloper(10), - Developer(9), + HeadBuilder(9), SrModerator(8), - HeadBuilder(7), - Moderator(6), - Builder(5), + Developer(7), + Builder(6), + Moderator(5), Supporter(4), Youtuber(3), Premium(2), diff --git a/src/main/java/eu/univento/core/api/player/Skin.java b/src/main/java/eu/univento/core/api/player/Skin.java new file mode 100644 index 0000000..24d7f2f --- /dev/null +++ b/src/main/java/eu/univento/core/api/player/Skin.java @@ -0,0 +1,55 @@ +package eu.univento.core.api.player; + +import java.net.URL; +import java.net.URLConnection; +import java.util.Scanner; +import java.util.logging.Level; + +import org.bukkit.Bukkit; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; + +class Skin { + private String uuid; + private String name; + private String value; + private String signature; + + Skin(String uuid){this.uuid = uuid;load();} + String getSkinValue(){return value;} + String getSkinName(){return name;} + String getSkinSignature(){return signature;} + + private void load(){ + try { + URL url = new URL("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid + "?unsigned=false"); + URLConnection uc = url.openConnection(); + uc.setUseCaches(false); + uc.setDefaultUseCaches(false); + uc.addRequestProperty("User-Agent", "Mozilla/5.0"); + uc.addRequestProperty("Cache-Control", "no-cache, no-store, must-revalidate"); + uc.addRequestProperty("Pragma", "no-cache"); + String json = new Scanner(uc.getInputStream(), "UTF-8").useDelimiter("\\A").next(); + + JSONParser parser = new JSONParser(); + Object obj = parser.parse(json); + JSONArray properties = (JSONArray) ((JSONObject) obj).get("properties"); + for (Object property1 : properties) { + try { + JSONObject property = (JSONObject) property1; + String name = (String) property.get("name"); + String value = (String) property.get("value"); + String signature = property.containsKey("signature") ? (String) property.get("signature") : null; + this.name = name; + this.value = value; + this.signature = signature; + } catch (Exception e) { + Bukkit.getLogger().log(Level.WARNING, "Failed to apply auth property", e); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/server/NetworkData.java b/src/main/java/eu/univento/core/api/server/NetworkData.java new file mode 100644 index 0000000..81415b5 --- /dev/null +++ b/src/main/java/eu/univento/core/api/server/NetworkData.java @@ -0,0 +1,59 @@ +package eu.univento.core.api.server; + +import com.google.common.io.ByteArrayDataInput; +import com.google.common.io.ByteArrayDataOutput; +import com.google.common.io.ByteStreams; +import eu.univento.core.Core; +import eu.univento.core.api.player.CustomPlayer; +import org.bukkit.entity.Player; +import org.bukkit.plugin.messaging.PluginMessageListener; + +import java.util.logging.Level; + +public class NetworkData implements PluginMessageListener{ + + private CustomPlayer player; + private int totalPlayerCount; + private String serverName; + private int serverPlayerCount; + + public NetworkData(CustomPlayer player) { + this.player = player; + refreshData(); + } + + public NetworkData() { + } + + private void refreshData() { + ByteArrayDataOutput output = ByteStreams.newDataOutput(); + output.writeUTF("PlayerCount"); + output.writeUTF("ALL"); + player.sendPluginMessage(Core.getInstance(), "BungeeCord", output.toByteArray()); + } + + public int getTotalPlayerCount() { + return totalPlayerCount; + } + + @Override + public void onPluginMessageReceived(String channel, Player player, byte[] message) { + if(!channel.equals("BungeeCord")) return; + + Core.log(Level.INFO, "Daten incomming"); + + ByteArrayDataInput input = ByteStreams.newDataInput(message); + String subchannel = input.readUTF(); + + if(subchannel.equals("PlayerCount")) { + String server = input.readUTF(); + if(server.equals("ALL")) { + this.totalPlayerCount = input.readInt(); + return; + } + this.serverName = server; + this.serverPlayerCount = input.readInt(); + } + } + +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/twitch/API.java b/src/main/java/eu/univento/core/api/twitch/API.java deleted file mode 100644 index de7c26e..0000000 --- a/src/main/java/eu/univento/core/api/twitch/API.java +++ /dev/null @@ -1,25 +0,0 @@ -package eu.univento.core.api.twitch; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.URL; - -public class API { - public static String readJsonFromUrl(String urlString) throws Exception { - BufferedReader reader = null; - try { - URL url = new URL(urlString); - reader = new BufferedReader(new InputStreamReader(url.openStream())); - StringBuffer buffer = new StringBuffer(); - int read; - char[] chars = new char[1024]; - while ((read = reader.read(chars)) != -1) - buffer.append(chars, 0, read); - - return buffer.toString(); - } finally { - if (reader != null) - reader.close(); - } - } -} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/twitch/Twitch_API.java b/src/main/java/eu/univento/core/api/twitch/Twitch_API.java deleted file mode 100644 index 8691770..0000000 --- a/src/main/java/eu/univento/core/api/twitch/Twitch_API.java +++ /dev/null @@ -1,43 +0,0 @@ -package eu.univento.core.api.twitch; - - -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; - - -public class Twitch_API { -public static Gson gson = new Gson(); - - - - -public static Twitch_Stream getStream(String channelname){ -try{ -String json = API.readJsonFromUrl("http://api.justin.tv/api/stream/list.json?channel="+channelname); - - -Twitch_Stream stream = new Twitch_Stream(); -if(json.equalsIgnoreCase("[]")){ -stream.setOnline(false); -return stream; -} -JsonArray jb = gson.fromJson(json, JsonArray.class); -JsonObject jo = (JsonObject) jb.get(0); -stream.setOnline(true); -stream.load(jo); -return stream; -} catch (Exception error){ -error.printStackTrace(); -} - - - - -return null; - - - - -} -} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/twitch/Twitch_Stream.java b/src/main/java/eu/univento/core/api/twitch/Twitch_Stream.java deleted file mode 100644 index 8ce5f5f..0000000 --- a/src/main/java/eu/univento/core/api/twitch/Twitch_Stream.java +++ /dev/null @@ -1,380 +0,0 @@ -package eu.univento.core.api.twitch; - -import com.google.gson.JsonObject; - -public class Twitch_Stream { - boolean online; - int broadcast_part; - boolean featured; - boolean channel_subscription; - String id; - String category; - String title; - int channel_count; - int video_height; - int site_count; - boolean embed_enabled; - String up_time; - String meta_game; - String format; - int embed_count; - String stream_type; - boolean abuse_reported; - int video_width; - String geo; - String name; - String language; - int stream_count; - double video_bitrate; - String broadcaster; - int channel_view_count; - String username; - String status; - String channel_url; - boolean producer; - String subcategory_title; - String screen_cap_url_large; - String screen_cap_url_small; - String screen_cap_url_medium; - String screen_cap_url_huge; - String timezone; - String category_title; - int views_count; - - public void load(JsonObject job) { - setBroadcast_part(job.get("broadcast_part").getAsInt()); - setFeatured(job.get("featured").getAsBoolean()); - setChannel_subscription(job.get("channel_subscription").getAsBoolean()); - setId(job.get("id").getAsString()); - setCategory(job.get("category").getAsString()); - setTitle(job.get("title").getAsString()); - setChannel_count(job.get("channel_count").getAsInt()); - setVideo_height(job.get("video_height").getAsInt()); - setSite_count(job.get("site_count").getAsInt()); - setEmbed_enabled(job.get("embed_enabled").getAsBoolean()); - setUp_time(job.get("up_time").getAsString()); - setMeta_game(job.get("meta_game").getAsString()); - setFormat(job.get("format").getAsString()); - setEmbed_count(job.get("embed_count").getAsInt()); - setStream_type(job.get("stream_type").getAsString()); - setAbuse_reported(job.get("abuse_reported").getAsBoolean()); - setVideo_width(job.get("video_width").getAsInt()); - setGeo(job.get("geo").getAsString()); - setName(job.get("name").getAsString()); - setLanguage(job.get("language").getAsString()); - setStream_count(job.get("stream_count").getAsInt()); - setVideo_bitrate(job.get("video_bitrate").getAsDouble()); - setBroadcaster(job.get("broadcaster").getAsString()); - setChannel_view_count(job.get("channel_view_count").getAsInt()); - - setUsername(job.get("channel").getAsJsonObject().get("login").getAsString()); - setTitle(job.get("channel").getAsJsonObject().get("status").getAsString()); - setChannel_url(job.get("channel").getAsJsonObject().get("channel_url").getAsString()); - setProducer(job.get("channel").getAsJsonObject().get("producer").getAsBoolean()); - - setSubcategory_title(job.get("channel").getAsJsonObject().get("subcategory_title").getAsString()); - setScreen_cap_url_large(job.get("channel").getAsJsonObject().get("screen_cap_url_large").getAsString()); - setScreen_cap_url_small(job.get("channel").getAsJsonObject().get("screen_cap_url_small").getAsString()); - setScreen_cap_url_medium(job.get("channel").getAsJsonObject().get("screen_cap_url_medium").getAsString()); - setScreen_cap_url_huge(job.get("channel").getAsJsonObject().get("screen_cap_url_huge").getAsString()); - setTimezone(job.get("channel").getAsJsonObject().get("timezone").getAsString()); - setCategory_title(job.get("channel").getAsJsonObject().get("category_title").getAsString()); - setViews_count(job.get("channel").getAsJsonObject().get("views_count").getAsInt()); - } - - public boolean isOnline() { - return this.online; - } - - public void setOnline(boolean online) { - this.online = online; - } - - public int getBroadcast_part() { - return this.broadcast_part; - } - - public void setBroadcast_part(int broadcast_part) { - this.broadcast_part = broadcast_part; - } - - public boolean isFeatured() { - return this.featured; - } - - public void setFeatured(boolean featured) { - this.featured = featured; - } - - public boolean isChannel_subscription() { - return this.channel_subscription; - } - - public void setChannel_subscription(boolean channel_subscription) { - this.channel_subscription = channel_subscription; - } - - public String getId() { - return this.id; - } - - public void setId(String id) { - this.id = id; - } - - public String getCategory() { - return this.category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getTitle() { - return this.title; - } - - public void setTitle(String title) { - this.title = title; - } - - public int getChannel_count() { - return this.channel_count; - } - - public void setChannel_count(int channel_count) { - this.channel_count = channel_count; - } - - public int getVideo_height() { - return this.video_height; - } - - public void setVideo_height(int video_height) { - this.video_height = video_height; - } - - public int getSite_count() { - return this.site_count; - } - - public void setSite_count(int site_count) { - this.site_count = site_count; - } - - public boolean isEmbed_enabled() { - return this.embed_enabled; - } - - public void setEmbed_enabled(boolean embed_enabled) { - this.embed_enabled = embed_enabled; - } - - public String getUp_time() { - return this.up_time; - } - - public void setUp_time(String up_time) { - this.up_time = up_time; - } - - public String getMeta_game() { - return this.meta_game; - } - - public void setMeta_game(String meta_game) { - this.meta_game = meta_game; - } - - public String getFormat() { - return this.format; - } - - public void setFormat(String format) { - this.format = format; - } - - public int getEmbed_count() { - return this.embed_count; - } - - public void setEmbed_count(int embed_count) { - this.embed_count = embed_count; - } - - public String getStream_type() { - return this.stream_type; - } - - public void setStream_type(String stream_type) { - this.stream_type = stream_type; - } - - public boolean isAbuse_reported() { - return this.abuse_reported; - } - - public void setAbuse_reported(boolean abuse_reported) { - this.abuse_reported = abuse_reported; - } - - public int getVideo_width() { - return this.video_width; - } - - public void setVideo_width(int video_width) { - this.video_width = video_width; - } - - public String getGeo() { - return this.geo; - } - - public void setGeo(String geo) { - this.geo = geo; - } - - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - public String getLanguage() { - return this.language; - } - - public void setLanguage(String language) { - this.language = language; - } - - public int getStream_count() { - return this.stream_count; - } - - public void setStream_count(int stream_count) { - this.stream_count = stream_count; - } - - public double getVideo_bitrate() { - return this.video_bitrate; - } - - public void setVideo_bitrate(double video_bitrate) { - this.video_bitrate = video_bitrate; - } - - public String getBroadcaster() { - return this.broadcaster; - } - - public void setBroadcaster(String broadcaster) { - this.broadcaster = broadcaster; - } - - public int getChannel_view_count() { - return this.channel_view_count; - } - - public void setChannel_view_count(int channel_view_count) { - this.channel_view_count = channel_view_count; - } - - public String getUsername() { - return this.username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getStatus() { - return this.status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getChannel_url() { - return this.channel_url; - } - - public void setChannel_url(String channel_url) { - this.channel_url = channel_url; - } - - public boolean isProducer() { - return this.producer; - } - - public void setProducer(boolean producer) { - this.producer = producer; - } - - public String getSubcategory_title() { - return this.subcategory_title; - } - - public void setSubcategory_title(String subcategory_title) { - this.subcategory_title = subcategory_title; - } - - public String getScreen_cap_url_large() { - return this.screen_cap_url_large; - } - - public void setScreen_cap_url_large(String screen_cap_url_large) { - this.screen_cap_url_large = screen_cap_url_large; - } - - public String getScreen_cap_url_small() { - return this.screen_cap_url_small; - } - - public void setScreen_cap_url_small(String screen_cap_url_small) { - this.screen_cap_url_small = screen_cap_url_small; - } - - public String getScreen_cap_url_medium() { - return this.screen_cap_url_medium; - } - - public void setScreen_cap_url_medium(String screen_cap_url_medium) { - this.screen_cap_url_medium = screen_cap_url_medium; - } - - public String getScreen_cap_url_huge() { - return this.screen_cap_url_huge; - } - - public void setScreen_cap_url_huge(String screen_cap_url_huge) { - this.screen_cap_url_huge = screen_cap_url_huge; - } - - public String getTimezone() { - return this.timezone; - } - - public void setTimezone(String timezone) { - this.timezone = timezone; - } - - public String getCategory_title() { - return this.category_title; - } - - public void setCategory_title(String category_title) { - this.category_title = category_title; - } - - public int getViews_count() { - return this.views_count; - } - - public void setViews_count(int views_count) { - this.views_count = views_count; - } -} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/utils/Camera.java b/src/main/java/eu/univento/core/api/utils/Camera.java new file mode 100644 index 0000000..addd73e --- /dev/null +++ b/src/main/java/eu/univento/core/api/utils/Camera.java @@ -0,0 +1,102 @@ +package eu.univento.core.api.utils; + +import eu.univento.core.api.player.CustomPlayer; +import org.bukkit.Location; + +import java.math.BigDecimal; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + +public class Camera { + + //TODO: add full functionality + + private String name; + private int time; + private ArrayList players = new ArrayList<>(); + private ArrayList locations = new ArrayList<>(); + + private double round(double unrounded, int precision) { + BigDecimal bigDecimal = new BigDecimal(unrounded); + BigDecimal rounded = bigDecimal.setScale(precision, 4); + return rounded.doubleValue(); + } + + private double positionDifference(Location loc1, Location loc2) { + double x1 = loc1.getX(); + double y1 = loc1.getY(); + double z1 = loc1.getZ(); + + double x2 = loc2.getX(); + double y2 = loc2.getY(); + double z2 = loc2.getZ(); + + double x = x2 - x1; + if (x < 0.0D) + x = -x; + double z = z2 - z1; + if (z < 0.0D) + z = -z; + double xz = Math.hypot(x, z); + double y = y2 - y1; + if (y < 0.0D) + y = -y; + return Math.hypot(xz, y); + } + + private Date parseTimeString(String timeString) throws ParseException { + Date length; + try { + SimpleDateFormat formatter = new SimpleDateFormat("mm'm'ss's'"); + length = formatter.parse(timeString); + } catch (Exception e) { + try { + SimpleDateFormat formatter = new SimpleDateFormat("m'm'ss's'"); + length = formatter.parse(timeString); + } catch (Exception e1) { + try { + SimpleDateFormat formatter = new SimpleDateFormat("m'm's's'"); + length = formatter.parse(timeString); + } catch (Exception e2) { + try { + SimpleDateFormat formatter = new SimpleDateFormat("mm'm's's'"); + length = formatter.parse(timeString); + } catch (Exception e3) { + try { + SimpleDateFormat formatter = new SimpleDateFormat("mm'm'"); + length = formatter.parse(timeString); + } catch (Exception e4) { + try { + SimpleDateFormat formatter = new SimpleDateFormat("m'm'"); + length = formatter.parse(timeString); + } catch (Exception e5) { + try { + SimpleDateFormat formatter = new SimpleDateFormat("s's'"); + length = formatter.parse(timeString); + } catch (Exception e6) { + SimpleDateFormat formatter = new SimpleDateFormat("ss's'"); + length = formatter.parse(timeString); + } + } + } + } + } + } + } + return length; + } + + private void load() { + + } + + public Camera(String name) { + this.name = name; + load(); + } + + public void start(CustomPlayer p) { + + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/utils/NameFetcher.java b/src/main/java/eu/univento/core/api/utils/NameFetcher.java deleted file mode 100644 index 1679f96..0000000 --- a/src/main/java/eu/univento/core/api/utils/NameFetcher.java +++ /dev/null @@ -1,49 +0,0 @@ -package eu.univento.core.api.utils; - -import com.google.common.collect.ImmutableList; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; - -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.Callable; - -public class NameFetcher implements Callable>{ - private static final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/"; - private final JSONParser jsonParser = new JSONParser(); - private final List uuids; - - public NameFetcher(List uuids) - { - this.uuids = ImmutableList.copyOf(uuids); - } - - public Map call() throws Exception - { - Map uuidStringMap = new HashMap(); - for (UUID uuid : this.uuids) { - HttpURLConnection connection = (HttpURLConnection)new URL("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid.toString().replace("-", "")).openConnection(); - JSONObject response = (JSONObject)this.jsonParser.parse(new InputStreamReader(connection.getInputStream())); - String name = (String)response.get("name"); - if (name == null) { - continue; - } - String cause = (String)response.get("cause"); - String errorMessage = (String)response.get("errorMessage"); - if ((cause != null) && (cause.length() > 0)) { - throw new IllegalStateException(errorMessage); - } - uuidStringMap.put(uuid, name); - } - return uuidStringMap; - } - -public static String getProfileUrl() { - return PROFILE_URL; -} -} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/utils/UUIDFetcher.java b/src/main/java/eu/univento/core/api/utils/UUIDFetcher.java new file mode 100644 index 0000000..6202ae5 --- /dev/null +++ b/src/main/java/eu/univento/core/api/utils/UUIDFetcher.java @@ -0,0 +1,132 @@ +package eu.univento.core.api.utils; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Consumer; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.mojang.util.UUIDTypeAdapter; + +/** + * @author Jofkos + */ + +public class UUIDFetcher{ + + /** + * Date when name changes were introduced + * @see UUIDFetcher#getUUIDAt(String, long) + */ + public static final long FEBRUARY_2015 = 1422748800000L; + + + private static Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create(); + + private static final String UUID_URL = "https://api.mojang.com/users/profiles/minecraft/%s?at=%d"; + private static final String NAME_URL = "https://api.mojang.com/user/profiles/%s/names"; + private static Map uuidCache = new HashMap<>(); + private static Map nameCache = new HashMap<>(); + private static ExecutorService pool = Executors.newCachedThreadPool(); + + private String name; + private UUID id; + + /** + * Fetches the uuid asynchronously and passes it to the consumer + * + * @param name The name + * @param action Do what you want to do with the uuid her + */ + public static void getUUID(String name, Consumer action) { + pool.execute(() -> action.accept(getUUID(name))); + } + + /** + * Fetches the uuid synchronously and returns it + * + * @param name The name + * @return The uuid + */ + public static UUID getUUID(String name) { + return getUUIDAt(name, System.currentTimeMillis()); + } + + /** + * Fetches the uuid synchronously for a specified name and time and passes the result to the consumer + * + * @param name The name + * @param timestamp Time when the player had this name in milliseconds + * @param action Do what you want to do with the uuid her + */ + public static void getUUIDAt(String name, long timestamp, Consumer action) { + pool.execute(() -> action.accept(getUUIDAt(name, timestamp))); + } + + /** + * Fetches the uuid synchronously for a specified name and time + * + * @param name The name + * @param timestamp Time when the player had this name in milliseconds + * @see UUIDFetcher#FEBRUARY_2015 + */ + public static UUID getUUIDAt(String name, long timestamp) { + name = name.toLowerCase(); + if (uuidCache.containsKey(name)) { + return uuidCache.get(name); + } + try { + HttpURLConnection connection = (HttpURLConnection) new URL(String.format(UUID_URL, name, timestamp/1000)).openConnection(); + connection.setReadTimeout(5000); + UUIDFetcher data = gson.fromJson(new BufferedReader(new InputStreamReader(connection.getInputStream())), UUIDFetcher.class); + + uuidCache.put(name, data.id); + nameCache.put(data.id, data.name); + return data.id; + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + /** + * Fetches the name asynchronously and passes it to the consumer + * + * @param uuid The uuid + * @param action Do what you want to do with the name her + */ + public static void getName(UUID uuid, Consumer action) { + pool.execute(() -> action.accept(getName(uuid))); + } + /** + * Fetches the name synchronously and returns it + * + * @param uuid The uuid + * @return The name + */ + public static String getName(UUID uuid) { + if (nameCache.containsKey(uuid)) { + return nameCache.get(uuid); + } + try { + HttpURLConnection connection = (HttpURLConnection) new URL(String.format(NAME_URL, UUIDTypeAdapter.fromUUID(uuid))).openConnection(); + connection.setReadTimeout(5000); + UUIDFetcher[] nameHistory = gson.fromJson(new BufferedReader(new InputStreamReader(connection.getInputStream())), UUIDFetcher[].class); + UUIDFetcher currentNameData = nameHistory[nameHistory.length - 1]; + uuidCache.put(currentNameData.name.toLowerCase(), uuid); + nameCache.put(uuid, currentNameData.name); + return currentNameData.name; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/src/main/java/eu/univento/core/api/utils/reflection/ArrayWrapper.java b/src/main/java/eu/univento/core/api/utils/reflection/ArrayWrapper.java new file mode 100644 index 0000000..ff23c08 --- /dev/null +++ b/src/main/java/eu/univento/core/api/utils/reflection/ArrayWrapper.java @@ -0,0 +1,112 @@ +package eu.univento.core.api.utils.reflection; + +import org.apache.commons.lang.Validate; + +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.Collection; + +/** + * Represents a wrapper around an array class of an arbitrary reference type, + * which properly implements "value" hash code and equality functions. + *

+ * This class is intended for use as a key to a map. + *

+ * + * @param The type of elements in the array. + * @author Glen Husman + * @see Arrays + */ + +public final class ArrayWrapper { + + + /** + * Creates an array wrapper with some elements. + * + * @param elements The elements of the array. + */ + public ArrayWrapper(E... elements) { + setArray(elements); + } + + private E[] _array; + + /** + * Retrieves a reference to the wrapped array instance. + * + * @return The array wrapped by this instance. + */ + public E[] getArray() { + return _array; + } + + /** + * Set this wrapper to wrap a new array instance. + * + * @param array The new wrapped array. + */ + public void setArray(E[] array) { + Validate.notNull(array, "The array must not be null."); + _array = array; + } + + /** + * Determines if this object has a value equivalent to another object. + * + * @see Arrays#equals(Object[], Object[]) + */ + @SuppressWarnings("rawtypes") + @Override + public boolean equals(Object other) { + if (!(other instanceof ArrayWrapper)) { + return false; + } + return Arrays.equals(_array, ((ArrayWrapper) other)._array); + } + + /** + * Gets the hash code represented by this objects value. + * + * @return This object's hash code. + * @see Arrays#hashCode(Object[]) + */ + @Override + public int hashCode() { + return Arrays.hashCode(_array); + } + + /** + * Converts an iterable element collection to an array of elements. + * The iteration order of the specified object will be used as the array element order. + * + * @param list The iterable of objects which will be converted to an array. + * @param c The type of the elements of the array. + * @return An array of elements in the specified iterable. + */ + @SuppressWarnings("unchecked") + public static T[] toArray(Iterable list, Class c) { + int size = -1; + if (list instanceof Collection) { + @SuppressWarnings("rawtypes") + Collection coll = (Collection) list; + size = coll.size(); + } + + + if (size < 0) { + size = 0; + // Ugly hack: Count it ourselves + for (@SuppressWarnings("unused") T element : list) { + size++; + } + } + + T[] result = (T[]) Array.newInstance(c, size); + int i = 0; + for (T element : list) { // Assumes iteration order is consistent + result[i++] = element; // Assign array element at index THEN increment counter + } + return result; + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/utils/reflection/Reflection.java b/src/main/java/eu/univento/core/api/utils/reflection/Reflection.java index c07997e..8710c3b 100644 --- a/src/main/java/eu/univento/core/api/utils/reflection/Reflection.java +++ b/src/main/java/eu/univento/core/api/utils/reflection/Reflection.java @@ -2,77 +2,237 @@ package eu.univento.core.api.utils.reflection; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; import org.bukkit.Bukkit; -public class Reflection { - public static String getVersion() { - String name = Bukkit.getServer().getClass().getPackage().getName(); - String version = name.substring(name.lastIndexOf('.') + 1) + "."; - return version; + +/** + * A class containing static utility methods and caches which are intended as reflective conveniences. + * Unless otherwise noted, upon failure methods will return {@code null}. + */ +public final class Reflection { + + private static String _versionString; + + private Reflection() { + } - public static Class getNMSClass(String className) { + /** + * Gets the version string from the package name of the CraftBukkit server implementation. + * This is needed to bypass the JAR package name changing on each update. + * + * @return The version string of the OBC and NMS packages, including the trailing dot. + */ + public synchronized static String getVersion() { + if (_versionString == null) { + if (Bukkit.getServer() == null) { + // The server hasn't started, static initializer call? + return null; + } + String name = Bukkit.getServer().getClass().getPackage().getName(); + _versionString = name.substring(name.lastIndexOf('.') + 1) + "."; + } + + return _versionString; + } + + /** + * Stores loaded classes from the {@code net.minecraft.server} package. + */ + private static final Map> _loadedNMSClasses = new HashMap<>(); + /** + * Stores loaded classes from the {@code org.bukkit.craftbukkit} package (and subpackages). + */ + private static final Map> _loadedOBCClasses = new HashMap<>(); + + /** + * Gets a {@link Class} object representing a type contained within the {@code net.minecraft.server} versioned package. + * The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this method simultaneously). + * + * @param className The name of the class, excluding the package, within NMS. + * @return The class instance representing the specified NMS class, or {@code null} if it could not be loaded. + */ + public synchronized static Class getNMSClass(String className) { + if (_loadedNMSClasses.containsKey(className)) { + return _loadedNMSClasses.get(className); + } + String fullName = "net.minecraft.server." + getVersion() + className; - Class clazz = null; + Class clazz; try { clazz = Class.forName(fullName); } catch (Exception e) { e.printStackTrace(); + _loadedNMSClasses.put(className, null); + return null; } + _loadedNMSClasses.put(className, clazz); return clazz; } - public static Class getOBCClass(String className) { + public synchronized static Class getCTBClass(String className) { + if (_loadedNMSClasses.containsKey(className)) { + return _loadedNMSClasses.get(className); + } + String fullName = "org.bukkit.craftbukkit." + getVersion() + className; - Class clazz = null; + Class clazz; try { clazz = Class.forName(fullName); } catch (Exception e) { e.printStackTrace(); + _loadedNMSClasses.put(className, null); + return null; } + _loadedNMSClasses.put(className, clazz); return clazz; } - public static Object getHandle(Object obj) { + /** + * Gets a {@link Class} object representing a type contained within the {@code org.bukkit.craftbukkit} versioned package. + * The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this method simultaneously). + * + * @param className The name of the class, excluding the package, within OBC. This name may contain a subpackage name, such as {@code inventory.CraftItemStack}. + * @return The class instance representing the specified OBC class, or {@code null} if it could not be loaded. + */ + public synchronized static Class getOBCClass(String className) { + if (_loadedOBCClasses.containsKey(className)) { + return _loadedOBCClasses.get(className); + } + + String fullName = "org.bukkit.craftbukkit." + getVersion() + className; + Class clazz; try { - return getMethod(obj.getClass(), "getHandle", new Class[0]).invoke(obj, new Object[0]); + clazz = Class.forName(fullName); } catch (Exception e) { e.printStackTrace(); + _loadedOBCClasses.put(className, null); + return null; } - return null; + _loadedOBCClasses.put(className, clazz); + return clazz; } - public static Field getField(Class clazz, String name) { + /** + * Attempts to get the NMS handle of a CraftBukkit object. + *

+ * The only match currently attempted by this method is a retrieval by using a parameterless {@code getHandle()} method implemented by the runtime type of the specified object. + *

+ * + * @param obj The object for which to retrieve an NMS handle. + * @return The NMS handle of the specified object, or {@code null} if it could not be retrieved using {@code getHandle()}. + */ + public synchronized static Object getHandle(Object obj) { + try { + return getMethod(obj.getClass(), "getHandle").invoke(obj); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + private static final Map, Map> _loadedFields = new HashMap, Map>(); + + /** + * Retrieves a {@link Field} instance declared by the specified class with the specified name. + * Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field + * returned will be an instance or static field. + *

+ * A global caching mechanism within this class is used to store fields. Combined with synchronization, this guarantees that + * no field will be reflectively looked up twice. + *

+ *

+ * If a field is deemed suitable for return, {@link Field#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code true} before it is returned. + * This ensures that callers do not have to check or worry about Java access modifiers when dealing with the returned instance. + *

+ * + * @param clazz The class which contains the field to retrieve. + * @param name The declared name of the field in the class. + * @return A field object with the specified name declared by the specified class. + * @see Class#getDeclaredField(String) + */ + public synchronized static Field getField(Class clazz, String name) { + Map loaded; + if (!_loadedFields.containsKey(clazz)) { + loaded = new HashMap<>(); + _loadedFields.put(clazz, loaded); + } else { + loaded = _loadedFields.get(clazz); + } + if (loaded.containsKey(name)) { + // If the field is loaded (or cached as not existing), return the relevant value, which might be null + return loaded.get(name); + } try { Field field = clazz.getDeclaredField(name); field.setAccessible(true); + loaded.put(name, field); return field; } catch (Exception e) { + // Error loading e.printStackTrace(); + // Cache field as not existing + loaded.put(name, null); + return null; } - return null; } - public static Method getMethod(Class clazz, String name, Class[] args) { - for (Method m : clazz.getMethods()) { - if ((m.getName().equals(name)) && ((args.length == 0) || (ClassListEqual(args, m.getParameterTypes())))) { + /** + * Contains loaded methods in a cache. + * The map maps [types to maps of [method names to maps of [parameter types to method instances]]]. + */ + private static final Map, Map>, Method>>> _loadedMethods = new HashMap<>(); + + /** + * Retrieves a {@link Method} instance declared by the specified class with the specified name and argument types. + * Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field + * returned will be an instance or static field. + *

+ * A global caching mechanism within this class is used to store method. Combined with synchronization, this guarantees that + * no method will be reflectively looked up twice. + *

+ *

+ * If a method is deemed suitable for return, {@link Method#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code true} before it is returned. + * This ensures that callers do not have to check or worry about Java access modifiers when dealing with the returned instance. + *

+ *

+ * This method does not search superclasses of the specified type for methods with the specified signature. + * Callers wishing this behavior should use {@link Class#getDeclaredMethod(String, Class...)}. + * + * @param clazz The class which contains the method to retrieve. + * @param name The declared name of the method in the class. + * @param args The formal argument types of the method. + * @return A method object with the specified name declared by the specified class. + */ + public synchronized static Method getMethod(Class clazz, String name, + Class... args) { + if (!_loadedMethods.containsKey(clazz)) { + _loadedMethods.put(clazz, new HashMap<>()); + } + + Map>, Method>> loadedMethodNames = _loadedMethods.get(clazz); + if (!loadedMethodNames.containsKey(name)) { + loadedMethodNames.put(name, new HashMap<>()); + } + + Map>, Method> loadedSignatures = loadedMethodNames.get(name); + ArrayWrapper> wrappedArg = new ArrayWrapper<>(args); + if (loadedSignatures.containsKey(wrappedArg)) { + return loadedSignatures.get(wrappedArg); + } + + for (Method m : clazz.getMethods()) + if (m.getName().equals(name) && Arrays.equals(args, m.getParameterTypes())) { m.setAccessible(true); + loadedSignatures.put(wrappedArg, m); return m; } - } + loadedSignatures.put(wrappedArg, null); return null; } - public static boolean ClassListEqual(Class[] l1, Class[] l2) { - boolean equal = true; - if (l1.length != l2.length) return false; - for (int i = 0; i < l1.length; i++) { - if (l1[i] != l2[i]) { - equal = false; - break; - } - } - return equal; - } } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/youtube/YTAPI.java b/src/main/java/eu/univento/core/api/youtube/YTAPI.java deleted file mode 100644 index 5835756..0000000 --- a/src/main/java/eu/univento/core/api/youtube/YTAPI.java +++ /dev/null @@ -1,119 +0,0 @@ -package eu.univento.core.api.youtube; - -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.URL; - -public class YTAPI { - - public static Gson gson = new Gson(); - - public static String readJsonFromUrl(String urlString) throws Exception { - BufferedReader reader = null; - try { - URL url = new URL(urlString); - reader = new BufferedReader(new InputStreamReader(url.openStream())); - StringBuffer buffer = new StringBuffer(); - int read; - char[] chars = new char[1024]; - while ((read = reader.read(chars)) != -1) - buffer.append(chars, 0, read); - - return buffer.toString(); - } finally { - if (reader != null) - reader.close(); - } - } - - public static String getGooglePlusId(String uri) throws Exception { - String endid = uri.split("/")[uri.split("/").length - 1]; - String json = YTAPI.readJsonFromUrl("http://gdata.youtube.com/feeds/api/users/" + endid + "?alt=json"); - JsonObject jo = gson.fromJson(json, JsonObject.class); - String gplusid = jo.get("entry").getAsJsonObject().get("yt$googlePlusUserId").getAsJsonObject().get("$t") - .getAsString(); - return gplusid; - } - - public static String getChannelFromGPlusId(String plusid, String uri, String developerkey) throws Exception { - - String endid = uri; - - try { - String json = YTAPI - .readJsonFromUrl("https://www.googleapis.com/plus/v1/people/" + plusid + "?key=" + developerkey); - JsonObject jb = gson.fromJson(json, JsonObject.class); - JsonObject jo = jb; - JsonArray ja = jo.get("urls").getAsJsonArray(); - for (int i = 0; i < ja.size(); i++) { - JsonObject jsob = (JsonObject) ja.get(i); - if (jsob.get("value").getAsString().toLowerCase().contains("youtube")) { - return jsob.get("value").getAsString(); - } - } - return "No Google Plus Data To Find The Channel"; - } catch (NullPointerException e) { - e.printStackTrace(); - return "No Google Plus Data To Find The Channel"; - } - - } - - public static YoutubeChannel getYTChannelFromUri(String uri) { - try { - System.out.println(uri); - YoutubeChannel ch; - String json = YTAPI.readJsonFromUrl(uri + "?alt=json"); - JsonObject jb = gson.fromJson(json, JsonObject.class); - String username = jb.get("entry").getAsJsonObject().get("yt$username").getAsJsonObject().get("$t") - .getAsString(); - String about_us = jb.get("entry").getAsJsonObject().get("content").getAsJsonObject().get("$t") - .getAsString(); - String title = jb.get("entry").getAsJsonObject().get("title").getAsJsonObject().get("$t").getAsString(); - String subscribers = jb.get("entry").getAsJsonObject().get("yt$statistics").getAsJsonObject() - .get("subscriberCount").getAsString(); - String gplusid = jb.get("entry").getAsJsonObject().get("yt$googlePlusUserId").getAsJsonObject().get("$t") - .getAsString(); - String firstname = ""; - String lastname = ""; - if (jb.get("entry").getAsJsonObject().get("yt$firstName") != null) { - firstname = jb.get("entry").getAsJsonObject().get("yt$firstName").getAsJsonObject().get("$t") - .getAsString(); - } - if (jb.get("entry").getAsJsonObject().get("yt$lastName") != null) { - - lastname = jb.get("entry").getAsJsonObject().get("yt$lastName").getAsJsonObject().get("$t") - .getAsString(); - - } - String location = jb.get("entry").getAsJsonObject().get("yt$location").getAsJsonObject().get("$t") - .getAsString(); - - String lastwebaccess = jb.get("entry").getAsJsonObject().get("yt$statistics").getAsJsonObject() - .get("lastWebAccess").getAsString(); - int videowatchcount = jb.get("entry").getAsJsonObject().get("yt$statistics").getAsJsonObject() - .get("videoWatchCount").getAsInt(); - int viewcount = jb.get("entry").getAsJsonObject().get("yt$statistics").getAsJsonObject().get("viewCount") - .getAsInt(); - String totaluploadviews = jb.get("entry").getAsJsonObject().get("yt$statistics").getAsJsonObject() - .get("totalUploadViews").getAsString(); - String avatar = jb.get("entry").getAsJsonObject().get("media$thumbnail").getAsJsonObject().get("url") - .getAsString(); - ch = new YoutubeChannel(about_us, title, username, subscribers, gplusid, firstname, lastname, location, - lastwebaccess, videowatchcount, viewcount, totaluploadviews, avatar); - return ch; - } catch (Exception err) { - err.printStackTrace(); - return null; - } - } - - public static YoutubeChannel getYTChannelFromName(String channel) { - return getYTChannelFromUri("http://gdata.youtube.com/feeds/api/users/" + channel); - } - -} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/youtube/YoutubeChannel.java b/src/main/java/eu/univento/core/api/youtube/YoutubeChannel.java deleted file mode 100644 index 951260b..0000000 --- a/src/main/java/eu/univento/core/api/youtube/YoutubeChannel.java +++ /dev/null @@ -1,242 +0,0 @@ -package eu.univento.core.api.youtube; - -import java.beans.ConstructorProperties; - -public class YoutubeChannel { - String about_us; - String title; - String username; - String subscribers; - String googleplusid; - String firstname = ""; - String lastname = ""; - String location; - String lastwebaccess; - int videoWatchCount; - int viewcount; - String totaluploadViews; - String avatar; - - @ConstructorProperties({ "about_us", "title", "username", "subscribers", "googleplusid", "firstname", "lastname", - "location", "lastwebaccess", "videoWatchCount", "viewcount", "totaluploadViews", "avatar" }) - public YoutubeChannel(String about_us, String title, String username, String subscribers, String googleplusid, - String firstname, String lastname, String location, String lastwebaccess, int videoWatchCount, - int viewcount, String totaluploadViews, String avatar) { - this.about_us = about_us; - this.title = title; - this.username = username; - this.subscribers = subscribers; - this.googleplusid = googleplusid; - this.firstname = firstname; - this.lastname = lastname; - this.location = location; - this.lastwebaccess = lastwebaccess; - this.videoWatchCount = videoWatchCount; - this.viewcount = viewcount; - this.totaluploadViews = totaluploadViews; - this.avatar = avatar; - } - - public String getAbout_us() { - return this.about_us; - } - - public String getTitle() { - return this.title; - } - - public String getUsername() { - return this.username; - } - - public String getSubscribers() { - return this.subscribers; - } - - public String getGoogleplusid() { - return this.googleplusid; - } - - public String getFirstname() { - return this.firstname; - } - - public String getLastname() { - return this.lastname; - } - - public String getLocation() { - return this.location; - } - - public String getLastwebaccess() { - return this.lastwebaccess; - } - - public int getVideoWatchCount() { - return this.videoWatchCount; - } - - public int getViewcount() { - return this.viewcount; - } - - public String getTotaluploadViews() { - return this.totaluploadViews; - } - - public String getAvatar() { - return this.avatar; - } - - public void setAbout_us(String about_us) { - this.about_us = about_us; - } - - public void setTitle(String title) { - this.title = title; - } - - public void setUsername(String username) { - this.username = username; - } - - public void setSubscribers(String subscribers) { - this.subscribers = subscribers; - } - - public void setGoogleplusid(String googleplusid) { - this.googleplusid = googleplusid; - } - - public void setFirstname(String firstname) { - this.firstname = firstname; - } - - public void setLastname(String lastname) { - this.lastname = lastname; - } - - public void setLocation(String location) { - this.location = location; - } - - public void setLastwebaccess(String lastwebaccess) { - this.lastwebaccess = lastwebaccess; - } - - public void setVideoWatchCount(int videoWatchCount) { - this.videoWatchCount = videoWatchCount; - } - - public void setViewcount(int viewcount) { - this.viewcount = viewcount; - } - - public void setTotaluploadViews(String totaluploadViews) { - this.totaluploadViews = totaluploadViews; - } - - public void setAvatar(String avatar) { - this.avatar = avatar; - } - - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof YoutubeChannel)) - return false; - YoutubeChannel other = (YoutubeChannel) o; - if (!other.canEqual(this)) - return false; - Object this$about_us = getAbout_us(); - Object other$about_us = other.getAbout_us(); - if (this$about_us == null ? other$about_us != null : !this$about_us.equals(other$about_us)) - return false; - Object this$title = getTitle(); - Object other$title = other.getTitle(); - if (this$title == null ? other$title != null : !this$title.equals(other$title)) - return false; - Object this$username = getUsername(); - Object other$username = other.getUsername(); - if (this$username == null ? other$username != null : !this$username.equals(other$username)) - return false; - Object this$subscribers = getSubscribers(); - Object other$subscribers = other.getSubscribers(); - if (this$subscribers == null ? other$subscribers != null : !this$subscribers.equals(other$subscribers)) - return false; - Object this$googleplusid = getGoogleplusid(); - Object other$googleplusid = other.getGoogleplusid(); - if (this$googleplusid == null ? other$googleplusid != null : !this$googleplusid.equals(other$googleplusid)) - return false; - Object this$firstname = getFirstname(); - Object other$firstname = other.getFirstname(); - if (this$firstname == null ? other$firstname != null : !this$firstname.equals(other$firstname)) - return false; - Object this$lastname = getLastname(); - Object other$lastname = other.getLastname(); - if (this$lastname == null ? other$lastname != null : !this$lastname.equals(other$lastname)) - return false; - Object this$location = getLocation(); - Object other$location = other.getLocation(); - if (this$location == null ? other$location != null : !this$location.equals(other$location)) - return false; - Object this$lastwebaccess = getLastwebaccess(); - Object other$lastwebaccess = other.getLastwebaccess(); - if (this$lastwebaccess == null ? other$lastwebaccess != null : !this$lastwebaccess.equals(other$lastwebaccess)) - return false; - if (getVideoWatchCount() != other.getVideoWatchCount()) - return false; - if (getViewcount() != other.getViewcount()) - return false; - Object this$totaluploadViews = getTotaluploadViews(); - Object other$totaluploadViews = other.getTotaluploadViews(); - if (this$totaluploadViews == null ? other$totaluploadViews != null - : !this$totaluploadViews.equals(other$totaluploadViews)) - return false; - Object this$avatar = getAvatar(); - Object other$avatar = other.getAvatar(); - return this$avatar == null ? other$avatar == null : this$avatar.equals(other$avatar); - } - - public boolean canEqual(Object other) { - return other instanceof YoutubeChannel; - } - - public int hashCode() { - int PRIME = 31; - int result = 1; - Object $about_us = getAbout_us(); - result = result * 31 + ($about_us == null ? 0 : $about_us.hashCode()); - Object $title = getTitle(); - result = result * 31 + ($title == null ? 0 : $title.hashCode()); - Object $username = getUsername(); - result = result * 31 + ($username == null ? 0 : $username.hashCode()); - Object $subscribers = getSubscribers(); - result = result * 31 + ($subscribers == null ? 0 : $subscribers.hashCode()); - Object $googleplusid = getGoogleplusid(); - result = result * 31 + ($googleplusid == null ? 0 : $googleplusid.hashCode()); - Object $firstname = getFirstname(); - result = result * 31 + ($firstname == null ? 0 : $firstname.hashCode()); - Object $lastname = getLastname(); - result = result * 31 + ($lastname == null ? 0 : $lastname.hashCode()); - Object $location = getLocation(); - result = result * 31 + ($location == null ? 0 : $location.hashCode()); - Object $lastwebaccess = getLastwebaccess(); - result = result * 31 + ($lastwebaccess == null ? 0 : $lastwebaccess.hashCode()); - result = result * 31 + getVideoWatchCount(); - result = result * 31 + getViewcount(); - Object $totaluploadViews = getTotaluploadViews(); - result = result * 31 + ($totaluploadViews == null ? 0 : $totaluploadViews.hashCode()); - Object $avatar = getAvatar(); - return result * 31 + ($avatar == null ? 0 : $avatar.hashCode()); - } - - public String toString() { - return "YoutubeChannel(about_us=" + getAbout_us() + ", title=" + getTitle() + ", username=" + getUsername() - + ", subscribers=" + getSubscribers() + ", googleplusid=" + getGoogleplusid() + ", firstname=" - + getFirstname() + ", lastname=" + getLastname() + ", location=" + getLocation() + ", lastwebaccess=" - + getLastwebaccess() + ", videoWatchCount=" + getVideoWatchCount() + ", viewcount=" + getViewcount() - + ", totaluploadViews=" + getTotaluploadViews() + ", avatar=" + getAvatar() + ")"; - } -} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/commands/Ban.java b/src/main/java/eu/univento/core/commands/Ban.java deleted file mode 100644 index 7164573..0000000 --- a/src/main/java/eu/univento/core/commands/Ban.java +++ /dev/null @@ -1,115 +0,0 @@ -package eu.univento.core.commands; - -import eu.univento.core.Core; -import eu.univento.core.api.AutoCommand; -import eu.univento.core.api.languages.Messages; -import eu.univento.core.api.player.CustomPlayer; -import eu.univento.core.api.player.Ranks; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -/** - * command to ban players - * @author joethei - * @version 1.0 - */ -public class Ban extends AutoCommand{ - - /** - * @param plugin main class - * @param command command to execute - * @param description describes the command - * @param aliases aliases of command - */ - public Ban(Core plugin, String command, String description, String... aliases) { - super(plugin, command, description, aliases); - } - - @Override - public boolean execute(CommandSender sender, String label, String[] args) { - if(sender instanceof Player) { - CustomPlayer p = CustomPlayer.getPlayer(sender.getName()); - Messages msgs = new Messages(p); - if(p.isAllowed(Ranks.Moderator)) { - if(args.length == 2) { - if(Bukkit.getPlayer(args[0]) != null) { - CustomPlayer t = CustomPlayer.getPlayer(args[0]); - if(getReasons().containsValue(args[1])) { - int id = getKey(args[1]); - }else { - p.sendMessage(msgs.PREFIX() + msgs.Core_BAN_NO_REASON()); - } - }else { - p.sendMessage(msgs.PREFIX() + msgs.NOT_ONLINE(args[0])); - } - }else { - p.sendMessage(msgs.PREFIX() + msgs.Core_BAN_USAGE()); - } - }else { - sender.sendMessage(msgs.NO_PERMS()); - } - }else { - sender.sendMessage(Messages.Console.NOT_A_PLAYER); - } - return true; - } - - @Override - public List tabComplete(CommandSender sender, String label, String[] args) { - List list = new ArrayList<>(); - for(int i = 0; i >= getReasons().size(); i++) { - list.add(getReasons().get(i)); - } - return list; - } - - /** - * @return all possible ban reasons - */ - private HashMap getReasons() { - HashMap map = new HashMap<>(); - - map.put(1, "Hacking"); - map.put(2, "Griefing"); - map.put(3, "Bugusing"); - map.put(4, "Insult"); - map.put(5, "Spam"); - map.put(6, "Banumgehung"); - map.put(7, "Advertising"); - map.put(8, "Trolling"); - - return map; - } - - /** - * @return ban durations to reason - */ - private HashMap getBanDurations() { - HashMap map = new HashMap<>(); - - map.put(1, 60); - map.put(2, 30); - map.put(3, 20); - map.put(4, 10); - map.put(5, 5); - map.put(6, 120); - map.put(7, 15); - map.put(8, 25); - - return map; - } - - private Integer getKey(String value) { - for(int key : getReasons().keySet()) { - if(getReasons().get(key).equals(value)) { - return key; - } - } - return null; - } -} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/commands/Fix.java b/src/main/java/eu/univento/core/commands/Fix.java index dd5a6fb..3fa2cee 100644 --- a/src/main/java/eu/univento/core/commands/Fix.java +++ b/src/main/java/eu/univento/core/commands/Fix.java @@ -66,6 +66,6 @@ public class Fix extends AutoCommand{ @Override public List tabComplete(CommandSender sender, String label, String[] args) { - return Bukkit.getOnlinePlayers().stream().map(Player::getDisplayName).collect(Collectors.toList()); + return Core.getOnlinePlayers().stream().map(CustomPlayer::getDisplayName).collect(Collectors.toList()); } } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/commands/RunAs.java b/src/main/java/eu/univento/core/commands/RunAs.java index cf48e61..e6c0b42 100644 --- a/src/main/java/eu/univento/core/commands/RunAs.java +++ b/src/main/java/eu/univento/core/commands/RunAs.java @@ -63,7 +63,7 @@ public class RunAs extends AutoCommand{ @Override public List tabComplete(CommandSender sender, String label, String[] args) { - return Bukkit.getOnlinePlayers().stream().map(Player::getDisplayName).collect(Collectors.toList()); + return Core.getOnlinePlayers().stream().map(CustomPlayer::getDisplayName).collect(Collectors.toList()); } diff --git a/src/main/java/eu/univento/core/commands/SetRank.java b/src/main/java/eu/univento/core/commands/SetRank.java index 6a47ed0..3e1efb4 100644 --- a/src/main/java/eu/univento/core/commands/SetRank.java +++ b/src/main/java/eu/univento/core/commands/SetRank.java @@ -35,8 +35,9 @@ public class SetRank extends AutoCommand{ CustomPlayer p = CustomPlayer.getPlayer(sender.getName()); if(p.isAllowed(Ranks.HeadBuilder)) { if(args.length == 2) { - Ranks rank = Ranks.valueOf(args[1]); - if(rank != null) { + Ranks rank; + try{ + rank = Ranks.valueOf(args[1]); if(Bukkit.getPlayer(args[0]) != null) { CustomPlayer player = CustomPlayer.getPlayer(args[0]); if(player.isAllowed(rank)) { @@ -47,36 +48,36 @@ public class SetRank extends AutoCommand{ if(p.isAllowed(Ranks.Admin)) { player.setRank(rank); p.sendMessage(p.getMessages().PREFIX() + p.getMessages().Core_SETRANK_SET(player, player.getRank())); - player.kickPlayer(player.getMessages().Core_SETRANK_KICK()); + refreshTablist(); } if(p.isAllowed(Ranks.SrDeveloper) && rank.equals(Ranks.Developer)) { player.setRank(Ranks.Developer); p.sendMessage(p.getMessages().PREFIX() + p.getMessages().Core_SETRANK_SET(player, Ranks.Developer)); - player.kickPlayer(player.getMessages().Core_SETRANK_KICK()); + refreshTablist(); } if(p.isAllowed(Ranks.SrModerator) && rank.equals(Ranks.Moderator)) { player.setRank(Ranks.Moderator); p.sendMessage(p.getMessages().PREFIX() + p.getMessages().Core_SETRANK_SET(player, Ranks.Moderator)); - player.kickPlayer(player.getMessages().Core_SETRANK_KICK()); - }if(p.isAllowed(Ranks.SrModerator) && rank.equals(Ranks.Supporter)) { + refreshTablist(); + } + if(p.isAllowed(Ranks.SrModerator) && rank.equals(Ranks.Supporter)) { player.setRank(Ranks.Supporter); p.sendMessage(p.getMessages().PREFIX() + p.getMessages().Core_SETRANK_SET(player, Ranks.Supporter)); - player.kickPlayer(player.getMessages().Core_SETRANK_KICK()); + refreshTablist(); } if(p.isAllowed(Ranks.HeadBuilder) && rank.equals(Ranks.Builder)) { player.setRank(Ranks.Builder); p.sendMessage(p.getMessages().PREFIX() + p.getMessages().Core_SETRANK_SET(player, Ranks.Builder)); - player.kickPlayer(player.getMessages().Core_SETRANK_KICK()); + refreshTablist(); } }else { p.sendMessage(p.getMessages().NOT_ONLINE(args[0])); - } - }else { - p.sendMessage(p.getMessages().Core_SETRANK_NO_RANK()); - } - }else { - p.sendMessage(p.getMessages().Core_SETRANK_NO_RANK()); - } + } + }catch(IllegalArgumentException ex) { + ex.printStackTrace(); + } + p.sendMessage(p.getMessages().Core_SETRANK_NO_RANK()); + } }else { p.sendMessage(p.getMessages().NO_PERMS()); } @@ -91,6 +92,7 @@ public class SetRank extends AutoCommand{ List list = Bukkit.getOnlinePlayers().stream().map(Player::getDisplayName).collect(Collectors.toList()); list.add("Admin"); + list.add("SrDeveloper"); list.add("Developer"); list.add("SrModerator"); list.add("Moderator"); @@ -103,7 +105,9 @@ public class SetRank extends AutoCommand{ return list; } - - + + private void refreshTablist() { + Core.getOnlinePlayers().forEach(CustomPlayer::refreshTablist); + } } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/commands/Stats.java b/src/main/java/eu/univento/core/commands/Stats.java index b2708d3..bd54be6 100644 --- a/src/main/java/eu/univento/core/commands/Stats.java +++ b/src/main/java/eu/univento/core/commands/Stats.java @@ -1,7 +1,3 @@ -/* - * Copyright (c) univento.eu 2016. Any attempt to use these program(s) without permission may result in a penalty of up to 1.000€ - */ - package eu.univento.core.commands; import eu.univento.core.Core; diff --git a/src/main/java/eu/univento/core/commands/TS.java b/src/main/java/eu/univento/core/commands/TS.java deleted file mode 100644 index c72c32e..0000000 --- a/src/main/java/eu/univento/core/commands/TS.java +++ /dev/null @@ -1,42 +0,0 @@ -package eu.univento.core.commands; - -import eu.univento.core.Core; -import eu.univento.core.api.AutoCommand; -import eu.univento.core.api.player.CustomPlayer; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import java.util.List; - -/** - * sets ts groups according to player rank - * @author joethei - * @version 1.0 - */ -public class TS extends AutoCommand{ - - /** - * @param plugin main class - * @param command command to execute - * @param description describes the command - * @param aliases aliases of command - */ - public TS(Core plugin, String command, String description, String... aliases) { - super(plugin, command, description, aliases); - } - - @Override - public boolean execute(CommandSender sender, String label, String[] args) { - if(sender instanceof Player) { - CustomPlayer p = CustomPlayer.getPlayer(sender.getName()); - p.sendMessage("Der TS Befehl ist momentan deaktivert"); - } - return true; - } - - @Override - public List tabComplete(CommandSender sender, String label, String[] args) { - return null; - } - -} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/listeners/JoinQuit.java b/src/main/java/eu/univento/core/listeners/JoinQuit.java index 52e51e9..6609ada 100644 --- a/src/main/java/eu/univento/core/listeners/JoinQuit.java +++ b/src/main/java/eu/univento/core/listeners/JoinQuit.java @@ -1,6 +1,7 @@ package eu.univento.core.listeners; import eu.univento.core.Core; +import eu.univento.core.api.Title; import eu.univento.core.api.Utils; import eu.univento.core.api.player.*; import eu.univento.core.api.server.ServerSettings; @@ -13,10 +14,12 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; -import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.scoreboard.Team; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; import java.util.HashMap; /** @@ -52,24 +55,33 @@ public class JoinQuit implements Listener { labyModFeatures.put(LabyMod.ARMOR, false); labyModFeatures.put(LabyMod.POTIONS, false); labyModFeatures.put(LabyMod.ANIMATIONS, false); + labyModFeatures.put(LabyMod.EXTRAS, false); p.setLabyModFeatures(labyModFeatures); p.sendMessage(new BetterPvP().getCodeString()); + + //disable code for minimap mod + p.sendMessage("§A§n§t§i§M§i§n§i§m§a§p"); + p.sendMessage("§3 §6 §3 §6 §3 §6 §e"); + p.sendMessage("§0§0§1§2§3§5§e§f"); + p.sendMessage("§0§0§c§d§e§f"); + + assert getPayload() != null; + p.sendPluginMessage(Core.getInstance(), "schematica", getPayload()); } - p.updateDatabaseEntry(); p.setGameMode(ServerSettings.getGameMode()); p.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); p.initScoreboard(); + Title.sendTabTitle(p, p.getMessages().Core_TAB_TITLE() + Bukkit.getServerName(), p.getMessages().TAB_PREFIX()); if (p.isNicked() && !ServerSettings.isLobby()) { p.setNick(NickName.getRandomNick()); } - for (CustomPlayer player : Core.getOnlinePlayers()) { + for(CustomPlayer player : Core.getOnlinePlayers()) { p.getScoreboard().getTeam(player.getTeam().getName()).addEntry(player.getDisplayName()); player.getScoreboard().getTeam(p.getTeam().getName()).addEntry(p.getDisplayName()); } - - - } + p.setCollidable(false); +} @EventHandler public void onQuit(PlayerQuitEvent e) { @@ -82,7 +94,7 @@ public class JoinQuit implements Listener { for (Team team : p.getScoreboard().getTeams()) { team.removeEntry(p.getDisplayName()); } - p.onLeave(); + Bukkit.getScheduler().runTaskLater(Core.getInstance(), p::onLeave, 5L); } @EventHandler(priority = EventPriority.HIGHEST) @@ -90,4 +102,20 @@ public class JoinQuit implements Listener { e.setLeaveMessage(null); } + private byte[] getPayload() { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream); + try { + dataOutputStream.writeByte(0); + dataOutputStream.writeBoolean(false); + dataOutputStream.writeBoolean(false); + dataOutputStream.writeBoolean(true); + + return byteArrayOutputStream.toByteArray(); + } catch (IOException ex) { + ex.printStackTrace(); + return null; + } + } + } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/listeners/PluginMessenger.java b/src/main/java/eu/univento/core/listeners/PluginMessenger.java index f53191c..9c46183 100644 --- a/src/main/java/eu/univento/core/listeners/PluginMessenger.java +++ b/src/main/java/eu/univento/core/listeners/PluginMessenger.java @@ -1,22 +1,63 @@ package eu.univento.core.listeners; +import com.google.common.io.ByteArrayDataOutput; +import com.google.common.io.ByteStreams; +import eu.univento.core.Core; import eu.univento.core.antihack.Hack; import eu.univento.core.api.player.CustomPlayer; import org.bukkit.entity.Player; import org.bukkit.plugin.messaging.PluginMessageListener; -public class PluginMessenger implements PluginMessageListener{ +import java.io.UnsupportedEncodingException; +import java.util.logging.Level; + +public class PluginMessenger implements PluginMessageListener { @Override public void onPluginMessageReceived(String channel, Player player, byte[] data) { CustomPlayer p = CustomPlayer.getPlayer(player); - if(channel.equals("WDL|INIT")) { - p.warn(Hack.WDL); - p.kickPlayer(p.getMessage("Prefix") + p.getMessage("Hack.WorldDownloader")); + if (channel.equals("WDL|INIT")) { + String version = null; + if(data.length == 0) version = "vor 1.8d"; + else try { + version = new String(data, "UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + Core.log(Level.INFO, p.getName() + " hat WDL installiert. Version : " + version); + p.sendMessage(p.getMessage("Prefix") + p.getMessage("Hack.WorldDownloader")); } - if(channel.equals("PERMISSIONSREPL") && new String(data).contains("mod.worlddownloader")) { + if(channel.equals("WDL|CONTROL")) { + p.sendPluginMessage(Core.getInstance(), "WDL|CONTROL", createWDLPacket(false, 0, false, false, false, false)); + } + if (channel.equals("PERMISSIONSREPL") && new String(data).contains("mod.worlddownloader")) { p.warn(Hack.WDL); - p.kickPlayer(p.getMessage("Prefix") + p.getMessage("Hack.WorldDownloader")); + p.sendMessage(p.getMessage("Prefix") + p.getMessage("Hack.WorldDownloader")); + } + if(channel.equals("5zig_Set")) { + try { + String version = new String(data, "UTF-8"); + Core.log(Level.INFO, p.getName() + " hat den 5zig Mod Version : " + version); + //TODO: disable only some 5zig mod settings | https://gist.github.com/5zig/35e0854504edda418f4b + p.sendPluginMessage(Core.getInstance(), "5zig_Set", new byte[]{0x01 | 0x02 | 0x04 | 0x08 | 0x10}); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } } } + + private byte[] createWDLPacket(boolean globalIsEnabled, int saveRadius, boolean cacheChunks, boolean saveEntities, boolean saveTileEntities, boolean saveContainers) { + ByteArrayDataOutput output = ByteStreams.newDataOutput(); + + output.writeInt(1); + + output.writeBoolean(globalIsEnabled); + output.writeInt(saveRadius); + output.writeBoolean(cacheChunks && globalIsEnabled); + output.writeBoolean(saveEntities && globalIsEnabled); + output.writeBoolean(saveTileEntities && globalIsEnabled); + output.writeBoolean(saveContainers && saveTileEntities && globalIsEnabled); + + return output.toByteArray(); + } } diff --git a/src/main/resources/language_de.properties b/src/main/resources/language_de.properties index 1194657..7164316 100644 --- a/src/main/resources/language_de.properties +++ b/src/main/resources/language_de.properties @@ -9,3 +9,23 @@ Kick_full = Command_no_found = §cDieser Befehl konnte nicht gefunden werden Core.fix_own = §7Du wurdest §egefixt + +Lobby.Item.Navigator = §eNavigator +Lobby.Item.LobbySwitcher = Lobby Wechsler +Lobby.Item.Adventure = §eAbenteuermodus +Lobby.Item.FunChest = FunChest +Lobby.Item.Profile = §eDein Profil +Lobby.Item.Youtuber = §5Youtuber Menü +Lobby.Item.YT.Forcefield = §cSchutzschild +Lobby.Item.YT.Nick.on = Nickname ist an +Lobby.Item.YT.Nick.off = Nickname ist aus +Lobby.Item.YT.SilentLobby = Ruhige Lobby +Lobby.Item.YT.Extras = Extras +Lobby.Item.YT.Back = Zurück + +Lobby.Menu.Nav.Spawn = Spawn +Lobby.Menu.Nav.Strive = Strive +Lobby.Menu.Nav.Hustle = Hustle +Lobby.Menu.Nav.Build = Bau-Server + +Hack.WorldDownloader = WorldDownloader wurde erkannt. \ No newline at end of file