diff --git a/.classpath b/.classpath deleted file mode 100644 index 7935976..0000000 --- a/.classpath +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml deleted file mode 100644 index b84c18f..0000000 --- a/.gitlab-ci.yml +++ /dev/null @@ -1,10 +0,0 @@ -stages: - - build - - test - - deploy - -job1: - stage: build - script: - - find -name "*.java" > sources.txt - - javac bin @sources.txt \ No newline at end of file diff --git a/.project b/.project deleted file mode 100644 index 22f9e97..0000000 --- a/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - Core - - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - - diff --git a/README.md b/README.md index 74ffd2e..48e6420 100644 --- a/README.md +++ b/README.md @@ -2,4 +2,4 @@ Core Plugin for univento.eu Written by joethei -API Doku at: http://joethei.de/javadocs/Core \ No newline at end of file +API Doku can be found at: http://dev.univento.eu/docs/Core \ No newline at end of file diff --git a/src/eu/univento/cloud/client/CloudClient.java b/src/eu/univento/cloud/client/CloudClient.java new file mode 100644 index 0000000..084a26f --- /dev/null +++ b/src/eu/univento/cloud/client/CloudClient.java @@ -0,0 +1,33 @@ +package eu.univento.cloud.client; + +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioSocketChannel; + +/** + * @author joethei + * @version 0.1 + */ +public class CloudClient { + +public CloudClient() throws Exception{ + NioEventLoopGroup child = new NioEventLoopGroup(); + try{ + Bootstrap bootstrap = new Bootstrap(); + bootstrap.channel(NioSocketChannel.class); + bootstrap.group(child); + bootstrap.handler(new ChannelInitializer() { + @Override + protected void initChannel(Channel channel) throws Exception { + + } + }); + bootstrap.connect("master.univento.eu", 8000).sync().channel().closeFuture().sync(); + }finally { + child.shutdownGracefully(); + } +} + +} \ No newline at end of file diff --git a/src/eu/univento/core/Core.java b/src/eu/univento/core/Core.java index 77be973..23db3a0 100644 --- a/src/eu/univento/core/Core.java +++ b/src/eu/univento/core/Core.java @@ -1,36 +1,23 @@ package eu.univento.core; -import java.io.IOException; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.logging.Level; -import java.util.logging.Logger; - +import eu.univento.core.api.BossBar; +import eu.univento.core.api.Config; +import eu.univento.core.api.SignInput; +import eu.univento.core.api.database.MySQL; +import eu.univento.core.api.events.MoveEventFilter; +import eu.univento.core.api.fakeplayer.PlayerKi; +import eu.univento.core.api.player.TeamSpeak; +import eu.univento.core.api.server.ServerSettings; +import eu.univento.core.commands.*; +import eu.univento.core.listeners.*; import org.bukkit.Bukkit; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; -import eu.univento.core.api.Config; -import eu.univento.core.api.Messages; -import eu.univento.core.api.MySQL; -import eu.univento.core.api.Settings; -import eu.univento.core.api.player.CustomPlayer; -import eu.univento.core.api.player.Perms; -import eu.univento.core.commands.Ban; -import eu.univento.core.commands.Build; -import eu.univento.core.commands.Fix; -import eu.univento.core.commands.GameMode; -import eu.univento.core.commands.GlobalMute; -import eu.univento.core.commands.RunAs; -import eu.univento.core.commands.SetRank; -import eu.univento.core.commands.SystemInfo; -import eu.univento.core.commands.TS; -import eu.univento.core.commands.Vanish; -import eu.univento.core.commands.Youtuber; -import eu.univento.core.listeners.Blocks; -import eu.univento.core.listeners.Chat; -import eu.univento.core.listeners.Commands; -import eu.univento.core.listeners.JoinQuit; +import java.io.IOException; +import java.sql.SQLException; +import java.util.logging.Level; +import java.util.logging.Logger; /** * main class @@ -38,6 +25,8 @@ import eu.univento.core.listeners.JoinQuit; * @version 1.0 */ public class Core extends JavaPlugin{ + + //TODO: rewrite time critical database functions from MySQL to MongoDB /** * plugin instance @@ -60,12 +49,12 @@ public class Core extends JavaPlugin{ public static MySQL returnSQL() { return sql; } - - /** - * nick names of players - */ - public static HashMap nicks = new HashMap(); - + + private static TeamSpeak ts; + + public static TeamSpeak getTs() { + return ts; + } /** * logging and stuff */ @@ -76,40 +65,51 @@ public class Core extends JavaPlugin{ * @param string String */ public static void log(Level level, String string) { - log.log(level, "[" + Messages.CONSOLE_PREFIX + Core.getInstance().getDescription().getName() + "] " + string); + if(ServerSettings.isDebug()) { + log.log(level, "[Core] " + string); + } } + + private SignInput signInput; + + public SignInput getSignInput() { + return signInput; + } @Override public void onEnable() { - Settings.setDebug(true); - Settings.setBuild(true); + ServerSettings.setDebug(true); try { Config.writeDefault(); } catch (ClassNotFoundException | SQLException | IOException e) { e.printStackTrace(); } instance = this; - if(Settings.isDebug()) log(Level.INFO, "Debug Modus aktiviert"); - Perms.initScoreboard(); + this.signInput = new SignInput(this); + if(ServerSettings.isDebug()) log(Level.INFO, "Debug Modus aktiviert"); PluginManager pm = Bukkit.getPluginManager(); pm.registerEvents(new Commands(), this); pm.registerEvents(new JoinQuit(), this); pm.registerEvents(new Chat(), this); pm.registerEvents(new Blocks(), this); + pm.registerEvents(new Events(), this); + pm.registerEvents(new MoveEventFilter(getServer()), this); + pm.registerEvents(new BossBar(), this); + pm.registerEvents(new PlayerKi(), this); - if(Settings.isDebug()) log(Level.INFO, "Events registriert"); + log(Level.INFO, "Events registriert"); String[] fix = {""}; - new Fix(this, "fix", "Fixe dich oder andere Spieler", fix); + if(ServerSettings.isGame()) new Fix(this, "fix", "Fixe dich oder andere Spieler", fix); String[] runas = {""}; new RunAs(this, "RunAs", "Sende einen Befehl als ein anderer Spieler", runas); String[] systeminfo = {""}; - new SystemInfo(this, "SystemInfo", "Gibt Infos über den Server aus", systeminfo); + new SystemInfo(this, "SystemInfo", "Gibt Infos über den ServerPinger aus", systeminfo); String[] vanish = {""}; - new Vanish(this, "vanish", "Lässt dich verschwinden", vanish); + new Vanish(this, "vanish", "Lässt dich verschwinden", vanish); String[] gamemode = {"gm"}; new GameMode(this, "gamemode" , "Setzt deinen GameMode", gamemode); @@ -118,7 +118,7 @@ public class Core extends JavaPlugin{ new SetRank(this, "setrank" , "Setzt den Rang eines Spielers", setrank); String[] globalmute = {"globalmute"}; - new GlobalMute(this, "globalmute", "Muted den gesamten Server", globalmute); + new GlobalMute(this, "globalmute", "Muted den gesamten ServerPinger", globalmute); String[] youtuber = {""}; new Youtuber(this, "youtuber", "setzt Spieler in den Youtuber Rang", youtuber); @@ -129,51 +129,31 @@ public class Core extends JavaPlugin{ String[] ban = {""}; new Ban(this, "ban", "Bannt Spieler", ban); - if(Settings.isBuild()) { - String[] build = {"b"}; - new Build(this, "build", "Setzt den Spieler in den Bau Modus", build); - - if(Settings.isDebug()) log(Level.INFO, "Build Modus aktiviert"); + String[] build = {"b"}; + new Build(this, "build", "Setzt den Spieler in den Bau Modus", build); + + String[] chatclear = {"cc"}; + new ChatClear(this, "chatclear", "Cleart den Chat", chatclear); + + if(ServerSettings.isGame()) { + String[] nick = {""}; + new Nick(this, "nick", "ändert das Verhalten des Nicksystems", nick); + log(Level.INFO, "/nick aktiviert"); } - if(Settings.isDebug()) log(Level.INFO, "Alle Befehle registriert"); - try - { - MySQL tempSQL = sql; - tempSQL.openConnection(); - - tempSQL.getConnection().createStatement().execute("CREATE TABLE IF NOT EXISTS PlayerData(ID bigint PRIMARY KEY auto_increment, player_uuid varchar(50), FirstJoin TIMESTAMP default now(), Coins bigint, mute boolean, Rank varchar(15),TS_ID bigint, Friends varchar(2500), nick boolean);"); - if(Settings.isDebug()) log(Level.INFO, "MySQL PlayerData ausgeführt"); - - tempSQL.getConnection().createStatement().execute("CREATE TABLE IF NOT EXISTS bans(ID bigint PRIMARY KEY auto_increment, player_uuid varchar(50), Reason varchar(50), who varchar(50));"); - if(Settings.isDebug()) log(Level.INFO, "MySQL Bans erstellt"); - - tempSQL.getConnection().createStatement().execute("CREATE TABLE IF NOT EXISTS bugs(ID bigint PRIMARY KEY auto_increment, player_uuid varchar(50), time timestamp, msg varchar(250));"); - if(Settings.isDebug()) log(Level.INFO, "MySQL Bugs erstellt"); - - tempSQL.getConnection().createStatement().execute("CREATE TABLE IF NOT EXISTS Friends(ID bigint PRIMARY KEY auto_increment, player_uuid VARCHAR(64), Friends VARCHAR(2500));"); - if(Settings.isDebug()) log(Level.INFO, "MySQL Friends erstellt"); - - tempSQL.getConnection().createStatement().execute("CREATE TABLE IF NOT EXISTS Messages(ID bigint PRIMARY KEY auto_increment,Ident varchar(25), Message varchar(250));"); - if(Settings.isDebug()) log(Level.INFO, "MySQL Messages erstellt"); - - tempSQL.closeConnection(); - } catch (SQLException | ClassNotFoundException e) { - e.printStackTrace(); - } + log(Level.INFO, "Alle Befehle registriert"); + Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); - try { - Messages.writeDefault(); - Messages.readStrings(); - } catch (ClassNotFoundException | SQLException e) { - e.printStackTrace(); - } + + this.ts = new TeamSpeak(); + log(Level.INFO, "Plugin ver. " + getDescription().getVersion() + " gestartet"); } @Override public void onDisable() { - Core.log(Level.INFO, "Plugin beendet"); + log(Level.INFO, "Plugin beendet"); + getTs().disconnect(); } } \ No newline at end of file diff --git a/src/eu/univento/core/api/Actionbar.java b/src/eu/univento/core/api/Actionbar.java index bd1cfc6..924b36d 100644 --- a/src/eu/univento/core/api/Actionbar.java +++ b/src/eu/univento/core/api/Actionbar.java @@ -1,38 +1,18 @@ package eu.univento.core.api; -import java.lang.reflect.Field; - -import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; -import org.bukkit.entity.Player; - import net.minecraft.server.v1_8_R3.IChatBaseComponent; import net.minecraft.server.v1_8_R3.IChatBaseComponent.ChatSerializer; import net.minecraft.server.v1_8_R3.PacketPlayOutChat; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; +import org.bukkit.entity.Player; public class Actionbar { - - public static void send(Player p, String text) { - - CraftPlayer cp = (CraftPlayer)p; - - IChatBaseComponent textC = ChatSerializer.a("{\"text\": \"" + text + "\"}"); - - PacketPlayOutChat actionbar = new PacketPlayOutChat(textC); - - try { - Field field = actionbar.getClass().getDeclaredField("a"); - field.setAccessible(true); - try { - field.set(actionbar, (byte)2); - } catch (IllegalArgumentException | IllegalAccessException e) { - e.printStackTrace(); - } - } catch (NoSuchFieldException | SecurityException e) { - e.printStackTrace(); - } finally { - cp.getHandle().playerConnection.sendPacket(actionbar); - } - } + public static void send(Player player, String message){ + CraftPlayer p = (CraftPlayer) player; + IChatBaseComponent cbc = ChatSerializer.a("{\"text\": \"" + message + "\"}"); + PacketPlayOutChat ppoc = new PacketPlayOutChat(cbc,(byte) 2); + ((CraftPlayer) p).getHandle().playerConnection.sendPacket(ppoc); + } } diff --git a/src/eu/univento/core/api/AutoCommand.java b/src/eu/univento/core/api/AutoCommand.java index d2b678b..2644456 100644 --- a/src/eu/univento/core/api/AutoCommand.java +++ b/src/eu/univento/core/api/AutoCommand.java @@ -1,21 +1,22 @@ package eu.univento.core.api; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandMap; import org.bukkit.command.CommandSender; import org.bukkit.plugin.java.JavaPlugin; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +/** + * @author PostCrafter + * @see href http://postcrafter.de/viewtopic.php?f=15&t=143 + * @param

main class + */ public abstract class AutoCommand

extends Command { - /** - * @author PostCrafter - * @see http://postcrafter.de/viewtopic.php?f=15&t=143 - */ - private static String VERSION; static { diff --git a/src/eu/univento/core/api/Blackscreen.java b/src/eu/univento/core/api/Blackscreen.java index 87844cc..acad260 100644 --- a/src/eu/univento/core/api/Blackscreen.java +++ b/src/eu/univento/core/api/Blackscreen.java @@ -1,14 +1,20 @@ package eu.univento.core.api; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.UUID; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; +/** + * + * @author janhektor + * + */ public class Blackscreen { private static Object packetObject; diff --git a/src/eu/univento/core/api/BossBar.java b/src/eu/univento/core/api/BossBar.java index 244b835..847249e 100644 --- a/src/eu/univento/core/api/BossBar.java +++ b/src/eu/univento/core/api/BossBar.java @@ -1,8 +1,8 @@ package eu.univento.core.api; -import java.util.HashMap; -import java.util.Map; - +import eu.univento.core.Core; +import eu.univento.core.api.utils.FDragon; +import eu.univento.core.api.utils.FWither; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -12,9 +12,8 @@ import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitRunnable; -import eu.univento.core.Core; -import eu.univento.core.api.utils.FDragon; -import eu.univento.core.api.utils.FWither; +import java.util.HashMap; +import java.util.Map; /** @@ -30,15 +29,15 @@ public class BossBar implements Listener { public static Plugin plugin; - public static Map playerdragonbartask = new HashMap(); - public static Map healthdragonbartask = new HashMap(); - public static Map cooldownsdragonbar= new HashMap(); - public static Map starttimerdragonbar= new HashMap(); + public static Map playerdragonbartask = new HashMap<>(); + public static Map healthdragonbartask = new HashMap<>(); + public static Map cooldownsdragonbar= new HashMap<>(); + public static Map starttimerdragonbar= new HashMap<>(); - public static Map playerwitherbartask = new HashMap(); - public static Map healthwitherbartask = new HashMap(); - public static Map cooldownswitherbar= new HashMap(); - public static Map starttimerwitherbar= new HashMap(); + public static Map playerwitherbartask = new HashMap<>(); + public static Map healthwitherbartask = new HashMap<>(); + public static Map cooldownswitherbar= new HashMap<>(); + public static Map starttimerwitherbar= new HashMap<>(); public void DragonBarTask() { @@ -65,7 +64,7 @@ public class BossBar implements Listener { } } - }.runTaskTimer(Core.getInstance(), 0, 40); + }.runTaskTimer(Core.getInstance(), 0, 40); diff --git a/src/eu/univento/core/api/Config.java b/src/eu/univento/core/api/Config.java index 41a4f9c..db310da 100644 --- a/src/eu/univento/core/api/Config.java +++ b/src/eu/univento/core/api/Config.java @@ -1,14 +1,14 @@ package eu.univento.core.api; -import java.io.File; -import java.io.IOException; -import java.sql.SQLException; - import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; +import java.io.File; +import java.io.IOException; +import java.sql.SQLException; + /** * gets data from config file * @author joethei @@ -16,7 +16,9 @@ import org.bukkit.configuration.file.YamlConfiguration; */ public class Config { + /**config file*/ private static File file = new File("plugins/Core", "config.yml"); + /**load configuration */ private static FileConfiguration cfg = YamlConfiguration.loadConfiguration(file); /** diff --git a/src/eu/univento/core/api/Hologram.java b/src/eu/univento/core/api/Hologram.java index 7bf9a04..635d9ea 100644 --- a/src/eu/univento/core/api/Hologram.java +++ b/src/eu/univento/core/api/Hologram.java @@ -1,13 +1,14 @@ package eu.univento.core.api; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; + import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Player; public class Hologram { diff --git a/src/eu/univento/core/api/Messages.java b/src/eu/univento/core/api/Messages.java deleted file mode 100644 index a412757..0000000 --- a/src/eu/univento/core/api/Messages.java +++ /dev/null @@ -1,123 +0,0 @@ -package eu.univento.core.api; - -import java.sql.ResultSet; -import java.sql.SQLException; - -import eu.univento.core.Core; - -/** - * messages from database - * @author joethei - * @version 1.0 - */ -public class Messages { - - public static String PREFIX; - public static String CONSOLE_PREFIX; - public static String UNKNOWN_ERROR; - public static String NOT_A_PLAYER; - public static String NO_PERMS; - public static String ERROR; - public static String NOT_ONLINE; - public static String KICK_RESTART; - public static String KICK_FULL; - public static String COMMAND_NOT_FOUND; - - /** - * write default data - * @throws ClassNotFoundException Class couldn't be found - * @throws SQLException SQL server not available or throwing error - */ - public static void writeDefault() throws ClassNotFoundException, SQLException { - //editable messages will be set here, but do not edit this messages. - MySQL sql = Core.returnSQL(); - sql.openConnection(); - if(!isInDatabase("Prefix")) writeData("INSERT INTO Messages(Ident, Message) values ('Prefix', '§aunivento §8»');"); - if(!isInDatabase("ConsolePrefix")) writeData("INSERT INTO Messages(Ident, Message) values ('ConsolePrefix', '[univento Core]');"); - if(!isInDatabase("UnknownError")) writeData("INSERT INTO Messages(Ident, Message) values ('UnknownError', '§cEs ist leider ein unbekannter Fehler aufgetreten');"); - if(!isInDatabase("Commands.NoPlayer")) writeData("INSERT INTO Messages(Ident, Message) values ('Commands.NoPlayer', '§cDu bist leider kein Spieler');"); - if(!isInDatabase("Commands.NoPerms")) writeData("INSERT INTO Messages(Ident, Message) values ('Commands.NoPerms', '§cDu hast keine Berechtigungen diesen Befehl auszuführen')"); - if(!isInDatabase("Commands.Error")) writeData("INSERT INTO Messages(Ident, Message) values ('Commands.Error', '§cBeim ausführen dieses Befehls ist ein Fehler aufgetreten');"); - if(!isInDatabase("Commands.NotOnline")) writeData("INSERT INTO Messages(Ident, Message) values ('Commands.NotOnline', '§cDer Spieler $player ist nicht online');"); - if(!isInDatabase("Commands.Unknown")) writeData("INSERT INTO Messages(Ident, Message) values ('Commands.Unknown', '§6Dieser Befehl konnte leider nicht gefunden werden');"); - if(!isInDatabase("Kick.Restart")) writeData("INSERT INTO Messages(Ident, Message) values ('Kick.Restart', '§cDer Server startet gerade neu');"); - if(!isInDatabase("Kick.Full")) writeData("INSERT INTO Messages(Ident, Message) values ('Kick.Full', '§cDer Server ist leider schon voll')"); - - sql.closeConnection(); - - } - - private static void writeData(String data) { - MySQL sql = Core.returnSQL(); - try { - sql.openConnection(); - sql.getConnection().createStatement().execute(data); - } catch (ClassNotFoundException | SQLException e) { - e.printStackTrace(); - } - } - - /** - * checks if message is in database - * @param ident identifier of message - * @return true/false - */ - private static boolean isInDatabase(String ident) { - MySQL sql = Core.returnSQL(); - try { - sql.openConnection(); - ResultSet rs = sql.getConnection().createStatement().executeQuery("SELECT * FROM Messages WHERE Ident='" + ident + "';"); - if (!rs.next()) { - sql.closeConnection(); - return false; - } - sql.closeConnection(); - return true; - } catch (ClassNotFoundException | SQLException e) { - e.printStackTrace(); - return false; - } - } - - /** - * reads all string to variables - * @throws ClassNotFoundException Class couldn't be found - * @throws SQLException SQL server not available or throwing error - */ - public static void readStrings() throws ClassNotFoundException, SQLException { - PREFIX = readString("Prefix") + " "; - CONSOLE_PREFIX = readString("ConsolePrefix") + " "; - UNKNOWN_ERROR = PREFIX + readString("UnknownError"); - NOT_A_PLAYER = readString("Commands.NoPlayer") ; - NO_PERMS = PREFIX + readString("Commands.NoPerms"); - ERROR = PREFIX + readString("Commands.Error"); - NOT_ONLINE = PREFIX + readString("Commands.NotOnline"); - KICK_RESTART = readString("Kick.Restart"); - KICK_FULL = readString("Kick.Full"); - COMMAND_NOT_FOUND = PREFIX + readString("Commands.Unkown"); - } - - /** - * reads single message from database - * @param path path - * @return String - */ - public static String readString(String path) { - MySQL sql = Core.returnSQL(); - try { - sql.openConnection(); - ResultSet rs = sql.getConnection().createStatement().executeQuery("SELECT * FROM Messages WHERE Ident='" + path + "';"); - if (!rs.next()) { - sql.closeConnection(); - return null; - } - String message = rs.getString("Message"); - sql.closeConnection(); - return message; - } catch (ClassNotFoundException | SQLException e) { - e.printStackTrace(); - return null; - } - } - -} \ No newline at end of file diff --git a/src/eu/univento/core/api/NPC.java b/src/eu/univento/core/api/NPC.java deleted file mode 100644 index 57b72dd..0000000 --- a/src/eu/univento/core/api/NPC.java +++ /dev/null @@ -1,364 +0,0 @@ -package eu.univento.core.api; - -import java.lang.reflect.Field; -import java.util.List; -import java.util.Random; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.craftbukkit.*; -import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; -import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; -import org.bukkit.craftbukkit.v1_8_R3.util.CraftChatMessage; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import com.mojang.authlib.GameProfile; - -import net.minecraft.server.v1_8_R3.*; -import net.minecraft.server.v1_8_R3.PacketPlayOutPlayerInfo.EnumPlayerInfoAction; -import net.minecraft.server.v1_8_R3.PacketPlayOutPlayerInfo.PlayerInfoData; -import net.minecraft.server.v1_8_R3.WorldSettings.EnumGamemode; - -/** - * @author Summerfeeling - */ - -public class NPC { - - private DataWatcher watcher; - private Material chestplate; - private Material leggings; - private Location location; - private Material inHand; - private Material helmet; - private Material boots; - private String tablist; - private int entityID; - private String name; - private UUID uuid; - - /* - * NPC, a class for spawning fake players in the 1.8 Copyright (C) - * [Summerfeeling] Dieses Programm ist freie Software. Sie können es unter - * den Bedingungen der GNU General Public License, wie von der Free Software - * Foundation veröffentlicht, weitergeben und/oder modifizieren, entweder - * gemäß Version 3 der Lizenz oder (nach Ihrer Option) jeder späteren - * Version. Die Veröffentlichung dieses Programms erfolgt in der Hoffnung, - * daß es Ihnen von Nutzen sein wird, aber OHNE IRGENDEINE GARANTIE, sogar - * ohne die implizite Garantie der MARKTREIFE oder der VERWENDBARKEIT FÜR - * EINEN BESTIMMTEN ZWECK. Details finden Sie in der GNU General Public - * License. Sie sollten ein Exemplar der GNU General Public License zusammen - * mit diesem Programm erhalten haben. Falls nicht, siehe - * . - */ - - public NPC(String name, String tablist, UUID uuid, int entityID, Location location, Material inHand) { - this.location = location; - this.tablist = tablist; - this.name = name; - this.uuid = uuid; - this.entityID = entityID; - this.inHand = inHand; - this.watcher = new DataWatcher(null); - watcher.a(6, (float) 20); - } - - public NPC(String name, Location location) { - this(name, name, UUID.randomUUID(), new Random().nextInt(10000), location, Material.AIR); - } - - public NPC(String name, Location location, Material inHand) { - this(name, name, UUID.randomUUID(), new Random().nextInt(10000), location, inHand); - } - - public NPC(String name, String tablist, Location location) { - this(name, tablist, UUID.randomUUID(), new Random().nextInt(10000), location, Material.AIR); - } - - public NPC(String name, String tablist, Location location, Material inHand) { - this(name, tablist, UUID.randomUUID(), new Random().nextInt(10000), location, inHand); - } - - @SuppressWarnings("deprecation") - public void spawn() { - try { - PacketPlayOutNamedEntitySpawn packet = new PacketPlayOutNamedEntitySpawn(); - this.addToTablist(); - - this.setValue(packet, "a", this.entityID); - this.setValue(packet, "b", this.uuid); - this.setValue(packet, "c", this.toFixedPoint(this.location.getX())); - this.setValue(packet, "d", this.toFixedPoint(this.location.getY())); - this.setValue(packet, "e", this.toFixedPoint(this.location.getZ())); - this.setValue(packet, "f", this.toPackedByte(this.location.getYaw())); - this.setValue(packet, "g", this.toPackedByte(this.location.getPitch())); - this.setValue(packet, "h", this.inHand == null ? 0 : this.inHand.getId()); - this.setValue(packet, "i", this.watcher); - - for (Player online : Bukkit.getOnlinePlayers()) { - ((CraftPlayer) online).getHandle().playerConnection.sendPacket(packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - @SuppressWarnings("deprecation") - public void despawn() { - PacketPlayOutEntityDestroy packet = new PacketPlayOutEntityDestroy(new int[] { this.entityID }); - this.removeFromTablist(); - for (Player online : Bukkit.getOnlinePlayers()) { - ((CraftPlayer) online).getHandle().playerConnection.sendPacket(packet); - } - } - - @SuppressWarnings("deprecation") - public void changePlayerlistName(String name) { - try { - PacketPlayOutPlayerInfo packet = new PacketPlayOutPlayerInfo(); - PlayerInfoData data = new PlayerInfoData(packet, new GameProfile(this.uuid, this.name), 0, - EnumGamemode.NOT_SET, CraftChatMessage.fromString(name)[0]); - @SuppressWarnings("unchecked") - List players = (List) this.getValue(packet, "b"); - players.add(data); - - this.setValue(packet, "a", EnumPlayerInfoAction.UPDATE_DISPLAY_NAME); - this.setValue(packet, "b", players); - this.tablist = name; - - for (Player online : Bukkit.getOnlinePlayers()) { - ((CraftPlayer) online).getHandle().playerConnection.sendPacket(packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - @SuppressWarnings("deprecation") - private void addToTablist() { - try { - PacketPlayOutPlayerInfo packet = new PacketPlayOutPlayerInfo(); - PlayerInfoData data = new PlayerInfoData(packet, new GameProfile(this.uuid, this.name), 0, - EnumGamemode.NOT_SET, CraftChatMessage.fromString(this.tablist)[0]); - @SuppressWarnings("unchecked") - List players = (List) this.getValue(packet, "b"); - players.add(data); - - this.setValue(packet, "a", EnumPlayerInfoAction.ADD_PLAYER); - this.setValue(packet, "b", players); - - for (Player online : Bukkit.getOnlinePlayers()) { - ((CraftPlayer) online).getHandle().playerConnection.sendPacket(packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - @SuppressWarnings("deprecation") - private void removeFromTablist() { - try { - PacketPlayOutPlayerInfo packet = new PacketPlayOutPlayerInfo(); - PlayerInfoData data = new PlayerInfoData(packet, new GameProfile(this.uuid, this.name), 0, - EnumGamemode.NOT_SET, CraftChatMessage.fromString(this.tablist)[0]); - @SuppressWarnings("unchecked") - List players = (List) this.getValue(packet, "b"); - players.add(data); - - this.setValue(packet, "a", EnumPlayerInfoAction.REMOVE_PLAYER); - this.setValue(packet, "b", players); - - for (Player online : Bukkit.getOnlinePlayers()) { - ((CraftPlayer) online).getHandle().playerConnection.sendPacket(packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - @SuppressWarnings("deprecation") - public void teleport(Location location) { - try { - PacketPlayOutEntityTeleport packet = new PacketPlayOutEntityTeleport(); - - this.setValue(packet, "a", this.entityID); - this.setValue(packet, "b", this.toFixedPoint(location.getX())); - this.setValue(packet, "c", this.toFixedPoint(location.getY())); - this.setValue(packet, "d", this.toFixedPoint(location.getZ())); - this.setValue(packet, "e", this.toPackedByte(location.getYaw())); - this.setValue(packet, "f", this.toPackedByte(location.getPitch())); - this.setValue(packet, "g", this.location.getBlock().getType() == Material.AIR ? false : true); - this.location = location; - - for (Player online : Bukkit.getOnlinePlayers()) { - ((CraftPlayer) online).getHandle().playerConnection.sendPacket(packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - @SuppressWarnings("deprecation") - public void setItemInHand(Material material) { - try { - PacketPlayOutEntityEquipment packet = new PacketPlayOutEntityEquipment(); - - this.setValue(packet, "a", this.entityID); - this.setValue(packet, "b", 0); - this.setValue(packet, "c", - material == Material.AIR || material == null ? CraftItemStack.asNMSCopy(new ItemStack(Material.AIR)) - : CraftItemStack.asNMSCopy(new ItemStack(material))); - this.inHand = material; - - for (Player online : Bukkit.getOnlinePlayers()) { - ((CraftPlayer) online).getHandle().playerConnection.sendPacket(packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public Material getItemInHand() { - return this.inHand; - } - - @SuppressWarnings("deprecation") - public void setHelmet(Material material) { - try { - PacketPlayOutEntityEquipment packet = new PacketPlayOutEntityEquipment(); - - this.setValue(packet, "a", this.entityID); - this.setValue(packet, "b", 4); - this.setValue(packet, "c", - material == Material.AIR || material == null ? CraftItemStack.asNMSCopy(new ItemStack(Material.AIR)) - : CraftItemStack.asNMSCopy(new ItemStack(material))); - this.helmet = material; - - for (Player online : Bukkit.getOnlinePlayers()) { - ((CraftPlayer) online).getHandle().playerConnection.sendPacket(packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public Material getHelmet() { - return this.helmet; - } - - @SuppressWarnings("deprecation") - public void setChestplate(Material material) { - try { - PacketPlayOutEntityEquipment packet = new PacketPlayOutEntityEquipment(); - - this.setValue(packet, "a", this.entityID); - this.setValue(packet, "b", 3); - this.setValue(packet, "c", - material == Material.AIR || material == null ? CraftItemStack.asNMSCopy(new ItemStack(Material.AIR)) - : CraftItemStack.asNMSCopy(new ItemStack(material))); - this.chestplate = material; - - for (Player online : Bukkit.getOnlinePlayers()) { - ((CraftPlayer) online).getHandle().playerConnection.sendPacket(packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public Material getChestplate() { - return this.chestplate; - } - - @SuppressWarnings("deprecation") - public void setLeggings(Material material) { - try { - PacketPlayOutEntityEquipment packet = new PacketPlayOutEntityEquipment(); - - this.setValue(packet, "a", this.entityID); - this.setValue(packet, "b", 2); - this.setValue(packet, "c", - material == Material.AIR || material == null ? CraftItemStack.asNMSCopy(new ItemStack(Material.AIR)) - : CraftItemStack.asNMSCopy(new ItemStack(material))); - this.leggings = material; - - for (Player online : Bukkit.getOnlinePlayers()) { - ((CraftPlayer) online).getHandle().playerConnection.sendPacket(packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public Material getLeggings() { - return this.leggings; - } - - @SuppressWarnings("deprecation") - public void setBoots(Material material) { - try { - PacketPlayOutEntityEquipment packet = new PacketPlayOutEntityEquipment(); - - this.setValue(packet, "a", this.entityID); - this.setValue(packet, "b", 1); - this.setValue(packet, "c", - material == Material.AIR || material == null ? CraftItemStack.asNMSCopy(new ItemStack(Material.AIR)) - : CraftItemStack.asNMSCopy(new ItemStack(material))); - this.boots = material; - - for (Player online : Bukkit.getOnlinePlayers()) { - ((CraftPlayer) online).getHandle().playerConnection.sendPacket(packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public Material getBoots() { - return this.boots; - } - - public int getEntityID() { - return this.entityID; - } - - public UUID getUUID() { - return this.uuid; - } - - public Location getLocation() { - return this.location; - } - - public String getName() { - return this.name; - } - - public String getPlayerlistName() { - return this.tablist; - } - - private void setValue(Object instance, String field, Object value) throws Exception { - Field f = instance.getClass().getDeclaredField(field); - f.setAccessible(true); - f.set(instance, value); - } - - private Object getValue(Object instance, String field) throws Exception { - Field f = instance.getClass().getDeclaredField(field); - f.setAccessible(true); - return f.get(instance); - } - - private int toFixedPoint(double d) { - return (int) (d * 32.0); - } - - private byte toPackedByte(float f) { - return (byte) ((int) (f * 256.0F / 360.0F)); - } - -} diff --git a/src/eu/univento/core/api/ServerPinger.java b/src/eu/univento/core/api/ServerPinger.java deleted file mode 100644 index f46014a..0000000 --- a/src/eu/univento/core/api/ServerPinger.java +++ /dev/null @@ -1,98 +0,0 @@ -package eu.univento.core.api; - -import java.io.DataOutputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.nio.charset.Charset; - -public class ServerPinger -{ - private String host; - private int port; - - public ServerPinger(String host, int port) - { - this.host = host; - this.port = port; - } - - public ServerPinger(String host) { - this.host = host; - this.port = 25565; - } - - public ServerPinger() { - this.host = "127.0.0.1"; - this.port = 25565; - } - - @SuppressWarnings("resource") -public String parseData(Connection connection) - { - try - { - Socket socket = new Socket(); - - socket.setSoTimeout(2500); - socket.connect(new InetSocketAddress(this.host, this.port)); - - OutputStream os = socket.getOutputStream(); - DataOutputStream dos = new DataOutputStream(os); - - InputStream is = socket.getInputStream(); - InputStreamReader isr = new InputStreamReader(is, Charset.forName("UTF-16BE")); - - dos.write(new byte[] { -2, 1 }); - - int packetID = is.read(); - - if (packetID == -1) { - System.out.println("Invalid Packet ID! (End Of Stream)"); - } - if (packetID != 255) { - System.out.println("Invalid Packet Id! " + packetID); - } - - int length = isr.read(); - - if (length == -1) { - System.out.println("End Of Stream"); - } - - if (length == 0) { - System.out.println("Invalid length"); - } - - char[] chars = new char[length]; - - if (isr.read(chars, 0, length) != length) { - System.out.println("End Of Stream"); - } - - String string = new String(chars); - String[] data = string.split(""); - - if (connection == Connection.ONLINE_PLAYERS) - return data[4]; - if (connection == Connection.MOTD) - return data[3]; - if (connection == Connection.MAX_PLAYERS) { - return data[5]; - } - System.out.println("Connection value not handled!"); - } - catch (Exception localException) - { - localException.printStackTrace(); - } - - return null; - } - - public static enum Connection { - ONLINE_PLAYERS, MAX_PLAYERS, MOTD; - } -} \ No newline at end of file diff --git a/src/eu/univento/core/api/Servers.java b/src/eu/univento/core/api/Servers.java deleted file mode 100644 index 34ee3e9..0000000 --- a/src/eu/univento/core/api/Servers.java +++ /dev/null @@ -1,109 +0,0 @@ -package eu.univento.core.api; - -import com.google.common.collect.Iterables; -import com.google.common.io.ByteArrayDataOutput; -import com.google.common.io.ByteStreams; - -import eu.univento.core.Core; - -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -/** - * sends player to other bungeecord servers - * @author joethei - * @version 1.0 - */ -public class Servers { - - - /** - * sends player to server - * @param p player - * @param server name of server - */ - public static void connectServer(Player p, String server) { - if ((p instanceof Player)) { - ByteArrayOutputStream b = new ByteArrayOutputStream(); - DataOutputStream out = new DataOutputStream(b); - try { - out.writeUTF("Connect"); - out.writeUTF(server); - } catch (IOException el) { - el.printStackTrace(); - } - p.sendPluginMessage(Core.getInstance(), "BungeeCord", b.toByteArray()); - } - } - - /** - * connects all player to server - * @param server name of server - */ - public static void connectAllToServer(String server) { - for (Player all : Bukkit.getOnlinePlayers()) - connectServer(all, server); - } - - /** - * gets player count of server - * @param server name of server - * @return player count - */ - public static int getOnlinePlayers(String server) { - int online = 0; - - ByteArrayDataOutput out = ByteStreams.newDataOutput(); - - out.writeUTF("PlayerCount"); - out.writeUTF(server); - - Player player = (Player) Iterables.getFirst(Bukkit.getOnlinePlayers(), null); - player.sendPluginMessage(Core.getInstance(), "BungeeCord", out.toByteArray()); - - return online; - } - - /** - * gets ip of server from bungeecord - * @param server server name - * @return server ip - */ - public static String getServerIP(String server) { - String ip = null; - - ByteArrayDataOutput out = ByteStreams.newDataOutput(); - - out.writeUTF("ServerInfo"); - out.writeUTF(server); - - Player player = (Player) Iterables.getFirst(Bukkit.getOnlinePlayers(), null); - player.sendPluginMessage(Core.getInstance(), "BungeeCord", out.toByteArray()); - - return ip; - - } - - /** - * gets port of server from bungeecord - * @param server server name - * @return server port - */ - public static int getServerPort(String server) { - int port = 0; - - ByteArrayDataOutput out = ByteStreams.newDataOutput(); - - out.writeUTF("ServerInfo"); - out.writeUTF(server); - - Player player = (Player) Iterables.getFirst(Bukkit.getOnlinePlayers(), null); - player.sendPluginMessage(Core.getInstance(), "BungeeCord", out.toByteArray()); - - return port; - - } -} \ No newline at end of file diff --git a/src/eu/univento/core/api/Settings.java b/src/eu/univento/core/api/Settings.java deleted file mode 100644 index e384b63..0000000 --- a/src/eu/univento/core/api/Settings.java +++ /dev/null @@ -1,67 +0,0 @@ -package eu.univento.core.api; - -/** - * server-wide settings - * @author joethei - * @version 0.1 - */ - -public class Settings { - - private static boolean build; - private static boolean lobby; - private static boolean debug; - private static boolean mute; - /** - * @return is build - */ - public static boolean isBuild() { - return build; - } - /** - * @param build the build to set - */ - public static void setBuild(boolean build) { - Settings.build = build; - } - /** - * @return is lobby - */ - public static boolean isLobby() { - return lobby; - } - /** - * @param lobby the lobby to set - */ - public static void setLobby(boolean lobby) { - Settings.lobby = lobby; - } - /** - * @return is debug - */ - public static boolean isDebug() { - return debug; - } - /** - * @param debug the debug to set - */ - public static void setDebug(boolean debug) { - Settings.debug = debug; - } - - /** - * @return is mute - */ - public static boolean isMute() { - return mute; - } - - /** - * - * @param mute the mute to set - */ - public static void setMute(boolean mute) { - Settings.mute = mute; - } - -} \ No newline at end of file diff --git a/src/eu/univento/core/api/SignInput.java b/src/eu/univento/core/api/SignInput.java index 02184d8..314a813 100644 --- a/src/eu/univento/core/api/SignInput.java +++ b/src/eu/univento/core/api/SignInput.java @@ -3,6 +3,13 @@ package eu.univento.core.api; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageDecoder; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.plugin.Plugin; + import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; @@ -12,12 +19,6 @@ import java.util.List; import java.util.Map; import java.util.UUID; import java.util.function.Consumer; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.plugin.Plugin; /** diff --git a/src/eu/univento/core/api/SimpleScoreboard.java b/src/eu/univento/core/api/SimpleScoreboard.java deleted file mode 100644 index 8de6224..0000000 --- a/src/eu/univento/core/api/SimpleScoreboard.java +++ /dev/null @@ -1,104 +0,0 @@ -package eu.univento.core.api; - -import com.google.common.base.Preconditions; -import com.google.common.base.Splitter; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import java.util.AbstractMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; -import org.bukkit.scoreboard.DisplaySlot; -import org.bukkit.scoreboard.Objective; -import org.bukkit.scoreboard.Scoreboard; -import org.bukkit.scoreboard.Team; - -public class SimpleScoreboard -{ - private Scoreboard scoreboard; - private String title; - private Map scores; - private List teams; - - public SimpleScoreboard(String title) - { - this.scoreboard = Bukkit.getScoreboardManager().getNewScoreboard(); - this.title = title; - this.scores = Maps.newLinkedHashMap(); - this.teams = Lists.newArrayList(); - } - - public void add(String text) { - add(text, null); - } - - public void add(String text, Integer score) { - Preconditions.checkArgument(text.length() < 48, "text cannot be over 48 characters in length"); - text = fixDuplicates(text); - this.scores.put(text, score); - } - - private String fixDuplicates(String text) { - while (this.scores.containsKey(text)) - text = text + "§r"; - if (text.length() > 48) - text = text.substring(0, 47); - return text; - } - - private Map.Entry createTeam(String text) - { - String result = ""; - if (text.length() <= 16) - return new AbstractMap.SimpleEntry(null, text); - Team team = this.scoreboard.registerNewTeam("text-" + this.scoreboard.getTeams().size()); - Iterator iterator = Splitter.fixedLength(16).split(text).iterator(); - team.setPrefix((String)iterator.next()); - result = (String)iterator.next(); - if (text.length() > 32) - team.setSuffix((String)iterator.next()); - this.teams.add(team); - return new AbstractMap.SimpleEntry(team, result); - } - - @SuppressWarnings({ "deprecation", "rawtypes" }) -public void build() - { - Objective obj = this.scoreboard.registerNewObjective(this.title.length() > 16 ? this.title.substring(0, 15) : this.title, "dummy"); - obj.setDisplayName(this.title); - obj.setDisplaySlot(DisplaySlot.SIDEBAR); - - int index = this.scores.size(); - - for (Map.Entry text : this.scores.entrySet()) { - Map.Entry team = createTeam((String)text.getKey()); - Integer score = Integer.valueOf(text.getValue() != null ? ((Integer)text.getValue()).intValue() : index); - OfflinePlayer player = Bukkit.getOfflinePlayer((String)team.getValue()); - if (team.getKey() != null) - ((Team)team.getKey()).addPlayer(player); - obj.getScore(player.getName()).setScore(score.intValue()); - index--; - } - } - - public void reset() { - this.title = null; - this.scores.clear(); - for (Team t : this.teams) - t.unregister(); - this.teams.clear(); - } - - public Scoreboard getScoreboard() { - return this.scoreboard; - } - - public void send(Player[] players) { - for (Player p : players) - p.setScoreboard(this.scoreboard); - } -} \ No newline at end of file diff --git a/src/eu/univento/core/api/Title.java b/src/eu/univento/core/api/Title.java index a7eb6f8..350bd56 100644 --- a/src/eu/univento/core/api/Title.java +++ b/src/eu/univento/core/api/Title.java @@ -1,6 +1,5 @@ package eu.univento.core.api; -import java.lang.reflect.Field; import net.minecraft.server.v1_8_R3.IChatBaseComponent; import net.minecraft.server.v1_8_R3.PacketPlayOutPlayerListHeaderFooter; import net.minecraft.server.v1_8_R3.PacketPlayOutTitle; @@ -9,78 +8,92 @@ import org.bukkit.ChatColor; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; import org.bukkit.entity.Player; -public class Title -{ - @Deprecated - public static void sendTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String message) - { - sendTitle(player, fadeIn, stay, fadeOut, message, null); - } - @Deprecated - public static void sendSubtitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String message) { - sendTitle(player, fadeIn, stay, fadeOut, null, message); - } - @Deprecated - public static void sendFullTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String title, String subtitle) { - sendTitle(player, fadeIn, stay, fadeOut, title, subtitle); - } +import java.lang.reflect.Field; - public static void sendTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String title, String subtitle) { - PlayerConnection connection = ((CraftPlayer)player).getHandle().playerConnection; +//TODO: find real author, its not me +/** + * sends title to player + * @author joethei + * @version 1.0 + */ +public class Title { - PacketPlayOutTitle packetPlayOutTimes = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TIMES, null, fadeIn.intValue(), stay.intValue(), fadeOut.intValue()); - connection.sendPacket(packetPlayOutTimes); + /** + * send title to player + * @param player Player + * @param fadeIn Integer + * @param stay Integer + * @param fadeOut Integer + * @param title String + * @param subtitle String + */ + public static void sendTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String title, String subtitle) { + PlayerConnection connection = ((CraftPlayer) player).getHandle().playerConnection; - if (subtitle != null) { - subtitle = subtitle.replaceAll("%player%", player.getDisplayName()); - subtitle = ChatColor.translateAlternateColorCodes('&', subtitle); - IChatBaseComponent titleSub = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + subtitle + "\"}"); - PacketPlayOutTitle packetPlayOutSubTitle = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.SUBTITLE, titleSub); - connection.sendPacket(packetPlayOutSubTitle); - } + PacketPlayOutTitle packetPlayOutTimes = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TIMES, null, fadeIn.intValue(), stay.intValue(), fadeOut.intValue()); + connection.sendPacket(packetPlayOutTimes); - if (title != null) { - title = title.replaceAll("%player%", player.getDisplayName()); - title = ChatColor.translateAlternateColorCodes('&', title); - IChatBaseComponent titleMain = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + title + "\"}"); - PacketPlayOutTitle packetPlayOutTitle = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TITLE, titleMain); - connection.sendPacket(packetPlayOutTitle); - } - } + if (subtitle != null) { + subtitle = subtitle.replaceAll("%player%", player.getDisplayName()); + subtitle = ChatColor.translateAlternateColorCodes('&', subtitle); + IChatBaseComponent titleSub = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + subtitle + "\"}"); + PacketPlayOutTitle packetPlayOutSubTitle = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.SUBTITLE, titleSub); + connection.sendPacket(packetPlayOutSubTitle); + } - public static void sendTabTitle(Player player, String header, String footer) { - if (header == null) header = ""; - header = ChatColor.translateAlternateColorCodes('&', header); + if (title != null) { + title = title.replaceAll("%player%", player.getDisplayName()); + title = ChatColor.translateAlternateColorCodes('&', title); + IChatBaseComponent titleMain = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + title + "\"}"); + PacketPlayOutTitle packetPlayOutTitle = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TITLE, titleMain); + connection.sendPacket(packetPlayOutTitle); + } + } - if (footer == null) footer = ""; - footer = ChatColor.translateAlternateColorCodes('&', footer); + /** + * sends tab title to player + * @param player Player + * @param header String + * @param footer String + */ + public static void sendTabTitle(Player player, String header, String footer) { + if (header == null) + header = ""; + header = ChatColor.translateAlternateColorCodes('&', header); - header = header.replaceAll("%player%", player.getDisplayName()); - footer = footer.replaceAll("%player%", player.getDisplayName()); + if (footer == null) + footer = ""; + footer = ChatColor.translateAlternateColorCodes('&', footer); - PlayerConnection connection = ((CraftPlayer)player).getHandle().playerConnection; - IChatBaseComponent tabTitle = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + header + "\"}"); - IChatBaseComponent tabFoot = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + footer + "\"}"); - PacketPlayOutPlayerListHeaderFooter headerPacket = new PacketPlayOutPlayerListHeaderFooter(tabTitle); - try - { - Field field = headerPacket.getClass().getDeclaredField("b"); - field.setAccessible(true); - field.set(headerPacket, tabFoot); - } catch (Exception e) { - e.printStackTrace(); - } finally { - connection.sendPacket(headerPacket); - } - } + header = header.replaceAll("%player%", player.getDisplayName()); + footer = footer.replaceAll("%player%", player.getDisplayName()); - boolean isInteger(String s) - { - try { - Integer.parseInt(s); - } catch (NumberFormatException e) { - return false; - } - return true; - } + PlayerConnection connection = ((CraftPlayer) player).getHandle().playerConnection; + IChatBaseComponent tabTitle = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + header + "\"}"); + IChatBaseComponent tabFoot = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + footer + "\"}"); + PacketPlayOutPlayerListHeaderFooter headerPacket = new PacketPlayOutPlayerListHeaderFooter(tabTitle); + try { + Field field = headerPacket.getClass().getDeclaredField("b"); + field.setAccessible(true); + field.set(headerPacket, tabFoot); + } catch (Exception e) { + e.printStackTrace(); + } finally { + connection.sendPacket(headerPacket); + } + } + + /** + * checks if String is integer + * @param s String + * @return boolean + */ + boolean isInteger(String s) { + try { + Integer.parseInt(s); + } catch (NumberFormatException e) { + return false; + } + return true; + } } \ No newline at end of file diff --git a/src/eu/univento/core/api/Utils.java b/src/eu/univento/core/api/Utils.java index a89a4cb..b05e365 100644 --- a/src/eu/univento/core/api/Utils.java +++ b/src/eu/univento/core/api/Utils.java @@ -1,26 +1,15 @@ package eu.univento.core.api; +import eu.univento.core.Core; +import org.bukkit.*; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; +import org.bukkit.util.Vector; + import java.io.File; import java.util.List; -import java.util.Random; -import net.minecraft.server.v1_8_R3.EnumParticle; -import net.minecraft.server.v1_8_R3.PacketPlayOutWorldParticles; -import org.bukkit.Bukkit; -import org.bukkit.Color; -import org.bukkit.Effect; -import org.bukkit.FireworkEffect; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Sound; -import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Firework; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.FireworkMeta; -import org.bukkit.potion.PotionEffect; -import org.bukkit.util.Vector; /** * some utils you may need @@ -104,45 +93,6 @@ public class Utils { return true; } - /** - * shoots random fireworks at defined location - * @param loc Location - */ - public static void randomFireworks(Location loc) { - Firework fw = (Firework) loc.getWorld().spawnEntity(loc, EntityType.FIREWORK); - FireworkMeta fwm = fw.getFireworkMeta(); - Random r = new Random(); - int rt = r.nextInt(5) + 1; - FireworkEffect.Type type = FireworkEffect.Type.BALL; - if (rt == 1) - type = FireworkEffect.Type.BALL; - if (rt == 2) - type = FireworkEffect.Type.BALL_LARGE; - if (rt == 3) - type = FireworkEffect.Type.BURST; - if (rt == 4) - type = FireworkEffect.Type.CREEPER; - if (rt == 5) - type = FireworkEffect.Type.STAR; - - int red = r.nextInt(256); - int b = r.nextInt(256); - int g = r.nextInt(256); - - Color c1 = Color.fromRGB(red, g, b); - - red = r.nextInt(256); - b = r.nextInt(256); - g = r.nextInt(256); - Color c2 = Color.fromRGB(red, g, b); - - FireworkEffect effect = FireworkEffect.builder().flicker(r.nextBoolean()).withColor(c1).withFade(c2).with(type) - .trail(r.nextBoolean()).build(); - fwm.addEffect(effect); - int rp = r.nextInt(2) + 1; - fwm.setPower(rp); - fw.setFireworkMeta(fwm); - } /** * removes list of entity and counts them @@ -167,20 +117,6 @@ public class Utils { player.removePotionEffect(effect.getType()); } - /** - * plays effect at defined location for all players - * @param loc Location - * @param ep EnumParticle - * @param f random placement of particles - * @param count count of particles - */ - 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, new int[] { 0, 0 }); - for (Player p : Bukkit.getOnlinePlayers()) - ((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet); - } - /** * calculates vector from one location to another * @param from Location @@ -214,4 +150,30 @@ public class Utils { return vector; } + + /** + * restarts server + */ + public static void restart() { + Bukkit.getScheduler().scheduleSyncDelayedTask(Core.getInstance(), new Runnable() { + + @Override + public void run() { + Bukkit.getServer().spigot().restart(); + } + + }, 10 * 20L); + } + + /** + * shots random firework at specified location + * @param loc Location + */ + public static void randomFirework(Location loc) { + FireworkEffect.Builder builder = FireworkEffect.builder(); + FireworkEffect effect = builder.flicker(false).trail(false).with(FireworkEffect.Type.BALL_LARGE).withColor(Color.RED).withFade(Color.BLUE).build(); + //TODO: make a random fireworks effect + //TODO: remove effect.toString(), its only to remove unused warnings + effect.toString(); + } } \ No newline at end of file diff --git a/src/eu/univento/core/api/Database.java b/src/eu/univento/core/api/database/Database.java similarity index 93% rename from src/eu/univento/core/api/Database.java rename to src/eu/univento/core/api/database/Database.java index 9893a65..76fa156 100644 --- a/src/eu/univento/core/api/Database.java +++ b/src/eu/univento/core/api/database/Database.java @@ -1,71 +1,72 @@ -package eu.univento.core.api; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import org.bukkit.plugin.Plugin; - -public abstract class Database -{ - protected Connection connection; - protected Plugin plugin; - - protected Database(Plugin plugin) - { - this.plugin = plugin; - this.connection = null; - } - - public abstract Connection openConnection() - throws SQLException, ClassNotFoundException; - - public boolean checkConnection() - throws SQLException - { - return (this.connection != null) && (!this.connection.isClosed()); - } - - public Connection getConnection() - { - return this.connection; - } - - public boolean closeConnection() - throws SQLException - { - if (this.connection == null) { - return false; - } - this.connection.close(); - return true; - } - - public ResultSet querySQL(String query) - throws SQLException, ClassNotFoundException - { - if (!checkConnection()) { - openConnection(); - } - - Statement statement = this.connection.createStatement(); - - ResultSet result = statement.executeQuery(query); - - return result; - } - - public int updateSQL(String query) - throws SQLException, ClassNotFoundException - { - if (!checkConnection()) { - openConnection(); - } - - Statement statement = this.connection.createStatement(); - - int result = statement.executeUpdate(query); - - return result; - } +package eu.univento.core.api.database; + +import org.bukkit.plugin.Plugin; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +public abstract class Database +{ + protected Connection connection; + protected Plugin plugin; + + protected Database(Plugin plugin) + { + this.plugin = plugin; + this.connection = null; + } + + public abstract Connection openConnection() + throws SQLException, ClassNotFoundException; + + public boolean checkConnection() + throws SQLException + { + return (this.connection != null) && (!this.connection.isClosed()); + } + + public Connection getConnection() + { + return this.connection; + } + + public boolean closeConnection() + throws SQLException + { + if (this.connection == null) { + return false; + } + this.connection.close(); + return true; + } + + public ResultSet querySQL(String query) + throws SQLException, ClassNotFoundException + { + if (!checkConnection()) { + openConnection(); + } + + Statement statement = this.connection.createStatement(); + + ResultSet result = statement.executeQuery(query); + + return result; + } + + public int updateSQL(String query) + throws SQLException, ClassNotFoundException + { + if (!checkConnection()) { + openConnection(); + } + + Statement statement = this.connection.createStatement(); + + int result = statement.executeUpdate(query); + + return result; + } } \ No newline at end of file diff --git a/src/eu/univento/core/api/MySQL.java b/src/eu/univento/core/api/database/MySQL.java similarity index 85% rename from src/eu/univento/core/api/MySQL.java rename to src/eu/univento/core/api/database/MySQL.java index b11a920..7f8353d 100644 --- a/src/eu/univento/core/api/MySQL.java +++ b/src/eu/univento/core/api/database/MySQL.java @@ -1,37 +1,36 @@ -package eu.univento.core.api; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import org.bukkit.plugin.Plugin; - -public class MySQL extends Database -{ - private final String user; - private final String database; - private final String password; - private final String port; - private final String hostname; - - public MySQL(Plugin plugin, String hostname, String port, String database, String username, String password) { - super(plugin); - this.hostname = hostname; - this.port = port; - this.database = database; - this.user = username; - this.password = password; - } - - public Connection openConnection() - throws SQLException, ClassNotFoundException - { - if (checkConnection()) { - return this.connection; - } - Class.forName("com.mysql.jdbc.Driver"); - this.connection = DriverManager.getConnection("jdbc:mysql://" + - this.hostname + ":" + this.port + "/" + this.database, - this.user, this.password); - return this.connection; - } +package eu.univento.core.api.database; + +import org.bukkit.plugin.Plugin; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class MySQL extends Database +{ + private final String user; + private final String database; + private final String password; + private final String port; + private final String hostname; + + public MySQL(Plugin plugin, String hostname, String port, String database, String username, String password) { + super(plugin); + this.hostname = hostname; + this.port = port; + this.database = database; + this.user = username; + this.password = password; + } + + public Connection openConnection() throws SQLException, ClassNotFoundException { + if (checkConnection()) { + return this.connection; + } + Class.forName("com.mysql.jdbc.Driver"); + this.connection = DriverManager.getConnection("jdbc:mysql://" + + this.hostname + ":" + this.port + "/" + this.database, + this.user, this.password); + return this.connection; + } } \ No newline at end of file diff --git a/src/eu/univento/core/api/SQLite.java b/src/eu/univento/core/api/database/SQLite.java similarity index 93% rename from src/eu/univento/core/api/SQLite.java rename to src/eu/univento/core/api/database/SQLite.java index 7dc16f3..51961a1 100644 --- a/src/eu/univento/core/api/SQLite.java +++ b/src/eu/univento/core/api/database/SQLite.java @@ -1,46 +1,47 @@ -package eu.univento.core.api; - -import java.io.File; -import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.logging.Level; -import org.bukkit.plugin.Plugin; - -public class SQLite extends Database -{ - private final String dbLocation; - - public SQLite(Plugin plugin, String dbLocation) - { - super(plugin); - this.dbLocation = dbLocation; - } - - public Connection openConnection() - throws SQLException, ClassNotFoundException - { - if (checkConnection()) { - return this.connection; - } - if (!this.plugin.getDataFolder().exists()) { - this.plugin.getDataFolder().mkdirs(); - } - File file = new File(this.plugin.getDataFolder(), this.dbLocation); - if (!file.exists()) { - try { - file.createNewFile(); - } catch (IOException e) { - this.plugin.getLogger().log(Level.SEVERE, - "Unable to create database!"); - } - } - Class.forName("org.sqlite.JDBC"); - this.connection = - DriverManager.getConnection("jdbc:sqlite:" + - this.plugin.getDataFolder().toPath().toString() + "/" + - this.dbLocation); - return this.connection; - } +package eu.univento.core.api.database; + +import org.bukkit.plugin.Plugin; + +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.logging.Level; + +public class SQLite extends Database +{ + private final String dbLocation; + + public SQLite(Plugin plugin, String dbLocation) + { + super(plugin); + this.dbLocation = dbLocation; + } + + public Connection openConnection() + throws SQLException, ClassNotFoundException + { + if (checkConnection()) { + return this.connection; + } + if (!this.plugin.getDataFolder().exists()) { + this.plugin.getDataFolder().mkdirs(); + } + File file = new File(this.plugin.getDataFolder(), this.dbLocation); + if (!file.exists()) { + try { + file.createNewFile(); + } catch (IOException e) { + this.plugin.getLogger().log(Level.SEVERE, + "Unable to create database!"); + } + } + Class.forName("org.sqlite.JDBC"); + this.connection = + DriverManager.getConnection("jdbc:sqlite:" + + this.plugin.getDataFolder().toPath().toString() + "/" + + this.dbLocation); + return this.connection; + } } \ No newline at end of file diff --git a/src/eu/univento/core/api/effects/WorldBoarder.java b/src/eu/univento/core/api/effects/WorldBoarder.java new file mode 100644 index 0000000..d37eb20 --- /dev/null +++ b/src/eu/univento/core/api/effects/WorldBoarder.java @@ -0,0 +1,129 @@ +package eu.univento.core.api.effects; + +import eu.univento.core.Core; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * @author MrSheepSheep + * @version 0.1 + */ +public class WorldBoarder { + + private static Method handle, sendPacket; + private static Method center, distance, time, movement; + private static Field player_connection; + private static Constructor constructor, border_constructor; + private static Object constant; + + static { + try { + handle = getClass("org.bukkit.craftbukkit", "entity.CraftPlayer").getMethod("getHandle"); + player_connection = getClass("net.minecraft.server", "EntityPlayer").getField("playerConnection"); + for (Method m : getClass("net.minecraft.server", "PlayerConnection").getMethods()) { + if (m.getName().equals("sendPacket")) { + sendPacket = m; + break; + } + } + Class enumclass; + try { + enumclass = getClass("net.minecraft.server", "EnumWorldBorderAction"); + } catch(ClassNotFoundException x) { + enumclass = getClass("net.minecraft.server", "PacketPlayOutWorldBorder$EnumWorldBorderAction"); + } + constructor = getClass("net.minecraft.server", "PacketPlayOutWorldBorder").getConstructor(getClass("net.minecraft.server", "WorldBorder"), enumclass); + border_constructor = getClass("net.minecraft.server", "WorldBorder").getConstructor(); + + Method[] methods = getClass("net.minecraft.server", "WorldBorder").getMethods(); + + String setCenter = "setCenter"; + String setWarningDistance = "setWarningDistance"; + String setWarningTime = "setWarningTime"; + String transitionSizeBetween = "transitionSizeBetween"; + + if (!inClass(methods, setCenter)) + setCenter = "c"; + if (!inClass(methods, setWarningDistance)) + setWarningDistance = "c"; + if (!inClass(methods, setWarningTime)) + setWarningTime = "b"; + if (!inClass(methods, transitionSizeBetween)) + transitionSizeBetween = "a"; + + center = getClass("net.minecraft.server", "WorldBorder").getMethod(setCenter, double.class, double.class); + distance = getClass("net.minecraft.server", "WorldBorder").getMethod(setWarningDistance, int.class); + time = getClass("net.minecraft.server", "WorldBorder").getMethod(setWarningTime, int.class); + movement = getClass("net.minecraft.server", "WorldBorder").getMethod(transitionSizeBetween, double.class, double.class, long.class); + + for (Object o: enumclass.getEnumConstants()) { + if (o.toString().equals("INITIALIZE")) { + constant = o; + break; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + private static boolean inClass(Method[] methods, String methodName){ + for (Method m : methods) + if (Objects.equals(m.getName(), methodName)) + return true; + return false; + } + + private static Class getClass(String prefix, String name) throws Exception { + return Class.forName((prefix + ".") + Bukkit.getServer().getClass().getPackage().getName().substring(Bukkit.getServer().getClass().getPackage().getName().lastIndexOf(".") + 1) + "." + name); + } + + Core plugin; + protected List togglelist = new ArrayList<>(); + + protected WorldBoarder(Core plugin) { + this.plugin = plugin; + } + + protected void sendBorder(Player p, int percentage, int intensity){ + percentage = Math.round(percentage / intensity); + setBorder(p, percentage); + fadeBorder(p, percentage, 5); + } + + protected void fadeBorder(Player p, int percentage, long time){ + int dist = -10000 * percentage + 1300000; + sendWorldBorderPacket(p, 0, 200000D, (double) dist, (long) 1000 * time + 4000); //Add 4000 to make sure the "security" zone does not count in the fade time + } + + protected void removeBorder(Player p) { + sendWorldBorderPacket(p, 0, 200000D, 200000D, 0); + } + + protected void setBorder(Player p, int percentage){ + int dist = -10000 * percentage + 1300000; + sendWorldBorderPacket(p, dist, 200000D, 200000D, 0); + } + + protected void sendWorldBorderPacket(Player p, int dist, double oldradius, double newradius, long delay) { + try { + Object worldborder = border_constructor.newInstance(); + center.invoke(worldborder, p.getLocation().getX(), p.getLocation().getY()); + distance.invoke(worldborder, dist); + time.invoke(worldborder, 15); + movement.invoke(worldborder, oldradius, newradius, delay); + + Object packet = constructor.newInstance(worldborder, constant); + sendPacket.invoke(player_connection.get(handle.invoke(p)), packet); + } catch(Exception x) { + x.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/src/eu/univento/core/api/EntityModifier.java b/src/eu/univento/core/api/entity/EntityModifier.java similarity index 95% rename from src/eu/univento/core/api/EntityModifier.java rename to src/eu/univento/core/api/entity/EntityModifier.java index 3373927..6841e6a 100644 --- a/src/eu/univento/core/api/EntityModifier.java +++ b/src/eu/univento/core/api/entity/EntityModifier.java @@ -1,233 +1,239 @@ -package eu.univento.core.api; - -import java.lang.reflect.Field; -import net.minecraft.server.v1_8_R3.EntityLiving; -import net.minecraft.server.v1_8_R3.NBTTagCompound; -import org.bukkit.Bukkit; -import org.bukkit.EntityEffect; -import org.bukkit.Location; -import org.bukkit.craftbukkit.v1_8_R3.entity.CraftCreature; -import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - -public class EntityModifier -{ - static org.bukkit.entity.Entity entity; - static CraftEntity craftentity; - static net.minecraft.server.v1_8_R3.Entity entityS; - static int scheduler; - static Plugin plugin; - static Player player = null; - static float Speed; - - public EntityModifier(org.bukkit.entity.Entity entity, Plugin plugin) - { - EntityModifier.entity = entity; - craftentity = (CraftEntity)entity; - entityS = craftentity.getHandle(); - EntityModifier.plugin = plugin; - } - - public static Builder modify() - { - return new Builder(); - } - - public static final class Builder - { - public Builder setDisplayName(String display) - { - EntityModifier.entity.setCustomName(display); - EntityModifier.entity.setCustomNameVisible(true); - return this; - } - - public Builder setDisplayNameVisible(Boolean visible) - { - EntityModifier.entity.setCustomNameVisible(visible.booleanValue()); - return this; - } - - public Builder playEffekt(EntityEffect entityeffect) - { - EntityModifier.entity.playEffect(entityeffect); - return this; - } - - public Builder remove() - { - EntityModifier.entity.remove(); - return this; - } - - public Builder setPassenger(org.bukkit.entity.Entity passenger) - { - EntityModifier.entity.setPassenger(passenger); - return this; - } - - public Builder setFireTicks(int ticks) - { - EntityModifier.entity.setFireTicks(ticks); - return this; - } - - public Builder setLocation(Location location) - { - teleport(location); - return this; - } - - public Builder setYawPitch(float yaw, float pitch) - { - Location loc = EntityModifier.entity.getLocation().clone(); - teleport( - new Location(loc.getWorld(), loc.getX(), loc.getY(), - loc.getZ(), yaw, pitch)); - return this; - } - - public Builder teleport(Location location) - { - EntityModifier.entity.teleport(location); - return this; - } - - public Builder die() - { - EntityModifier.entityS.die(); - return this; - } - - public Builder setInvisible(boolean invisible) - { - EntityModifier.entityS.setInvisible(invisible); - return this; - } - - public Builder noClip(boolean noClip) - { - EntityModifier.entityS.noclip = noClip; - return this; - } - - public Builder setInvulnerable(boolean invulnerable) - { - try - { - Field invulnerableField = net.minecraft.server.v1_8_R3.Entity.class - .getDeclaredField("invulnerable"); - invulnerableField.setAccessible(true); - invulnerableField.setBoolean(EntityModifier.entityS, invulnerable); - } catch (Exception ex) { - ex.printStackTrace(); - } - return this; - } - - public Builder setNoAI(boolean noAI) - { - NBTTagCompound tag = new NBTTagCompound(); - EntityModifier.entityS.c(tag); - tag.setBoolean("NoAI", noAI); - EntityLiving el = (EntityLiving)EntityModifier.entityS; - el.a(tag); - return this; - } - - public Builder setSilent(boolean silent) - { - NBTTagCompound tag = new NBTTagCompound(); - EntityModifier.entityS.c(tag); - tag.setBoolean("Silent", silent); - EntityLiving el = (EntityLiving)EntityModifier.entityS; - el.a(tag); - return this; - } - - public Builder setCanPickUpLoot(boolean canpickuploot) - { - NBTTagCompound tag = new NBTTagCompound(); - EntityModifier.entityS.c(tag); - tag.setBoolean("CanPickUpLoot", canpickuploot); - EntityLiving el = (EntityLiving)EntityModifier.entityS; - el.a(tag); - return this; - } - - public Builder setHealth(float health) - { - NBTTagCompound tag = new NBTTagCompound(); - EntityModifier.entityS.c(tag); - tag.setFloat("HealF", health); - EntityLiving el = (EntityLiving)EntityModifier.entityS; - el.a(tag); - return this; - } - - public Builder setCanDespawn(boolean candespawn) - { - candespawn = !candespawn; - NBTTagCompound tag = new NBTTagCompound(); - EntityModifier.entityS.c(tag); - tag.setBoolean("PersistenceRequired", candespawn); - EntityLiving el = (EntityLiving)EntityModifier.entityS; - el.a(tag); - return this; - } - - public Builder walkToLocation(Location location, float speed) - { - ((CraftCreature)EntityModifier.entity) - .getHandle() - .getNavigation() - .a(location.getX(), location.getY(), location.getZ(), speed); - return this; - } - - public Builder followPlayer(Player target, float speed) - { - EntityModifier.player = target; - EntityModifier.Speed = speed; - EntityModifier.scheduler = Bukkit.getScheduler().scheduleSyncRepeatingTask(EntityModifier.plugin, - new Runnable() - { - @SuppressWarnings("deprecation") - public void run() { - double distance = EntityModifier.entity.getLocation().distance( - EntityModifier.player.getLocation()); - if (distance < 11.0D) { - float speed = EntityModifier.Speed; - if (distance < 3.0D) { - speed = 0.0F; - } - ((CraftCreature)EntityModifier.entity) - .getHandle() - .getNavigation() - .a(EntityModifier.player.getLocation().getX(), - EntityModifier.player.getLocation().getY(), - EntityModifier.player.getLocation().getZ(), - speed); - } - else if (EntityModifier.player.isOnGround()) { - EntityModifier.entity.teleport(EntityModifier.player); - } - } - } - , 0L, 1L); - return this; - } - - public Builder stopFollowingPlayer() - { - Bukkit.getScheduler().cancelTask(EntityModifier.scheduler); - return this; - } - - public org.bukkit.entity.Entity build() - { - return EntityModifier.entity; - } - } +package eu.univento.core.api.entity; + +import net.minecraft.server.v1_8_R3.EntityLiving; +import net.minecraft.server.v1_8_R3.NBTTagCompound; +import org.bukkit.Bukkit; +import org.bukkit.EntityEffect; +import org.bukkit.Location; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftCreature; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import java.lang.reflect.Field; + +/** + * + * @author GerVorbis + * @version 1.0 + */ +public class EntityModifier +{ + static org.bukkit.entity.Entity entity; + static CraftEntity craftentity; + static net.minecraft.server.v1_8_R3.Entity entityS; + static int scheduler; + static Plugin plugin; + static Player player = null; + static float Speed; + + public EntityModifier(org.bukkit.entity.Entity entity, Plugin plugin) + { + EntityModifier.entity = entity; + craftentity = (CraftEntity)entity; + entityS = craftentity.getHandle(); + EntityModifier.plugin = plugin; + } + + public static Builder modify() + { + return new Builder(); + } + + public static final class Builder + { + public Builder setDisplayName(String display) + { + EntityModifier.entity.setCustomName(display); + EntityModifier.entity.setCustomNameVisible(true); + return this; + } + + public Builder setDisplayNameVisible(Boolean visible) + { + EntityModifier.entity.setCustomNameVisible(visible.booleanValue()); + return this; + } + + public Builder playEffekt(EntityEffect entityeffect) + { + EntityModifier.entity.playEffect(entityeffect); + return this; + } + + public Builder remove() + { + EntityModifier.entity.remove(); + return this; + } + + public Builder setPassenger(org.bukkit.entity.Entity passenger) + { + EntityModifier.entity.setPassenger(passenger); + return this; + } + + public Builder setFireTicks(int ticks) + { + EntityModifier.entity.setFireTicks(ticks); + return this; + } + + public Builder setLocation(Location location) + { + teleport(location); + return this; + } + + public Builder setYawPitch(float yaw, float pitch) + { + Location loc = EntityModifier.entity.getLocation().clone(); + teleport( + new Location(loc.getWorld(), loc.getX(), loc.getY(), + loc.getZ(), yaw, pitch)); + return this; + } + + public Builder teleport(Location location) + { + EntityModifier.entity.teleport(location); + return this; + } + + public Builder die() + { + EntityModifier.entityS.die(); + return this; + } + + public Builder setInvisible(boolean invisible) + { + EntityModifier.entityS.setInvisible(invisible); + return this; + } + + public Builder noClip(boolean noClip) + { + EntityModifier.entityS.noclip = noClip; + return this; + } + + public Builder setInvulnerable(boolean invulnerable) + { + try + { + Field invulnerableField = net.minecraft.server.v1_8_R3.Entity.class + .getDeclaredField("invulnerable"); + invulnerableField.setAccessible(true); + invulnerableField.setBoolean(EntityModifier.entityS, invulnerable); + } catch (Exception ex) { + ex.printStackTrace(); + } + return this; + } + + public Builder setNoAI(boolean noAI) + { + NBTTagCompound tag = new NBTTagCompound(); + EntityModifier.entityS.c(tag); + tag.setBoolean("NoAI", noAI); + EntityLiving el = (EntityLiving)EntityModifier.entityS; + el.a(tag); + return this; + } + + public Builder setSilent(boolean silent) + { + NBTTagCompound tag = new NBTTagCompound(); + EntityModifier.entityS.c(tag); + tag.setBoolean("Silent", silent); + EntityLiving el = (EntityLiving)EntityModifier.entityS; + el.a(tag); + return this; + } + + public Builder setCanPickUpLoot(boolean canpickuploot) + { + NBTTagCompound tag = new NBTTagCompound(); + EntityModifier.entityS.c(tag); + tag.setBoolean("CanPickUpLoot", canpickuploot); + EntityLiving el = (EntityLiving)EntityModifier.entityS; + el.a(tag); + return this; + } + + public Builder setHealth(float health) + { + NBTTagCompound tag = new NBTTagCompound(); + EntityModifier.entityS.c(tag); + tag.setFloat("HealF", health); + EntityLiving el = (EntityLiving)EntityModifier.entityS; + el.a(tag); + return this; + } + + public Builder setCanDespawn(boolean candespawn) + { + candespawn = !candespawn; + NBTTagCompound tag = new NBTTagCompound(); + EntityModifier.entityS.c(tag); + tag.setBoolean("PersistenceRequired", candespawn); + EntityLiving el = (EntityLiving)EntityModifier.entityS; + el.a(tag); + return this; + } + + public Builder walkToLocation(Location location, float speed) + { + ((CraftCreature)EntityModifier.entity) + .getHandle() + .getNavigation() + .a(location.getX(), location.getY(), location.getZ(), speed); + return this; + } + + public Builder followPlayer(Player target, float speed) + { + EntityModifier.player = target; + EntityModifier.Speed = speed; + EntityModifier.scheduler = Bukkit.getScheduler().scheduleSyncRepeatingTask(EntityModifier.plugin, + new Runnable() + { + @SuppressWarnings("deprecation") + public void run() { + double distance = EntityModifier.entity.getLocation().distance( + EntityModifier.player.getLocation()); + if (distance < 11.0D) { + float speed = EntityModifier.Speed; + if (distance < 3.0D) { + speed = 0.0F; + } + ((CraftCreature)EntityModifier.entity) + .getHandle() + .getNavigation() + .a(EntityModifier.player.getLocation().getX(), + EntityModifier.player.getLocation().getY(), + EntityModifier.player.getLocation().getZ(), + speed); + } + else if (EntityModifier.player.isOnGround()) { + EntityModifier.entity.teleport(EntityModifier.player); + } + } + } + , 0L, 1L); + return this; + } + + public Builder stopFollowingPlayer() + { + Bukkit.getScheduler().cancelTask(EntityModifier.scheduler); + return this; + } + + public org.bukkit.entity.Entity build() + { + return EntityModifier.entity; + } + } } \ No newline at end of file diff --git a/src/eu/univento/core/api/events/MoveEventFilter.java b/src/eu/univento/core/api/events/MoveEventFilter.java new file mode 100644 index 0000000..de71feb --- /dev/null +++ b/src/eu/univento/core/api/events/MoveEventFilter.java @@ -0,0 +1,89 @@ +package eu.univento.core.api.events; + +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerMoveEvent; + +import java.util.WeakHashMap; + +/** + * @author Crislibaer + */ +public class MoveEventFilter implements Listener +{ + public static class PlayerBlockMoveEvent extends PlayerMoveEvent + { + public PlayerBlockMoveEvent(PlayerMoveEvent pEvent) + { + super(pEvent.getPlayer(), pEvent.getFrom(), pEvent.getTo()); + } + } + + private static class BlockPosition + { + public int x; + public int y; + public int z; + public World world; + } + + private Server mServer; + private WeakHashMap mLastPosition = new WeakHashMap<>(); + + public MoveEventFilter(Server pServer) + { + mServer = pServer; + } + + @EventHandler + public void onPlayerMove(PlayerMoveEvent pEvent) + { + if(pEvent.isCancelled() || pEvent instanceof PlayerBlockMoveEvent) + { + return; + } + + BlockPosition lastPos = mLastPosition.get(pEvent.getPlayer()); + Location currentPos = pEvent.getTo(); + boolean fireEvent = false; + + if(lastPos == null) + { + lastPos = new BlockPosition(); + mLastPosition.put(pEvent.getPlayer(), lastPos); + fireEvent = true; + } + else if(lastPos.x != currentPos.getBlockX() || lastPos.z != currentPos.getBlockZ() || lastPos.y != currentPos.getBlockY()) + { + fireEvent = true; + } + else if(lastPos.world != currentPos.getWorld()) + { + fireEvent = true; + } + + if(fireEvent) + { + // make sure that our event is synchronous + assert !pEvent.isAsynchronous(); + + // fire event + PlayerBlockMoveEvent event = new PlayerBlockMoveEvent(pEvent); + mServer.getPluginManager().callEvent(event); + + // check event state and only update new position if event does not gets canceled + if(!event.isCancelled()) + { + // update new position + lastPos.world = currentPos.getWorld(); + lastPos.x = currentPos.getBlockX(); + lastPos.y = currentPos.getBlockY(); + lastPos.z = currentPos.getBlockZ(); + } + } + } +} \ No newline at end of file diff --git a/src/eu/univento/core/api/fakeplayer/FakePlayer.java b/src/eu/univento/core/api/fakeplayer/FakePlayer.java new file mode 100644 index 0000000..0bd98e5 --- /dev/null +++ b/src/eu/univento/core/api/fakeplayer/FakePlayer.java @@ -0,0 +1,232 @@ +package eu.univento.core.api.fakeplayer; + +import com.mojang.authlib.GameProfile; +import eu.univento.core.Core; +import net.minecraft.server.v1_8_R3.*; +import org.bukkit.Location; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; + +import java.lang.reflect.Field; +import java.util.Arrays; + +/** + * @author joethei + * @version 0.3 + */ +public class FakePlayer { + + private static final double MOVE_SPEED = 4.3D / 20; + + private Player player; + private int entityId; + private GameProfile gameProfile; + private DataWatcher dataWatcher; + + private Location location; + private ArmorStand armorStand; + private LivingEntity target; + private BukkitTask task; + + private boolean moveable; + + public FakePlayer(GameProfile gameProfile, boolean moveable, Player player) { + + this.player = player; + + this.moveable = moveable; + + this.entityId = (int) get(Entity.class, null, "entityCount"); + set(Entity.class, null, "entityCount", this.entityId + 1); + this.gameProfile = gameProfile; + + this.dataWatcher = new DataWatcher(null); + byte status = 0; + this.dataWatcher.a(0, status); + this.dataWatcher.a(10, (byte) 127); + this.dataWatcher.a(6, 20F); + } + + private final BukkitRunnable tickTask = new BukkitRunnable() { + + private int ticksLiving = 0; + + @Override + public void run() { + if(target != null) { + followEntity(target); + + ticksLiving++; + } + } + }; + + private byte changeMask(byte bitMask, int bit, boolean state) { + if(state) + return bitMask |= 1 << bit; + else + return bitMask &= ~(1 << bit); + + } + + public void setTarget(LivingEntity target) { + this.target = target; + } + + public void clearTarget() { + this.target = null; + } + + public void setFire(boolean fire) { + setStatus(0, fire); + } + + public void setSneaking(boolean sneaking) { + setStatus(1, sneaking); + } + + public void setSprinting(boolean sprinting) { + setStatus(3, sprinting); + } + + public void setUseItem(boolean useItem) { + setStatus(4, useItem); + } + + public void setInvisible(boolean invisible) { + setStatus(5, invisible); + } + + private void setStatus(int data, boolean bool) { + DataWatcher dataWatcher = this.dataWatcher; + byte status = 0; + status = changeMask(status, data, bool); + dataWatcher.a(0, status); + dataWatcher.a(10, (byte) 127); + dataWatcher.a(6, 20F); + } + + public void followEntity(LivingEntity entity) { + double diffX = entity.getLocation().getX() - location.getX(); + double diffY = (entity.getLocation().getY() + entity.getEyeHeight() * 0.9D) - location.getY() + 1.6F; + double diffZ = entity.getLocation().getZ() - location.getZ(); + double hypoXZ = Math.sqrt(diffX * diffX + diffZ * diffZ); + float yaw = (float) (Math.atan2(diffZ, diffX) * 180D / Math.PI) - 90F; + float pitch = (float) -(Math.atan2(diffY, hypoXZ) * 18D / Math.PI); + look(yaw, pitch); + + if(moveable) { + if(Math.abs(diffX) > 3D || Math.abs(diffZ) > 3D) { + yaw = (float) Math.toRadians(yaw); + double x = Math.sin(yaw); + double z = Math.cos(yaw); + move(x * MOVE_SPEED, 0, z * MOVE_SPEED); + } + } + } + + private void move(double x, int y, double z) { + sendPackets(new PacketPlayOutEntity.PacketPlayOutRelEntityMoveLook(this.entityId, (byte) toFixedPointNumber(x), (byte) toFixedPointNumber(y), (byte) toFixedPointNumber(z), toAngle(location.getYaw()), toAngle(location.getPitch()), true)); + this.location.add(toFixedPointNumber(x) / 32D, toFixedPointNumber(y) / 32D, toFixedPointNumber(z) / 32D); + this.armorStand.teleport(this.location); + } + + public void spawn(Location location) { + + PacketPlayOutNamedEntitySpawn playerSpawn = new PacketPlayOutNamedEntitySpawn(); + set(playerSpawn, "a", this.entityId); + set(playerSpawn, "b", this.gameProfile.getId()); + set(playerSpawn, "c", toFixedPointNumber(location.getX())); + set(playerSpawn, "d", toFixedPointNumber(location.getY())); + set(playerSpawn, "e", toFixedPointNumber(location.getZ())); + set(playerSpawn, "f", toAngle(location.getYaw())); + set(playerSpawn, "g", toAngle(location.getPitch())); + set(playerSpawn, "h", 0); + set(playerSpawn, "i", this.dataWatcher); + + PacketPlayOutPlayerInfo playerInfo = new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER); + set(playerInfo, "b", Arrays.asList(playerInfo.new PlayerInfoData(this.gameProfile, 0, WorldSettings.EnumGamemode.NOT_SET, new ChatComponentText(this.gameProfile.getName())))); + sendPackets(playerInfo, playerSpawn); + + this.location = location; + this.armorStand = (ArmorStand) location.getWorld().spawnEntity(location, EntityType.ARMOR_STAND); + this.armorStand.setGravity(true); + this.armorStand.setVisible(false); + + this.task = tickTask.runTaskTimer(Core.getInstance(), 0L, 1L); + } + + public void despawn() { + PacketPlayOutPlayerInfo playerInfo = new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER); + set(playerInfo, "b", Arrays.asList(playerInfo.new PlayerInfoData(this.gameProfile, 0, null, null))); + sendPackets(new PacketPlayOutEntityDestroy(this.entityId), playerInfo); + + this.armorStand.remove(); + this.armorStand = null; + this.task.cancel(); + } + + public void removeTablist() { + PacketPlayOutPlayerInfo playerInfo = new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER); + set(playerInfo, "b", Arrays.asList(playerInfo.new PlayerInfoData(this.gameProfile, 0, null, null))); + sendPackets(new PacketPlayOutEntityDestroy(this.entityId), playerInfo); + } + + + private void look(float yaw, float pitch) { + PacketPlayOutEntityHeadRotation headRotation = new PacketPlayOutEntityHeadRotation(); + set(headRotation, "a", this.entityId); + set(headRotation, "b", toAngle(yaw)); + sendPackets(headRotation, new PacketPlayOutEntity.PacketPlayOutEntityLook(this.entityId, toAngle(yaw), toAngle(pitch), false)); + this.location.setYaw(yaw); + this.location.setPitch(pitch); + } + + private int toFixedPointNumber(double value) { + return (int) Math.floor(value * 32D); + } + + private byte toAngle(float value) { + return (byte) ((int) (value * 256.0F / 360.F)); + } + + public void sendPackets(Packet... packets) { + for(Packet packet : packets) + ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); + } + + private void set(Object instance, String name, Object value) { + set(instance.getClass(), instance, name, value); + } + + private void set(Class clazz, Object instance, String name, Object value) { + try{ + Field field = clazz.getDeclaredField(name); + field.setAccessible(true); + field.set(instance, value); + }catch (Exception e) { + e.printStackTrace(); + } + } + + 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); + field.setAccessible(true); + return field.get(instance); + }catch (Exception e) { + e.printStackTrace(); + } + return null; + } + +} \ No newline at end of file diff --git a/src/eu/univento/core/api/fakeplayer/PlayerKi.java b/src/eu/univento/core/api/fakeplayer/PlayerKi.java new file mode 100644 index 0000000..4661219 --- /dev/null +++ b/src/eu/univento/core/api/fakeplayer/PlayerKi.java @@ -0,0 +1,51 @@ +package eu.univento.core.api.fakeplayer; + +import com.mojang.authlib.GameProfile; +import eu.univento.core.api.utils.GameProfileBuilder; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; + +import java.util.UUID; + +/** + * @author joethei + * @version 0.1 + */ +public class PlayerKi implements Listener{ + + FakePlayer player; + + public FakePlayer createPlayer(Player p, String uuid, String name, String skinUrl, String capeUrl) { + GameProfile gameProfile = GameProfileBuilder.getProfile(UUID.fromString(uuid), name, skinUrl, capeUrl); + return new FakePlayer(gameProfile, true, p); + } + + @EventHandler + public void onInteract(PlayerInteractEvent e) { + if(e.getAction() == Action.RIGHT_CLICK_AIR) { + if(e.getItem().getType() == Material.DIAMOND) { + if(this.player != null) { + this.player.despawn(); + } + FakePlayer player = createPlayer(e.getPlayer(), e.getPlayer().getUniqueId().toString(), + "TestUser", "http://textures.minecraft.net/texture/a116e69a845e227f7ca1fdde8c357c8c821ebd4ba619382ea4a1f87d4ae94", + "http://textures.minecraft.net/texture/3f688e0e699b3d9fe448b5bb50a3a288f9c589762b3dae8308842122dcb81"); + this.player = player; + player.spawn(e.getPlayer().getLocation()); + player.setTarget(e.getPlayer()); + player.setSneaking(true); + player.removeTablist(); + } + if(e.getItem().getType() == Material.DIAMOND_SWORD) { + player.despawn(); + } + if(e.getItem().getType() == Material.NETHER_STAR) { + player.followEntity(e.getPlayer()); + } + } + } +} diff --git a/src/eu/univento/core/api/gui/AnvilGui.java b/src/eu/univento/core/api/gui/AnvilGui.java new file mode 100644 index 0000000..834d1ec --- /dev/null +++ b/src/eu/univento/core/api/gui/AnvilGui.java @@ -0,0 +1,224 @@ +package eu.univento.core.api.gui; + +import eu.univento.core.Core; +import net.minecraft.server.v1_8_R3.*; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; +import org.bukkit.entity.Player; +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.event.player.PlayerQuitEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.HashMap; + +/** + * Created by chasechocolate. + */ +public class AnvilGUI { + private class AnvilContainer extends ContainerAnvil { + public AnvilContainer(EntityHuman entity){ + super(entity.inventory, entity.world,new BlockPosition(0, 0, 0), entity); + } + + @Override + public boolean a(EntityHuman entityhuman){ + return true; + } + } + + public enum AnvilSlot { + INPUT_LEFT(0), + INPUT_RIGHT(1), + OUTPUT(2); + + private int slot; + + private AnvilSlot(int slot){ + this.slot = slot; + } + + public int getSlot(){ + return slot; + } + + public static AnvilSlot bySlot(int slot){ + for(AnvilSlot anvilSlot : values()){ + if(anvilSlot.getSlot() == slot){ + return anvilSlot; + } + } + + return null; + } + } + + public class AnvilClickEvent { + private AnvilSlot slot; + + private String name; + + private boolean close = true; + private boolean destroy = true; + + public AnvilClickEvent(AnvilSlot slot, String name){ + this.slot = slot; + this.name = name; + } + + public AnvilSlot getSlot(){ + return slot; + } + + public String getName(){ + return name; + } + + public boolean getWillClose(){ + return close; + } + + public void setWillClose(boolean close){ + this.close = close; + } + + public boolean getWillDestroy(){ + return destroy; + } + + public void setWillDestroy(boolean destroy){ + this.destroy = destroy; + } + } + + public interface AnvilClickEventHandler { + public void onAnvilClick(AnvilClickEvent event); + } + + private Player player; + + private AnvilClickEventHandler handler; + + private HashMap items = new HashMap(); + + private Inventory inv; + + private Listener listener; + + public AnvilGUI(Player player, final AnvilClickEventHandler handler){ + this.player = player; + this.handler = handler; + + this.listener = new Listener(){ + @EventHandler + public void onInventoryClick(InventoryClickEvent event){ + if(event.getWhoClicked() instanceof Player){ + Player clicker = (Player) event.getWhoClicked(); + + if(event.getInventory().equals(inv)){ + event.setCancelled(true); + + ItemStack item = event.getCurrentItem(); + int slot = event.getRawSlot(); + String name = ""; + + if(item != null){ + if(item.hasItemMeta()){ + ItemMeta meta = item.getItemMeta(); + + if(meta.hasDisplayName()){ + name = meta.getDisplayName(); + } + } + } + + AnvilClickEvent clickEvent = new AnvilClickEvent(AnvilSlot.bySlot(slot), name); + + handler.onAnvilClick(clickEvent); + + if(clickEvent.getWillClose()){ + event.getWhoClicked().closeInventory(); + } + + if(clickEvent.getWillDestroy()){ + destroy(); + } + } + } + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event){ + if(event.getPlayer() instanceof Player){ + Player player = (Player) event.getPlayer(); + Inventory inv = event.getInventory(); + + if(inv.equals(AnvilGUI.this.inv)){ + inv.clear(); + destroy(); + } + } + } + + @EventHandler + public void onPlayerQuit(PlayerQuitEvent event){ + if(event.getPlayer().equals(getPlayer())){ + destroy(); + } + } + }; + + Bukkit.getPluginManager().registerEvents(listener, Core.getInstance()); //Replace with instance of main class + } + + public Player getPlayer(){ + return player; + } + + public void setSlot(AnvilSlot slot, ItemStack item){ + items.put(slot, item); + } + + public void open(){ + EntityPlayer p = ((CraftPlayer) player).getHandle(); + + AnvilContainer container = new AnvilContainer(p); + + //Set the items to the items from the inventory given + inv = container.getBukkitView().getTopInventory(); + + for(AnvilSlot slot : items.keySet()){ + inv.setItem(slot.getSlot(), items.get(slot)); + } + + //Counter stuff that the game uses to keep track of inventories + int c = p.nextContainerCounter(); + + //Send the packet + p.playerConnection.sendPacket(new PacketPlayOutOpenWindow(c, "minecraft:anvil", new ChatMessage("Repairing", new Object[]{}), 0)); + + //Set their active container to the container + p.activeContainer = container; + + //Set their active container window id to that counter stuff + p.activeContainer.windowId = c; + + //Add the slot listener + p.activeContainer.addSlotListener(p); + } + + public void destroy(){ + player = null; + handler = null; + items = null; + + HandlerList.unregisterAll(listener); + + listener = null; + } +} \ No newline at end of file diff --git a/src/eu/univento/core/api/ItemSkulls.java b/src/eu/univento/core/api/items/ItemSkulls.java similarity index 96% rename from src/eu/univento/core/api/ItemSkulls.java rename to src/eu/univento/core/api/items/ItemSkulls.java index 0480aa2..665a4ec 100644 --- a/src/eu/univento/core/api/ItemSkulls.java +++ b/src/eu/univento/core/api/items/ItemSkulls.java @@ -1,123 +1,124 @@ -package eu.univento.core.api; - -import com.mojang.authlib.GameProfile; -import com.mojang.authlib.properties.Property; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Base64; -import java.util.UUID; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.SkullMeta; - -public class ItemSkulls -{ - private static Class skullMetaClass; - private static Class tileEntityClass; - private static Class blockPositionClass; - private static int mcVersion; - - static - { - String version = org.bukkit.Bukkit.getServer().getClass().getPackage().getName() - .split("\\.")[3]; - mcVersion = Integer.parseInt(version.replaceAll("[^0-9]", "")); - try { - skullMetaClass = Class.forName("org.bukkit.craftbukkit." + version + - ".inventory.CraftMetaSkull"); - tileEntityClass = Class.forName("net.minecraft.server." + version + - ".TileEntitySkull"); - if (mcVersion > 174) - blockPositionClass = Class.forName("net.minecraft.server." + - version + ".BlockPosition"); - else - blockPositionClass = null; - } - catch (ClassNotFoundException e) { - e.printStackTrace(); - } - } - - public static ItemStack getSkull(String skinURL) - { - return getSkull(skinURL, 1); - } - - public static ItemStack getSkull(String skinURL, int amount) - { - ItemStack skull = new ItemStack(Material.SKULL_ITEM, amount, (short) 3); - SkullMeta meta = (SkullMeta)skull.getItemMeta(); - try { - Field profileField = skullMetaClass.getDeclaredField("profile"); - profileField.setAccessible(true); - profileField.set(meta, getProfile(skinURL)); - } catch (Exception ex) { - ex.printStackTrace(); - } - skull.setItemMeta(meta); - return skull; - } - - public static boolean setBlock(Location loc, String skinURL) - { - return setBlock(loc.getBlock(), skinURL); - } - - public static boolean setBlock(Block block, String skinURL) - { - boolean flag = block.getType() == Material.SKULL; - if (!flag) - block.setType(Material.SKULL); - try - { - Object nmsWorld = block.getWorld().getClass() - .getMethod("getHandle", new Class[0]).invoke(block.getWorld(), new Object[0]); - Object tileEntity = null; - - if (mcVersion <= 174) { - Method getTileEntity = nmsWorld.getClass().getMethod( - "getTileEntity", new Class[] { Integer.TYPE, Integer.TYPE, Integer.TYPE }); - tileEntity = tileEntityClass.cast(getTileEntity.invoke( - nmsWorld, new Object[] { Integer.valueOf(block.getX()), Integer.valueOf(block.getY()), Integer.valueOf(block.getZ()) })); - } else { - Method getTileEntity = nmsWorld.getClass().getMethod( - "getTileEntity", new Class[] { blockPositionClass }); - tileEntity = tileEntityClass.cast(getTileEntity.invoke( - nmsWorld, new Object[] { - getBlockPositionFor(block.getX(), block.getY(), - block.getZ()) })); - } - - tileEntityClass.getMethod("setGameProfile", new Class[] { GameProfile.class }) - .invoke(tileEntity, new Object[] { getProfile(skinURL) }); - } catch (Exception ex) { - ex.printStackTrace(); - } - return !flag; - } - - private static GameProfile getProfile(String skinURL) { - GameProfile profile = new GameProfile(UUID.randomUUID(), null); - String base64encoded = Base64.getEncoder().encodeToString( - new String("{textures:{SKIN:{url:\"" + skinURL + "\"}}}") - .getBytes()); - Property property = new Property("textures", base64encoded); - profile.getProperties().put("textures", property); - return profile; - } - - private static Object getBlockPositionFor(int x, int y, int z) { - Object blockPosition = null; - try { - Constructor cons = blockPositionClass.getConstructor(new Class[] { Integer.TYPE, - Integer.TYPE, Integer.TYPE }); - blockPosition = cons.newInstance(new Object[] { Integer.valueOf(x), Integer.valueOf(y), Integer.valueOf(z) }); - } catch (Exception ex) { - ex.printStackTrace(); - } - return blockPosition; - } +package eu.univento.core.api.items; + +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Base64; +import java.util.UUID; + +public class ItemSkulls +{ + private static Class skullMetaClass; + private static Class tileEntityClass; + private static Class blockPositionClass; + private static int mcVersion; + + static + { + String version = org.bukkit.Bukkit.getServer().getClass().getPackage().getName() + .split("\\.")[3]; + mcVersion = Integer.parseInt(version.replaceAll("[^0-9]", "")); + try { + skullMetaClass = Class.forName("org.bukkit.craftbukkit." + version + + ".inventory.CraftMetaSkull"); + tileEntityClass = Class.forName("net.minecraft.server." + version + + ".TileEntitySkull"); + if (mcVersion > 174) + blockPositionClass = Class.forName("net.minecraft.server." + + version + ".BlockPosition"); + else + blockPositionClass = null; + } + catch (ClassNotFoundException e) { + e.printStackTrace(); + } + } + + public static ItemStack getSkull(String skinURL) + { + return getSkull(skinURL, 1); + } + + public static ItemStack getSkull(String skinURL, int amount) + { + ItemStack skull = new ItemStack(Material.SKULL_ITEM, amount, (short) 3); + SkullMeta meta = (SkullMeta)skull.getItemMeta(); + try { + Field profileField = skullMetaClass.getDeclaredField("profile"); + profileField.setAccessible(true); + profileField.set(meta, getProfile(skinURL)); + } catch (Exception ex) { + ex.printStackTrace(); + } + skull.setItemMeta(meta); + return skull; + } + + public static boolean setBlock(Location loc, String skinURL) + { + return setBlock(loc.getBlock(), skinURL); + } + + public static boolean setBlock(Block block, String skinURL) + { + boolean flag = block.getType() == Material.SKULL; + if (!flag) + block.setType(Material.SKULL); + try + { + Object nmsWorld = block.getWorld().getClass() + .getMethod("getHandle", new Class[0]).invoke(block.getWorld(), new Object[0]); + Object tileEntity = null; + + if (mcVersion <= 174) { + Method getTileEntity = nmsWorld.getClass().getMethod( + "getTileEntity", new Class[] { Integer.TYPE, Integer.TYPE, Integer.TYPE }); + tileEntity = tileEntityClass.cast(getTileEntity.invoke( + nmsWorld, new Object[] { Integer.valueOf(block.getX()), Integer.valueOf(block.getY()), Integer.valueOf(block.getZ()) })); + } else { + Method getTileEntity = nmsWorld.getClass().getMethod( + "getTileEntity", new Class[] { blockPositionClass }); + tileEntity = tileEntityClass.cast(getTileEntity.invoke( + nmsWorld, new Object[] { + getBlockPositionFor(block.getX(), block.getY(), + block.getZ()) })); + } + + tileEntityClass.getMethod("setGameProfile", new Class[] { GameProfile.class }) + .invoke(tileEntity, new Object[] { getProfile(skinURL) }); + } catch (Exception ex) { + ex.printStackTrace(); + } + return !flag; + } + + private static GameProfile getProfile(String skinURL) { + GameProfile profile = new GameProfile(UUID.randomUUID(), null); + String base64encoded = Base64.getEncoder().encodeToString( + new String("{textures:{SKIN:{url:\"" + skinURL + "\"}}}") + .getBytes()); + Property property = new Property("textures", base64encoded); + profile.getProperties().put("textures", property); + return profile; + } + + private static Object getBlockPositionFor(int x, int y, int z) { + Object blockPosition = null; + try { + Constructor cons = blockPositionClass.getConstructor(new Class[] { Integer.TYPE, + Integer.TYPE, Integer.TYPE }); + blockPosition = cons.newInstance(new Object[] { Integer.valueOf(x), Integer.valueOf(y), Integer.valueOf(z) }); + } catch (Exception ex) { + ex.printStackTrace(); + } + return blockPosition; + } } \ No newline at end of file diff --git a/src/eu/univento/core/api/Pagifier.java b/src/eu/univento/core/api/items/Pagifier.java similarity index 91% rename from src/eu/univento/core/api/Pagifier.java rename to src/eu/univento/core/api/items/Pagifier.java index f024d14..8899d3a 100644 --- a/src/eu/univento/core/api/Pagifier.java +++ b/src/eu/univento/core/api/items/Pagifier.java @@ -1,66 +1,67 @@ -package eu.univento.core.api; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -/*************************** - * Pagifier by leNic * - ***************************/ -/** - * @author leNic - * @version 1.0 - */ - public class Pagifier { - // Properties - private int pageSize; - // List of pages - private List> pages; - // Constructor - public Pagifier(int pageSize){ - this.pageSize = pageSize; - this.pages = new ArrayList<>(); - // Create first page - this.pages.add(new ArrayList<>()); - } - /** - * Add item to pages - * (Creates a new page if the previous page is not existing or full) - * @param item The item you want to add - */ - public void addItem(T item){ - int pageNum = pages.size() - 1; - List currentPage = this.pages.get(pageNum); - // Add page if full - if(currentPage.size() >= this.pageSize) { - currentPage = new ArrayList<>(); - this.pages.add(currentPage); - pageNum++; - } - currentPage.add(item); - } - /** - * Get the items of a page - * @param pageNum Number of the page (beginning at 0) - * @return Optional with a list of the page's items - */ - public Optional> getPage(int pageNum){ - if(this.pages.size() == 0) - return Optional.empty(); - return Optional.of(this.pages.get(pageNum)); - } - /** - * Get all pages - * @return List containing all pages - */ - public List> getPages(){ - return this.pages; - } - /** - * Get the current set page size - * @return The current page size - */ - public int getPageSize(){ - return this.pageSize; - } +package eu.univento.core.api.items; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/*************************** +* Pagifier by leNic * +***************************/ + +/** + * @author leNic + * @version 1.0 + */ + public class Pagifier { + // Properties + private int pageSize; + // List of pages + private List> pages; + // Constructor + public Pagifier(int pageSize){ + this.pageSize = pageSize; + this.pages = new ArrayList<>(); + // Create first page + this.pages.add(new ArrayList<>()); + } + /** + * Add item to pages + * (Creates a new page if the previous page is not existing or full) + * @param item The item you want to add + */ + public void addItem(T item){ + int pageNum = pages.size() - 1; + List currentPage = this.pages.get(pageNum); + // Add page if full + if(currentPage.size() >= this.pageSize) { + currentPage = new ArrayList<>(); + this.pages.add(currentPage); + pageNum++; + } + currentPage.add(item); + } + /** + * Get the items of a page + * @param pageNum Number of the page (beginning at 0) + * @return Optional with a list of the page's items + */ + public Optional> getPage(int pageNum){ + if(this.pages.size() == 0) + return Optional.empty(); + return Optional.of(this.pages.get(pageNum)); + } + /** + * Get all pages + * @return List containing all pages + */ + public List> getPages(){ + return this.pages; + } + /** + * Get the current set page size + * @return The current page size + */ + public int getPageSize(){ + return this.pageSize; + } } \ No newline at end of file diff --git a/src/eu/univento/core/api/languages/Language_DE.java b/src/eu/univento/core/api/languages/Language_DE.java new file mode 100644 index 0000000..46eb57d --- /dev/null +++ b/src/eu/univento/core/api/languages/Language_DE.java @@ -0,0 +1,557 @@ +package eu.univento.core.api.languages; + +import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.Perms; + +/** + * @author joethei + * @version 1.0 + */ + +public class Language_DE implements Languages{ + + @Override + public String UNKNOWN_ERROR() { + return "§cEs ist ein unbekannter Fehler aufgetreten"; + } + + @Override + public String NO_PERMS() { + return "§cDu hast keine Berechtigung diesen Befehl auszuführen"; + } + + @Override + public String ERROR() { + return "§cFehler: "; + } + + @Override + public String NOT_ONLINE(String name) { + return "§7" + name + " ist §cnicht §7online"; + } + + @Override + public String KICK_RESTART() { + return "§cDer Server wurde neu gestartet"; + } + + @Override + public String KICK_FULL() { + return "§cDieser Server ist bereits voll"; + } + + @Override + public String COMMAND_NOT_FOUND() { + return "§cDieser Befehl konnte nicht gefunden werden"; + } + + @Override + public String Core_FIX_OWN() { + return "§7Du wurdest §egefixt"; + } + + @Override + public String Core_FIX_OTHER(CustomPlayer p) { + return "§7Du hast " + p.getDisplayName() + " §egefixt"; + } + + @Override + public String Core_FIX_BY_OTHER(CustomPlayer p) { + return "§7Du wurdest von " + p.getDisplayName() + " §egefixt"; + } + + @Override + public String Core_NICK_ON() { + return "§7Du hast einen §eNicknamen §7zugewiesen bekommen"; + } + + @Override + public String Core_NICK_OFF() { + return "§7Du hast nun §ckeinen §eNicknamen §7mehr"; + } + + @Override + public String Core_BUILD_ON() { + return "§7Du hast den Baumodus §abetreten"; + } + + @Override + public String Core_BUILD_OFF() { + return "§7Du hast den Baumodus §cverlassen"; + } + + @Override + public String Core_BAN_NO_REASON() { + return "§cDieser Grund exsistiert nicht"; + } + + @Override + public String Core_BAN_USAGE() { + return "§cNutze "; + } + + @Override + public String Core_BAN_BANNED(CustomPlayer p) { + return "§7Du hast " + p.getColor() + p.getDisplayName() + " §cgebannt"; + } + + @Override + public String Core_GM_USAGE() { + return "§7Nutze §e/gm <0 | 1 | 2 | 3>"; + } + + @Override + public String Core_GM_CHANGED() { + return "§7Dein Spielmodus wurde §ageändert"; + } + + @Override + public String Core_GLOBALMUTE_ON() { + return "§7Der Server wurde §cstumm gestellt"; + } + + @Override + public String Core_GLOBALMUTE_OFF() { + return "§7Der Server wurde §asozial §7gestellt"; + } + + @Override + public String Core_RUNAS_USAGE() { + return "§cFühre /runas "; + } + + @Override + public String Core_RUNAS_RUN(CustomPlayer p) { + return "§7Der Spieler " + p.getColor() + p.getDisplayName() + " §7hat deinen Befehl §eerfolgreich §7ausgeführt"; + } + + @Override + public String Core_SETRANK_USAGE() { + return "§cNutze /setrank "; + } + + @Override + public String Core_SETRANK_KICK() { + return "\n§aDu hast nun einen neuen Rang.§e\nBitte joine neu§7."; + } + + @Override + public String Core_SETRANK_NO_RANK() { + return "§cDieser Rang exsistiert nicht"; + } + + @Override + public String Core_SETRANK_SET(CustomPlayer p, Perms.Ranks rank) { + return "§7Du hast dem Spieler " + p.getDisplayName() + " auf §e" + rank.toString() + " §7gesetzt"; + } + @Override + public String Core_TS_ALLREADY_VERIFIED() { + return "§cDu hast bereits einen verifizierten Account"; + } + + @Override + public String Core_TS_VERIFIED() { + return "§7Du hast deinen Account §eerfolgreich §7verifiziert"; + } + + @Override + public String Core_VANISH_ON() { + return "§7Du bist nun §aunsichtbar"; + } + + @Override + public String Core_VANISH_OFF() { + return "§7Du bist nun wieder §csichtbar"; + } + + @Override + public String Core_SERVER_MUTED() { + return "§7Der Chat ist bis auf weiteres §cgesperrt"; + } + + @Override + public String Core_CHAT_CLEARED(CustomPlayer p) { + return "§7Der Chat wurde von " + p.getColor() + p.getDisplayName() + " §cgereinigt"; + } + + @Override + public String Core_TAB_TITLE() { + return "§7Du spielst auf §e"; + } + + @Override + public String Lobby_PLAYERS_HIDE() { + return "§7Du kannst nun §ckeine §7Spieler mehr sehen"; + } + + @Override + public String Lobby_PLAYERS_SHOW() { + return "§7Du kannst nun §aalle §7Spieler sehen"; + } + + @Override + public String Lobby_AUTONICK_ON() { + return "§7Du §aerhälst §7nun einen automatischen §eNicknamen"; + } + + @Override + public String Lobby_AUTONICK_OFF() { + return "§7Du hast nun §ckeinen §7automatischen §eNicknamen §7mehr"; + } + + @Override + public String Lobby_FORCEFIELD_ON() { + return "§7Du hast das §eSchutzschild §aaktiviert"; + } + + @Override + public String Lobby_FORCEFIELD_OFF() { + return "§7Du hast das §eSchutzschild §cdeaktiviert"; + } + + @Override + public String Lobby_SILENT_LOBBY_ON() { + return "§7Du hast die §eSilent-Lobby §abetreten"; + } + + @Override + public String Lobby_SILENT_LOBBY_OFF() { + return "§7Du hast die §eSilent-Lobby §cverlassen"; + } + + @Override + public String Lobby_PLAYING_MUSIC_PREFIX() { + return "§6Jetzt spielt: "; + } + + @Override + public String Lobby_FOUND_ITEM_PREFIX() { + return "§7Du hast etwas §egefunden"; + } + + @Override + public String Lobby_SET_LOCATION() { + return "§aPosition wurde gesetzt"; + } + + @Override + public String Lobby_SET_LOCATION_USAGE() { + return "§cNutze /setloc "; + } + + @Override + public String Lobby_DROP_ITEM_USAGE() { + return "§cNutze /dropitem "; + } + + @Override + public String Lobby_DROP_ITEM() { + return "§aDu hast ein Item gelegt"; + } + + @Override + public String Lobby_SET_SIGN() { + return "§aNeues Status Schild erstellt"; + } + + @Override + public String Lobby_JOIN_TITLE_1() { + return "§6univento§7.§eeu"; + } + + @Override + public String Lobby_JOIN_TITLE_2() { + return "§cIch putze hier nur"; + } + + @Override + public String Lobby_PET_ADD() { + return "§7Du hast nun ein §eHaustier"; + } + + @Override + public String Lobby_PET_REMOVE() { + return "§7Du hast nun §ckein §eHaustier §7mehr"; + } + + @Override + public String Lobby_PARKOUR_ON() { + return "§7Du hast den §eParkourmodus §abetreten"; + } + + @Override + public String Lobby_PARKOUR_OFF() { + return "§7Du hast den §eParkourmodus §cverlassen"; + } + + @Override + public String LobbyItems_NAVIGATOR() { + return "§eNavigator"; + } + + @Override + public String LobbyItems_PLAYER_HIDER_ON() { + return "§cSpieler verstecken"; + } + + @Override + public String LobbyItems_PLAYER_HIDER_OFF() { + return "§aSpieler anzeigen"; + } + + @Override + public String LobbyItems_AUTO_NICK() { + return "§5AutoNick"; + } + + @Override + public String LobbyItems_SILENT_LOBBY() { + return "§cSilent-Lobby"; + } + + @Override + public String LobbyItems_FORCEFIELD() { + return "§aSchutzschild"; + } + + @Override + public String LobbyItems_FUN_CHEST() { + return "§cF§aU§eN§3Chest"; + } + + @Override + public String LobbyItems_PROFILE() { + return "§eDein Profil"; + } + + @Override + public String LobbyItems_YOUTUBER() { + return "§5Youtuber Funktionen"; + } + + @Override + public String LobbyItems_SUGGESTION() { + return "§6Vorschläge"; + } + + @Override + public String LobbyItems_SPAWN() { + return "§6Spawn"; + } + + @Override + public String LobbyItems_PREMIUMHUB() { + return "§6Premium Lobby"; + } + + @Override + public String LobbyItems_MAYA() { + return "§6Maya"; + } + + @Override + public String LobbyItems_WOOLGET() { + return "§6WoolGet"; + } + + @Override + public String LobbyItems_BUILDSERVER() { + return "§aBau-Server"; + } + + @Override + public String LobbyItems_PLAYERS_ONLINE() { + return " §6Spieler online"; + } + + @Override + public String LobbyItems_GADGETS() { + return "§6Gadgets"; + } + + @Override + public String LobbyItems_MUSIC() { + return "§6Musik"; + } + + @Override + public String LobbyItems_PARTICLE() { + return "§6Partikel"; + } + + @Override + public String LobbyItems_PETS() { + return "§6Haustiere"; + } + + @Override + public String LobbyItems_YOUR_PET() { + return "§6Dein Haustier"; + } + + @Override + public String LobbyItems_PETS_NAME() { + return "§6Namen ändern"; + } + + @Override + public String LobbyItems_PETS_AGE() { + return "§6Alter ändern"; + } + + @Override + public String LobbyItems_PETS_RIDE() { + return "§6Reiten"; + } + + @Override + public String LobbyItems_PETS_REMOVE() { + return "§6Haustier entfernen"; + } + + @Override + public String LobbyItems_PETS_PIG() { + return "§6Schwein"; + } + + @Override + public String LobbyItems_PETS_COW() { + return "§6Kuh"; + } + + @Override + public String LobbyItems_PETS_CHICKEN() { + return "§6Hühnchen"; + } + + @Override + public String LobbyItems_PETS_RABBIT() { + return "§6Hase"; + } + + @Override + public String LobbyItems_PETS_MUSHROM_COW() { + return "§6Pilzkuh"; + } + + @Override + public String LobbyItems_PLAYER_MENU() { + return " Menü"; + } + + @Override + public String LobbyItems_PLAYER_FRIEND() { + return "§6Freundschaftsanfrage senden"; + } + + @Override + public String LobbyItems_PLAYER_PARTY() { + return "§6Party Anfrage senden"; + } + + @Override + public String LobbyItems_PLAYER_PROFILE() { + return "§6Profil"; + } + + @Override + public String LobbyItems_PLAYER_STATS() { + return "§6Statistiken"; + } + + @Override + public String LobbyItems_STATS() { + return "§6Deine Statistiken"; + } + + @Override + public String LobbyItems_FRIENDS() { + return "§6Freunde"; + } + + @Override + public String LobbyItems_SETTINGS() { + return "§eEinstellungen"; + } + + @Override + public String LobbyItems_SETTINGS_FASTMENU() { + return "§6Inventar Animation"; + } + + @Override + public String LobbyItems_SETTINGS_SERVER_TELEPORT() { + return "§6Server-Teleport"; + } + + @Override + public String LobbyItems_SETTINGS_PARTY_REQUESTS() { + return "§6Party Anfragen"; + } + + @Override + public String LobbyItems_SETTINGS_FRIEND_REQUESTS() { + return "§6Freundschafts Anfragen"; + } + + @Override + public String LobbyItems_SETTINGS_CHATSOUNDS() { + return "§6Chat Geräusche"; + } + + @Override + public String LobbyItems_SETTINGS_EFFECTS() { + return "§6Effekte"; + } + + @Override + public String LobbyItems_SETTINGS_LANGUAGES() { + return "§6Sprachen"; + } + + @Override + public String LobbyItems_SETTINGS_ON() { + return "§aaktiviert"; + } + + @Override + public String LobbyItems_SETTINGS_OFF() { + return "§cdeaktiviert"; + } + + @Override + public String LobbyItems_BACK() { + return "§cZurück"; + } + + @Override + public String LobbyBoard_FOUND_SECRETS() { + return "§eVerstecke§7:"; + } + + @Override + public String LobbyBoard_COINS() { + return "§eDeine Coins§7:"; + } + + @Override + public String LobbyBoard_TS() { + return "§eTeamSpeak§7:"; + } + + @Override + public String LobbyBoard_FORUM() { + return "§eForum§7:"; + } + + @Override + public String LobbyBoard_NEW() { + return "§e§lJetzt neu:"; + } + + @Override + public String LobbyBoard_NEWS() { + return "Scheibenwischer"; + } + +} \ No newline at end of file diff --git a/src/eu/univento/core/api/languages/Language_EN.java b/src/eu/univento/core/api/languages/Language_EN.java new file mode 100644 index 0000000..f706b53 --- /dev/null +++ b/src/eu/univento/core/api/languages/Language_EN.java @@ -0,0 +1,556 @@ +package eu.univento.core.api.languages; + +import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.Perms; + +/** + * @author joethei + * @version 0.1 + */ +public class Language_EN implements Languages{ + + @Override + public String UNKNOWN_ERROR() { + return "§cEs ist ein unbekannter Fehler aufgetreten"; + } + + @Override + public String NO_PERMS() { + return "§cYou're not allowed do use this command"; + } + + @Override + public String ERROR() { + return "§cERROR: "; + } + + @Override + public String NOT_ONLINE(String name) { + return "§7" + name + " is §cnot §7online"; + } + + @Override + public String KICK_RESTART() { + return "§cThe server has been restarted"; + } + + @Override + public String KICK_FULL() { + return "§cThe server is full"; + } + + @Override + public String COMMAND_NOT_FOUND() { + return "§cThis command hasn't been found."; + } + + @Override + public String Core_FIX_OWN() { + return "§7You were §efixed"; + } + + @Override + public String Core_FIX_OTHER(CustomPlayer p) { + return "§7You §efixed " + p.getDisplayName(); + } + + @Override + public String Core_FIX_BY_OTHER(CustomPlayer p) { + return "§7You've been §efixed §7by " + p.getDisplayName(); + } + + @Override + public String Core_NICK_ON() { + return "§7You got a §enickname"; + } + + @Override + public String Core_NICK_OFF() { + return "§7Now you have §cno more keinen §enickname"; + } + + @Override + public String Core_BUILD_ON() { + return "§7You've §ajoined §7the building-mode"; + } + + @Override + public String Core_BUILD_OFF() { + return "§7You've §cleft §7the building-mode"; + } + + @Override + public String Core_BAN_NO_REASON() { + return "§cThis reason doesn't exist"; + } + + @Override + public String Core_BAN_USAGE() { + return "§cUse "; + } + + @Override + public String Core_BAN_BANNED(CustomPlayer p) { + return "§7You've §cbanned " + p.getColor() + p.getDisplayName(); + } + + @Override + public String Core_GM_USAGE() { + return "§7Use §e/gm <0 | 1 | 2 | 3>"; + } + + @Override + public String Core_GM_CHANGED() { + return "§7You're gamemode has been §achanged"; + } + + @Override + public String Core_GLOBALMUTE_ON() { + return "§7The server has been §cmuted"; + } + + @Override + public String Core_GLOBALMUTE_OFF() { + return "§7The server has been §aunmuted"; + } + + @Override + public String Core_RUNAS_USAGE() { + return "§cUse /runas "; + } + + @Override + public String Core_RUNAS_RUN(CustomPlayer p) { + return "§7The player " + p.getColor() + p.getDisplayName() + " §7has executed your command §esuccesfully"; + } + + @Override + public String Core_SETRANK_USAGE() { + return "§cUse /setrank "; + } + + @Override + public String Core_SETRANK_KICK() { + return "\n§aYou've got a new rank,§e\nplease rejoin§7."; + } + + @Override + public String Core_SETRANK_NO_RANK() { + return "§cThis rank doesn't exist"; + } + + @Override + public String Core_SETRANK_SET(CustomPlayer p, Perms.Ranks rank) { + return "§7You gave " + p.getDisplayName() + " the rank §e" + rank.toString(); + } + + @Override + public String Core_TS_ALLREADY_VERIFIED() { + return "§cYou've already had a verificated account"; + } + + @Override + public String Core_TS_VERIFIED() { + return "§7You verificated your account §esuccesfully"; + } + + @Override + public String Core_VANISH_ON() { + return "§7You are now §aunvisible"; + } + + @Override + public String Core_VANISH_OFF() { + return "§7You are now §cvisible §7again"; + } + + @Override + public String Core_SERVER_MUTED() { + return "§7The chat has been §cblocked"; + } + + @Override + public String Core_CHAT_CLEARED(CustomPlayer p) { + return "§7The chat has been §ccleaned §7by " + p.getColor() + p.getDisplayName(); + } + + @Override + public String Core_TAB_TITLE() { + return "§7You're playing on §e"; + } + + @Override + public String Lobby_PLAYERS_HIDE() { + return "§7You've §chidden §7all other players"; + } + + @Override + public String Lobby_PLAYERS_SHOW() { + return "§7Now you can §asee §7all other players "; + } + + @Override + public String Lobby_AUTONICK_ON() { + return "§7You'll §aget an automatical §enickname"; + } + + @Override + public String Lobby_AUTONICK_OFF() { + return "§7You're §cnot getting an automatical §enickname §eanymore"; + } + + @Override + public String Lobby_FORCEFIELD_ON() { + return "§7You §aactivated §7your §eforcefield"; + } + + @Override + public String Lobby_FORCEFIELD_OFF() { + return "§7You §cdeactivated §7your §eforcefield"; + } + + @Override + public String Lobby_SILENT_LOBBY_ON() { + return "§7You §ajoined §7the §esilent-lobby"; + } + + @Override + public String Lobby_SILENT_LOBBY_OFF() { + return "§7You §eleft §7the §esilent-lobby"; + } + + @Override + public String Lobby_PLAYING_MUSIC_PREFIX() { + return "§6Now playing: "; + } + + @Override + public String Lobby_FOUND_ITEM_PREFIX() { + return "§7You've §efound §7something"; + } + + @Override + public String Lobby_SET_LOCATION() { + return "§aPoisition has been set"; + } + + @Override + public String Lobby_SET_LOCATION_USAGE() { + return "§cUse /setloc "; + } + + @Override + public String Lobby_DROP_ITEM_USAGE() { + return "§cUse /dropitem "; + } + + @Override + public String Lobby_DROP_ITEM() { + return "§aYou set an item"; + } + + @Override + public String Lobby_SET_SIGN() { + return "§aNeues Status Schild erstellt"; + } + + @Override + public String Lobby_JOIN_TITLE_1() { + return "§6univento§7.§eeu"; + } + + @Override + public String Lobby_JOIN_TITLE_2() { + return "§cI'm just cleaning hear"; + } + + @Override + public String Lobby_PET_ADD() { + return "§7Now you have a §epet"; + } + + @Override + public String Lobby_PET_REMOVE() { + return "§7Du hast nun §ckein §eHaustier §7mehr"; + } + + @Override + public String Lobby_PARKOUR_ON() { + return "§7You §ajoined §7the §eparkour mode"; + } + + @Override + public String Lobby_PARKOUR_OFF() { + return "§7You §cleft §7the §eparkour mode"; + } + + @Override + public String LobbyItems_NAVIGATOR() { + return "§eNavigator"; + } + + @Override + public String LobbyItems_PLAYER_HIDER_ON() { + return "§cHide players"; + } + + @Override + public String LobbyItems_PLAYER_HIDER_OFF() { + return "§aShow players"; + } + + @Override + public String LobbyItems_AUTO_NICK() { + return "§5AutoNick"; + } + + @Override + public String LobbyItems_SILENT_LOBBY() { + return "§cSilent-Lobby"; + } + + @Override + public String LobbyItems_FORCEFIELD() { + return "§aForcefield"; + } + + @Override + public String LobbyItems_FUN_CHEST() { + return "§cF§aU§eN§3Chest"; + } + + @Override + public String LobbyItems_PROFILE() { + return "§eYour profile"; + } + + @Override + public String LobbyItems_YOUTUBER() { + return "§5Youtuber Funktionen"; + } + + @Override + public String LobbyItems_SUGGESTION() { + return "§6Suggestions"; + } + + @Override + public String LobbyItems_SPAWN() { + return "§6Spawn"; + } + + @Override + public String LobbyItems_PREMIUMHUB() { + return "§6Premium Lobby"; + } + + @Override + public String LobbyItems_MAYA() { + return "§6Maya"; + } + + @Override + public String LobbyItems_WOOLGET() { + return "§6WoolGet"; + } + + @Override + public String LobbyItems_BUILDSERVER() { + return "§aBuilding-Server"; + } + + @Override + public String LobbyItems_PLAYERS_ONLINE() { + return " §6players online"; + } + + @Override + public String LobbyItems_GADGETS() { + return "§6Gadgets"; + } + + @Override + public String LobbyItems_MUSIC() { + return "§6Music"; + } + + @Override + public String LobbyItems_PARTICLE() { + return "§6Particles"; + } + + @Override + public String LobbyItems_PETS() { + return "§6Pets"; + } + + @Override + public String LobbyItems_YOUR_PET() { + return "§6your pet"; + } + + @Override + public String LobbyItems_PETS_NAME() { + return "§6change name"; + } + + @Override + public String LobbyItems_PETS_AGE() { + return "§6change age"; + } + + @Override + public String LobbyItems_PETS_RIDE() { + return "§6ride"; + } + + @Override + public String LobbyItems_PETS_REMOVE() { + return "§6ride pet"; + } + + @Override + public String LobbyItems_PETS_PIG() { + return "§6pig"; + } + + @Override + public String LobbyItems_PETS_COW() { + return "§6cow"; + } + + @Override + public String LobbyItems_PETS_CHICKEN() { + return "§6chicken"; + } + + @Override + public String LobbyItems_PETS_RABBIT() { + return "§6rabbit"; + } + + @Override + public String LobbyItems_PETS_MUSHROM_COW() { + return "§6mushroom-cow"; + } + + @Override + public String LobbyItems_PLAYER_MENU() { + return " menu"; + } + + @Override + public String LobbyItems_PLAYER_FRIEND() { + return "§6send freind request"; + } + + @Override + public String LobbyItems_PLAYER_PARTY() { + return "§6send party request"; + } + + @Override + public String LobbyItems_PLAYER_PROFILE() { + return "§6Profil"; + } + + @Override + public String LobbyItems_PLAYER_STATS() { + return "§6stats"; + } + + @Override + public String LobbyItems_STATS() { + return "§6Deine Statistiken"; + } + + @Override + public String LobbyItems_FRIENDS() { + return "§6friends"; + } + + @Override + public String LobbyItems_SETTINGS() { + return "§eSettings"; + } + + @Override + public String LobbyItems_SETTINGS_FASTMENU() { + return "§6inventory animations"; + } + + @Override + public String LobbyItems_SETTINGS_SERVER_TELEPORT() { + return "§6Server-Teleport"; + } + + @Override + public String LobbyItems_SETTINGS_PARTY_REQUESTS() { + return "§6party requests"; + } + + @Override + public String LobbyItems_SETTINGS_FRIEND_REQUESTS() { + return "§6friend requests"; + } + + @Override + public String LobbyItems_SETTINGS_CHATSOUNDS() { + return "§6chat sounds"; + } + + @Override + public String LobbyItems_SETTINGS_EFFECTS() { + return "§6effects"; + } + + @Override + public String LobbyItems_SETTINGS_LANGUAGES() { + return "§6languages"; + } + + @Override + public String LobbyItems_SETTINGS_ON() { + return "§aactivated"; + } + + @Override + public String LobbyItems_SETTINGS_OFF() { + return "§cdeactivated"; + } + + @Override + public String LobbyItems_BACK() { + return "§cback"; + } + + @Override + public String LobbyBoard_FOUND_SECRETS() { + return "§eSecrets§7:"; + } + + @Override + public String LobbyBoard_COINS() { + return "§eYour coins§7:"; + } + + @Override + public String LobbyBoard_TS() { + return "§eTeamSpeak§7:"; + } + + @Override + public String LobbyBoard_FORUM() { + return "§eForum§7:"; + } + + @Override + public String LobbyBoard_NEW() { + return "§e§lJetzt neu:"; + } + + @Override + public String LobbyBoard_NEWS() { + return "Scheibenwischer"; + } +} \ No newline at end of file diff --git a/src/eu/univento/core/api/languages/Language_IT.java b/src/eu/univento/core/api/languages/Language_IT.java new file mode 100644 index 0000000..913c576 --- /dev/null +++ b/src/eu/univento/core/api/languages/Language_IT.java @@ -0,0 +1,555 @@ +package eu.univento.core.api.languages; + +import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.Perms; + +/** + * @author joethei + * @version 0.1 + */ +public class Language_IT implements Languages{ + + @Override + public String UNKNOWN_ERROR() { + return "§cSi è presentato un errore sconosciuto"; + } + + @Override + public String NO_PERMS() { + return "§cNon hai accesso a quel commando"; + } + + @Override + public String ERROR() { + return "§cErrore: "; + } + + @Override + public String NOT_ONLINE(String name) { + return "§7" + name + " §cnon §7è online"; + } + + @Override + public String KICK_RESTART() { + return "§cIl server è stato riavviato"; + } + + @Override + public String KICK_FULL() { + return "§cQuesto server è pieno"; + } + + @Override + public String COMMAND_NOT_FOUND() { + return "§cNon è stato trovato questo commando"; + } + + @Override + public String Core_FIX_OWN() { + return "§7Tu sei stato §efissato"; + } + + @Override + public String Core_FIX_OTHER(CustomPlayer p) { + return "§7Tu hai §efissato " + p.getDisplayName(); + } + + @Override + public String Core_FIX_BY_OTHER(CustomPlayer p) { + return "§7Tu sei stato §efissato §7da" + p.getDisplayName(); + } + + @Override + public String Core_NICK_ON() { + return "§7Hai ricevuto un §eNickname"; + } + + @Override + public String Core_NICK_OFF() { + return "§7Adesso §cnon §7hai più un §eNickname"; + } + + @Override + public String Core_BUILD_ON() { + return "§7Tu sei §aentrato nel §emodo di costruzione"; + } + + @Override + public String Core_BUILD_OFF() { + return "§7Tu sei §auscito dal §emodo di costruzione"; + } + + @Override + public String Core_BAN_NO_REASON() { + return "§cQuesto motivo non esiste"; + } + + @Override + public String Core_BAN_USAGE() { + return "§cDevi usare /ban "; + } + + @Override + public String Core_BAN_BANNED(CustomPlayer p) { + return "§7Tu hai §ebannato " + p.getColor() + p.getDisplayName(); + } + + @Override + public String Core_GM_USAGE() { + return "§7Usi §e/gm <0 | 1 | 2 | 3>"; + } + + @Override + public String Core_GM_CHANGED() { + return "§7La tua modalitá del gioco è stata §aaggiornata"; + } + + @Override + public String Core_GLOBALMUTE_ON() { + return "§7Il server è stato messo §csilenzioso"; + } + + @Override + public String Core_GLOBALMUTE_OFF() { + return "§7Il server è stato rimesso §cnormale"; + } + + @Override + public String Core_RUNAS_USAGE() { + return "§cUsi /runas "; + } + + @Override + public String Core_RUNAS_RUN(CustomPlayer p) { + return p.getColor() + p.getDisplayName() + " §7ha eseguito il tuo commando"; + } + + @Override + public String Core_SETRANK_USAGE() { + return "§cUsi /setrank "; + } + + @Override + public String Core_SETRANK_KICK() { + return "\n§aHai un nuovo gruppo§e\nti prego di rientrare il server§7."; + } + + @Override + public String Core_SETRANK_NO_RANK() { + return "§cQuesto gruppo non esiste"; + } + + @Override + public String Core_SETRANK_SET(CustomPlayer p, Perms.Ranks rank) { + return "§7Hai dato " + p.getDisplayName() + " il gruppo §e" + rank.toString(); + } + @Override + public String Core_TS_ALLREADY_VERIFIED() { + return "§cTu hai già un account verificato"; + } + + @Override + public String Core_TS_VERIFIED() { + return "§7Hai verificato il tuo account con §esuccesso"; + } + + @Override + public String Core_VANISH_ON() { + return "§7Adesso sei §ainvisibile §7per gli altri"; + } + + @Override + public String Core_VANISH_OFF() { + return "§7Adesso sei §crivisibile §7per gli altri"; + } + + @Override + public String Core_SERVER_MUTED() { + return "§7Il chat è stato §cmutato"; + } + + @Override + public String Core_CHAT_CLEARED(CustomPlayer p) { + return "§7La chat è stato §cpulito §7da " + p.getColor() + p.getDisplayName(); + } + + @Override + public String Core_TAB_TITLE() { + return "§7Stai giocando su §e"; + } + + @Override + public String Lobby_PLAYERS_HIDE() { + return "§7Adesso gli altri sono §cinvisibili §7per te"; + } + + @Override + public String Lobby_PLAYERS_SHOW() { + return "§7Adesso gli altri sono §avisibili §7per te"; + } + + @Override + public String Lobby_AUTONICK_ON() { + return "§7Adesso ti viene dato un §esoprannome §7automatico"; + } + + @Override + public String Lobby_AUTONICK_OFF() { + return "§7Adesso §cnon §7ti viene più dato un §esoprannome §7automatico"; + } + + @Override + public String Lobby_FORCEFIELD_ON() { + return "§7Hai §7attivato §7il §eforcefield"; + } + + @Override + public String Lobby_FORCEFIELD_OFF() { + return "§7Hai §cdisattivato §7il §eforcefield"; + } + + @Override + public String Lobby_SILENT_LOBBY_ON() { + return "§7Sei §aentrato §7nella §esilent-lobby"; + } + + @Override + public String Lobby_SILENT_LOBBY_OFF() { + return "§7Sei §euscita §7della §esilent-lobby"; + } + + @Override + public String Lobby_PLAYING_MUSIC_PREFIX() { + return "§6In riproduzione: "; + } + + @Override + public String Lobby_FOUND_ITEM_PREFIX() { + return "§7Hai §etrovato §7qualcosa"; + } + + @Override + public String Lobby_SET_LOCATION() { + return "§aPosizione è stata fissata"; + } + + @Override + public String Lobby_SET_LOCATION_USAGE() { + return "§cUsi /setloc "; + } + + @Override + public String Lobby_DROP_ITEM_USAGE() { + return "§cUsi /dropitem "; + } + + @Override + public String Lobby_DROP_ITEM() { + return "§aHai messo un nuovo item qui."; + } + + @Override + public String Lobby_SET_SIGN() { + return "§aNeues Status Schild erstellt"; + } + + @Override + public String Lobby_JOIN_TITLE_1() { + return "§6univento§7.§eeu"; + } + + @Override + public String Lobby_JOIN_TITLE_2() { + return "§cIo solo pulisco qui"; + } + + @Override + public String Lobby_PET_ADD() { + return "§7Adesso hai un §eanimale domestico"; + } + + @Override + public String Lobby_PET_REMOVE() { + return "§cNon §7hai più un §eanimale domestico"; + } + + @Override + public String Lobby_PARKOUR_ON() { + return "§7Sei §aentrato §7nel §emodo del parkour"; + } + + @Override + public String Lobby_PARKOUR_OFF() { + return "§7Sei §cuscito §7del §emodo del parkour"; + } + + @Override + public String LobbyItems_NAVIGATOR() { + return "§eNavigatore"; + } + + @Override + public String LobbyItems_PLAYER_HIDER_ON() { + return "§cNascondere i giocatori"; + } + + @Override + public String LobbyItems_PLAYER_HIDER_OFF() { + return "§aMostrare i giocatori"; + } + + @Override + public String LobbyItems_AUTO_NICK() { + return "§5AutoNick"; + } + + @Override + public String LobbyItems_SILENT_LOBBY() { + return "§cSilent-Lobby"; + } + + @Override + public String LobbyItems_FORCEFIELD() { + return "§aForcefield"; + } + + @Override + public String LobbyItems_FUN_CHEST() { + return "§cF§aU§eN§3Chest"; + } + + @Override + public String LobbyItems_PROFILE() { + return "§eIl tuo profilo"; + } + + @Override + public String LobbyItems_YOUTUBER() { + return "§5Altri funzioni"; + } + + @Override + public String LobbyItems_SUGGESTION() { + return "§6Suggestioni"; + } + + @Override + public String LobbyItems_SPAWN() { + return "§6Spawn"; + } + + @Override + public String LobbyItems_PREMIUMHUB() { + return "§6Lobby dei VIP"; + } + + @Override + public String LobbyItems_MAYA() { + return "§6Maya"; + } + + @Override + public String LobbyItems_WOOLGET() { + return "§6WoolGet"; + } + + @Override + public String LobbyItems_BUILDSERVER() { + return "§aServer per costruire"; + } + + @Override + public String LobbyItems_PLAYERS_ONLINE() { + return " §6giocatori sono online"; + } + + @Override + public String LobbyItems_GADGETS() { + return "§6Gadgets"; + } + + @Override + public String LobbyItems_MUSIC() { + return "§6Musica"; + } + + @Override + public String LobbyItems_PARTICLE() { + return "§6Particelle"; + } + + @Override + public String LobbyItems_PETS() { + return "§6Animali domestici"; + } + + @Override + public String LobbyItems_YOUR_PET() { + return "§6Il tuo animale domestico"; + } + + @Override + public String LobbyItems_PETS_NAME() { + return "§6Cambiare il nome"; + } + + @Override + public String LobbyItems_PETS_AGE() { + return "§6Cambiare l'età"; + } + + @Override + public String LobbyItems_PETS_RIDE() { + return "§6Cavalcarlo"; + } + + @Override + public String LobbyItems_PETS_REMOVE() { + return "§6Cancellarlo"; + } + + @Override + public String LobbyItems_PETS_PIG() { + return "§6Maiale"; + } + + @Override + public String LobbyItems_PETS_COW() { + return "§6Mucca"; + } + + @Override + public String LobbyItems_PETS_CHICKEN() { + return "§6Gallina"; + } + + @Override + public String LobbyItems_PETS_RABBIT() { + return "§6Coniglio"; + } + + @Override + public String LobbyItems_PETS_MUSHROM_COW() { + return "§6Muucelio"; + } + + @Override + public String LobbyItems_PLAYER_MENU() { + return " menu"; + } + + @Override + public String LobbyItems_PLAYER_FRIEND() { + return "§6Inviare una richiesta di amicizia"; + } + + @Override + public String LobbyItems_PLAYER_PARTY() { + return "§6Inviare una richiesta per una party"; + } + + @Override + public String LobbyItems_PLAYER_PROFILE() { + return "§6Il suo profilo"; + } + + @Override + public String LobbyItems_PLAYER_STATS() { + return "§6Statistiche"; + } + + @Override + public String LobbyItems_STATS() { + return "§6Le tue statistiche"; + } + + @Override + public String LobbyItems_FRIENDS() { + return "§6Amici"; + } + + @Override + public String LobbyItems_SETTINGS() { + return "§eOpzioni"; + } + + @Override + public String LobbyItems_SETTINGS_FASTMENU() { + return "§6Animazioni dell'inventario"; + } + + @Override + public String LobbyItems_SETTINGS_SERVER_TELEPORT() { + return "§6Server-Teleport"; + } + + @Override + public String LobbyItems_SETTINGS_PARTY_REQUESTS() { + return "§6Richieste per una party"; + } + + @Override + public String LobbyItems_SETTINGS_FRIEND_REQUESTS() { + return "§6Richieste di amicizia"; + } + + @Override + public String LobbyItems_SETTINGS_CHATSOUNDS() { + return "§6Suoni del chat"; + } + + @Override + public String LobbyItems_SETTINGS_EFFECTS() { + return "§6Effetti"; + } + + @Override + public String LobbyItems_SETTINGS_LANGUAGES() { + return "§6Lingue"; + } + + @Override + public String LobbyItems_SETTINGS_ON() { + return "§aattivato"; + } + + @Override + public String LobbyItems_SETTINGS_OFF() { + return "§cdisattivato"; + } + + @Override + public String LobbyItems_BACK() { + return "§cindietro"; + } + + @Override + public String LobbyBoard_FOUND_SECRETS() { + return "§eSegreti§7:"; + } + + @Override + public String LobbyBoard_COINS() { + return "§eI tuoi Coins§7:"; + } + + @Override + public String LobbyBoard_TS() { + return "§eTeamSpeak§7:"; + } + + @Override + public String LobbyBoard_FORUM() { + return "§eForum§7:"; + } + + @Override + public String LobbyBoard_NEW() { + return "§e§lNovità:"; + } + + @Override + public String LobbyBoard_NEWS() { + return "Scheibenwischer"; + } +} \ No newline at end of file diff --git a/src/eu/univento/core/api/languages/Languages.java b/src/eu/univento/core/api/languages/Languages.java new file mode 100644 index 0000000..a74dd53 --- /dev/null +++ b/src/eu/univento/core/api/languages/Languages.java @@ -0,0 +1,125 @@ +package eu.univento.core.api.languages; + +import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.Perms; + +/** + * @author joethei + * @version 0.3 + */ +public interface Languages{ + + String UNKNOWN_ERROR(); + String NO_PERMS(); + String ERROR(); + String NOT_ONLINE(String name); + String KICK_RESTART(); + String KICK_FULL(); + String COMMAND_NOT_FOUND(); + + String Core_FIX_OWN(); + String Core_FIX_OTHER(CustomPlayer p); + String Core_FIX_BY_OTHER(CustomPlayer p); + String Core_NICK_ON(); + String Core_NICK_OFF(); + String Core_BUILD_ON(); + String Core_BUILD_OFF(); + String Core_BAN_NO_REASON(); + String Core_BAN_USAGE(); + String Core_BAN_BANNED(CustomPlayer p); + String Core_GM_USAGE(); + String Core_GM_CHANGED(); + String Core_GLOBALMUTE_ON(); + String Core_GLOBALMUTE_OFF(); + String Core_RUNAS_USAGE(); + String Core_RUNAS_RUN(CustomPlayer p); + String Core_SETRANK_USAGE(); + String Core_SETRANK_KICK(); + String Core_SETRANK_NO_RANK(); + String Core_SETRANK_SET(CustomPlayer p, Perms.Ranks rank); + String Core_TS_ALLREADY_VERIFIED(); + String Core_TS_VERIFIED(); + String Core_VANISH_ON(); + String Core_VANISH_OFF(); + String Core_SERVER_MUTED(); + String Core_CHAT_CLEARED(CustomPlayer p); + String Core_TAB_TITLE(); + + String Lobby_PLAYERS_HIDE(); + String Lobby_PLAYERS_SHOW(); + String Lobby_AUTONICK_ON(); + String Lobby_AUTONICK_OFF(); + String Lobby_FORCEFIELD_ON(); + String Lobby_FORCEFIELD_OFF(); + String Lobby_SILENT_LOBBY_ON(); + String Lobby_SILENT_LOBBY_OFF(); + String Lobby_PLAYING_MUSIC_PREFIX(); + String Lobby_FOUND_ITEM_PREFIX(); + String Lobby_SET_LOCATION(); + String Lobby_SET_LOCATION_USAGE(); + String Lobby_DROP_ITEM_USAGE(); + String Lobby_DROP_ITEM(); + String Lobby_SET_SIGN(); + String Lobby_JOIN_TITLE_1(); + String Lobby_JOIN_TITLE_2(); + String Lobby_PET_ADD(); + String Lobby_PET_REMOVE(); + String Lobby_PARKOUR_ON(); + String Lobby_PARKOUR_OFF(); + + String LobbyItems_NAVIGATOR(); + String LobbyItems_PLAYER_HIDER_ON(); + String LobbyItems_PLAYER_HIDER_OFF(); + String LobbyItems_AUTO_NICK(); + String LobbyItems_SILENT_LOBBY(); + String LobbyItems_FORCEFIELD(); + String LobbyItems_FUN_CHEST(); + String LobbyItems_PROFILE(); + String LobbyItems_YOUTUBER(); + String LobbyItems_SUGGESTION(); + String LobbyItems_SPAWN(); + String LobbyItems_PREMIUMHUB(); + String LobbyItems_MAYA(); + String LobbyItems_WOOLGET(); + String LobbyItems_BUILDSERVER(); + String LobbyItems_PLAYERS_ONLINE(); + String LobbyItems_GADGETS(); + String LobbyItems_MUSIC(); + String LobbyItems_PARTICLE(); + String LobbyItems_PETS(); + String LobbyItems_YOUR_PET(); + String LobbyItems_PETS_NAME(); + String LobbyItems_PETS_AGE(); + String LobbyItems_PETS_RIDE(); + String LobbyItems_PETS_REMOVE(); + String LobbyItems_PETS_PIG(); + String LobbyItems_PETS_COW(); + String LobbyItems_PETS_CHICKEN(); + String LobbyItems_PETS_RABBIT(); + String LobbyItems_PETS_MUSHROM_COW(); + String LobbyItems_PLAYER_MENU(); + String LobbyItems_PLAYER_FRIEND(); + String LobbyItems_PLAYER_PARTY(); + String LobbyItems_PLAYER_PROFILE(); + String LobbyItems_PLAYER_STATS(); + String LobbyItems_STATS(); + String LobbyItems_FRIENDS(); + String LobbyItems_SETTINGS(); + String LobbyItems_SETTINGS_FASTMENU(); + String LobbyItems_SETTINGS_SERVER_TELEPORT(); + String LobbyItems_SETTINGS_PARTY_REQUESTS(); + String LobbyItems_SETTINGS_FRIEND_REQUESTS(); + String LobbyItems_SETTINGS_CHATSOUNDS(); + String LobbyItems_SETTINGS_EFFECTS(); + String LobbyItems_SETTINGS_LANGUAGES(); + String LobbyItems_SETTINGS_ON(); + String LobbyItems_SETTINGS_OFF(); + String LobbyItems_BACK(); + + String LobbyBoard_FOUND_SECRETS(); + String LobbyBoard_COINS(); + String LobbyBoard_NEW(); + String LobbyBoard_NEWS(); + String LobbyBoard_TS(); + String LobbyBoard_FORUM(); +} \ No newline at end of file diff --git a/src/eu/univento/core/api/languages/Messages.java b/src/eu/univento/core/api/languages/Messages.java new file mode 100644 index 0000000..e06a357 --- /dev/null +++ b/src/eu/univento/core/api/languages/Messages.java @@ -0,0 +1,312 @@ +package eu.univento.core.api.languages; + +import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.Perms; + +/** + * @author joethei + * @version 2.0 + */ +public class Messages { + + CustomPlayer player; + + Language_DE de = new Language_DE(); + Language_EN en = new Language_EN(); + Language_IT it = new Language_IT(); + + Languages lang; + + public Messages(CustomPlayer player) { + this.player = player; + if(player.getLang().equals("DE")) this.lang = de; + if(player.getLang().equals("IT")) this.lang = it; + if(player.getLang().equals("EN")) this.lang = en; + } + + public String PREFIX() { + return " §7• §6univento§7.§eeu §7• "; + } + + public String UNKNOWN_ERROR() { + return lang.UNKNOWN_ERROR(); + } + public String NO_PERMS() { + return lang.NO_PERMS(); + } + public String ERROR() { + return lang.ERROR(); + } + public String NOT_ONLINE(String name) { + return lang.NOT_ONLINE(name); + } + public String KICK_RESTART() { + return lang.KICK_RESTART(); + } + public String KICK_FULL() { + return lang.KICK_FULL(); + } + public String COMMAND_NOT_FOUND() { + return lang.COMMAND_NOT_FOUND(); + } + + public String Core_FIX_OWN() { + return lang.Core_FIX_OWN(); + } + public String Core_FIX_OTHER(CustomPlayer p) { + return lang.Core_FIX_OTHER(p); + } + public String Core_FIX_BY_OTHER(CustomPlayer p) { + return lang.Core_FIX_BY_OTHER(p); + } + public String Core_NICK_ON() { + return lang.Core_NICK_ON(); + } + public String Core_NICK_OFF() { + return lang.Core_NICK_OFF(); + } + public String Core_BUILD_ON() { + return lang.Core_BUILD_ON(); + } + public String Core_BUILD_OFF() { + return lang.Core_BUILD_OFF(); + } + public String Core_BAN_NO_REASON() { + return lang.Core_BAN_NO_REASON(); + } + public String Core_BAN_USAGE() { + return lang.Core_BAN_USAGE(); + } + public String Core_BAN_BANNED(CustomPlayer p) { + return lang.Core_BAN_BANNED(p); + } + public String Core_GM_USAGE() { + return lang.Core_GM_USAGE(); + } + public String Core_GM_CHANGED() { + return lang.Core_GM_CHANGED(); + } + public String Core_GLOBALMUTE_ON() { + return lang.Core_GLOBALMUTE_ON(); + } + public String Core_GLOBALMUTE_OFF() { + return lang.Core_GLOBALMUTE_OFF(); + } + public String Core_RUNAS_USAGE() { + return lang.Core_RUNAS_USAGE(); + } + public String Core_RUNAS_RUN(CustomPlayer p) { + return lang.Core_RUNAS_RUN(p); + } + public String Core_SETRANK_USAGE() { + return lang.Core_SETRANK_USAGE(); + } + public String Core_SETRANK_KICK() { + return lang.Core_SETRANK_KICK(); + } + public String Core_SETRANK_NO_RANK() { + return lang.Core_SETRANK_NO_RANK(); + } + public String Core_SETRANK_SET(CustomPlayer p, Perms.Ranks rank) { + return lang.Core_SETRANK_SET(p, rank); + } + public String Core_TS_ALLREADY_VERIFIED() { + return lang.Core_TS_ALLREADY_VERIFIED(); + } + public String Core_TS_VERIFIED() { + return lang.Core_TS_VERIFIED(); + } + public String Core_VANISH_ON() { + return lang.Core_VANISH_ON(); + } + public String Core_VANISH_OFF() { + return lang.Core_VANISH_OFF(); + } + public String Core_SERVER_MUTED() { + return lang.Core_SERVER_MUTED(); + } + public String Core_CHAT_CLEARED(CustomPlayer p) { return lang.Core_CHAT_CLEARED(p);} + public String Core_TAB_TITLE() { return lang.Core_TAB_TITLE(); } + + public String Lobby_PLAYERS_HIDE() { + return lang.Lobby_PLAYERS_HIDE(); + } + public String Lobby_PLAYERS_SHOW() { + return lang.Lobby_PLAYERS_SHOW(); + } + public String Lobby_AUTONICK_ON() { + return lang.Lobby_AUTONICK_ON(); + } + public String Lobby_AUTONICK_OFF() { + return lang.Lobby_AUTONICK_OFF(); + } + public String Lobby_FORCEFIELD_ON() { + return lang.Lobby_FORCEFIELD_ON(); + } + public String Lobby_FORCEFIELD_OFF() { + return lang.Lobby_FORCEFIELD_OFF(); + } + public String Lobby_SILENT_LOBBY_ON() { + return lang.Lobby_SILENT_LOBBY_ON(); + } + public String Lobby_SILENT_LOBBY_OFF() { + return lang.Lobby_SILENT_LOBBY_OFF(); + } + public String Lobby_PLAYING_MUSIC_PREFIX() { + return lang.Lobby_PLAYING_MUSIC_PREFIX(); + } + public String Lobby_FOUND_ITEM_PREFIX() { + return lang.Lobby_FOUND_ITEM_PREFIX(); + } + public String Lobby_SET_LOCATION() { + return lang.Lobby_SET_LOCATION(); + } + public String Lobby_SET_LOCATION_USAGE() { + return lang.Lobby_SET_LOCATION_USAGE(); + } + public String Lobby_DROP_ITEM_USAGE() { + return lang.Lobby_DROP_ITEM_USAGE(); + } + public String Lobby_DROP_ITEM() { + return lang.Lobby_DROP_ITEM(); + } + public String Lobby_SET_SIGN() { + return lang.Lobby_SET_SIGN(); + } + public String Lobby_JOIN_TITLE_1() { + return lang.Lobby_JOIN_TITLE_1(); + } + public String Lobby_JOIN_TITLE_2() { + return lang.Lobby_JOIN_TITLE_2(); + } + public String Lobby_PET_ADD() { + return lang.Lobby_PET_ADD(); + } + public String Lobby_PET_REMOVE() { + return lang.Lobby_PET_REMOVE(); + } + public String Lobby_PARKOUR_ON() { + return lang.Lobby_PARKOUR_ON(); + } + public String Lobby_PARKOUR_OFF() { + return lang.Lobby_PARKOUR_OFF(); + } + + public String LobbyItems_NAVIGATOR() { + return lang.LobbyItems_NAVIGATOR(); + } + public String LobbyItems_PLAYER_HIDER_ON() { + return lang.LobbyItems_PLAYER_HIDER_ON(); + } + public String LobbyItems_PLAYER_HIDER_OFF() { + return lang.LobbyItems_PLAYER_HIDER_OFF(); + } + public String LobbyItems_AUTO_NICK() { + return lang.LobbyItems_AUTO_NICK(); + } + public String LobbyItems_SILENT_LOBBY() { + return lang.LobbyItems_SILENT_LOBBY(); + } + public String LobbyItems_FORCEFIELD() { + return lang.LobbyItems_FORCEFIELD(); + } + public String LobbyItems_FUN_CHEST() { + return lang.LobbyItems_FUN_CHEST(); + } + public String LobbyItems_PROFILE() { + return lang.LobbyItems_PROFILE(); + } + public String LobbyItems_YOUTUBER() { return lang.LobbyItems_YOUTUBER(); } + public String LobbyItems_SUGGESTION() { return lang.LobbyItems_SUGGESTION(); } + public String LobbyItems_SPAWN() { + return lang.LobbyItems_SPAWN(); + } + public String LobbyItems_PREMIUMHUB() { + return lang.LobbyItems_PREMIUMHUB(); + } + public String LobbyItems_MAYA() { + return lang.LobbyItems_MAYA(); + } + public String LobbyItems_WOOLGET() { return lang.LobbyItems_WOOLGET(); } + public String LobbyItems_BUILDSERVER() { + return lang.LobbyItems_BUILDSERVER(); + } + public String LobbyItems_PLAYERS_ONLINE() { + return lang.LobbyItems_PLAYERS_ONLINE(); + } + public String LobbyItems_GADGETS() { + return lang.LobbyItems_GADGETS(); + } + public String LobbyItems_MUSIC() { + return lang.LobbyItems_MUSIC(); + } + public String LobbyItems_PARTICLE() { + return lang.LobbyItems_PARTICLE(); + } + public String LobbyItems_PETS() { + return lang.LobbyItems_PETS(); + } + public String LobbyItems_YOUR_PET() { return lang.LobbyItems_YOUR_PET(); } + public String LobbyItems_PETS_NAME() { return lang.LobbyItems_PETS_NAME(); } + public String LobbyItems_PETS_AGE() { return lang.LobbyItems_PETS_AGE(); } + public String LobbyItems_PETS_RIDE() { return lang.LobbyItems_PETS_RIDE(); } + public String LobbyItems_PETS_REMOVE() { return lang.LobbyItems_PETS_REMOVE(); } + public String LobbyItems_PETS_PIG() { return lang.LobbyItems_PETS_PIG(); } + public String LobbyItems_PETS_COW() { return lang.LobbyItems_PETS_COW(); } + public String LobbyItems_PETS_CHICKEN() { return lang.LobbyItems_PETS_CHICKEN(); } + public String LobbyItems_PETS_RABBIT() { return lang.LobbyItems_PETS_RABBIT(); } + public String LobbyItems_PETS_MUSHROM_COW () { return lang.LobbyItems_PETS_MUSHROM_COW(); } + public String LobbyItems_PLAYER_MENU() { return lang.LobbyItems_PLAYER_MENU(); } + public String LobbyItems_PLAYER_FRIEND() { return lang.LobbyItems_PLAYER_FRIEND(); } + public String LobbyItems_PLAYER_PARTY() { return lang.LobbyItems_PLAYER_PARTY(); } + public String LobbyItems_PLAYER_PROFILE() { return lang.LobbyItems_PLAYER_PROFILE(); } + public String LobbyItems_PLAYER_STATS() { return lang.LobbyItems_PLAYER_STATS();} + public String LobbyItems_STATS() { + return lang.LobbyItems_STATS(); + } + public String LobbyItems_FRIENDS() { + return lang.LobbyItems_FRIENDS(); + } + public String LobbyItems_SETTINGS() { + return lang.LobbyItems_SETTINGS(); + } + public String LobbyItems_SETTINGS_FASTMENU() { return lang.LobbyItems_SETTINGS_FASTMENU();} + public String LobbyItems_SETTINGS_SERVER_TELEPORT() { return lang.LobbyItems_SETTINGS_SERVER_TELEPORT(); } + public String LobbyItems_SETTINGS_PARTY_REQUESTS() { + return lang.LobbyItems_SETTINGS_PARTY_REQUESTS(); + } + public String LobbyItems_SETTINGS_FRIEND_REQUESTS() { + return lang.LobbyItems_SETTINGS_FRIEND_REQUESTS(); + } + public String LobbyItems_SETTINGS_CHATSOUNDS() { + return lang.LobbyItems_SETTINGS_CHATSOUNDS(); + } + public String LobbyItems_SETTINGS_EFFECTS() { + return lang.LobbyItems_SETTINGS_EFFECTS(); + } + public String LobbyItems_SETTINGS_LANGUAGES() { + return lang.LobbyItems_SETTINGS_LANGUAGES(); + } + public String LobbyItems_SETTINGS_ON() { + return lang.LobbyItems_SETTINGS_ON(); + } + public String LobbyItems_SETTINGS_OFF() { + return lang.LobbyItems_SETTINGS_OFF(); + } + public String LobbyItems_BACK() { return lang.LobbyItems_BACK(); } + + public String LobbyBoard_COINS() { return lang.LobbyBoard_COINS(); } + public String LobbyBoard_NEW() { return lang.LobbyBoard_NEW(); } + public String LobbyBoard_NEWS() { return lang.LobbyBoard_NEWS(); } + public String LobbyBoard_TS() { return lang.LobbyBoard_TS(); } + public String LobbyBoard_FORUM() { return lang.LobbyBoard_FORUM(); } + public String LobbyBoard_FOUND_SECRETS() { return lang.LobbyBoard_FOUND_SECRETS(); } + + public class Build { + public String PREFIX = "• §bTeam§3Vento • "; + } + + public static class Console{ + public static String NOT_A_PLAYER = "You are not a valid player"; + } +} \ No newline at end of file diff --git a/src/eu/univento/core/api/map/Region.java b/src/eu/univento/core/api/map/Region.java new file mode 100644 index 0000000..100d45f --- /dev/null +++ b/src/eu/univento/core/api/map/Region.java @@ -0,0 +1,88 @@ +package eu.univento.core.api.map; + +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; + + +/** + * @author RainyCrafter + */ +public class Region { + + World w; + + int minx; + int miny; + int minz; + + int maxx; + int maxy; + int maxz; + + String name; + + + + public Region(Location loc1, Location loc2, String name) { + + w = loc1.getWorld(); + + this.name = name; + + minx = Math.min(loc1.getBlockX(), loc2.getBlockX()); + miny = Math.min(loc1.getBlockY(), loc2.getBlockY()); + minz = Math.min(loc1.getBlockZ(), loc2.getBlockZ()); + + maxx = Math.max(loc1.getBlockX(), loc2.getBlockX()); + maxy = Math.max(loc1.getBlockY(), loc2.getBlockY()); + maxz = Math.max(loc1.getBlockZ(), loc2.getBlockZ()); + + + + } + public void save(){ + File file = new File("plugins/Core/regions.yml"); + FileConfiguration cfg = YamlConfiguration.loadConfiguration(file); + + cfg.set(name+".W", w.getName()); + + cfg.set(name+".Min.X", minx); + cfg.set(name+".Min.Y", miny); + cfg.set(name+".Min.Z", minz); + + cfg.set(name+".Max.X", maxx); + cfg.set(name+".Max.Y", maxy); + cfg.set(name+".Max.Z", maxz); + + try { + cfg.save(file); + } catch (IOException e) { + e.printStackTrace(); + } + + } + public boolean between(int w1, int zw, int w2){ + if(zw >= w1 && zw <= w2){ + return true; + } + return false; + } + + public boolean isInside(Location loc) { + if (loc.getWorld() != w) { + return false; + } + + if (between(minx, loc.getBlockX(), maxx) && between(miny, loc.getBlockY(), maxy) && between(minz, loc.getBlockZ(), maxz)) { + return true; + } + return false; + } + + +} \ No newline at end of file diff --git a/src/eu/univento/core/api/map/Schematic.java b/src/eu/univento/core/api/map/Schematic.java new file mode 100644 index 0000000..dc21f9a --- /dev/null +++ b/src/eu/univento/core/api/map/Schematic.java @@ -0,0 +1,98 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package eu.univento.core.api.map; + +import ch.spacebase.opennbt.stream.NBTInputStream; +import ch.spacebase.opennbt.tag.*; +import eu.univento.core.api.map.Constants.MinecraftSchematicTagNames; + +import java.io.File; +import java.io.FileInputStream; +import java.util.List; + +/** + * + * @author James + */ +public class Schematic { + + private CompoundTag _baseTag; + private ShortTag _width; + private ShortTag _length; + private ShortTag _height; + private StringTag _materials; + private ByteArrayTag _blocks; + private ByteArrayTag _blockData; + private List _entities; + private List _tileEntities; + + public Schematic(File schematicFile) { + _baseTag = getSchematicTagFromNBTFile(schematicFile); + + _width = (ShortTag) _baseTag.get(MinecraftSchematicTagNames.WIDTH); + _length = (ShortTag) _baseTag.get(MinecraftSchematicTagNames.LENGTH); + _height = (ShortTag) _baseTag.get(MinecraftSchematicTagNames.HEIGHT); + _blocks = (ByteArrayTag) _baseTag.get(MinecraftSchematicTagNames.BLOCKS); + _blockData = (ByteArrayTag) _baseTag.get(MinecraftSchematicTagNames.DATA); + + _entities = ((ListTag) _baseTag.get(MinecraftSchematicTagNames.ENTITIES)).getValue(); + _tileEntities = ((ListTag) _baseTag.get(MinecraftSchematicTagNames.TILE_ENTITIES)).getValue(); + + + + } + + private static CompoundTag getSchematicTagFromNBTFile(File schematicFile) { + CompoundTag schematicTag = null; + + try { + FileInputStream stream = new FileInputStream(schematicFile); + NBTInputStream nbtStream = new NBTInputStream(stream); + + schematicTag = (CompoundTag) nbtStream.readTag(); + nbtStream.close(); + stream.close(); + } catch (Exception e) { + //TODO: LOG ERROR + } + return schematicTag; + } + + public CompoundTag getBaseTag() { + return _baseTag; + } + + public ShortTag getWidth() { + return _width; + } + + public ShortTag getLength() { + return _length; + } + + public ShortTag getHeight() { + return _height; + } + + public StringTag getMaterials() { + return _materials; + } + + public ByteArrayTag getBlocks() { + return _blocks; + } + + public ByteArrayTag getBlockData() { + return _blockData; + } + + public List getEntities() { + return _entities; + } + + public List getTileEntities() { + return _tileEntities; + } +} diff --git a/src/eu/univento/core/api/player/BanSystem.java b/src/eu/univento/core/api/player/BanSystem.java index ec68adb..654b888 100644 --- a/src/eu/univento/core/api/player/BanSystem.java +++ b/src/eu/univento/core/api/player/BanSystem.java @@ -1,17 +1,17 @@ package eu.univento.core.api.player; import eu.univento.core.Core; -import eu.univento.core.api.MySQL; +import eu.univento.core.api.database.MySQL; import eu.univento.core.api.utils.NameFetcher; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; /** * bans and unbans players @@ -29,18 +29,19 @@ public class BanSystem{ * @throws SQLException SQL server not available or throwing error * @throws ClassNotFoundException class couldn't be found */ -public static void setBanned(Player p, String reason, Player who, int time)throws SQLException, ClassNotFoundException { +static void setBanned(CustomPlayer p, String reason, CustomPlayer who, int time)throws SQLException, ClassNotFoundException { + int id = p.getID(); MySQL sql = Core.returnSQL(); sql.openConnection(); - String uuid = p.getUniqueId().toString(); - String whouuid = who.getUniqueId().toString(); Date date = new Date(); - date.setTime(date.getTime() + (time + 24)); - - Core.returnSQL().getConnection().createStatement().execute("INSERT INTO bans (player_uuid, Reason, who, time) VALUES ('" + uuid + "', '" + reason + "', '" + whouuid + "', '" + date.getTime() + "');"); - p.kickPlayer("§cDu wurdest gebannt. §6Grund: " + reason + "\nDauer: " + time); - who.sendMessage("§cDu hast den Spieler " + p.getName() + " für " + time + " Tage gebannt"); + date.setTime(date.getTime() + (time * 24)); + Timestamp timestamp = new Timestamp(date.getTime()); + + PreparedStatement st = sql.getConnection().prepareStatement("INSERT INTO bans (BID, Reason, until, BannerID) VALUES ('" + id + "', '" + reason + "', '" + who.getID() + "', '" + timestamp + "');"); + st.execute(); + p.kickPlayer("§cYou have been banned. §6Reason: " + reason + "\nUntil: " + timestamp); + who.sendMessage("§cDu hast den Spieler " + p.getColor() + p.getName() + "§c für " + time + " Tage gebannt wegen " + reason); sql.closeConnection(); } @@ -50,11 +51,12 @@ public static void setBanned(Player p, String reason, Player who, int time)throw * @throws SQLException SQL server not available or throwing error * @throws ClassNotFoundException class couldn't be found */ -public static void unban(OfflinePlayer p)throws SQLException, ClassNotFoundException{ +static void removeAllBans(CustomPlayer p) throws SQLException, ClassNotFoundException{ + int id = p.getID(); MySQL sql = Core.returnSQL(); sql.openConnection(); - String uuid = p.getUniqueId().toString(); - Core.returnSQL().getConnection().createStatement().executeUpdate("DELETE FROM bans WHERE player_uuid ='" + uuid + "';"); + PreparedStatement st = sql.getConnection().prepareStatement("DELETE FROM bans WHERE ID ='" + id + "';"); + st.execute(); sql.closeConnection(); } @@ -65,16 +67,37 @@ public static void unban(OfflinePlayer p)throws SQLException, ClassNotFoundExcep * @throws SQLException SQL server not available or throwing error * @throws ClassNotFoundException class couldn't be found */ -public static boolean isBanned(OfflinePlayer p)throws SQLException, ClassNotFoundException { +static boolean isBanned(CustomPlayer p) throws SQLException, ClassNotFoundException { + int id = p.getID(); MySQL sql = Core.returnSQL(); - sql.openConnection(); - String uuid = p.getUniqueId().toString(); - ResultSet rs = Core.returnSQL().getConnection().createStatement().executeQuery("SELECT * FROM bans WHERE player_uuid='" + uuid + "';"); - sql.closeConnection(); - return rs.next(); - + PreparedStatement st = sql.getConnection().prepareStatement("SELECT * FROM bans WHERE ID='" + id + "';"); + ResultSet rs = st.executeQuery(); + if(rs.next()) { + Date date = new Date(); + Timestamp time = new Timestamp(date.getTime()); + sql.closeConnection(); + return time.before(getBanTime(p)); + }else { + sql.closeConnection(); + return false; + } + } + static Timestamp getBanTime(CustomPlayer p) throws SQLException { + int id = p.getID(); + MySQL sql = Core.returnSQL(); + PreparedStatement st = sql.getConnection().prepareStatement("SELECT * FROM bans WHERE ID='" + id + "';"); + ResultSet rs = st.executeQuery(); + if(rs.next()) { + Timestamp time = rs.getTimestamp("until"); + sql.closeConnection(); + return time; + } + sql.closeConnection(); + return null; + } + /** * return reason for ban * @param p player @@ -82,17 +105,20 @@ public static boolean isBanned(OfflinePlayer p)throws SQLException, ClassNotFoun * @throws SQLException SQL server not available or throwing error * @throws ClassNotFoundException class couldn't be found */ -public static String getBanReason(OfflinePlayer p)throws SQLException, ClassNotFoundException { +static String getBanReason(CustomPlayer p)throws SQLException, ClassNotFoundException { + int id = p.getID(); MySQL sql = Core.returnSQL(); sql.openConnection(); - String uuid = p.getUniqueId().toString(); - ResultSet rs = Core.returnSQL().getConnection().createStatement().executeQuery("SELECT * FROM bans WHERE player_uuid='" + uuid + "';"); - if (!rs.next()) { + PreparedStatement st = sql.getConnection().prepareStatement("SELECT * FROM bans WHERE ID='" + id + "';"); + ResultSet rs = st.executeQuery(); + if(rs.next()) { + String reason = rs.getString("Reason"); + sql.closeConnection(); + return reason; + }else { sql.closeConnection(); return null; } - sql.closeConnection(); - return rs.getString("Reason"); } /** @@ -102,18 +128,18 @@ public static String getBanReason(OfflinePlayer p)throws SQLException, ClassNotF * @throws SQLException SQL server not available or throwing error * @throws ClassNotFoundException class couldn't be found */ -public static String getWhoBanned(OfflinePlayer p)throws SQLException, ClassNotFoundException { +static String getWhoBanned(CustomPlayer p)throws SQLException, ClassNotFoundException { + int id = p.getID(); MySQL sql = Core.returnSQL(); sql.openConnection(); - String uuid = p.getUniqueId().toString(); - ResultSet rs = Core.returnSQL().getConnection().createStatement().executeQuery("SELECT * FROM bans WHERE player_uuid='" + uuid + "';"); + ResultSet rs = Core.returnSQL().getConnection().createStatement().executeQuery("SELECT * FROM bans WHERE ID='" + id + "';"); if (!rs.next()) { sql.closeConnection(); return null; } String whouuid = rs.getString("who"); UUID who = UUID.fromString(whouuid); - List list = new ArrayList(); + List list = new ArrayList<>(); list.add(who); NameFetcher name = new NameFetcher(list); sql.closeConnection(); diff --git a/src/eu/univento/core/api/player/CustomPlayer.java b/src/eu/univento/core/api/player/CustomPlayer.java index fbb6c5e..c95daab 100644 --- a/src/eu/univento/core/api/player/CustomPlayer.java +++ b/src/eu/univento/core/api/player/CustomPlayer.java @@ -1,22 +1,29 @@ package eu.univento.core.api.player; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.HashMap; - +import com.github.theholywaffle.teamspeak3.api.wrapper.ClientInfo; +import eu.univento.core.Core; +import eu.univento.core.api.Actionbar; +import eu.univento.core.api.Utils; +import eu.univento.core.api.database.MySQL; +import eu.univento.core.api.server.ServerSettings; +import eu.univento.core.api.server.Servers; +import eu.univento.core.api.utils.NameFetcher; import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Sound; import org.bukkit.craftbukkit.v1_8_R3.CraftServer; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; import org.bukkit.entity.Player; import org.bukkit.scoreboard.Team; -import com.github.theholywaffle.teamspeak3.api.wrapper.ClientInfo; - -import eu.univento.core.Core; -import eu.univento.core.api.MySQL; -import eu.univento.core.api.Servers; -import eu.univento.core.api.Utils; -import eu.univento.core.api.player.Perms.Ranks; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; /** * custom player implementation @@ -48,6 +55,16 @@ public class CustomPlayer extends CraftPlayer { */ private String customColor; + /** + * player id from database + */ + private int id = 0; + + /** + * if player has open inventory + */ + private boolean openInventory; + /** * inits player * @param player Player @@ -56,6 +73,7 @@ public class CustomPlayer extends CraftPlayer { super((CraftServer) Bukkit.getServer(), ((CraftPlayer) player).getHandle()); PLAYERS.put(player.getName().toLowerCase(), this); PLAYER = player; + id = getID(); } /** @@ -80,6 +98,47 @@ public class CustomPlayer extends CraftPlayer { return p == null ? null : new CustomPlayer(p); } } + + /** + * gets custom player from player + * @param player Player + * @return CustomPlayer + */ + public static CustomPlayer getPlayer(Player player) { + return getPlayer(player.getName()); + } + + /** + * gets custom player from database id + * @param id database id of player + * @return CustomPlayer + */ + public static CustomPlayer getPlayer(int id) { + MySQL sql = Core.returnSQL(); + try { + sql.openConnection(); + PreparedStatement st = sql.getConnection().prepareStatement("SELECT ID, UUID FROM users WHERE ID='" + id + "');"); + ResultSet rs = st.executeQuery(); + String uuidString = rs.getString("UUID"); + sql.closeConnection(); + UUID uuid = UUID.fromString(uuidString); + NameFetcher names = new NameFetcher(Arrays.asList(uuid)); + Map map = null; + try { + map = names.call(); + } catch (Exception e) { + e.printStackTrace(); + } + String name = map.toString(); + String Name = name.substring(name.indexOf('=') + 1, name.indexOf('}')); + + return CustomPlayer.getPlayer(Name); + + } catch (ClassNotFoundException | SQLException e) { + e.printStackTrace(); + return null; + } + } /** * get normal player @@ -91,7 +150,7 @@ public class CustomPlayer extends CraftPlayer { /** * connects player to server in bungeecord - * @param server Server to connect to + * @param server ServerPinger to connect to */ public void connectToServer(String server) { Servers.connectServer(PLAYER, server); @@ -102,7 +161,7 @@ public class CustomPlayer extends CraftPlayer { * @param rank Ranks * @return true/false */ - public boolean isAllowed(Ranks rank) { + public boolean isAllowed(Perms.Ranks rank) { try { return Perms.isAllowed(this, rank); } catch (ClassNotFoundException | SQLException e) { @@ -110,38 +169,51 @@ public class CustomPlayer extends CraftPlayer { return false; } } - - /** - * gets fresh rank of player - * @return Ranks - */ - public Ranks getRankFresh() { - try { - return Perms.getRankFresh(this); - } catch (SQLException | ClassNotFoundException e) { - e.printStackTrace(); - return null; - } - } - + /** * rank of player * @return Ranks */ - public Ranks getRank() { - return Perms.getRank(this); + public Perms.Ranks getRank() { + try { + return Perms.getRank(this); + } catch (ClassNotFoundException | SQLException e) { + e.printStackTrace(); + return Perms.Ranks.Player; + } } + + public Perms.Ranks getFreshRank() { + try{ + return Perms.getRankFresh(this); + }catch (ClassNotFoundException | SQLException e) { + e.printStackTrace(); + return Perms.Ranks.Player; + } + } + + /** + * sets rank of this custom player + * @param r Ranks + */ + public void setRank(Perms.Ranks r) { + try { + Perms.setRank(this, r); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (SQLException e) { + e.printStackTrace(); + } + } /** * prefix of player * @return String */ public String getPrefix() { - if(customPrefix != null) { - return customPrefix; - }else { - return Perms.getPrefix(getRank()); - } + if(customPrefix != null) return customPrefix; + if(isNicked()) return Perms.getPrefix(Perms.Ranks.Premium); + return Perms.getPrefix(getRank()); } /** @@ -149,9 +221,8 @@ public class CustomPlayer extends CraftPlayer { * @return String */ public String getSuffix() { - if(customSuffix != null) { - return customSuffix; - } + if(customSuffix != null) return customSuffix; + if(isNicked()) return Perms.getSuffix(Perms.Ranks.Premium); return Perms.getSuffix(getRank()); } @@ -160,11 +231,14 @@ public class CustomPlayer extends CraftPlayer { * @return String */ public String getColor() { - if(customColor != null) { - return customColor; - } + if(customColor != null) return customColor; + if(isNicked()) return Perms.getColor(Perms.Ranks.Premium); return Perms.getColor(getRank()); } + + public Color getArmorColor() { + return Perms.getArmorColor(getRank()); + } /** * sets a custom prefix @@ -195,22 +269,14 @@ public class CustomPlayer extends CraftPlayer { * @return Team */ public Team getTeam() { - return Perms.getTeam(getRank()); - } - - /** - * if player is muted - * @return true/false - */ - public boolean isMuted() { - try { - return MuteSystem.isMuted(PLAYER); - } catch (SQLException | ClassNotFoundException e) { - e.printStackTrace(); - return false; + Perms.Teams teams = new Perms.Teams(this); + if(isNicked()) { + return teams.Premium; + }else { + return Perms.Teams.getTeam(this); } } - + /** * bans player * @param reason why ban him ? @@ -219,7 +285,7 @@ public class CustomPlayer extends CraftPlayer { */ public void ban(String reason, CustomPlayer who, Integer time) { try { - BanSystem.setBanned(PLAYER, reason, who.getPLAYER(), time); + BanSystem.setBanned(this, reason, who, time); } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); } @@ -230,7 +296,7 @@ public class CustomPlayer extends CraftPlayer { */ public boolean isBanned() { try { - return BanSystem.isBanned(PLAYER); + return BanSystem.isBanned(this); } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); return false; @@ -243,7 +309,7 @@ public class CustomPlayer extends CraftPlayer { */ public String getBanReason() { try { - return BanSystem.getBanReason(PLAYER); + return BanSystem.getBanReason(this); } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); return null; @@ -257,19 +323,28 @@ public class CustomPlayer extends CraftPlayer { */ public String getWhoBanned() { try { - return BanSystem.getWhoBanned(PLAYER); + return BanSystem.getWhoBanned(this); } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); return null; } } + + public Timestamp getBanTime() { + try { + return BanSystem.getBanTime(this); + } catch (SQLException e) { + e.printStackTrace(); + return null; + } + } /** * unbans the player */ - public void unban() { + public void removeAllBans() { try { - BanSystem.unban(PLAYER); + BanSystem.removeAllBans(this); } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); } @@ -280,7 +355,7 @@ public class CustomPlayer extends CraftPlayer { * @return String */ public String getNick() { - return NickName.getNick(PLAYER); + return NickName.getNick(this); } /** @@ -288,21 +363,37 @@ public class CustomPlayer extends CraftPlayer { * @return true/false */ public boolean isNicked() { - try { - return NickName.isNicked(PLAYER); - } catch (SQLException | ClassNotFoundException e) { - e.printStackTrace(); - return false; - } + if(ServerSettings.isGame()) { + try { + return NickName.isNicked(this); + } catch (SQLException | ClassNotFoundException e) { + e.printStackTrace(); + return false; + } + } + return false; } + + /** + * checks if player is nicked + * @return true/false + */ + public boolean isNickedReal() { + try { + return NickName.isNicked(this); + } catch (SQLException | ClassNotFoundException e) { + e.printStackTrace(); + } + return false; + } /** * sets nickname * @param is boolean */ - public void setNick(boolean is) { + public void setNicked(boolean is) { try { - NickName.setNick(PLAYER, is); + NickName.setNick(this, is); } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); } @@ -313,7 +404,7 @@ public class CustomPlayer extends CraftPlayer { * @return ClientInfo */ public ClientInfo getTSClientInfo() { - TeamSpeak ts = new TeamSpeak(); + TeamSpeak ts = Core.getTs(); try { return ts.getClientInfo(ts.getTsId(this)); } catch (ClassNotFoundException | SQLException e) { @@ -326,13 +417,29 @@ public class CustomPlayer extends CraftPlayer { * verifys player account on teamspeak */ public void verifyTs() { - TeamSpeak ts = new TeamSpeak(); try { - ts.setRank(this); + Core.getTs().verify(this); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } + + public void checkVerifiedTs() { + try { + Core.getTs().checkVerifiyed(this); + } catch (SQLException | ClassNotFoundException e) { + e.printStackTrace(); + } + } + + public boolean hasVerifiedTs() { + try { + return Core.getTs().hasVerified(this); + } catch (SQLException | ClassNotFoundException e) { + e.printStackTrace(); + return false; + } + } /** * checks if player has played on the network before @@ -341,17 +448,18 @@ public class CustomPlayer extends CraftPlayer { @Override public boolean hasPlayedBefore() { MySQL sql = Core.returnSQL(); - boolean bool; try { sql.openConnection(); String uuid = this.getUniqueId().toString(); - ResultSet rs = sql.getConnection().createStatement().executeQuery("SELECT * FROM PlayerData WHERE player_uuid='" + uuid + "';"); - if (rs.next()) - bool = true; - bool = false; - - sql.closeConnection(); - return bool; + ResultSet rs = sql.getConnection().createStatement().executeQuery("SELECT * FROM users WHERE UUID= '" + uuid + "';"); + if (rs.next()) { + sql.closeConnection(); + return true; + }else { + sql.closeConnection(); + return false; + } + } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); return false; @@ -373,4 +481,161 @@ public class CustomPlayer extends CraftPlayer { Utils.clearPotionEffects(PLAYER); } + /** + * gets database id of player + * @return Integer + */ + public int getID() { + if(id == 0) { + MySQL sql = Core.returnSQL(); + try { + sql.openConnection(); + String uuid = this.getUniqueId().toString(); + PreparedStatement st = sql.getConnection().prepareStatement("SELECT * FROM users WHERE UUID ='" + uuid + "';"); + ResultSet rs = st.executeQuery(); + if(rs.next()) { + int id = rs.getInt("ID"); + this.id = id; + sql.closeConnection(); + return id; + }else { + sql.closeConnection(); + + return 0; + } + } catch (ClassNotFoundException | SQLException e) { + e.printStackTrace(); + return 0; + } + }else { + return id; + } + + } + + /** + * checks if players has a open inventory + * @return true/false + */ + public boolean hasOpenInventory() { + return openInventory; + } + + /** + * sets opened inventory + * @param openInventory true/false + */ + public void setOpenInventory(boolean openInventory) { + this.openInventory = openInventory; + } + + /** + * gets coins from player + * @return coins as integer + */ + public int getCoins() { + return Coins.getCoins(this); + } + + /** + * sets coins if player + * @param coins coins as integer + */ + public void setCoins(int coins) { + Coins.setCoins(this, coins); + } + + /** + * adds coins to player coins + * @param coins coins as integer + */ + public void addCoins(int coins) { + int temp = Coins.getCoins(this); + Coins.setCoins(this, temp + coins); + } + + /** + * substracts coins from player coins + * @param coins coins as integer + */ + public void substractCoins(int coins) { + int temp = Coins.getCoins(this); + Coins.setCoins(this, temp - coins); + } + + /** + * sends message with actionbar to player + * @param text String + */ + public void sendActionBar(String text) { + Actionbar.send(PLAYER, text); + } + + /** + * gets experience from player + * @return experience experience as integer + */ + public int getExperience() { + return Experience.getExperience(this); + } + + /** + * sets experience of player + * @param experience experience to set + */ + public void setExperience(int experience) { + Experience.setExperience(this, experience); + } + + /** + * adds experience to player + * @param experience experience to add + */ + public void addExperience(int experience) { + int temp = Experience.getExperience(this); + Experience.setExperience(this, temp + experience); + setExp(0F); + giveExp(getExperience()); + playSound(getLocation(), Sound.LEVEL_UP, 1.0F, 1.0F); + } + + /** + * removes experience from player + * @param experience experience to remove + */ + public void substractExperience(int experience) { + int temp = Experience.getExperience(this); + Experience.setExperience(this, temp - experience); + setExp(0F); + giveExp(getExperience()); + } + + public void refreshExperience() { + setLevel(0); + setExp(0F); + giveExp(getExperience()); + } + //TODO: add other functions for secrets + + public int getFoundSecrets() { + return 0; + } + + public String getLang() { + return PlayerSettings.get("lang", this); + } + + public void setLang(String lang) { + PlayerSettings.set(lang, "lang", this); + }; + + public boolean isSetting(String setting) { + return PlayerSettings.isSet(setting, this); + } + + public String getSetting(String setting) { return PlayerSettings.get(setting, this); } + + public void changeSetting(String setting) { + PlayerSettings.change(setting, this); + } } \ No newline at end of file diff --git a/src/eu/univento/core/api/player/MuteSystem.java b/src/eu/univento/core/api/player/MuteSystem.java deleted file mode 100644 index 52f98b4..0000000 --- a/src/eu/univento/core/api/player/MuteSystem.java +++ /dev/null @@ -1,52 +0,0 @@ -package eu.univento.core.api.player; - -import java.sql.ResultSet; -import java.sql.SQLException; -import org.bukkit.entity.Player; - -import eu.univento.core.Core; -import eu.univento.core.api.MySQL; - -/** - * querys database for muted players - * @author joethei - * @version 1.0 - */ -public class MuteSystem { - - - /** - * checks if player is muted - * @param p player - * @return true /false - * @throws SQLException SQL server not available or throwing error - * @throws ClassNotFoundException class couldn't be found - */ - public static boolean isMuted(Player p) throws SQLException, ClassNotFoundException { - MySQL sql = Core.returnSQL(); - sql.openConnection(); - String uuid = p.getUniqueId().toString(); - ResultSet rs = sql.getConnection().createStatement().executeQuery("SELECT mute FROM PlayerData WHERE player_uuid='" + uuid + "';"); - if (rs.next()) { - return rs.getInt("mute") == 1; - } - sql.closeConnection(); - return false; - } - - - /** - * sets / unsets mute - * @param p player - * @param mute boolean - * @throws SQLException SQL server not available or throwing error - * @throws ClassNotFoundException class couldn't be found - */ - public static void setUser(Player p, boolean mute) throws SQLException, ClassNotFoundException { - MySQL sql = Core.returnSQL(); - sql.openConnection(); - String uuid = p.getUniqueId().toString(); - sql.getConnection().createStatement().executeUpdate("UPDATE PlayerData SET mute = " + mute + " WHERE player_uuid='" + uuid + "';"); - sql.closeConnection(); - } -} \ No newline at end of file diff --git a/src/eu/univento/core/api/player/NickName.java b/src/eu/univento/core/api/player/NickName.java index 39c666b..cba1a25 100644 --- a/src/eu/univento/core/api/player/NickName.java +++ b/src/eu/univento/core/api/player/NickName.java @@ -1,13 +1,13 @@ package eu.univento.core.api.player; +import eu.univento.core.Core; +import eu.univento.core.api.database.MySQL; + import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; +import java.util.HashMap; import java.util.Random; -import org.bukkit.entity.Player; - -import eu.univento.core.Core; -import eu.univento.core.api.MySQL; /** * gets nick settings for players @@ -15,14 +15,20 @@ import eu.univento.core.api.MySQL; * @version 1.1 */ public class NickName { - + + /** + * nick names of players + */ + static HashMap nicks = new HashMap<>(); + + /** * * @param p remove nickname from player */ - public static void remove(Player p) { - if (Core.nicks.containsKey(p)) - Core.nicks.remove(p); + public static void remove(CustomPlayer p) { + if (nicks.containsKey(p)) + nicks.remove(p); } /** @@ -32,14 +38,13 @@ public class NickName { * @throws ClassNotFoundException Class couldn't be found * @throws SQLException SQL server not available or throwing error */ - public static void setNick(Player p, boolean nick) throws SQLException, ClassNotFoundException { + static void setNick(CustomPlayer p, boolean nick) throws SQLException, ClassNotFoundException { MySQL sql = Core.returnSQL(); sql.openConnection(); - String uuid = p.getUniqueId().toString(); if (nick) - sql.getConnection().createStatement().executeUpdate("UPDATE PlayerData SET nick = '1' WHERE player_uuid = '" + uuid + "';"); + sql.getConnection().createStatement().executeUpdate("UPDATE PlayerSettings SET nick = '1' WHERE ID = '" + p.getID() + "';"); else - sql.getConnection().createStatement().executeUpdate("UPDATE PlayerData SET nick = '0' WHERE player_uuid = '" + uuid + "';"); + sql.getConnection().createStatement().executeUpdate("UPDATE PlayerSettings SET nick = '0' WHERE ID = '" + p.getID() + "';"); sql.closeConnection(); } @@ -50,11 +55,10 @@ public class NickName { * @throws ClassNotFoundException Class couldn't be found * @throws SQLException SQL server not available or throwing error */ - public static boolean isNicked(Player p) throws SQLException, ClassNotFoundException { + static boolean isNicked(CustomPlayer p) throws SQLException, ClassNotFoundException { MySQL sql = Core.returnSQL(); sql.openConnection(); - String uuid = p.getUniqueId().toString(); - ResultSet rs = sql.getConnection().createStatement().executeQuery("SELECT nick FROM PlayerData WHERE player_uuid = '" + uuid + "';"); + ResultSet rs = sql.getConnection().createStatement().executeQuery("SELECT nick FROM PlayerSettings WHERE ID = '" + p.getID() + "';"); if (rs.next()) { return rs.getInt("nick") == 1; } @@ -67,28 +71,32 @@ public class NickName { * @param p player * @return String */ - public static String getNick(Player p) { - if (Core.nicks.containsKey(p)) { - String nick = (String) Core.nicks.get(p); - return nick; - } + static String getNick(CustomPlayer p) { + if (nicks.containsKey(p)) { + return nicks.get(p); + }else if(p.isNicked()){ + nicks.put(p, getRandomNick()); + return nicks.get(p); + } return null; } /** * gets random Nickname * @return String - * @throws SQLException SQL server not available or throwing error */ - public static String getNicks() throws SQLException { - ArrayList names = new ArrayList(); + static String getRandomNick() { + ArrayList names = new ArrayList<>(); names.add("XXKevinXX"); names.add("xxGamelcrafterxx"); names.add("LiaaamDesigns"); + names.add("Firestarter88"); + names.add("MatelLucario99"); + names.add("Ghostcraft_No"); Random r = new Random(); int i = r.nextInt(names.size()); - return (String) names.get(i); + return names.get(i); } } \ No newline at end of file diff --git a/src/eu/univento/core/api/player/Perms.java b/src/eu/univento/core/api/player/Perms.java index f8b7ee3..d814a16 100644 --- a/src/eu/univento/core/api/player/Perms.java +++ b/src/eu/univento/core/api/player/Perms.java @@ -1,16 +1,16 @@ package eu.univento.core.api.player; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.HashMap; - -import org.bukkit.Bukkit; +import eu.univento.core.Core; +import eu.univento.core.api.database.MySQL; +import org.bukkit.Color; import org.bukkit.scoreboard.NameTagVisibility; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.Team; -import eu.univento.core.Core; -import eu.univento.core.api.MySQL; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; /** * some permission management @@ -19,7 +19,14 @@ import eu.univento.core.api.MySQL; */ public class Perms{ - private static HashMap ranks = new HashMap(); + /** + * contains all joined players and there ranks + */ + private static HashMap ranks = new HashMap<>(); + /** + * gets ranks + * @return HashMap + */ public static HashMap getRanks() { return ranks; } @@ -29,18 +36,20 @@ public class Perms{ * @param r Ranks * @return String */ -public static String getPrefix(Ranks r) { +static String getPrefix(Ranks r) { switch(r) { - case Admin: return "§7[§4Admin§7]§4 "; - case Developer: return "§7[§3Developer§7]§3 "; - case Moderator: return "§7[§cModerator§7]§c "; - case HeadBuilder: return "§7[§aHead-Builder§7]§a "; - case Builder: return "§7[§2Builder§7]§2 "; - case Supporter: return "§7[§bSupporter§7]§b "; - case Youtuber: return "§5"; - case Premium: return "§6"; - case Spieler: return "§7"; - default: return "§cFehler "; + case Admin: return "§8[§4Admin§8]§4 "; + case SrDeveloper: return "§8[§3Dev+§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 "; } } @@ -49,18 +58,20 @@ public static String getPrefix(Ranks r) { * @param r Ranks * @return String */ -public static String getSuffix(Ranks r) { +static String getSuffix(Ranks r) { switch(r) { - case Admin: return " §8» §f§l"; - case Developer: return " §8» §f"; - case Moderator: return " §8» §f"; - case HeadBuilder: return " §8» §f"; - case Builder: return " §8» §f"; - case Supporter: return " §8» §f"; - case Youtuber: return " §8» §f"; - case Premium: return " §8» §f"; - case Spieler: return " §8» §f"; - default: return "§cFehler"; + 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"; } } @@ -69,100 +80,156 @@ public static String getSuffix(Ranks r) { * @param r Ranks * @return String */ -public static String getColor(Ranks r) { +static String getColor(Ranks r) { switch(r) { - case Admin: return "§4"; - case Developer: return "§3"; - case Moderator: return "§c"; - case HeadBuilder: return "§a"; - case Builder: return "§2"; - case Supporter: return "§b"; - case Youtuber: return "§5"; - case Premium: return "§6"; - case Spieler: return "§7"; - default: return "§cFehler"; + 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"; } } -/** - * returns scoreboard team for rank - * @param r Ranks - * @return Team - */ -public static Team getTeam(Ranks r) { - switch(r) { - case Admin: return Teams.Admin; - case Developer: return Teams.Developer; - case Moderator: return Teams.Moderator; - case HeadBuilder: return Teams.HeadBuilder; - case Builder: return Teams.Builder; - case Supporter: return Teams.Supporter; - case Youtuber: return Teams.Youtuber; - case Premium: return Teams.Premium; - case Spieler: return Teams.Spieler; - default: return null; - } +static 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; + } } /** + * contains all scoreboard ranks * @author joethei * @version 1.0 */ public static class Teams { - private static Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard(); - public static Team Admin = board.getTeam("a"); - public static Team Developer = board.getTeam("b"); - public static Team Moderator = board.getTeam("c"); - public static Team HeadBuilder = board.getTeam("d"); - public static Team Builder = board.getTeam("e"); - public static Team Supporter = board.getTeam("f"); - public static Team Youtuber = board.getTeam("g"); - public static Team Premium = board.getTeam("h"); - public static Team Spieler = board.getTeam("i"); + + CustomPlayer player; + public Scoreboard board; + + public Team Admin; + public Team SrDeveloper; + public Team Developer; + public Team SrModerator; + public Team Moderator; + public Team HeadBuilder; + public Team Builder; + public Team Supporter; + public Team Youtuber; + public Team Premium; + public Team Player; + + public Teams(CustomPlayer player) { + this.player = player; + board = player.getScoreboard(); + Admin = board.getTeam("a"); + SrDeveloper = board.getTeam("b"); + Developer = board.getTeam("c"); + SrModerator = board.getTeam("d"); + HeadBuilder = board.getTeam("e"); + Moderator = board.getTeam("f"); + Builder = board.getTeam("g"); + Supporter = board.getTeam("h"); + Youtuber = board.getTeam("i"); + Premium = board.getTeam("j"); + Player = board.getTeam("k"); + } + + /** + * returns scoreboard team for rank + * @param p CustomPlayer + * @return Team + */ + public static Team getTeam(CustomPlayer p) { + Teams teams = new Teams(p); + switch(p.getRank()) { + case Admin: return teams.Admin; + case SrDeveloper: return teams.SrDeveloper; + case Developer: return teams.Developer; + case SrModerator: return teams.SrModerator; + case HeadBuilder: return teams.HeadBuilder; + case Moderator: return teams.Moderator; + case Builder: return teams.Builder; + case Supporter: return teams.Supporter; + case Youtuber: return teams.Youtuber; + case Premium: return teams.Premium; + case Player: return teams.Player; + default: return null; + } + } } /** - * setsup scoreboards + * setup scoreboards */ -public static void initScoreboard() { - Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard(); - Teams.Admin.unregister(); - Teams.Developer.unregister(); - Teams.Moderator.unregister(); - Teams.HeadBuilder.unregister(); - Teams.Builder.unregister(); - Teams.Supporter.unregister(); - Teams.Youtuber.unregister(); - Teams.Premium.unregister(); - Teams.Spieler.unregister(); +public static void initScoreboard(CustomPlayer p) { + Scoreboard board = p.getScoreboard(); + board.getTeams().forEach(Team::unregister); Team Admin = board.registerNewTeam("a"); - Team Developer = board.registerNewTeam("b"); - Team Moderator = board.registerNewTeam("c"); - Team HeadBuilder = board.registerNewTeam("d"); - Team Builder = board.registerNewTeam("e"); - Team Supporter = board.registerNewTeam("f"); - Team Youtuber = board.registerNewTeam("g"); - Team Premium = board.registerNewTeam("h"); - Team Spieler = board.registerNewTeam("i"); + Team SrDeveloper = board.registerNewTeam("b"); + Team Developer = board.registerNewTeam("c"); + Team SrModerator = board.registerNewTeam("d"); + Team HeadBuilder = board.registerNewTeam("e"); + Team Moderator = board.registerNewTeam("f"); + Team Builder = board.registerNewTeam("g"); + Team Supporter = board.registerNewTeam("h"); + Team Youtuber = board.registerNewTeam("i"); + Team Premium = board.registerNewTeam("j"); + Team Player = board.registerNewTeam("k"); - Teams.Admin.setPrefix(getColor(Ranks.Admin)); - Teams.Developer.setPrefix(getColor(Ranks.Developer)); - Teams.Moderator.setPrefix(getColor(Ranks.Moderator)); - Teams.HeadBuilder.setPrefix(getColor(Ranks.HeadBuilder)); - Teams.Builder.setPrefix(getColor(Ranks.Builder)); - Teams.Supporter.setPrefix(getColor(Ranks.Supporter)); - Teams.Youtuber.setPrefix(getColor(Ranks.Youtuber)); - Teams.Premium.setPrefix(getColor(Ranks.Premium)); - Teams.Spieler.setPrefix(getColor(Ranks.Spieler)); + Admin.setPrefix(getColor(Ranks.Admin)); + SrDeveloper.setPrefix(getColor(Ranks.SrDeveloper)); + Developer.setPrefix(getColor(Ranks.Developer)); + SrModerator.setPrefix(getColor(Ranks.SrModerator)); + HeadBuilder.setPrefix(getColor(Ranks.HeadBuilder)); + Moderator.setPrefix(getColor(Ranks.Moderator)); + Builder.setPrefix(getColor(Ranks.Builder)); + Supporter.setPrefix(getColor(Ranks.Supporter)); + Youtuber.setPrefix(getColor(Ranks.Youtuber)); + Premium.setPrefix(getColor(Ranks.Premium)); + Player.setPrefix(getColor(Ranks.Player)); + + Admin.setNameTagVisibility(NameTagVisibility.ALWAYS); + SrDeveloper.setNameTagVisibility(NameTagVisibility.ALWAYS); + Developer.setNameTagVisibility(NameTagVisibility.ALWAYS); + SrModerator.setNameTagVisibility(NameTagVisibility.ALWAYS); + HeadBuilder.setNameTagVisibility(NameTagVisibility.ALWAYS); + Moderator.setNameTagVisibility(NameTagVisibility.ALWAYS); + Builder.setNameTagVisibility(NameTagVisibility.ALWAYS); + Supporter.setNameTagVisibility(NameTagVisibility.ALWAYS); + Youtuber.setNameTagVisibility(NameTagVisibility.ALWAYS); + Premium.setNameTagVisibility(NameTagVisibility.ALWAYS); + Player.setNameTagVisibility(NameTagVisibility.ALWAYS); } /** * gets Rank of player * @param p Player * @return Ranks + * @throws ClassNotFoundException Class couldn't be found + * @throws SQLException SQL server not available or throwing error */ -public static Ranks getRank(CustomPlayer p) { - return getRanks().get(p); +static Ranks getRank(CustomPlayer p) throws ClassNotFoundException, SQLException { + if(getRanks().get(p) != null) { + return getRanks().get(p); + }else { + return getRankFresh(p); + } + } /** @@ -172,19 +239,20 @@ public static Ranks getRank(CustomPlayer p) { * @throws ClassNotFoundException Class couldn't be found * @throws SQLException SQL server not available or throwing error */ -public static Ranks getRankFresh(CustomPlayer p) throws SQLException, ClassNotFoundException { +static Ranks getRankFresh(CustomPlayer p) throws SQLException, ClassNotFoundException { MySQL sql = Core.returnSQL(); sql.openConnection(); - ResultSet rs = sql.getConnection().createStatement().executeQuery("SELECT * FROM PlayerData WHERE player_uuid='" + p.getUniqueId() + "'"); - rs.next(); - if (rs.getString("player_uuid") != null) { + String uuid = p.getUniqueId().toString(); + PreparedStatement st = sql.getConnection().prepareStatement("SELECT * FROM users WHERE UUID= '" + uuid + "';"); + ResultSet rs = st.executeQuery(); + if(rs.next()) { String rank = rs.getString("Rank"); - Ranks Rank = Ranks.valueOf(rank); sql.closeConnection(); - return Rank; + return Ranks.valueOf(rank); + }else { + sql.closeConnection(); + return null; } - sql.closeConnection(); - return null; } /** @@ -194,10 +262,11 @@ public static Ranks getRankFresh(CustomPlayer p) throws SQLException, ClassNotFo * @throws ClassNotFoundException Class couldn't be found * @throws SQLException SQL server not available or throwing error */ -public static void setRank(CustomPlayer p, Ranks r) throws ClassNotFoundException, SQLException { +static void setRank(CustomPlayer p, Ranks r) throws ClassNotFoundException, SQLException { MySQL sql = Core.returnSQL(); sql.openConnection(); - sql.getConnection().createStatement().execute("UPDATE PlayerData SET Rank='" + r.toString() + "' WHERE player_uuid='" + p.getUniqueId() + "';"); + PreparedStatement st = sql.getConnection().prepareStatement("UPDATE users SET Rank='" + r.toString() + "' WHERE ID='" + p.getID() + "';"); + st.execute(); sql.closeConnection(); } @@ -209,7 +278,7 @@ public static void setRank(CustomPlayer p, Ranks r) throws ClassNotFoundExceptio * @throws ClassNotFoundException Class couldn't be found * @throws SQLException SQL server not available or throwing error */ -public static boolean isAllowed(CustomPlayer p, Ranks r) throws ClassNotFoundException, SQLException{ +static boolean isAllowed(CustomPlayer p, Ranks r) throws ClassNotFoundException, SQLException{ Ranks rank; if(getRank(p) == null) { rank = getRankFresh(p); @@ -219,16 +288,23 @@ public static boolean isAllowed(CustomPlayer p, Ranks r) throws ClassNotFoundExc return rank.value >= r.value; } +/** + * contains all ranks + * @author joethei + * @version 1.0 + */ public static enum Ranks{ - Admin(9), - Developer(8), - Moderator(7), - HeadBuilder(6), + Admin(11), + SrDeveloper(10), + Developer(9), + SrModerator(8), + HeadBuilder(7), + Moderator(6), Builder(5), Supporter(4), Youtuber(3), Premium(2), - Spieler(1); + Player(1); public final int value; diff --git a/src/eu/univento/core/api/player/PlayerSettings.java b/src/eu/univento/core/api/player/PlayerSettings.java new file mode 100644 index 0000000..07cf824 --- /dev/null +++ b/src/eu/univento/core/api/player/PlayerSettings.java @@ -0,0 +1,144 @@ +package eu.univento.core.api.player; + +import eu.univento.core.Core; +import eu.univento.core.api.database.MySQL; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; + +/** + * server-wide settings + * @author joethei + * @version 0.1 + */ + +public class PlayerSettings { + + /** + * returns if setting is set + * @param what what setting is set + * @param p CustomPlayer + * @return boolean + */ + static boolean isSet(String what, CustomPlayer p) { + int id = p.getID(); + MySQL sql = Core.returnSQL(); + try { + sql.openConnection(); + PreparedStatement st = sql.getConnection().prepareStatement("SELECT * FROM PlayerSettings WHERE ID = '" + id + "';"); + ResultSet rs = st.executeQuery(); + if (rs.next()) { + boolean is = rs.getInt(what) == 1; + sql.closeConnection(); + return is; + } + sql.closeConnection(); + return false; + } catch (ClassNotFoundException | SQLException e) { + e.printStackTrace(); + return false; + } + } + + /** + * sets setting + * @param p CustomPlayer + * @param bool boolean to set to + * @param what what to set + * @throws ClassNotFoundException class could not be found + * @throws SQLException SQL ServerPinger not available or throwing error + */ + static void set(boolean bool, String what, CustomPlayer p) throws SQLException, ClassNotFoundException { + int id = p.getID(); + MySQL sql = Core.returnSQL(); + sql.openConnection(); + if (bool) { + PreparedStatement st = sql.getConnection().prepareStatement("UPDATE PlayerSettings SET " + what + " = '1' WHERE ID = '" + id + "';"); + st.execute(); + }else { + PreparedStatement st = sql.getConnection().prepareStatement("UPDATE PlayerSettings SET " + what + " = '0' WHERE ID = '" + id + "';"); + st.execute(); + } + sql.closeConnection(); + } + + /** + * gets setting from player + * @param what what to get + * @param p CustomPlayer + * @return String + */ + static String get(String what, CustomPlayer p) { + int id = p.getID(); + MySQL sql = Core.returnSQL(); + try { + sql.openConnection(); + PreparedStatement st = sql.getConnection().prepareStatement("SELECT " + what + " FROM PlayerSettings WHERE ID='" + id + "';"); + ResultSet rs = st.executeQuery(); + if(rs.next()) { + String rt = rs.getString(what); + sql.closeConnection(); + return rt; + } + return null; + } catch (SQLException | ClassNotFoundException e) { + e.printStackTrace(); + return null; + } + } + + /** + * sets settings for player + * @param set value to set + * @param what what to set + * @param p CustomPlayer + */ + static void set(String set, String what, CustomPlayer p) { + int id = p.getID(); + MySQL sql = Core.returnSQL(); + try { + sql.openConnection(); + PreparedStatement st = sql.getConnection().prepareStatement("UPDATE PlayerSettings SET " + what + " = '" + set + "' WHERE ID = '" + id + "';"); + st.execute(); + } catch (SQLException | ClassNotFoundException e) { + e.printStackTrace(); + } + } + + /** + * changes settings + * @param what what to set + * @param p CustomPlayer + */ + static void change(String what, CustomPlayer p) { + if(isSet(what, p)) { + try { + set(false, what, p); + } catch (ClassNotFoundException | SQLException e) { + e.printStackTrace(); + } + }else { + try { + set(true, what, p); + } catch (ClassNotFoundException | SQLException e) { + e.printStackTrace(); + } + } + } + + public static ArrayList getAllPlayersWithEffectsEnabled() { + ArrayList list = new ArrayList<>(); + for(Player players : Bukkit.getOnlinePlayers()) { + CustomPlayer p = CustomPlayer.getPlayer(players); + if(isSet("effects", p)) { + list.add(p); + } + } + return list; + } + +} \ No newline at end of file diff --git a/src/eu/univento/core/api/player/Spectator.java b/src/eu/univento/core/api/player/Spectator.java index b1b3d1a..66a33aa 100644 --- a/src/eu/univento/core/api/player/Spectator.java +++ b/src/eu/univento/core/api/player/Spectator.java @@ -1,44 +1,67 @@ package eu.univento.core.api.player; -import java.util.ArrayList; - +import eu.univento.core.api.server.ServerSettings; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.entity.Player; +import java.util.ArrayList; + +/** + * + * @author joethei + * @version 1.0 + */ public class Spectator { + + /** + * contains all spectators + */ + private static ArrayList spectators = new ArrayList<>(); + + /** + * adds player to spectators + * @param p CustomPlayer + */ + public static void add(CustomPlayer p) { + for (Player on : Bukkit.getOnlinePlayers()) { + on.hidePlayer(p); + } + spectators.add(p); + p.setGameMode(GameMode.ADVENTURE); + p.setAllowFlight(true); + p.setFlying(true); + } + + /** + * removes player from spectator + * @param p CustomPlayer + */ + public static void remove(CustomPlayer p) { + for (Player on : Bukkit.getOnlinePlayers()) { + on.showPlayer(p); + } + spectators.remove(p); + p.setGameMode(ServerSettings.getGameMode()); + p.setAllowFlight(false); + p.setFlying(false); + } + + /** + * gets all spectators + * @return ArrayList + */ + public static ArrayList getSpectators() { + return spectators; + } - private static ArrayList spectators = new ArrayList(); - - public Spectator() { - } - - public static void add(Player p) { - for(Player on : Bukkit.getOnlinePlayers()) { - on.hidePlayer(p); - } - spectators.add(CustomPlayer.getPlayer(p.getName())); - p.setGameMode(GameMode.CREATIVE); - p.setAllowFlight(true); - p.setFlying(true); - } - - public static void remove(Player p) { - for(Player on : Bukkit.getOnlinePlayers()) { - on.showPlayer(p); - } - spectators.remove(CustomPlayer.getPlayer(p.getName())); - p.setGameMode(GameMode.SURVIVAL); - p.setAllowFlight(false); - p.setFlying(false); - } - - public static ArrayList getSpectators() { - return spectators; - } - - public static boolean is(CustomPlayer p) { - return spectators.contains(p.getName()); - } + /** + * checks if players is spectator + * @param p CustomPlayer + * @return true/false + */ + public static boolean is(CustomPlayer p) { + return spectators.contains(p); + } } \ No newline at end of file diff --git a/src/eu/univento/core/api/player/TeamSpeak.java b/src/eu/univento/core/api/player/TeamSpeak.java index 5841e22..20d8d8c 100644 --- a/src/eu/univento/core/api/player/TeamSpeak.java +++ b/src/eu/univento/core/api/player/TeamSpeak.java @@ -1,19 +1,22 @@ package eu.univento.core.api.player; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.logging.Level; - import com.github.theholywaffle.teamspeak3.TS3Api; import com.github.theholywaffle.teamspeak3.TS3Config; import com.github.theholywaffle.teamspeak3.TS3Query; import com.github.theholywaffle.teamspeak3.api.wrapper.Client; import com.github.theholywaffle.teamspeak3.api.wrapper.ClientInfo; - import eu.univento.core.Core; import eu.univento.core.api.Config; -import eu.univento.core.api.MySQL; +import eu.univento.core.api.database.MySQL; import eu.univento.core.api.player.Perms.Ranks; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.UUID; +import java.util.logging.Level; /** * basic functions for teamspeak communication @@ -21,37 +24,39 @@ import eu.univento.core.api.player.Perms.Ranks; * @version 1.0 */ public class TeamSpeak { - + + private TS3Query query; private TS3Api api; - - private static int verified = 11; - public static int getVerifiedId() { - return verified; - } - - /** + + int verified = 11; + + /** * inits class */ public TeamSpeak() { final TS3Config config = new TS3Config(); config.setHost(Config.readString("TS.IP")); config.setQueryPort(Config.readInt("TS.QueryPort")); - config.setDebugLevel(Level.ALL); + config.setDebugLevel(Level.OFF); config.setLoginCredentials(Config.readString("TS.QueryUser"), Config.readString("TS.Query.Pass")); final TS3Query query = new TS3Query(config); query.connect(); - final TS3Api api = query.getApi(); api.selectVirtualServerById(1); - api.setNickname("Rechteverteiler"); + api.setNickname("Rechteverteiler von " + Bukkit.getServerName()); this.api = api; + this.query = query; } + + public void disconnect() { + query.exit(); + } /** * gets teamspeak api * @return TS3Api */ - public TS3Api getAPI() { + TS3Api getAPI() { return api; } @@ -60,7 +65,7 @@ public class TeamSpeak { * @param id database id * @return ClientInfo */ - public ClientInfo getClientInfo(int id) { + ClientInfo getClientInfo(int id) { return api.getClientInfo(id); } @@ -74,7 +79,8 @@ public class TeamSpeak { public int getTsId(CustomPlayer p) throws ClassNotFoundException, SQLException { MySQL sql = Core.returnSQL(); sql.openConnection(); - ResultSet rs = sql.getConnection().createStatement().executeQuery("SELECT * FROM PlayerData WHERE player_uuid='" + p.getUniqueId() + "'"); + PreparedStatement st = sql.getConnection().prepareStatement("SELECT TS_ID FROM users WHERE ID='" + p.getID() + "'"); + ResultSet rs = st.executeQuery(); rs.next(); if (rs.getInt("TS_ID") != 0) { int id = rs.getInt("TS_ID"); @@ -84,6 +90,20 @@ public class TeamSpeak { sql.closeConnection(); return 0; } + + public String getUUID(int id) throws SQLException, ClassNotFoundException { + MySQL sql = Core.returnSQL(); + sql.openConnection(); + PreparedStatement st = sql.getConnection().prepareStatement("SELECT UUID FROM users WHERE TS_ID='" + id + "';"); + ResultSet rs = st.executeQuery(); + if(rs.next()) { + String uuid = rs.getString("UUID"); + sql.closeConnection(); + return uuid; + } + sql.closeConnection(); + return null; + } /** * writes id of player to database @@ -92,10 +112,11 @@ public class TeamSpeak { * @throws SQLException SQL server not available or throwing error * @throws ClassNotFoundException class couldn't be found */ - private void setTsId(CustomPlayer p, int id) throws ClassNotFoundException, SQLException { + void setTsId(CustomPlayer p, int id) throws ClassNotFoundException, SQLException { MySQL sql = Core.returnSQL(); sql.openConnection(); - sql.getConnection().createStatement().execute("UPDATE PlayerData SET TS_ID='" + id + "' WHERE player_uuid='" + p.getUniqueId() + "';"); + PreparedStatement st = sql.getConnection().prepareStatement("UPDATE users SET TS_ID='" + id + "' WHERE UUID='" + p.getUniqueId().toString() + "';"); + st.execute(); sql.closeConnection(); } @@ -105,25 +126,65 @@ public class TeamSpeak { * @throws SQLException SQL server not available or throwing error * @throws ClassNotFoundException class couldn't be found */ - public void setRank(CustomPlayer p) throws ClassNotFoundException, SQLException { - TS3Api api = getAPI(); - for(int i = 0; i >= api.getClients().size(); i++) { - String player_ip = p.getAddress().getHostName(); - Client client = api.getClients().get(i); - ClientInfo info = api.getClientInfo(client.getId()); - String ts_ip = info.getIp(); - if(player_ip == ts_ip) { - int db_id = getTsId(p); - if(db_id == 0) { - api.removeClientFromServerGroup(getIdForRank(p.getRank()), db_id); - api.removeClientFromServerGroup(getVerifiedId(), db_id); - } - api.addClientToServerGroup(getIdForRank(p.getRank()), client.getDatabaseId()); - api.addClientToServerGroup(getVerifiedId(), client.getDatabaseId()); - setTsId(p, client.getDatabaseId()); - } - } - } + private void setRank(CustomPlayer p, Client client) throws ClassNotFoundException, SQLException { + //for(ServerGroup groups : api.getServerGroupsByClient(client)) { + // api.removeClientFromServerGroup(groups, client); + //} + api.addClientToServerGroup(getIdForRank(p.getRank()), client.getDatabaseId()); + api.addClientToServerGroup(verified, client.getDatabaseId()); + api.pokeClient(client.getId(), "Du wurdest von unserem freundlichem Bot verifiziert"); + } + + public void verify(CustomPlayer p) throws SQLException, ClassNotFoundException { + TS3Api api = getAPI(); + if(hasVerified(p)) { + p.sendMessage("§cDu hast bereits einen verknüpften Account"); + }else { + Client client = api.getClientByNameExact(p.getName(), false); + if(client != null) { + setRank(p, client); + return; + } + p.sendMessage("§cDu bist gerade nicht im TS online oder dein Nickname entspricht nicht dem IGN"); + + } + } + + private Client getClient(CustomPlayer p) throws SQLException, ClassNotFoundException { + if(hasVerified(p)) { + int id = getTsId(p); + for (Client client : api.getClients()) { + if (client.getDatabaseId() == id) { + return client; + } + return null; + } + } + return null; + } + + private CustomPlayer getPlayer(Client client) throws SQLException, ClassNotFoundException { + Player player = Bukkit.getPlayer(UUID.fromString(getUUID(client.getDatabaseId()))); + return CustomPlayer.getPlayer(player); + } + + public void checkVerifiyed(CustomPlayer p) throws SQLException, ClassNotFoundException { + if(hasVerified(p)) { + Client client = getClient(p); + if(client != null) { + //for(ServerGroup group : api.getServerGroupsByClient(client)) { + // if(group.getId() == getIdForRank(p.getRank())) { + // return; + // } + // setRank(p, client); + //} + } + } + } + + public boolean hasVerified(CustomPlayer p) throws SQLException, ClassNotFoundException { + return getTsId(p) != 0; + } /** * gets group id for rank @@ -132,16 +193,17 @@ public class TeamSpeak { */ public int getIdForRank(Ranks r) { switch(r) { - case Admin: return 10; - case Developer: return 13; - case Moderator: return 12; - case HeadBuilder: return 19; - case Builder: return 20; - case Supporter: return 14; - case Youtuber: return 21; - case Premium: return 22; - case Spieler: return 42; - default: return 0; + case Admin: return 10; + case Developer: return 13; + case SrModerator: return 60; + case Moderator: return 12; + case HeadBuilder: return 19; + case Builder: return 20; + case Supporter: return 14; + case Youtuber: return 21; + case Premium: return 22; + case Player: return 8; + default: return 0; } } diff --git a/src/eu/univento/core/api/server/GameInfo.java b/src/eu/univento/core/api/server/GameInfo.java new file mode 100644 index 0000000..bb55932 --- /dev/null +++ b/src/eu/univento/core/api/server/GameInfo.java @@ -0,0 +1,27 @@ +package eu.univento.core.api.server; + +/** + * @author joethei + * @version 0.1 + */ +public class GameInfo { + + Game game; + + public GameInfo(Game game) { + this.game = game; + } + + public int getPlayerCount() { + return 0; + } + + public int getServerCount() { + return 0; + } + + public ServerInfo[] getServers() { + return null; + } + +} \ No newline at end of file diff --git a/src/eu/univento/core/api/MojangService.java b/src/eu/univento/core/api/server/MojangService.java similarity index 88% rename from src/eu/univento/core/api/MojangService.java rename to src/eu/univento/core/api/server/MojangService.java index 7421f72..2207006 100644 --- a/src/eu/univento/core/api/MojangService.java +++ b/src/eu/univento/core/api/server/MojangService.java @@ -1,122 +1,122 @@ -package eu.univento.core.api; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.URL; - -import org.bukkit.ChatColor; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -public enum MojangService { - - ACCOUNTS("Accounts Service", "account.mojang.com"), - AUTHENTICATION("Authentication Service", "auth.mojang.com"), - AUTHENTICATION_SERVER("Authentication Server", "authserver.mojang.com"), - LOGIN("Login Service", "login.minecraft.net"), - SESSION_MINECRAFT("Minecraft Session Server", "session.minecraft.net"), - SESSION_MOJANG("Mojang Session Server", "sessionserver.mojang.com"), - SKINS("Skin Server", "skins.minecraft.net"), - MAIN_WEBSITE("Main Site", "minecraft.net"); - - /* - * @Author TheTinySpider - * Idea from: sebasju1234 - * - * Status names and other information can be found at: - * [url]http://minecraft.gamepedia.com/User_talk:Oxguy3/Minecraft.net_API[/url] - */ - - private String name, serviceURL; - private JSONParser jsonParser = new JSONParser(); - - MojangService(String name, String serviceURL) { - this.name = name; - this.serviceURL = serviceURL; - } - - public String getName() { - return name; - } - - /** - * Check the current Mojang service for it's status, errors are ignored. - * - * @return Status of the service. - */ - public Status getStatus() { - return getStatus(true); - } - - /** - * Check the current Mojang service for it's status. - * - * @param suppressErrors - Don't print errors in console. - * @return Status of the service. - */ - public Status getStatus(boolean suppressErrors) { - try { - URL url = new URL("[url]http://status.mojang.com/check?service=[/url]" + serviceURL); - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); - - Object object = jsonParser.parse(bufferedReader); - JSONObject jsonObject = (JSONObject) object; - - String status = (String) jsonObject.get(serviceURL); - - return Status.get(status); - - } catch (IOException | ParseException exception) { - - if (!suppressErrors) { - exception.printStackTrace(); - } - - return Status.UNKNOWN; - } - } - - public enum Status { - ONLINE("Online", ChatColor.GREEN.toString(), "No problems detected!"), - UNSTABLE("Unstable", ChatColor.YELLOW.toString(), "May be experiencing issues..."), - OFFLINE("Offline", ChatColor.DARK_RED.toString(), "Experiencing problems!"), - UNKNOWN("Unknown", ChatColor.WHITE.toString(), "Couldn't connect to Mojang!"); - - private String status, color, description; - - Status(String status, String color, String description) { - this.status = status; - this.color = color; - this.description = description; - } - - public String getStatus() { - return status; - } - - public String getColor() { - return color; - } - - public String getDescription() { - return description; - } - - public static Status get(String status) { - status = status.toLowerCase(); - - switch (status) { - case "green": - return Status.ONLINE; - case "yellow": - return Status.UNSTABLE; - case "red": - return Status.OFFLINE; - default: - return Status.UNKNOWN; - } - } - } +package eu.univento.core.api.server; + +import org.bukkit.ChatColor; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; + +public enum MojangService { + + ACCOUNTS("Accounts Service", "account.mojang.com"), + AUTHENTICATION("Authentication Service", "auth.mojang.com"), + AUTHENTICATION_SERVER("Authentication ServerPinger", "authserver.mojang.com"), + LOGIN("Login Service", "login.minecraft.net"), + SESSION_MINECRAFT("Minecraft Session ServerPinger", "session.minecraft.net"), + SESSION_MOJANG("Mojang Session ServerPinger", "sessionserver.mojang.com"), + SKINS("Skin ServerPinger", "skins.minecraft.net"), + MAIN_WEBSITE("Main Site", "minecraft.net"); + + /* + * @Author TheTinySpider + * Idea from: sebasju1234 + * + * Status names and other information can be found at: + * [url]http://minecraft.gamepedia.com/User_talk:Oxguy3/Minecraft.net_API[/url] + */ + + private String name, serviceURL; + private JSONParser jsonParser = new JSONParser(); + + MojangService(String name, String serviceURL) { + this.name = name; + this.serviceURL = serviceURL; + } + + public String getName() { + return name; + } + + /** + * Check the current Mojang service for it's status, errors are ignored. + * + * @return Status of the service. + */ + public Status getStatus() { + return getStatus(true); + } + + /** + * Check the current Mojang service for it's status. + * + * @param suppressErrors - Don't print errors in console. + * @return Status of the service. + */ + public Status getStatus(boolean suppressErrors) { + try { + URL url = new URL("[url]http://status.mojang.com/check?service=[/url]" + serviceURL); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); + + Object object = jsonParser.parse(bufferedReader); + JSONObject jsonObject = (JSONObject) object; + + String status = (String) jsonObject.get(serviceURL); + + return Status.get(status); + + } catch (IOException | ParseException exception) { + + if (!suppressErrors) { + exception.printStackTrace(); + } + + return Status.UNKNOWN; + } + } + + public enum Status { + ONLINE("Online", ChatColor.GREEN.toString(), "No problems detected!"), + UNSTABLE("Unstable", ChatColor.YELLOW.toString(), "May be experiencing issues..."), + OFFLINE("Offline", ChatColor.DARK_RED.toString(), "Experiencing problems!"), + UNKNOWN("Unknown", ChatColor.WHITE.toString(), "Couldn't connect to Mojang!"); + + private String status, color, description; + + Status(String status, String color, String description) { + this.status = status; + this.color = color; + this.description = description; + } + + public String getStatus() { + return status; + } + + public String getColor() { + return color; + } + + public String getDescription() { + return description; + } + + public static Status get(String status) { + status = status.toLowerCase(); + + switch (status) { + case "green": + return Status.ONLINE; + case "yellow": + return Status.UNSTABLE; + case "red": + return Status.OFFLINE; + default: + return Status.UNKNOWN; + } + } + } } \ No newline at end of file diff --git a/src/eu/univento/core/api/server/ServerDatabase.java b/src/eu/univento/core/api/server/ServerDatabase.java new file mode 100644 index 0000000..ffbe22c --- /dev/null +++ b/src/eu/univento/core/api/server/ServerDatabase.java @@ -0,0 +1,51 @@ +package eu.univento.core.api.server; + +import eu.univento.core.Core; +import eu.univento.core.api.database.MySQL; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +/** + * @author joethei + * @version 0.1 + */ +public class ServerDatabase { + + public static String getIP(String name) { + MySQL sql = Core.returnSQL(); + try { + sql.openConnection(); + PreparedStatement st = sql.getConnection().prepareStatement("SELECT ip FROM Servers WHERE name='" + name + "'"); + ResultSet rs = st.executeQuery(); + if(rs.next()) { + String ip = rs.getString("ip"); + sql.closeConnection(); + return ip; + } + return null; + } catch (SQLException | ClassNotFoundException e) { + e.printStackTrace(); + return null; + } + } + + public static int getPort(String name) { + MySQL sql = Core.returnSQL(); + try { + sql.openConnection(); + PreparedStatement st = sql.getConnection().prepareStatement("SELECT port FROM Servers WHERE name='" + name + "'"); + ResultSet rs = st.executeQuery(); + if(rs.next()) { + int port = rs.getInt("port"); + sql.closeConnection(); + return port; + } + return 0; + } catch (SQLException | ClassNotFoundException e) { + e.printStackTrace(); + return 0; + } + } +} \ No newline at end of file diff --git a/src/eu/univento/core/api/server/ServerInfo.java b/src/eu/univento/core/api/server/ServerInfo.java new file mode 100644 index 0000000..2800d7d --- /dev/null +++ b/src/eu/univento/core/api/server/ServerInfo.java @@ -0,0 +1,46 @@ +package eu.univento.core.api.server; + +import java.util.regex.Pattern; + +/** + * @author joethei + * @version 0.1 + */ +public class ServerInfo { + + String name; + ServerPinger pinger; + + public ServerInfo(String name) { + this.name = name; + pinger = new ServerPinger(name, 200); + pinger.ping(); + } + + public String getName() { + return name; + } + + public Game getGame() { + String[] parts = getMotd().split(Pattern.quote(";")); + return Game.valueOf(parts[0]); + } + + public String getGameState() { + String[] parts = getMotd().split(Pattern.quote(";")); + return parts[1]; + } + + public int getOnlinePlayers() { + return pinger.getPlayerCount(); + } + + public int getMaxPlayers() { + return pinger.getMaxPlayers(); + } + + public String getMotd() { + return pinger.getMotd(); + } + +} \ No newline at end of file diff --git a/src/eu/univento/core/api/server/ServerPinger.java b/src/eu/univento/core/api/server/ServerPinger.java new file mode 100644 index 0000000..3185bd9 --- /dev/null +++ b/src/eu/univento/core/api/server/ServerPinger.java @@ -0,0 +1,164 @@ +package eu.univento.core.api.server; + +import java.io.*; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketException; +import java.nio.charset.Charset; + +public class ServerPinger { + + private String address; + private int port; + private int timeout; + + private boolean online; + private int playercount; + private int maxplayers; + private String motd; + + public ServerPinger(String name, int timeout){ + this.address = ServerDatabase.getIP(name); + this.port = ServerDatabase.getPort(name); + this.timeout = timeout; + } + + public String getAddress(){ + return this.address; + } + + public void setAddress(String address){ + this.address = address; + } + + public int getPort(){ + return this.port; + } + + public void setPort(int port){ + this.port = port; + } + + public int getTimeout(){ + return this.timeout; + } + + public void setTimeout(int timeout){ + this.timeout = timeout; + } + + public boolean isOnline(){ + return this.online; + } + + private void setOnline(boolean online){ + this.online = online; + } + + public int getPlayerCount(){ + return this.playercount; + } + + private void setPlayerCount(int playercount){ + this.playercount = playercount; + } + + public int getMaxPlayers(){ + return this.maxplayers; + } + + private void setMaxPlayers(int maxplayers){ + this.maxplayers = maxplayers; + } + + public String getMotd(){ + return this.motd; + } + + private void setMotd(String motd){ + this.motd = motd; + } + + public void ping(){ + try{ + Socket socket = new Socket(); + OutputStream outputStream; + DataOutputStream dataOutputStream; + InputStream inputStream; + InputStreamReader inputStreamReader; + socket.setSoTimeout(this.timeout); + socket.connect(new InetSocketAddress(this.getAddress(), this.getPort()), this.getTimeout()); + outputStream = socket.getOutputStream(); + dataOutputStream = new DataOutputStream(outputStream); + inputStream = socket.getInputStream(); + inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-16BE")); + dataOutputStream.write(new byte[]{(byte) 0xFE,(byte) 0x01}); + int packetId = inputStream.read(); + if(packetId == -1){ + dataOutputStream.close(); + outputStream.close(); + inputStreamReader.close(); + inputStream.close(); + socket.close(); + throw new IOException("Premature end of stream."); + } + if(packetId != 0xFF){ + dataOutputStream.close(); + outputStream.close(); + inputStreamReader.close(); + inputStream.close(); + socket.close(); + throw new IOException("Invalid packet ID (" + packetId + ")."); + } + int length = inputStreamReader.read(); + if(length == -1){ + dataOutputStream.close(); + outputStream.close(); + inputStreamReader.close(); + inputStream.close(); + socket.close(); + throw new IOException("Premature end of stream."); + } + if(length == 0){ + dataOutputStream.close(); + outputStream.close(); + inputStreamReader.close(); + inputStream.close(); + socket.close(); + throw new IOException("Invalid string length."); + } + char[] chars = new char[length]; + if(inputStreamReader.read(chars,0,length) != length){ + dataOutputStream.close(); + outputStream.close(); + inputStreamReader.close(); + inputStream.close(); + socket.close(); + throw new IOException("Premature end of stream."); + } + String string = new String(chars); + if(string.startsWith("§")){ + String[] data = string.split("\0"); + this.setMotd(data[3]); + this.setPlayerCount(Integer.parseInt(data[4])); + this.setMaxPlayers(Integer.parseInt(data[5])); + } + else{ + String[] data = string.split("§"); + this.setMotd(data[0]); + this.setPlayerCount(Integer.parseInt(data[1])); + this.setMaxPlayers(Integer.parseInt(data[2])); + } + dataOutputStream.close(); + outputStream.close(); + inputStreamReader.close(); + inputStream.close(); + socket.close(); + } catch (SocketException exception) { + this.setOnline(false); + } catch (IOException exception) { + this.setOnline(false); + } + } + +} diff --git a/src/eu/univento/core/api/server/ServerSettings.java b/src/eu/univento/core/api/server/ServerSettings.java new file mode 100644 index 0000000..c641526 --- /dev/null +++ b/src/eu/univento/core/api/server/ServerSettings.java @@ -0,0 +1,74 @@ +package eu.univento.core.api.server; + +import org.bukkit.GameMode; + +/** + * @author joethei + * @version 0.1 + */ +public class ServerSettings { + + private static boolean build; + private static boolean lobby; + private static boolean debug; + private static boolean mute; + private static boolean game; + private static Game playedGame; + private static GameMode gameMode; + + public static Game getPlayedGameGame() { + return playedGame; + } + + public static void setPlayedGame(Game game) { + ServerSettings.playedGame = game; + } + + public static GameMode getGameMode() { + return gameMode; + } + + public static void setGameMode(GameMode gameMode) { + ServerSettings.gameMode = gameMode; + } + + public static boolean isGame() { + return game; + } + + public static void setGame(boolean game) { + ServerSettings.game = game; + } + + public static boolean isBuild() { + return build; + } + + public static void setBuild(boolean build) { + ServerSettings.build = build; + } + + public static boolean isLobby() { + return lobby; + } + + public static void setLobby(boolean lobby) { + ServerSettings.lobby = lobby; + } + + public static boolean isDebug() { + return debug; + } + + public static void setDebug(boolean debug) { + ServerSettings.debug = debug; + } + + public static boolean isMute() { + return mute; + } + + public static void setMute(boolean mute) { + ServerSettings.mute = mute; + } +} \ No newline at end of file diff --git a/src/eu/univento/core/api/server/Servers.java b/src/eu/univento/core/api/server/Servers.java new file mode 100644 index 0000000..6a830af --- /dev/null +++ b/src/eu/univento/core/api/server/Servers.java @@ -0,0 +1,44 @@ +package eu.univento.core.api.server; + +import eu.univento.core.Core; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +/** + * sends player to other bungeecord servers + * @author joethei + * @version 1.0 + */ +public class Servers { + + + /** + * sends player to server + * @param p player + * @param server name of server + */ + public static void connectServer(Player p, String server) { + ByteArrayOutputStream b = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(b); + try { + out.writeUTF("Connect"); + out.writeUTF(server); + } catch (IOException el) { + el.printStackTrace(); + } + p.sendPluginMessage(Core.getInstance(), "BungeeCord", b.toByteArray()); + } + + /** + * connects all player to server + * @param server name of server + */ + public static void connectAllToServer(String server) { + for (Player all : Bukkit.getOnlinePlayers()) + connectServer(all, server); + } +} \ No newline at end of file diff --git a/src/eu/univento/core/api/twitch/API.java b/src/eu/univento/core/api/twitch/API.java index 8faf136..2f23717 100644 --- a/src/eu/univento/core/api/twitch/API.java +++ b/src/eu/univento/core/api/twitch/API.java @@ -1,28 +1,25 @@ 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); + 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(); -} -} + return buffer.toString(); + } finally { + if (reader != null) + reader.close(); + } + } } \ No newline at end of file diff --git a/src/eu/univento/core/api/twitch/Twitch_Stream.java b/src/eu/univento/core/api/twitch/Twitch_Stream.java index 333cafa..85b5e9f 100644 --- a/src/eu/univento/core/api/twitch/Twitch_Stream.java +++ b/src/eu/univento/core/api/twitch/Twitch_Stream.java @@ -1,6 +1,5 @@ package eu.univento.core.api.twitch; -import com.google.gson.JsonElement; import com.google.gson.JsonObject; public class Twitch_Stream { diff --git a/src/eu/univento/core/api/utils/FDragon.java b/src/eu/univento/core/api/utils/FDragon.java index d6d6964..6f226b4 100644 --- a/src/eu/univento/core/api/utils/FDragon.java +++ b/src/eu/univento/core/api/utils/FDragon.java @@ -1,5 +1,9 @@ package eu.univento.core.api.utils; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; + import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; @@ -7,10 +11,6 @@ import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.Player; - /** * @author mgone2010 */ diff --git a/src/eu/univento/core/api/utils/FWither.java b/src/eu/univento/core/api/utils/FWither.java index 1f577cf..a14933a 100644 --- a/src/eu/univento/core/api/utils/FWither.java +++ b/src/eu/univento/core/api/utils/FWither.java @@ -1,5 +1,9 @@ package eu.univento.core.api.utils; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; + import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; @@ -8,10 +12,6 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.Player; - /** * @author mgone2010 */ diff --git a/src/eu/univento/core/api/utils/GameProfileBuilder.java b/src/eu/univento/core/api/utils/GameProfileBuilder.java index 935d3b6..591e765 100644 --- a/src/eu/univento/core/api/utils/GameProfileBuilder.java +++ b/src/eu/univento/core/api/utils/GameProfileBuilder.java @@ -1,21 +1,14 @@ package eu.univento.core.api.utils; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonParser; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; +import com.google.gson.*; import com.mojang.authlib.GameProfile; import com.mojang.authlib.properties.Property; import com.mojang.authlib.properties.PropertyMap; import com.mojang.util.UUIDTypeAdapter; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; import java.io.BufferedReader; +import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.net.HttpURLConnection; @@ -23,123 +16,156 @@ import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.Map; +import java.util.Map.Entry; import java.util.UUID; -import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; -public class GameProfileBuilder -{ - private HashMap cache = new HashMap(); - private Gson gson; +/** + * @author Jofkos + */ +public class GameProfileBuilder { - public GameProfileBuilder() - { - GsonBuilder builder = new GsonBuilder().disableHtmlEscaping(); + private static final String SERVICE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/%s?unsigned=false"; + private static final String JSON_SKIN = "{\"timestamp\":%d,\"profileId\":\"%s\",\"profileName\":\"%s\",\"isPublic\":true,\"textures\":{\"SKIN\":{\"url\":\"%s\"}}}"; + private static final String JSON_CAPE = "{\"timestamp\":%d,\"profileId\":\"%s\",\"profileName\":\"%s\",\"isPublic\":true,\"textures\":{\"SKIN\":{\"url\":\"%s\"},\"CAPE\":{\"url\":\"%s\"}}}"; - builder.registerTypeAdapter(UUID.class, new UUIDTypeAdapter()); - builder.registerTypeAdapter(GameProfile.class, new GameProfileSerializer()); - builder.registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()); + private static Gson gson = new GsonBuilder().disableHtmlEscaping().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).registerTypeAdapter(GameProfile.class, new GameProfileSerializer()).registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create(); - this.gson = builder.create(); - } + private static HashMap cache = new HashMap<>(); - public GameProfile fetch(UUID uuid) throws Exception { - return fetch(uuid, false); - } + private static long cacheTime = -1; - public GameProfile fetch(UUID uuid, boolean forceNew) throws Exception { - if ((!forceNew) && (this.cache.containsKey(uuid)) && (this.cache.get(uuid).isValid())) { - return this.cache.get(uuid).profile; - } - HttpURLConnection connection = (HttpURLConnection)new URL(String.format("https://sessionserver.mojang.com/session/minecraft/profile/%s?unsigned=false", new Object[] { UUIDTypeAdapter.fromUUID(uuid) })).openConnection(); - connection.setReadTimeout(5000); - - if (connection.getResponseCode() == 200) { - String json = new BufferedReader(new InputStreamReader(connection.getInputStream())).readLine(); - - GameProfile result = this.gson.fromJson(json, GameProfile.class); - this.cache.put(uuid, new CachedProfile(result)); - return result; - } - if ((!forceNew) && (this.cache.containsKey(uuid))) { - return this.cache.get(uuid).profile; - } - JsonObject error = (JsonObject)new JsonParser().parse(new BufferedReader(new InputStreamReader(connection.getErrorStream())).readLine()); - throw new Exception(error.get("error").getAsString() + ": " + error.get("errorMessage").getAsString()); - } - - public GameProfile getProfile(UUID uuid, String name, String skinUrl) - { - return getProfile(uuid, name, skinUrl, null); - } - - @SuppressWarnings({ "rawtypes" }) -public GameProfile getProfile(UUID uuid, String name, String skinUrl, String capeUrl) { - GameProfile profile = new GameProfile(uuid, name); - boolean cape = (capeUrl != null) && (!capeUrl.isEmpty()); - - List args = new ArrayList(); - args.add(Long.valueOf(System.currentTimeMillis())); - args.add(UUIDTypeAdapter.fromUUID(uuid)); - args.add(name); - args.add(skinUrl); - if (cape) args.add(capeUrl); - - profile.getProperties().put("textures", new Property("textures", Base64Coder.encodeString(String.format(cape ? "{\"timestamp\":%d,\"profileId\":\"%s\",\"profileName\":\"%s\",\"isPublic\":true,\"textures\":{\"SKIN\":{\"url\":\"%s\"},\"CAPE\":{\"url\":\"%s\"}}}" : "{\"timestamp\":%d,\"profileId\":\"%s\",\"profileName\":\"%s\",\"isPublic\":true,\"textures\":{\"SKIN\":{\"url\":\"%s\"}}}", args.toArray(new Object[args.size()]))))); - return profile; - } - - private class CachedProfile - { - private GameProfile profile; - private long timestamp; - - public CachedProfile(GameProfile profile) - { - this.profile = profile; - this.timestamp = System.currentTimeMillis(); + /** + * Don't run in main thread! + * + * Fetches the GameProfile from the Mojang servers + * + * @param uuid The player uuid + * @return The GameProfile + * @throws IOException If something wents wrong while fetching + * @see GameProfile + */ + public static GameProfile fetch(UUID uuid) throws IOException { + return fetch(uuid, false); } - public boolean isValid() { - return System.currentTimeMillis() - this.timestamp < 150000L; - } - } + /** + * Don't run in main thread! + * + * Fetches the GameProfile from the Mojang servers + * @param uuid The player uuid + * @param forceNew If true the cache is ignored + * @return The GameProfile + * @throws IOException If something wents wrong while fetching + * @see GameProfile + */ + public static GameProfile fetch(UUID uuid, boolean forceNew) throws IOException { + if (!forceNew && cache.containsKey(uuid) && cache.get(uuid).isValid()) { + return cache.get(uuid).profile; + } else { + HttpURLConnection connection = (HttpURLConnection) new URL(String.format(SERVICE_URL, UUIDTypeAdapter.fromUUID(uuid))).openConnection(); + connection.setReadTimeout(5000); - private class GameProfileSerializer - implements JsonSerializer, JsonDeserializer - { - private GameProfileSerializer() - { - } + if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { + String json = new BufferedReader(new InputStreamReader(connection.getInputStream())).readLine(); - @SuppressWarnings("rawtypes") - public GameProfile deserialize(JsonElement json, Type type, JsonDeserializationContext context) - throws JsonParseException - { - JsonObject object = (JsonObject)json; - UUID id = object.has("id") ? (UUID)context.deserialize(object.get("id"), UUID.class) : null; - String name = object.has("name") ? object.getAsJsonPrimitive("name").getAsString() : null; - GameProfile profile = new GameProfile(id, name); - - PropertyMap properties = object.has("properties") ? (PropertyMap)context.deserialize(object.get("properties"), PropertyMap.class) : null; - - if (properties != null) { - for (Map.Entry prop : properties.entries()) { - profile.getProperties().put((String)prop.getKey(), (Property)prop.getValue()); + GameProfile result = gson.fromJson(json, GameProfile.class); + cache.put(uuid, new CachedProfile(result)); + return result; + } else { + if (!forceNew && cache.containsKey(uuid)) { + return cache.get(uuid).profile; + } + JsonObject error = (JsonObject) new JsonParser().parse(new BufferedReader(new InputStreamReader(connection.getErrorStream())).readLine()); + throw new IOException(error.get("error").getAsString() + ": " + error.get("errorMessage").getAsString()); + } } - } - return profile; } - public JsonElement serialize(GameProfile profile, Type type, JsonSerializationContext context) { - JsonObject result = new JsonObject(); - if (profile.getId() != null) - result.add("id", context.serialize(profile.getId())); - if (profile.getName() != null) - result.addProperty("name", profile.getName()); - if (!profile.getProperties().isEmpty()) - result.add("properties", context.serialize(profile.getProperties())); - return result; + /** + * Builds a GameProfile for the specified args + * + * @param uuid The uuid + * @param name The name + * @param skin The url from the skin image + * @return A GameProfile built from the arguments + * @see GameProfile + */ + public static GameProfile getProfile(UUID uuid, String name, String skin) { + return getProfile(uuid, name, skin, null); + } + + /** + * Builds a GameProfile for the specified args + * + * @param uuid The uuid + * @param name The name + * @param skinUrl Url from the skin image + * @param capeUrl Url from the cape image + * @return A GameProfile built from the arguments + * @see GameProfile + */ + public static GameProfile getProfile(UUID uuid, String name, String skinUrl, String capeUrl) { + GameProfile profile = new GameProfile(uuid, name); + boolean cape = capeUrl != null && !capeUrl.isEmpty(); + + List args = new ArrayList(); + args.add(System.currentTimeMillis()); + args.add(UUIDTypeAdapter.fromUUID(uuid)); + args.add(name); + args.add(skinUrl); + if (cape) args.add(capeUrl); + + profile.getProperties().put("textures", new Property("textures", Base64Coder.encodeString(String.format(cape ? JSON_CAPE : JSON_SKIN, args.toArray(new Object[args.size()]))))); + return profile; + } + + /** + * Sets the time as long as you want to keep the gameprofiles in cache (-1 = never remove it) + * @param time cache time (default = -1) + */ + public static void setCacheTime(long time) { + cacheTime = time; + } + + private static class GameProfileSerializer implements JsonSerializer, JsonDeserializer { + + public GameProfile deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { + JsonObject object = (JsonObject) json; + UUID id = object.has("id") ? (UUID) context.deserialize(object.get("id"), UUID.class) : null; + String name = object.has("name") ? object.getAsJsonPrimitive("name").getAsString() : null; + GameProfile profile = new GameProfile(id, name); + + if (object.has("properties")) { + for (Entry prop : ((PropertyMap) context.deserialize(object.get("properties"), PropertyMap.class)).entries()) { + profile.getProperties().put(prop.getKey(), prop.getValue()); + } + } + return profile; + } + + public JsonElement serialize(GameProfile profile, Type type, JsonSerializationContext context) { + JsonObject result = new JsonObject(); + if (profile.getId() != null) + result.add("id", context.serialize(profile.getId())); + if (profile.getName() != null) + result.addProperty("name", profile.getName()); + if (!profile.getProperties().isEmpty()) + result.add("properties", context.serialize(profile.getProperties())); + return result; + } + } + + private static class CachedProfile { + + private long timestamp = System.currentTimeMillis(); + private GameProfile profile; + + public CachedProfile(GameProfile profile) { + this.profile = profile; + } + + public boolean isValid() { + return cacheTime < 0 ? true : (System.currentTimeMillis() - timestamp) < cacheTime; + } } - } } \ No newline at end of file diff --git a/src/eu/univento/core/api/utils/NameFetcher.java b/src/eu/univento/core/api/utils/NameFetcher.java index 7365c24..ee04212 100644 --- a/src/eu/univento/core/api/utils/NameFetcher.java +++ b/src/eu/univento/core/api/utils/NameFetcher.java @@ -1,6 +1,9 @@ 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; @@ -9,12 +12,8 @@ import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.Callable; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -public class NameFetcher - implements 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; diff --git a/src/eu/univento/core/api/utils/reflection/IReflection.java b/src/eu/univento/core/api/utils/reflection/IReflection.java new file mode 100644 index 0000000..841fe5f --- /dev/null +++ b/src/eu/univento/core/api/utils/reflection/IReflection.java @@ -0,0 +1,256 @@ +package eu.univento.core.api.utils.reflection; + +import org.bukkit.Bukkit; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + + +/** + * -== IReflection ==- + * + * This library was created by @Ingrim4 and allows you to use the reflection-api implemented in java easily for spigot plugins + * You are welcome to use it and redistribute it under the following conditions: + * * Don't claim this class as your own + * * Don't remove this disclaimer + * + * @author Ingrim4 + * @version 1.2.8 + */ +public class IReflection { + + public interface ConstructorAccessor { + + public Object newInstance(Object... args); + + public Constructor getConstructor(); + + } + + public interface MethodAccessor { + + public Object invoke(Object target, Object... args); + + public Method getMehtod(); + + } + + public interface FieldAccessor { + + public T get(Object target); + + public void set(Object target, Object value); + + public Field getField(); + + } + + public static Class getClass(ServerPacket packet, String name) { + try { + return Class.forName(packet + name); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + return null; + } + + public static ConstructorAccessor getConstructor(Class clazz, Class... parameterTypes) { + Class[] p = DataType.convertToPrimitive(parameterTypes); + for (Constructor c : clazz.getDeclaredConstructors()) + if (DataType.equalsArray(DataType.convertToPrimitive(c.getParameterTypes()), p)) { + c.setAccessible(true); + return new ConstructorAccessor() { + + @Override + public Object newInstance(Object... args) { + try { + return c.newInstance(args); + } catch (IllegalAccessException e) { + throw new IllegalStateException("Cannot use reflection.", e); + } catch (InvocationTargetException e) { + throw new RuntimeException("An internal error occured.", e.getCause()); + } catch (InstantiationException e) { + throw new RuntimeException("Cannot instantiate object.", e); + } catch (IllegalArgumentException e) { + throw e; + } + } + + @Override + public Constructor getConstructor() { + return c; + } + }; + } + if (clazz.getSuperclass() != null) + return IReflection.getConstructor(clazz.getSuperclass(), parameterTypes); + return null; + } + + public static MethodAccessor getMethod(Class target, String methodName, Class... parameterTypes) { + return IReflection.getMethod(target, methodName, null, parameterTypes); + } + + public static MethodAccessor getMethod(Class target, String methodName, Class returnType, Class... parameterTypes) { + Class[] primitiveParameter = DataType.convertToPrimitive(parameterTypes); + for (Method method : target.getDeclaredMethods()) + if ((methodName == null || method.getName().equals(methodName)) && (returnType == null || method.getReturnType().equals(returnType)) && (primitiveParameter.length == 0 || DataType.equalsArray(DataType.convertToPrimitive(method.getParameterTypes()), primitiveParameter))) { + method.setAccessible(true); + return new MethodAccessor() { + + @Override + public Object invoke(Object target, Object... args) { + try { + return method.invoke(target, args); + } catch (IllegalAccessException e) { + throw new IllegalStateException("Cannot use reflection.", e); + } catch (InvocationTargetException e) { + throw new RuntimeException("An internal error occured.", e.getCause()); + } catch (IllegalArgumentException e) { + throw e; + } + } + + @Override + public Method getMehtod() { + return method; + } + }; + } + if (target.getSuperclass() != null) + return IReflection.getMethod(target.getSuperclass(), methodName, returnType, parameterTypes); + + throw new IllegalStateException(String.format("Unable to find method %s (%s).", methodName, parameterTypes)); + } + + public static FieldAccessor getField(Class target, String fieldName) { + return IReflection.getField(target, fieldName, null, 0); + } + + public static FieldAccessor getField(Class target, Class fieldType, int index) { + return IReflection.getField(target, null, fieldType, index); + } + + private static FieldAccessor getField(Class target, String fieldName, Class fieldType, int index) { + for (Field field : target.getDeclaredFields()) + if ((fieldName == null || fieldName.equals(field.getName())) && (fieldType == null || (fieldType.isAssignableFrom(field.getType()) && index-- <= 0))) { + field.setAccessible(true); + return new FieldAccessor() { + + @Override + @SuppressWarnings("unchecked") + public T get(Object target) { + try { + return (T) field.get(target); + } catch (IllegalAccessException e) { + throw new IllegalStateException("Cannot use reflection.", e); + } catch (IllegalArgumentException e) { + throw e; + } + } + + @Override + public void set(Object target, Object value) { + try { + field.set(target, value); + } catch (IllegalAccessException e) { + throw new IllegalStateException("Cannot use reflection.", e); + } catch (IllegalArgumentException e) { + throw e; + } + } + + @Override + public Field getField() { + return field; + } + }; + } + + if (target.getSuperclass() != null) + return IReflection.getField(target.getSuperclass(), fieldName, fieldType, index); + + throw new IllegalStateException(String.format("Unable to find field %s (%s).", fieldName, fieldType)); + } + + public enum DataType { + BYTE(byte.class, Byte.class), SHORT(short.class, Short.class), INTEGER(int.class, + Integer.class), LONG(long.class, Long.class), CHARACTER(char.class, Character.class), FLOAT(float.class, + Float.class), DOUBLE(double.class, Double.class), BOOLEAN(boolean.class, Boolean.class); + + private static final Map, DataType> CLASS_MAP = new HashMap, DataType>(); + private final Class primitive; + private final Class reference; + + static { + for (DataType t : DataType.values()) { + DataType.CLASS_MAP.put(t.primitive, t); + DataType.CLASS_MAP.put(t.reference, t); + } + } + + private DataType(Class primitive, Class reference) { + this.primitive = primitive; + this.reference = reference; + } + + public Class getPrimitive() { + return this.primitive; + } + + public Class getReference() { + return this.reference; + } + + public static DataType fromClass(Class c) { + return DataType.CLASS_MAP.get(c); + } + + public static Class getPrimitive(Class c) { + DataType t = DataType.fromClass(c); + return t == null ? c : t.getPrimitive(); + } + + public static Class getReference(Class c) { + DataType t = DataType.fromClass(c); + return t == null ? c : t.getReference(); + } + + public static Class[] convertToPrimitive(Class[] classes) { + int length = classes == null ? 0 : classes.length; + Class[] types = new Class[length]; + for (int i = 0; i < length; i++) + types[i] = DataType.getPrimitive(classes[i]); + return types; + } + + public static boolean equalsArray(Class[] a1, Class[] a2) { + if (a1 == null || a2 == null || a1.length != a2.length) + return false; + for (int i = 0; i < a1.length; i++) + if (!a1[i].equals(a2[i]) && !a1[i].isAssignableFrom(a2[i])) + return false; + return true; + } + } + + public enum ServerPacket { + + MINECRAFT_PACKAGE("net.minecraft.server." + Bukkit.getServer().getClass().getPackage().getName().substring(23)), MOJANG_AUTHLIB("com.mojang.authlib"), CRAFTBUKKIT_PACKAGE(Bukkit.getServer().getClass().getPackage().getName()); + + ServerPacket(String source) { + this.name = source; + } + + private final String name; + + @Override + public String toString() { + return this.name + "."; + } + } +} \ No newline at end of file diff --git a/src/eu/univento/core/api/utils/Reflection.java b/src/eu/univento/core/api/utils/reflection/Reflection.java similarity index 95% rename from src/eu/univento/core/api/utils/Reflection.java rename to src/eu/univento/core/api/utils/reflection/Reflection.java index 17880fe..6c4dd1d 100644 --- a/src/eu/univento/core/api/utils/Reflection.java +++ b/src/eu/univento/core/api/utils/reflection/Reflection.java @@ -1,140 +1,141 @@ -package eu.univento.core.api.utils; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import org.bukkit.Bukkit; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -public class Reflection -{ - public static final Class CLASS_CRAFTITEMSTACK = getCraftBukkitClass("inventory.CraftItemStack"); - public static final Method METHOD_ASNMSCOPY = getMethod(CLASS_CRAFTITEMSTACK, "asNMSCopy"); - - public static void sendPacket(Player p, Object packet) { - try { - Object nmsPlayer = getNMSPlayer(p); - Object connection = nmsPlayer.getClass() - .getField("playerConnection").get(nmsPlayer); - connection.getClass() - .getMethod("sendPacket", new Class[] { getNMSClass("Packet") }) - .invoke(connection, new Object[] { packet }); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static Field getField(Class clazz, String field) { - Field re = null; - try { - re = clazz.getDeclaredField(field); - } catch (NoSuchFieldException e) { - e.printStackTrace(); - } catch (SecurityException e) { - e.printStackTrace(); - } - return re; - } - - public static void sendPacket(Player p, String packetName, Class[] parameterclass, Object[] parameters) { - try { - Object nmsPlayer = getNMSPlayer(p); - Object connection = nmsPlayer.getClass() - .getField("playerConnection").get(nmsPlayer); - Object packet = - Class.forName( - nmsPlayer.getClass().getPackage().getName() + "." + - packetName) - .getConstructor(parameterclass).newInstance(parameters); - connection.getClass() - .getMethod("sendPacket", new Class[] { getNMSClass("Packet") }) - .invoke(connection, new Object[] { packet }); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static String getVersion() { - String name = Bukkit.getServer().getClass().getPackage().getName(); - String version = name.substring(name.lastIndexOf('.') + 1) + "."; - return version; - } - - public static Class getNMSClass(String className) { - String fullName = "net.minecraft.server." + getVersion() + className; - Class clazz = null; - try { - clazz = Class.forName(fullName); - } catch (Exception e) { - e.printStackTrace(); - } - return clazz; - } - public static Class getCraftBukkitClass(String className) { - String fullName = "org.bukkit.craftbukkit." + getVersion() + className; - Class clazz = null; - try { - clazz = Class.forName(fullName); - } catch (Exception e) { - e.printStackTrace(); - } - return clazz; - } - - public static Object asNMSCopy(ItemStack i) throws IllegalAccessException, InvocationTargetException { - Object re = null; - try - { - METHOD_ASNMSCOPY.invoke(null, new Object[] { i }); - } - catch (java.lang.IllegalArgumentException e) { - e.printStackTrace(); - } - - return re; - } - - public static Field getField(Field f) { - f.setAccessible(true); - return f; - } - public static Constructor getConstructor(Class clazz, Class[] param) { - Constructor re = null; - try { - re = clazz.getConstructor(param); - } catch (Exception e) { - e.printStackTrace(); - } - return re; - } - public static Object getHandle(Entity entity) { - Object object = null; - try - { - object = getMethod(entity.getClass(), "getHandle").invoke(entity, new Object[0]); - } catch (Exception e) { - e.printStackTrace(); - } - - return object; - } - - public static Object getNMSPlayer(Player player) { - return getHandle(player); - } - - public static Method getMethod(Class c, String methodName) { - Method returnMethod = null; - - for (Method m : c.getDeclaredMethods()) { - if (m.getName().equals(methodName)) { - returnMethod = m; - } - } - - return returnMethod; - } +package eu.univento.core.api.utils.reflection; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public class Reflection +{ + public static final Class CLASS_CRAFTITEMSTACK = getCraftBukkitClass("inventory.CraftItemStack"); + public static final Method METHOD_ASNMSCOPY = getMethod(CLASS_CRAFTITEMSTACK, "asNMSCopy"); + + public static void sendPacket(Player p, Object packet) { + try { + Object nmsPlayer = getNMSPlayer(p); + Object connection = nmsPlayer.getClass() + .getField("playerConnection").get(nmsPlayer); + connection.getClass() + .getMethod("sendPacket", new Class[] { getNMSClass("Packet") }) + .invoke(connection, new Object[] { packet }); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static Field getField(Class clazz, String field) { + Field re = null; + try { + re = clazz.getDeclaredField(field); + } catch (NoSuchFieldException e) { + e.printStackTrace(); + } catch (SecurityException e) { + e.printStackTrace(); + } + return re; + } + + public static void sendPacket(Player p, String packetName, Class[] parameterclass, Object[] parameters) { + try { + Object nmsPlayer = getNMSPlayer(p); + Object connection = nmsPlayer.getClass() + .getField("playerConnection").get(nmsPlayer); + Object packet = + Class.forName( + nmsPlayer.getClass().getPackage().getName() + "." + + packetName) + .getConstructor(parameterclass).newInstance(parameters); + connection.getClass() + .getMethod("sendPacket", new Class[] { getNMSClass("Packet") }) + .invoke(connection, new Object[] { packet }); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static String getVersion() { + String name = Bukkit.getServer().getClass().getPackage().getName(); + String version = name.substring(name.lastIndexOf('.') + 1) + "."; + return version; + } + + public static Class getNMSClass(String className) { + String fullName = "net.minecraft.server." + getVersion() + className; + Class clazz = null; + try { + clazz = Class.forName(fullName); + } catch (Exception e) { + e.printStackTrace(); + } + return clazz; + } + public static Class getCraftBukkitClass(String className) { + String fullName = "org.bukkit.craftbukkit." + getVersion() + className; + Class clazz = null; + try { + clazz = Class.forName(fullName); + } catch (Exception e) { + e.printStackTrace(); + } + return clazz; + } + + public static Object asNMSCopy(ItemStack i) throws IllegalAccessException, InvocationTargetException { + Object re = null; + try + { + METHOD_ASNMSCOPY.invoke(null, new Object[] { i }); + } + catch (java.lang.IllegalArgumentException e) { + e.printStackTrace(); + } + + return re; + } + + public static Field getField(Field f) { + f.setAccessible(true); + return f; + } + public static Constructor getConstructor(Class clazz, Class[] param) { + Constructor re = null; + try { + re = clazz.getConstructor(param); + } catch (Exception e) { + e.printStackTrace(); + } + return re; + } + public static Object getHandle(Entity entity) { + Object object = null; + try + { + object = getMethod(entity.getClass(), "getHandle").invoke(entity, new Object[0]); + } catch (Exception e) { + e.printStackTrace(); + } + + return object; + } + + public static Object getNMSPlayer(Player player) { + return getHandle(player); + } + + public static Method getMethod(Class c, String methodName) { + Method returnMethod = null; + + for (Method m : c.getDeclaredMethods()) { + if (m.getName().equals(methodName)) { + returnMethod = m; + } + } + + return returnMethod; + } } \ No newline at end of file diff --git a/src/eu/univento/core/api/youtube/YTAPI.java b/src/eu/univento/core/api/youtube/YTAPI.java index 53bea44..c15a4fd 100644 --- a/src/eu/univento/core/api/youtube/YTAPI.java +++ b/src/eu/univento/core/api/youtube/YTAPI.java @@ -1,13 +1,13 @@ package eu.univento.core.api.youtube; -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.URL; - 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(); diff --git a/src/eu/univento/core/commands/Ban.java b/src/eu/univento/core/commands/Ban.java index 0a08ad8..c8d91e2 100644 --- a/src/eu/univento/core/commands/Ban.java +++ b/src/eu/univento/core/commands/Ban.java @@ -1,18 +1,17 @@ package eu.univento.core.commands; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - +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.Perms.Ranks; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import eu.univento.core.Core; -import eu.univento.core.api.AutoCommand; -import eu.univento.core.api.Messages; -import eu.univento.core.api.player.CustomPlayer; -import eu.univento.core.api.player.Perms.Ranks; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; /** * command to ban players @@ -35,36 +34,35 @@ public class Ban extends AutoCommand{ 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 >= 3) { + if(args.length == 2) { if(Bukkit.getPlayer(args[0]) != null) { CustomPlayer t = CustomPlayer.getPlayer(args[0]); - if(getReasons().containsKey(args[1])) { - String string = getReasons().get(args[1]); - int id = Integer.parseInt(string); - + if(getReasons().containsValue(args[1])) { + int id = getKey(args[1]); t.ban(getReasons().get(id), p, getBanDurations().get(id)); }else { - p.sendMessage(Messages.PREFIX + "§cDieser Grund exsistiert nicht"); + p.sendMessage(msgs.PREFIX() + msgs.Core_BAN_NO_REASON()); } }else { - p.sendMessage(Messages.PREFIX + "§cDer Spieler " + args[0] + " exsistiert nicht, oder ist nicht online."); + p.sendMessage(msgs.PREFIX() + msgs.NOT_ONLINE(args[0])); } }else { - p.sendMessage(Messages.PREFIX + "§cNutze /ban "); + p.sendMessage(msgs.PREFIX() + msgs.Core_BAN_USAGE()); } }else { - sender.sendMessage(Messages.NO_PERMS); + sender.sendMessage(msgs.NO_PERMS()); } }else { - sender.sendMessage(Messages.NOT_A_PLAYER); + sender.sendMessage(Messages.Console.NOT_A_PLAYER); } return true; } @Override public List tabComplete(CommandSender sender, String label, String[] args) { - List list = new ArrayList(); + List list = new ArrayList<>(); for(int i = 0; i >= getReasons().size(); i++) { list.add(getReasons().get(i)); } @@ -75,36 +73,44 @@ public class Ban extends AutoCommand{ * @return all possible ban reasons */ private HashMap getReasons() { - HashMap map = new HashMap(); + HashMap map = new HashMap<>(); map.put(1, "Hacking"); map.put(2, "Griefing"); map.put(3, "Bugusing"); - map.put(4, "Beleidigung"); + map.put(4, "Insult"); map.put(5, "Spam"); map.put(6, "Banumgehung"); - map.put(7, "Werbung"); + map.put(7, "Advertising"); map.put(8, "Trolling"); return map; } - + /** * @return ban durations to reason */ private HashMap getBanDurations() { - HashMap map = new HashMap(); + 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, 50); + 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/eu/univento/core/commands/Build.java b/src/eu/univento/core/commands/Build.java index c6b519f..341f16b 100644 --- a/src/eu/univento/core/commands/Build.java +++ b/src/eu/univento/core/commands/Build.java @@ -1,16 +1,18 @@ package eu.univento.core.commands; -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - import eu.univento.core.Core; import eu.univento.core.api.AutoCommand; -import eu.univento.core.api.Messages; +import eu.univento.core.api.languages.Messages; import eu.univento.core.api.player.CustomPlayer; import eu.univento.core.api.player.Perms.Ranks; +import eu.univento.core.api.server.ServerSettings; +import org.bukkit.GameMode; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.List; /** * lets player build @@ -22,12 +24,12 @@ public class Build extends AutoCommand{ /** * player who can build */ - private static ArrayList players = new ArrayList(); + private static HashMap players = new HashMap<>(); /** * @return player that can build */ - public static ArrayList getPlayers() { + public static HashMap getPlayers() { return players; } @@ -45,19 +47,27 @@ public class Build extends AutoCommand{ 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.Builder)) { - if(players.contains(p)) { + if(players.containsKey(p)) { + p.sendMessage(msgs.PREFIX() + msgs.Core_BUILD_OFF()); + + ItemStack[] content = players.get(p); + p.getInventory().setContents(content); players.remove(p); - p.sendMessage("§cDu kannst nun nicht mehr bauen"); - }else { - players.add(p); - p.sendMessage("§aDu kannst nun bauen"); + p.setGameMode(ServerSettings.getGameMode()); + + }else { + players.put(p, p.getInventory().getContents()); + p.sendMessage(msgs.PREFIX() + msgs.Core_BUILD_ON()); + p.getInventory().clear(); + p.setGameMode(GameMode.CREATIVE); } }else { - sender.sendMessage(Messages.NO_PERMS); + sender.sendMessage(msgs.NO_PERMS()); } }else { - sender.sendMessage(Messages.NOT_A_PLAYER); + sender.sendMessage(Messages.Console.NOT_A_PLAYER); } return false; } @@ -66,5 +76,7 @@ public class Build extends AutoCommand{ public List tabComplete(CommandSender sender, String label, String[] args) { return null; } + + } \ No newline at end of file diff --git a/src/eu/univento/core/commands/ChatClear.java b/src/eu/univento/core/commands/ChatClear.java new file mode 100644 index 0000000..32741d2 --- /dev/null +++ b/src/eu/univento/core/commands/ChatClear.java @@ -0,0 +1,53 @@ +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.Perms.Ranks; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; + +/** + * @author joethei + * @version 1.0 + */ +public class ChatClear extends AutoCommand { + + public ChatClear(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.Supporter)) { + for(int i = 0; i <= 100; i++) { + Bukkit.broadcastMessage(" "); + } + for(Player players : Bukkit.getOnlinePlayers()) { + CustomPlayer player = CustomPlayer.getPlayer(players); + if (player.isAllowed(Ranks.Supporter)) { + Messages messages = new Messages(player); + player.sendMessage(messages.Core_CHAT_CLEARED(p)); + } + } + }else { + p.sendMessage(msgs.NO_PERMS()); + } + }else { + sender.sendMessage(Messages.Console.NOT_A_PLAYER); + } + return true; + } + + @Override + public List tabComplete(CommandSender sender, String label, String[] args) { + return null; + } +} \ No newline at end of file diff --git a/src/eu/univento/core/commands/Fix.java b/src/eu/univento/core/commands/Fix.java index 553f691..bb683f2 100644 --- a/src/eu/univento/core/commands/Fix.java +++ b/src/eu/univento/core/commands/Fix.java @@ -1,16 +1,15 @@ package eu.univento.core.commands; -import java.util.ArrayList; -import java.util.List; - +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 org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import eu.univento.core.Core; -import eu.univento.core.api.AutoCommand; -import eu.univento.core.api.Messages; -import eu.univento.core.api.player.CustomPlayer; +import java.util.List; +import java.util.stream.Collectors; /** * fixes players @@ -33,43 +32,42 @@ public class Fix extends AutoCommand{ 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(args.length == 0) { for(Player player : Bukkit.getOnlinePlayers()) { player.hidePlayer(p); player.showPlayer(p); } p.teleport(p.getLocation()); - p.sendMessage("§6Du hast dich gefixt"); + p.sendMessage(msgs.PREFIX() + msgs.Core_FIX_OWN()); } if(args.length == 1) { if(Bukkit.getPlayer(args[0]) != null) { CustomPlayer t = CustomPlayer.getPlayer(Bukkit.getPlayer(args[0]).getName()); + Messages tMsgs = new Messages(t); if(t != p) { p.hidePlayer(t); p.showPlayer(t); p.teleport(p.getLocation()); - p.sendMessage("§6Du hast den Spieler " + t.getDisplayName() + " gefixt"); - t.sendMessage("§6Du wurdest von " + p.getDisplayName() + " gefixt"); + p.sendMessage(msgs.Core_FIX_OTHER(t)); + t.sendMessage(tMsgs.Core_FIX_BY_OTHER(p)); }else { p.chat("/fix"); } }else { - p.sendMessage("§cDieser Spieler ist nicht online"); + p.sendMessage(msgs.NOT_ONLINE(args[0])); } } }else { - sender.sendMessage(Messages.NOT_A_PLAYER); + sender.sendMessage(Messages.Console.NOT_A_PLAYER); } return true; } @Override public List tabComplete(CommandSender sender, String label, String[] args) { - List list = new ArrayList(); - - for(Player players : Bukkit.getOnlinePlayers()) { - list.add(players.getDisplayName()); - } + List list = Bukkit.getOnlinePlayers().stream().map(Player::getDisplayName).collect(Collectors.toList()); + return list; } } \ No newline at end of file diff --git a/src/eu/univento/core/commands/GameMode.java b/src/eu/univento/core/commands/GameMode.java index da8a6bd..e92d33d 100644 --- a/src/eu/univento/core/commands/GameMode.java +++ b/src/eu/univento/core/commands/GameMode.java @@ -1,16 +1,15 @@ package eu.univento.core.commands; -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - import eu.univento.core.Core; import eu.univento.core.api.AutoCommand; -import eu.univento.core.api.Messages; +import eu.univento.core.api.languages.Messages; import eu.univento.core.api.player.CustomPlayer; import eu.univento.core.api.player.Perms.Ranks; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; /** * changes game modes @@ -33,26 +32,27 @@ public class GameMode extends AutoCommand{ 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.Builder)) { if(args.length == 1) { String mode = args[0]; p.setGameMode(getModeFromString(mode)); - p.sendMessage("§aDein Spielmodus wurde geändert"); - }else { - p.sendMessage("§cNutze /gm <0 | 1 | 2 | 3>"); + p.sendMessage(msgs.Core_GM_CHANGED()); + }if(args.length == 0){ + p.sendMessage(msgs.Core_GM_USAGE()); } }else { - p.sendMessage(Messages.NO_PERMS); + p.sendMessage(msgs.NO_PERMS()); } }else { - sender.sendMessage(Messages.NOT_A_PLAYER); + sender.sendMessage(Messages.Console.NOT_A_PLAYER); } return true; } @Override public List tabComplete(CommandSender sender, String label, String[] args) { - List list = new ArrayList(); + List list = new ArrayList<>(); list.add("0"); list.add("1"); diff --git a/src/eu/univento/core/commands/GlobalMute.java b/src/eu/univento/core/commands/GlobalMute.java index 89c8fc2..86f1f0b 100644 --- a/src/eu/univento/core/commands/GlobalMute.java +++ b/src/eu/univento/core/commands/GlobalMute.java @@ -1,16 +1,15 @@ package eu.univento.core.commands; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - import eu.univento.core.Core; import eu.univento.core.api.AutoCommand; -import eu.univento.core.api.Messages; -import eu.univento.core.api.Settings; +import eu.univento.core.api.languages.Messages; import eu.univento.core.api.player.CustomPlayer; import eu.univento.core.api.player.Perms.Ranks; +import eu.univento.core.api.server.ServerSettings; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; /** * mutes the whole server @@ -33,19 +32,20 @@ public class GlobalMute extends AutoCommand{ 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(Settings.isMute()) { - Settings.setMute(false); - p.sendMessage("§cGlobal Mute deaktiviert"); + if(ServerSettings.isMute()) { + ServerSettings.setMute(false); + p.sendMessage(msgs.Core_GLOBALMUTE_OFF()); }else { - Settings.setMute(true); - p.sendMessage("§aGlobal Mute aktiviert"); + ServerSettings.setMute(true); + p.sendMessage(msgs.Core_GLOBALMUTE_ON()); } }else { - p.sendMessage(Messages.NO_PERMS); + p.sendMessage(msgs.NO_PERMS()); } }else { - sender.sendMessage(Messages.NOT_A_PLAYER); + sender.sendMessage(Messages.Console.NOT_A_PLAYER); } return false; } diff --git a/src/eu/univento/core/commands/RunAs.java b/src/eu/univento/core/commands/RunAs.java index b801905..2d76357 100644 --- a/src/eu/univento/core/commands/RunAs.java +++ b/src/eu/univento/core/commands/RunAs.java @@ -1,17 +1,16 @@ package eu.univento.core.commands; -import java.util.ArrayList; -import java.util.List; - +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.Perms.Ranks; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import eu.univento.core.Core; -import eu.univento.core.api.AutoCommand; -import eu.univento.core.api.Messages; -import eu.univento.core.api.player.CustomPlayer; -import eu.univento.core.api.player.Perms.Ranks; +import java.util.List; +import java.util.stream.Collectors; /** * lets other player run commands @@ -35,6 +34,7 @@ public class RunAs extends AutoCommand{ 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.Admin)) { if(args.length >= 2) { CustomPlayer t = CustomPlayer.getPlayer(Bukkit.getPlayer(args[0]).getName()); @@ -44,33 +44,26 @@ public class RunAs extends AutoCommand{ msg = msg + args[i] + " "; } t.chat(msg); - p.sendMessage("§2Erfolgreich ausgeführt"); + p.sendMessage(msgs.Core_RUNAS_RUN(t)); return true; }else { - String msg = Messages.readString("Messages.Player.NotOnline"); - msg = msg.replace("$player", args[0]); - p.sendMessage(msg); + p.sendMessage(msgs.NOT_ONLINE(args[0])); } }else { - p.sendMessage("§cDu musst §6/RunAs §causführen"); + p.sendMessage(msgs.Core_RUNAS_USAGE()); } }else { - p.sendMessage(Messages.NO_PERMS); + p.sendMessage(msgs.NO_PERMS()); } }else { - sender.sendMessage(Messages.NOT_A_PLAYER); + sender.sendMessage(Messages.Console.NOT_A_PLAYER); } return false; } @Override public List tabComplete(CommandSender sender, String label, String[] args) { - List list = new ArrayList(); - - for(Player players : Bukkit.getOnlinePlayers()) { - list.add(players.getDisplayName()); - } - return list; + return Bukkit.getOnlinePlayers().stream().map(Player::getDisplayName).collect(Collectors.toList()); } diff --git a/src/eu/univento/core/commands/SetRank.java b/src/eu/univento/core/commands/SetRank.java index bbeef8f..b58b2c3 100644 --- a/src/eu/univento/core/commands/SetRank.java +++ b/src/eu/univento/core/commands/SetRank.java @@ -1,19 +1,16 @@ package eu.univento.core.commands; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - +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.Perms.Ranks; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import eu.univento.core.Core; -import eu.univento.core.api.AutoCommand; -import eu.univento.core.api.Messages; -import eu.univento.core.api.player.CustomPlayer; -import eu.univento.core.api.player.Perms; -import eu.univento.core.api.player.Perms.Ranks; +import java.util.List; +import java.util.stream.Collectors; /** * sets ranks for players @@ -36,54 +33,67 @@ public class SetRank extends AutoCommand{ public boolean execute(CommandSender sender, String label, String[] args) { if(sender instanceof Player) { CustomPlayer p = CustomPlayer.getPlayer(sender.getName()); - if(p.isAllowed(Ranks.Admin)) { + Messages msgs = new Messages(p); + if(p.isAllowed(Ranks.HeadBuilder)) { if(args.length == 2) { Ranks rank = Ranks.valueOf(args[1]); if(rank != null) { if(Bukkit.getPlayer(args[0]) != null) { - CustomPlayer player = CustomPlayer.getPlayer(Bukkit.getPlayer(args[0]).getName()); - try { - Perms.setRank(player, rank); - p.sendMessage("§aDer Rang wurde erfolgreich gesetzt"); - } catch (ClassNotFoundException | SQLException e) { - e.printStackTrace(); - p.sendMessage(Messages.readString("Messages.UnknownError")); - } + CustomPlayer player = CustomPlayer.getPlayer(Bukkit.getPlayer(args[0]).getName()); + if(p.isAllowed(Ranks.HeadBuilder) && rank == Ranks.Builder) { + player.setRank(rank); + p.sendMessage(msgs.PREFIX() + msgs.Core_SETRANK_SET(player, player.getRank())); + player.kickPlayer(msgs.Core_SETRANK_KICK()); + }if(p.isAllowed(Ranks.SrModerator) && rank == Ranks.Moderator) { + player.setRank(rank); + p.sendMessage(msgs.PREFIX() + msgs.Core_SETRANK_SET(player, player.getRank())); + player.kickPlayer(msgs.Core_SETRANK_KICK()); + }if(p.isAllowed(Ranks.SrModerator) && rank == Ranks.Supporter) { + player.setRank(rank); + p.sendMessage(msgs.PREFIX() + msgs.Core_SETRANK_SET(player, player.getRank())); + player.kickPlayer(msgs.Core_SETRANK_KICK()); + }if(p.isAllowed(Ranks.SrDeveloper) && rank == Ranks.Developer) { + player.setRank(rank); + p.sendMessage(msgs.PREFIX() + msgs.Core_SETRANK_SET(player, player.getRank())); + player.kickPlayer(msgs.Core_SETRANK_KICK()); + } + if(p.isAllowed(Ranks.Admin)) { + player.setRank(rank); + p.sendMessage(msgs.PREFIX() + msgs.Core_SETRANK_SET(player, player.getRank())); + player.kickPlayer(msgs.Core_SETRANK_KICK()); + } }else { - p.sendMessage(Messages.NOT_ONLINE); + p.sendMessage(msgs.NOT_ONLINE(args[0])); } }else { - p.sendMessage("§cDen Rang gibt es nicht"); + p.sendMessage(msgs.Core_SETRANK_NO_RANK()); } }else { - p.sendMessage("§cNutze §6/setRank "); + p.sendMessage(msgs.Core_SETRANK_NO_RANK()); } }else { - p.sendMessage(Messages.NO_PERMS); + p.sendMessage(msgs.NO_PERMS()); } }else { - sender.sendMessage(Messages.NOT_A_PLAYER); + sender.sendMessage(Messages.Console.NOT_A_PLAYER); } return true; } @Override public List tabComplete(CommandSender sender, String label, String[] args) { - List list = new ArrayList(); - - for(Player players : Bukkit.getOnlinePlayers()) { - list.add(players.getDisplayName()); - } + List list = Bukkit.getOnlinePlayers().stream().map(Player::getDisplayName).collect(Collectors.toList()); list.add("Admin"); list.add("Developer"); + list.add("SrModerator"); + list.add("Moderator"); list.add("HeadBuilder"); list.add("Builder"); - list.add("Moderator"); list.add("Supporter"); list.add("Youtuber"); list.add("Premium"); - list.add("Spieler"); + list.add("Player"); return list; } diff --git a/src/eu/univento/core/commands/SystemInfo.java b/src/eu/univento/core/commands/SystemInfo.java index a1bccab..e840a19 100644 --- a/src/eu/univento/core/commands/SystemInfo.java +++ b/src/eu/univento/core/commands/SystemInfo.java @@ -1,16 +1,15 @@ package eu.univento.core.commands; -import java.util.List; - +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.Perms.Ranks; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import eu.univento.core.Core; -import eu.univento.core.api.AutoCommand; -import eu.univento.core.api.Messages; -import eu.univento.core.api.player.CustomPlayer; -import eu.univento.core.api.player.Perms.Ranks; +import java.util.List; /** * prints infos about the server @@ -33,22 +32,23 @@ public class SystemInfo extends AutoCommand{ public boolean execute(CommandSender sender, String label, String[] args) { if(sender instanceof Player) { CustomPlayer p = CustomPlayer.getPlayer(sender.getName()); - if(p.isAllowed(Ranks.Admin)) { + Messages msgs = new Messages(p); + if(p.isAllowed(Ranks.SrModerator)) { Runtime run = Runtime.getRuntime(); - p.sendMessage("§6§l===SystemInfo ==="); - p.sendMessage("§6Spigot Version: " + Bukkit.getVersion()); - p.sendMessage("§6Genutzter Arbeitsspeicher: " + (run.totalMemory() - run.freeMemory() / 1048576L) + " MB"); - p.sendMessage("§6Freier Arbeitsspeicher: " + run.freeMemory() / 1048576L + " MB"); - p.sendMessage("§6Gesamter Arbeitsspeicher: " + run.maxMemory() / 1048576L + " MB"); - p.sendMessage("§6Verfügbare Prozessoren: " + run.availableProcessors()); - p.sendMessage("§6Betriebssystem: " + System.getProperty("os.name")); - p.sendMessage("§6Betriebsystem Version: " + System.getProperty("os.version")); - p.sendMessage("§6Betriebssystem Architektur: " + System.getProperty("os.arch")); + p.sendMessage("§6§l===SystemInfo ==="); + p.sendMessage("§6Spigot version: " + Bukkit.getVersion()); + p.sendMessage("§6used memory: " + (run.totalMemory() - run.freeMemory() / 1048576L) + " MB"); + p.sendMessage("§6free memory: " + run.freeMemory() / 1048576L + " MB"); + p.sendMessage("§6total memory: " + run.maxMemory() / 1048576L + " MB"); + p.sendMessage("§6avaiable cores: " + run.availableProcessors()); + p.sendMessage("§6OS: " + System.getProperty("os.name")); + p.sendMessage("§6OS version: " + System.getProperty("os.version")); + p.sendMessage("§6OS architecture: " + System.getProperty("os.arch")); }else { - p.sendMessage(Messages.NO_PERMS); + p.sendMessage(msgs.NO_PERMS()); } }else { - sender.sendMessage(Messages.NOT_A_PLAYER); + sender.sendMessage(Messages.Console.NOT_A_PLAYER); } return false; } diff --git a/src/eu/univento/core/commands/TS.java b/src/eu/univento/core/commands/TS.java index ea528b0..930ec5e 100644 --- a/src/eu/univento/core/commands/TS.java +++ b/src/eu/univento/core/commands/TS.java @@ -1,15 +1,12 @@ package eu.univento.core.commands; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - import eu.univento.core.Core; import eu.univento.core.api.AutoCommand; -import eu.univento.core.api.Messages; import eu.univento.core.api.player.CustomPlayer; -import eu.univento.core.api.player.TeamSpeak; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; /** * sets ts groups according to player rank @@ -32,20 +29,8 @@ public class TS extends AutoCommand{ public boolean execute(CommandSender sender, String label, String[] args) { if(sender instanceof Player) { CustomPlayer p = CustomPlayer.getPlayer(sender.getName()); - if(p.getTSClientInfo() != null) { - for(int i = 0; i >= p.getTSClientInfo().getServerGroups().length; i++) { - int[] groups = p.getTSClientInfo().getServerGroups(); - if(groups[i] == TeamSpeak.getVerifiedId()) { - p.sendMessage(Messages.PREFIX + "§cDu hast schon einen verknüpften TS Account !"); - }else { - p.verifyTs(); - p.sendMessage(Messages.PREFIX + "§aDu bist nun verifiziert"); - } - } + p.verifyTs(); } - }else { - sender.sendMessage(Messages.NOT_A_PLAYER); - } return true; } diff --git a/src/eu/univento/core/commands/Twitch.java b/src/eu/univento/core/commands/Twitch.java index aff1f68..837f3bc 100644 --- a/src/eu/univento/core/commands/Twitch.java +++ b/src/eu/univento/core/commands/Twitch.java @@ -1,16 +1,15 @@ package eu.univento.core.commands; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - import eu.univento.core.Core; import eu.univento.core.api.AutoCommand; -import eu.univento.core.api.Messages; +import eu.univento.core.api.languages.Messages; import eu.univento.core.api.player.CustomPlayer; import eu.univento.core.api.twitch.Twitch_API; import eu.univento.core.api.twitch.Twitch_Stream; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; /** * send info about twitch streams @@ -33,26 +32,27 @@ public class Twitch extends AutoCommand{ 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(args.length == 1) { Twitch_Stream stream = Twitch_API.getStream(args[0]); if(stream != null) { - p.sendMessage("§a" + stream.getBroadcaster()); - p.sendMessage("§aBenutzername: " + stream.getUsername()); - p.sendMessage("§aSpiel: " + stream.getMeta_game()); - p.sendMessage("§aKategorie: " + stream.getCategory()); - p.sendMessage("§aTitel: " + stream.getTitle()); - p.sendMessage("§aStatus: " + stream.getStatus()); - p.sendMessage("§aZuschauer:" + stream.getChannel_view_count()); - p.sendMessage("§aSprachen: " + stream.getGeo()); - p.sendMessage("§aOnline seit: " + stream.getUp_time()); + p.sendMessage("§a" + stream.getBroadcaster()); + p.sendMessage("§aBenutzername: " + stream.getUsername()); + p.sendMessage("§aSpiel: " + stream.getMeta_game()); + p.sendMessage("§aKategorie: " + stream.getCategory()); + p.sendMessage("§aTitel: " + stream.getTitle()); + p.sendMessage("§aStatus: " + stream.getStatus()); + p.sendMessage("§aZuschauer:" + stream.getChannel_view_count()); + p.sendMessage("§aSprachen: " + stream.getGeo()); + p.sendMessage("§aOnline seit: " + stream.getUp_time()); }else { - p.sendMessage(Messages.PREFIX + "§aDen Benutzer gibt es nicht"); + p.sendMessage(msgs.PREFIX() + "§aDen Benutzer gibt es nicht"); } }else { - p.sendMessage(Messages.PREFIX + "§cNutze /twitch "); + p.sendMessage(msgs.PREFIX() + "§cNutze /twitch "); } }else { - sender.sendMessage(Messages.NOT_A_PLAYER); + sender.sendMessage(Messages.Console.NOT_A_PLAYER); } return true; } diff --git a/src/eu/univento/core/commands/Vanish.java b/src/eu/univento/core/commands/Vanish.java index 83c4c80..326563e 100644 --- a/src/eu/univento/core/commands/Vanish.java +++ b/src/eu/univento/core/commands/Vanish.java @@ -1,17 +1,16 @@ package eu.univento.core.commands; -import java.util.ArrayList; -import java.util.List; - +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.Perms.Ranks; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import eu.univento.core.Core; -import eu.univento.core.api.AutoCommand; -import eu.univento.core.api.Messages; -import eu.univento.core.api.player.CustomPlayer; -import eu.univento.core.api.player.Perms.Ranks; +import java.util.ArrayList; +import java.util.List; /** * vanish players @@ -45,25 +44,26 @@ public class Vanish extends AutoCommand{ 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(players.contains(p)) { for(Player players : Bukkit.getOnlinePlayers()) { players.showPlayer(p); } players.remove(p); - p.sendMessage(Messages.PREFIX + "§eDu bist nun wieder §csichtbar"); + p.sendMessage(msgs.PREFIX() + msgs.Core_VANISH_OFF()); }else { for(Player players : Bukkit.getOnlinePlayers()) { players.hidePlayer(p); } players.add(p); - p.sendMessage(Messages.PREFIX + "§eDu bist nun §aunsichtbar"); + p.sendMessage(msgs.PREFIX() + msgs.Core_VANISH_ON()); } }else { - p.sendMessage(Messages.NO_PERMS); + p.sendMessage(msgs.NO_PERMS()); } }else { - sender.sendMessage(Messages.NOT_A_PLAYER); + sender.sendMessage(Messages.Console.NOT_A_PLAYER); } return false; } diff --git a/src/eu/univento/core/commands/Youtuber.java b/src/eu/univento/core/commands/Youtuber.java index 0a89831..4cf47c9 100644 --- a/src/eu/univento/core/commands/Youtuber.java +++ b/src/eu/univento/core/commands/Youtuber.java @@ -1,16 +1,15 @@ package eu.univento.core.commands; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - import eu.univento.core.Core; import eu.univento.core.api.AutoCommand; -import eu.univento.core.api.Messages; +import eu.univento.core.api.languages.Messages; import eu.univento.core.api.player.CustomPlayer; import eu.univento.core.api.youtube.YTAPI; import eu.univento.core.api.youtube.YoutubeChannel; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; /** * sets player to youtube rank @@ -33,24 +32,25 @@ public class Youtuber extends AutoCommand{ 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(args.length == 1) { YoutubeChannel yt = YTAPI.getYTChannelFromName(args[0]); if(yt != null) { - p.sendMessage("§aBenutzername: " + yt.getUsername()); - p.sendMessage("§aGooglePlus ID: " + yt.getGoogleplusid()); - p.sendMessage("§aZuletzt online: " + yt.getLastwebaccess()); - p.sendMessage("§aVon: " + yt.getLocation()); - p.sendMessage("§aAbos: " + yt.getSubscribers()); - p.sendMessage("§aVideo Watch Count: " + yt.getVideoWatchCount()); - p.sendMessage("§aViewcount: " + yt.getViewcount()); + p.sendMessage("§aBenutzername: " + yt.getUsername()); + p.sendMessage("§aGooglePlus ID: " + yt.getGoogleplusid()); + p.sendMessage("§aZuletzt online: " + yt.getLastwebaccess()); + p.sendMessage("§aVon: " + yt.getLocation()); + p.sendMessage("§aAbos: " + yt.getSubscribers()); + p.sendMessage("§aVideo Watch Count: " + yt.getVideoWatchCount()); + p.sendMessage("§aViewcount: " + yt.getViewcount()); }else { - p.sendMessage(Messages.PREFIX + "§cDer Youtube Kanal exsistiert nicht"); + p.sendMessage(msgs.PREFIX() + "§cDer Youtube Kanal exsistiert nicht"); } }else { - p.sendMessage(Messages.PREFIX + "§cBenutze doch /youtuber "); + p.sendMessage(msgs.PREFIX() + "§cBenutze doch /youtuber "); } }else { - sender.sendMessage(Messages.NOT_A_PLAYER); + sender.sendMessage(Messages.Console.NOT_A_PLAYER); } return true; } diff --git a/src/eu/univento/core/listeners/Blocks.java b/src/eu/univento/core/listeners/Blocks.java index 49dc70a..aa59ea8 100644 --- a/src/eu/univento/core/listeners/Blocks.java +++ b/src/eu/univento/core/listeners/Blocks.java @@ -1,46 +1,53 @@ package eu.univento.core.listeners; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; - -import eu.univento.core.api.Settings; import eu.univento.core.api.player.CustomPlayer; import eu.univento.core.commands.Build; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockCanBuildEvent; +import org.bukkit.event.block.BlockPlaceEvent; /** - * cancels building + * some stuff with blocks * @author joethei * @version 1.0 */ public class Blocks implements Listener{ /** + * cancels block placement if player is not in build mode * @param e BlockPlaceEvent */ @EventHandler public void onBlockPlace(BlockPlaceEvent e) { - CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer().getName()); - if(Settings.isBuild()) { - if(!Build.getPlayers().contains(p)) { - e.setCancelled(true); - } + CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer()); + if(!Build.getPlayers().containsKey(p)) { + e.setCancelled(true); } } /** + * cancels block breaking if player is not in build mode * @param e BlockBreakEvent */ @EventHandler public void onBlockBreak(BlockBreakEvent e) { - CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer().getName()); - if(Settings.isBuild()) { - if(!Build.getPlayers().contains(p)) { - e.setCancelled(true); - } + CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer()); + if(!Build.getPlayers().containsKey(p)) { + e.setCancelled(true); } } + + /** + * sets buildable true so players can place blocks, even if vanished player is standing there + * @param e BlockCanBuildEvent + */ + @EventHandler(priority = EventPriority.LOW) + public void onBlockCanBuildEvent(BlockCanBuildEvent e){ + e.setBuildable(true); + } } \ No newline at end of file diff --git a/src/eu/univento/core/listeners/Chat.java b/src/eu/univento/core/listeners/Chat.java index 166ff4e..546811c 100644 --- a/src/eu/univento/core/listeners/Chat.java +++ b/src/eu/univento/core/listeners/Chat.java @@ -1,15 +1,14 @@ package eu.univento.core.listeners; +import eu.univento.core.api.languages.Messages; +import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.Perms.Ranks; +import eu.univento.core.api.server.ServerSettings; +import net.md_5.bungee.api.ChatColor; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; -import eu.univento.core.api.Messages; -import eu.univento.core.api.Settings; -import eu.univento.core.api.player.CustomPlayer; -import eu.univento.core.api.player.Perms.Ranks; -import net.md_5.bungee.api.ChatColor; - /** * manages chat * @author joethei @@ -23,23 +22,25 @@ public class Chat implements Listener{ @EventHandler public void onChat(AsyncPlayerChatEvent e) { CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer().getName()); - if(Settings.isMute()) { + Messages msgs = new Messages(p); + if(ServerSettings.isMute()) { if(!p.isAllowed(Ranks.Supporter)) { e.setCancelled(true); - p.sendMessage(Messages.PREFIX + "§cMomentan ist dieser Server gemutet"); + p.sendMessage(msgs.PREFIX() + msgs.Core_SERVER_MUTED()); } } - if(!p.isMuted()) { String format; - if(p.isAllowed(Ranks.Supporter)) { - format = p.getPrefix() + p.getDisplayName() + p.getSuffix() + ChatColor.translateAlternateColorCodes('&', e.getMessage()); + if(p.isAllowed(Ranks.Youtuber)) { + if(p.isNicked() && !ServerSettings.isLobby()) { + format = p.getPrefix() + p.getDisplayName() + p.getSuffix() + ChatColor.translateAlternateColorCodes('&', e.getMessage()); + }else { + format = p.getPrefix() + p.getDisplayName() + p.getSuffix() + ChatColor.translateAlternateColorCodes('&', e.getMessage()); + } }else { format = p.getPrefix() + p.getDisplayName() + p.getSuffix() + e.getMessage(); } e.setFormat(format); - }else { - p.sendMessage(Messages.PREFIX + "§cDu wurdest leider vom Chat ausgeschlossen"); - } + } } \ No newline at end of file diff --git a/src/eu/univento/core/listeners/Commands.java b/src/eu/univento/core/listeners/Commands.java index 5e31232..44b7486 100644 --- a/src/eu/univento/core/listeners/Commands.java +++ b/src/eu/univento/core/listeners/Commands.java @@ -1,5 +1,9 @@ package eu.univento.core.listeners; +import eu.univento.core.Core; +import eu.univento.core.api.languages.Messages; +import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.Perms.Ranks; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -8,11 +12,6 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.help.HelpTopic; -import eu.univento.core.Core; -import eu.univento.core.api.Messages; -import eu.univento.core.api.player.CustomPlayer; -import eu.univento.core.api.player.Perms.Ranks; - /** * commands * @author joethei @@ -25,47 +24,38 @@ public class Commands implements Listener{ * prints unknown command message * @param e PlayerCommandPreprocessEvent */ - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerPreprocess(PlayerCommandPreprocessEvent e) { - if(!(e.isCancelled())) { - CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer().getName()); - String cmd = e.getMessage().split(" ")[0]; - HelpTopic topic = Bukkit.getServer().getHelpMap().getHelpTopic(cmd); - if(topic == null) { - String msg = Messages.COMMAND_NOT_FOUND; - p.sendMessage(msg); - e.setCancelled(true); - } - } - } - - /** - * custom reload - * @param e PlayerPreprocessEvent - */ - @EventHandler - public void onReload(PlayerCommandPreprocessEvent e) { - CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer().getName()); - String cmd = e.getMessage(); + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent e) { + CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer()); + Messages msgs = new Messages(p); + if (!e.isCancelled()) { + String cmd = e.getMessage().split(" ")[0]; + HelpTopic topic = Bukkit.getServer().getHelpMap().getHelpTopic(cmd); + if (topic == null) { + p.sendMessage(msgs.COMMAND_NOT_FOUND()); + e.setCancelled(true); + } + } + String cmd = e.getMessage(); if(cmd.equalsIgnoreCase("/rl") || cmd.equalsIgnoreCase("/reload")) { if(p.isAllowed(Ranks.Admin)) { e.setCancelled(true); - Bukkit.broadcastMessage(Messages.PREFIX + "§cAchtung der Server wird gleich neu geladen"); + Bukkit.broadcastMessage(msgs.PREFIX() + "§cWarning ! Server will be restarted"); Bukkit.getScheduler().scheduleSyncDelayedTask(Core.getInstance(), new Runnable() { @Override public void run() { for(Player players : Bukkit.getOnlinePlayers()) { - players.kickPlayer("§cServer wurde neu geladen \n §6Bitte joine doch neu unter \n §bplay§5.§6univento§5.§aeu"); + players.kickPlayer("§cServer has been restarted \n §6Please join again at: \n §bplay§5.§6univento§5.§aeu"); } - Bukkit.reload(); + Bukkit.getServer().spigot().restart(); } - + }, 100L); }else { - p.sendMessage(Messages.NO_PERMS); + p.sendMessage(msgs.NO_PERMS()); } } - } + } } \ No newline at end of file diff --git a/src/eu/univento/core/listeners/JoinQuit.java b/src/eu/univento/core/listeners/JoinQuit.java index 76546df..464c417 100644 --- a/src/eu/univento/core/listeners/JoinQuit.java +++ b/src/eu/univento/core/listeners/JoinQuit.java @@ -1,28 +1,36 @@ package eu.univento.core.listeners; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.Date; - +import eu.univento.core.Core; +import eu.univento.core.api.Title; +import eu.univento.core.api.Utils; +import eu.univento.core.api.database.MySQL; +import eu.univento.core.api.languages.Messages; +import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.NickName; +import eu.univento.core.api.player.Perms; +import eu.univento.core.api.player.Spectator; +import eu.univento.core.api.server.ServerSettings; +import eu.univento.core.commands.Build; +import eu.univento.core.commands.Vanish; import org.bukkit.Bukkit; +import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; 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.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; -import eu.univento.core.Core; -import eu.univento.core.api.Messages; -import eu.univento.core.api.MySQL; -import eu.univento.core.api.Utils; -import eu.univento.core.api.player.CustomPlayer; -import eu.univento.core.api.player.NickName; -import eu.univento.core.api.player.Perms; -import eu.univento.core.api.player.Perms.Ranks; -import eu.univento.core.commands.Vanish; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.Date; /** * @author joethei @@ -34,106 +42,153 @@ public class JoinQuit implements Listener{ * Handles JoinMessage and vanished players * @param e event */ - @SuppressWarnings("deprecation") @EventHandler public void onJoin(PlayerJoinEvent e) { - CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer().getName()); + CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer()); + Messages msgs = new Messages(p); + + p.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); + + for(Player players : Bukkit.getOnlinePlayers()) { + CustomPlayer player = CustomPlayer.getPlayer(players); + if(Vanish.getPlayers().contains(player)) { + p.hidePlayer(player); + } + if(Spectator.is(player)) { + p.hidePlayer(player); + } + } + if(p.isNicked()) { + p.setDisplayName(p.getNick()); + } + + if(!p.isSetting("joined")) { + p.changeSetting("joined"); + } if(!p.hasPlayedBefore()) { createPlayer(p); - p.sendMessage(Messages.PREFIX + "§aHerzlich willkommen auf univento.eu"); - p.sendMessage(Messages.PREFIX + "§6Dem Netzwerk mit Style"); + Perms.getRanks().put(p, p.getFreshRank()); for(int i = 0; i >= 15; i++) { - Utils.randomFireworks(p.getEyeLocation()); + Utils.randomFirework(p.getEyeLocation()); } + Title.sendTitle(p, 0, 100, 0, "§6Welcome", "§aPlease choose a language"); + Bukkit.getScheduler().scheduleSyncDelayedTask(Core.getInstance(), () -> p.openInventory(getLanguageChooser(p)), 140L); } - - e.setJoinMessage(null); - Perms.getRanks().put(p, p.getRankFresh()); - p.getTeam().addPlayer(p); - p.setScoreboard(Bukkit.getScoreboardManager().getMainScoreboard()); - try { - setup(p, p.getRank()); - } catch (SQLException e1) { - e1.printStackTrace(); - } - for(Player players : Bukkit.getOnlinePlayers()) { - if(Vanish.getPlayers().contains(players)) { - p.hidePlayer(players); - } - } - if(p.isNicked()) { - p.setDisplayName(p.getNick()); - } + Perms.getRanks().put(p, p.getFreshRank()); + Perms.initScoreboard(p); + Title.sendTabTitle(p, msgs.Core_TAB_TITLE() + Bukkit.getServerName() , msgs.PREFIX()); + p.setGameMode(ServerSettings.getGameMode()); + p.checkVerifiedTs(); + + + + for(Player players : Bukkit.getOnlinePlayers()) { + CustomPlayer player = CustomPlayer.getPlayer(players); + p.getScoreboard().getTeam(player.getTeam().getName()).addEntry(player.getDisplayName()); + player.getScoreboard().getTeam(p.getTeam().getName()).addEntry(p.getDisplayName()); + } } + + @EventHandler + public void onLogin(PlayerLoginEvent e) { + CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer()); + //Core.log(Level.INFO, "PlayerLogin " + p.getName() + " | " + p.isBanned()); + //if(p.isBanned()) { + // e.disallow(PlayerLoginEvent.Result.KICK_BANNED, "§cYou have been banned. §6Reason: " + p.getBanReason() + "\nUntil: " + p.getBanTime()); + //} + } + + /** * Handles QuitMessage and other needed stuff * @param e event */ - @SuppressWarnings("deprecation") @EventHandler public void onQuit(PlayerQuitEvent e) { - CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer().getName()); + CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer()); NickName.remove(p); + if(Build.getPlayers().containsKey(p)) + Build.getPlayers().remove(p); + if(!ServerSettings.isGame()) + p.getTeam().removeEntry(p.getDisplayName()); + if(ServerSettings.isGame()) + p.setNicked(false); Perms.getRanks().remove(p); - p.getTeam().removePlayer(p); p.onLeave(); - e.setQuitMessage(null); } /** * creates player in database * @param p CustomPlayer */ - private static void createPlayer(CustomPlayer p) { + void createPlayer(CustomPlayer p) { + MySQL sql = Core.returnSQL(); Date date = new Date(); Timestamp time = new Timestamp(date.getTime()); String uuid = p.getUniqueId().toString(); try { - MySQL sql = Core.returnSQL(); sql.openConnection(); - ResultSet res = Core.returnSQL().getConnection().createStatement().executeQuery("SELECT player_uuid FROM PlayerData WHERE player_uuid ='" + uuid + "';"); - if (!res.next()) - Core.returnSQL().getConnection().createStatement().execute("INSERT INTO PlayerData (player_uuid, FirstJoin, Coins, mute, Rank, nick, FastMenu, teleport) VALUES ('" + uuid + "','" + time + "', '0', '0', '" + Perms.Ranks.Spieler.toString() + "', '0', '0', '1');"); - sql.closeConnection(); + PreparedStatement st = sql.getConnection().prepareStatement("SELECT UUID FROM users WHERE UUID ='" + uuid + "'"); + ResultSet res = st.executeQuery(); + if (!res.next()){ + PreparedStatement st2 = sql.getConnection().prepareStatement("INSERT INTO users (UUID, FirstJoin, Rank, Coins) VALUES ('" + uuid + "','" + time + "', '" + Perms.Ranks.Player.toString() + "', 0);"); + st2.execute(); + + int id = p.getID(); + + PreparedStatement st3 = sql.getConnection().prepareStatement("INSERT INTO PlayerSettings (ID, teleport, FastMenu, requestsParty, requestsFriend, joined, nick) VALUES ('" + id +"', '1', '0', '1', '1', '0', '0',);"); + st3.execute(); + + PreparedStatement st4 = sql.getConnection().prepareStatement("INSERT INTO FoundItems(ID, music_3, sugar, feather, hearts) VALUES ('" + id + "',0, 0, 0, 0);"); + st4.execute(); + + sql.closeConnection(); + return; + } + sql.closeConnection(); } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); } } - /** - * sets up the player - * @param p CustomPlayer - * @param r Ranks - * @throws SQLException Database not available - */ - private void setup(CustomPlayer p, Ranks r) throws SQLException { - if (p.isNicked()) { - Core.nicks.put(p, NickName.getNicks()); - setName(p, Core.nicks.get(p)); - } else { - setName(p, p.getName()); - } - } - /** - * sets DisplayName of Player - * @param p CustomPlayer - * @param name name to set - */ - private void setName(CustomPlayer p, String name) { - p.setDisplayName(name); - p.setPlayerListName(p.getColor() + name); - } /** * Handles KickMessage * @param e event */ @EventHandler(priority=EventPriority.HIGHEST) public void onKick(PlayerKickEvent e) { + CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer()); e.setLeaveMessage(null); - NickName.remove(e.getPlayer()); + p.setNicked(false); } + + public static Inventory getLanguageChooser(CustomPlayer p) { + Inventory inv = Bukkit.createInventory(p, 9, "§6Language Chooser"); + + ItemStack en = new ItemStack(Material.PAPER); + ItemMeta enMeta = en.getItemMeta(); + enMeta.setDisplayName("§6English"); + en.setItemMeta(enMeta); + + ItemStack de = new ItemStack(Material.PAPER); + ItemMeta deMeta = de.getItemMeta(); + deMeta.setDisplayName("§6Deutsch"); + de.setItemMeta(deMeta); + + + ItemStack it = new ItemStack(Material.PAPER); + ItemMeta itMeta = it.getItemMeta(); + itMeta.setDisplayName("§6Italienisch"); + it.setItemMeta(itMeta); + + inv.setItem(0, en); + inv.setItem(1, de); + inv.setItem(2, it); + + return inv; + } } \ No newline at end of file diff --git a/src/plugin.yml b/src/plugin.yml index a72a69e..60024ca 100644 --- a/src/plugin.yml +++ b/src/plugin.yml @@ -2,5 +2,5 @@ main: eu.univento.core.Core name: Core description: univento Core author: joethei -version: 0.5 +version: 0.6 website: http://univento.eu \ No newline at end of file