From f6854fc14670461b2c0de3476b608e7820a89e8a Mon Sep 17 00:00:00 2001 From: Georg Hagen Date: Sat, 2 Aug 2014 18:06:45 +0200 Subject: [PATCH] First Upload V1.0 --- Lang/de.yml | 20 ++ Lang/en.yml | 20 ++ plugin.yml | 60 ++++ .../georgh/MinePacks/Backpack.java | 184 +++++++++++ .../georgh/MinePacks/Database/Config.java | 199 ++++++++++++ .../georgh/MinePacks/Database/Database.java | 90 ++++++ .../georgh/MinePacks/Database/Language.java | 121 ++++++++ .../georgh/MinePacks/Database/MySQL.java | 286 ++++++++++++++++++ .../georgh/MinePacks/Database/SQLite.java | 280 +++++++++++++++++ .../MinePacks/Database/UUIDConverter.java | 138 +++++++++ .../georgh/MinePacks/EventListener.java | 119 ++++++++ .../georgh/MinePacks/MinePacks.java | 109 +++++++ .../georgh/MinePacks/OnCommand.java | 154 ++++++++++ 13 files changed, 1780 insertions(+) create mode 100644 Lang/de.yml create mode 100644 Lang/en.yml create mode 100644 plugin.yml create mode 100644 src/at/pcgamingfreaks/georgh/MinePacks/Backpack.java create mode 100644 src/at/pcgamingfreaks/georgh/MinePacks/Database/Config.java create mode 100644 src/at/pcgamingfreaks/georgh/MinePacks/Database/Database.java create mode 100644 src/at/pcgamingfreaks/georgh/MinePacks/Database/Language.java create mode 100644 src/at/pcgamingfreaks/georgh/MinePacks/Database/MySQL.java create mode 100644 src/at/pcgamingfreaks/georgh/MinePacks/Database/SQLite.java create mode 100644 src/at/pcgamingfreaks/georgh/MinePacks/Database/UUIDConverter.java create mode 100644 src/at/pcgamingfreaks/georgh/MinePacks/EventListener.java create mode 100644 src/at/pcgamingfreaks/georgh/MinePacks/MinePacks.java create mode 100644 src/at/pcgamingfreaks/georgh/MinePacks/OnCommand.java diff --git a/Lang/de.yml b/Lang/de.yml new file mode 100644 index 0000000..67550fe --- /dev/null +++ b/Lang/de.yml @@ -0,0 +1,20 @@ +Version: 1 +Language: + Console: + Enabled: MinePacks wurde aktiviert! + Disabled: MinePacks wurde deaktiviert. + NotFromConsole: Befehlt nicht von der Console aus verwendbar. + LangUpdated: Sprachdatei wurde aktualisiert. + UpdateUUIDs: Starte Datenbank Update auf UUIDs ... + UpdatedUUIDs: '%s Datensätze wurden auf UUIDs geupdated.' + Ingame: + NoPermission: 'Dir fehlen die Rechte dafür.' + OwnBackPackClose: 'Rucksack geschlossen!' + PlayerBackPackClose: "%s's Rucksack geschlossen!" + IvalidBackpack: Rucksack fehlerhaft. + BackpackCleaned: Rucksack gelehrt. + Description: + Backpack: Öffnet deinen Rucksack. + Clean: Leert deinen Rucksack. + CleanOther: Leert den Rucksack von Spielern. + View: Zeigt den Rucksack von anderen Spielern. \ No newline at end of file diff --git a/Lang/en.yml b/Lang/en.yml new file mode 100644 index 0000000..c616c98 --- /dev/null +++ b/Lang/en.yml @@ -0,0 +1,20 @@ +Version: 1 +Language: + Console: + Enabled: MinePacks has been enabled! + Disabled: MinePacks has been disabled. + NotFromConsole: Command not useable from console. + LangUpdated: Language File has been updated. + UpdateUUIDs: Start updating database to UUIDs ... + UpdatedUUIDs: 'Updated %s accounts to UUIDs.' + Ingame: + NoPermission: You don't have the Permission to do that. + OwnBackPackClose: 'Backpack closed!' + PlayerBackPackClose: "%s's backpack closed!" + IvalidBackpack: Invalid backpack. + BackpackCleaned: Backpack cleaned. + Description: + Backpack: Opens your backpack. + Clean: Cleans your backpack. + CleanOther: Cleans the backpack of other players. + View: Shows the backpack of other player. \ No newline at end of file diff --git a/plugin.yml b/plugin.yml new file mode 100644 index 0000000..e335a2a --- /dev/null +++ b/plugin.yml @@ -0,0 +1,60 @@ +name: MinePacks +author: GeorgH93 +website: http://dev.bukkit.org/bukkit-plugins/minepacks/ +main: at.pcgamingfreaks.georgh.MinePacks.MinePacks +version: 1.0 +commands: + backpack: + description: Main command + usage: /backpack +permissions: + backpack.*: + description: Gives acces to the full MinePacks functionality + children: + backpack: true + backpack.size.6: true + backpack.others: true + backpack.others.edit: true + backpack.KeepOnDeath: true + backpack.clean: true + backpack.clean.other: true + backpack: + description: Allows to open the backback + default: false + backpack.size.1: + description: Mini size for a backpack, if player has backpack permission he will also have at least a backpack with the size 1 + default: false + backpack.size.2: + description: 2*9 backpack + default: false + backpack.size.3: + description: 3*9 backpack + default: false + backpack.size.4: + description: 4*9 backpack + default: false + backpack.size.5: + description: 5*9 backpack + default: false + backpack.size.6: + description: 6*9 backpack + default: false + backpack.clean: + description: Allows to clean the own backpack. + default: false + backpack.clean.other: + description: Allows to clean the others backpacks. + default: op + children: + backpack.clean: true + backpack.others: + description: Allows to open backpacks of other players + default: op + backpack.others.edit: + description: Allows to edit backpacks of other players + default: op + children: + backpack.others: true + backpack.KeepOnDeath: + description: Allows to keeps the items in backpack on death + defautl: op \ No newline at end of file diff --git a/src/at/pcgamingfreaks/georgh/MinePacks/Backpack.java b/src/at/pcgamingfreaks/georgh/MinePacks/Backpack.java new file mode 100644 index 0000000..aa23145 --- /dev/null +++ b/src/at/pcgamingfreaks/georgh/MinePacks/Backpack.java @@ -0,0 +1,184 @@ +/* + * Copyright (C) 2014 GeorgH93 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package at.pcgamingfreaks.georgh.MinePacks; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map.Entry; + +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +public class Backpack +{ + private OfflinePlayer owner; + private HashMap opend = new HashMap(); + private Inventory bp; + private int size, id; + private String title; + private boolean inwork; + + public Backpack(OfflinePlayer Owner) + { + owner = Owner; + size = 9; + id = -1; + title = String.format(MinePacks.BackpackTitle, Owner.getName()); + bp = Bukkit.createInventory(null, size, title); + inwork = false; + } + + public Backpack(OfflinePlayer Owner, int Size) + { + owner = Owner; + title = String.format(MinePacks.BackpackTitle, Owner.getName()); + bp = Bukkit.createInventory(null, Size, title); + size = Size; + id = -1; + inwork = false; + } + + public Backpack(OfflinePlayer Owner, ItemStack[] backpack, int ID) + { + owner = Owner; + size = backpack.length; + title = String.format(MinePacks.BackpackTitle, Owner.getName()); + bp = Bukkit.createInventory(null, size, title); + bp.setContents(backpack); + id = ID; + inwork = false; + } + + public int getID() + { + return id; + } + + public void setID(int ID) + { + id = ID; + } + + public OfflinePlayer getOwner() + { + return owner; + } + + public void Open(Player p, boolean editable) + { + opend.put(p, editable); + p.openInventory(bp); + } + + public void Close(Player p) + { + opend.remove(p); + } + + public boolean isOpen() + { + if(opend.isEmpty()) + { + return false; + } + else + { + return true; + } + } + + public boolean canEdit(Player p) + { + if(opend.containsKey(p)) + { + return opend.get(p); + } + return false; + } + + public boolean inUse() + { + return inwork; + } + + public int getSize() + { + return size; + } + + public List setSize(int newSize) + { + inwork = true; + for(Entry e : opend.entrySet()) + { + e.getKey().closeInventory(); + } + List RemovedItems = new ArrayList(); + ItemStack[] itsa; + if(bp.getSize() > newSize) + { + int count = 0; + itsa = new ItemStack[newSize]; + for(ItemStack i : bp.getContents()) + { + if(i != null) + { + if(count < newSize) + { + itsa[count] = i; + count++; + } + else + { + RemovedItems.add(i); + } + } + } + } + else + { + itsa = bp.getContents(); + } + bp = Bukkit.createInventory(null, newSize, title); + for(int i = 0; i < itsa.length; i++) + { + bp.setItem(i, itsa[0]); + } + size = newSize; + for(Entry e : opend.entrySet()) + { + e.getKey().openInventory(bp); + } + inwork = false; + return RemovedItems; + } + + public Inventory getBackpack() + { + return bp; + } + + public String getTitle() + { + return title; + } +} \ No newline at end of file diff --git a/src/at/pcgamingfreaks/georgh/MinePacks/Database/Config.java b/src/at/pcgamingfreaks/georgh/MinePacks/Database/Config.java new file mode 100644 index 0000000..7f53861 --- /dev/null +++ b/src/at/pcgamingfreaks/georgh/MinePacks/Database/Config.java @@ -0,0 +1,199 @@ +/* + * Copyright (C) 2014 GeorgH93 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package at.pcgamingfreaks.georgh.MinePacks.Database; + +import java.io.File; +import java.io.IOException; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import at.pcgamingfreaks.georgh.MinePacks.MinePacks; + +public class Config +{ + private MinePacks MP; + private FileConfiguration config; + private static final int CONFIG_VERSION = 1; + + public Config(MinePacks mp) + { + MP = mp; + LoadConfig(); + } + + public void Reload() + { + LoadConfig(); + } + + private void LoadConfig() + { + File file = new File(MP.getDataFolder(), "config.yml"); + if(!file.exists()) + { + NewConfig(file); + } + else + { + config = YamlConfiguration.loadConfiguration(file); + UpdateConfig(file); + } + } + + private boolean UUIDComp() + { + try + { + String[] GameVersion = Bukkit.getBukkitVersion().split("-"); + GameVersion = GameVersion[0].split("\\."); + if(Integer.parseInt(GameVersion[1]) > 7 || (Integer.parseInt(GameVersion[1]) == 7 && Integer.parseInt(GameVersion[2]) > 5)) + { + return true; + } + else + { + return false; + } + } + catch(Exception e) + { + return false; + } + } + + private void NewConfig(File file) + { + config = new YamlConfiguration(); + config.set("BackpackTitle", ChatColor.AQUA + "%s Backpack"); + config.set("drop_on_death", true); + config.set("Language","en"); + config.set("LanguageUpdateMode","Overwrite"); + config.set("UseUUIDs", Bukkit.getServer().getOnlineMode() && UUIDComp()); + config.set("Database.Type","sqlite"); + config.set("Database.UpdatePlayer", true); + config.set("Database.MySQL.Host", "localhost:3306"); + config.set("Database.MySQL.Database", "minecraft"); + config.set("Database.MySQL.User", "minecraft"); + config.set("Database.MySQL.Password", "minecraft"); + config.set("Database.Tables.User", "backpack_players"); + config.set("Database.Tables.Backpack", "backpacks"); + config.set("Version",CONFIG_VERSION); + + try + { + config.save(file); + MP.log.info("Config File has been generated."); + } + catch (IOException e) + { + e.printStackTrace(); + } + } + + private boolean UpdateConfig(File file) + { + switch(config.getInt("Version")) + { + case 0: + break; + case CONFIG_VERSION: return false; + default: MP.log.info("Config File Version newer than expected!"); return false; + } + config.set("Version", CONFIG_VERSION); + try + { + config.save(file); + MP.log.info("Config File has been updated."); + } + catch (IOException e) + { + e.printStackTrace(); + return false; + } + return true; + } + + public String GetLanguage() + { + return config.getString("Language"); + } + + public String GetLanguageUpdateMode() + { + return config.getString("LanguageUpdateMode"); + } + + public String GetDatabaseType() + { + return config.getString("Database.Type"); + } + + public String GetMySQLHost() + { + return config.getString("Database.MySQL.Host"); + } + + public String GetMySQLDatabase() + { + return config.getString("Database.MySQL.Database"); + } + + public String GetMySQLUser() + { + return config.getString("Database.MySQL.User"); + } + + public String GetMySQLPassword() + { + return config.getString("Database.MySQL.Password"); + } + + public String getUserTable() + { + return config.getString("Database.Tables.User", "backpack_players"); + } + + public String getBackpackTable() + { + return config.getString("Database.Tables.Backpack", "backpacks"); + } + + public boolean getUpdatePlayer() + { + return config.getBoolean("Database.UpdatePlayer", true); + } + + public boolean UseUUIDs() + { + return config.getBoolean("UseUUIDs"); + } + + public String getBPTitle() + { + String BPTitle = config.getString("BackpackTitle", "%s Backpack"); + return BPTitle; + } + + public boolean getDropOnDeath() + { + return config.getBoolean("drop_on_death", true); + } +} \ No newline at end of file diff --git a/src/at/pcgamingfreaks/georgh/MinePacks/Database/Database.java b/src/at/pcgamingfreaks/georgh/MinePacks/Database/Database.java new file mode 100644 index 0000000..980554f --- /dev/null +++ b/src/at/pcgamingfreaks/georgh/MinePacks/Database/Database.java @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2014 GeorgH93 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package at.pcgamingfreaks.georgh.MinePacks.Database; + +import java.util.HashSet; + +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; + +import at.pcgamingfreaks.georgh.MinePacks.Backpack; +import at.pcgamingfreaks.georgh.MinePacks.MinePacks; + +public class Database +{ + protected MinePacks plugin; + + public HashSet backpacks = new HashSet(); + + public Database(MinePacks mp) + { + plugin = mp; + } + + private Backpack findBackpack(OfflinePlayer player) + { + for(Backpack bp : backpacks) + { + if(bp.getOwner().equals(player)) + { + return bp; + } + } + return null; + } + + public Backpack getBackpack(String title) + { + for(Backpack bp : backpacks) + { + if(bp.getTitle().equals(title)) + { + return bp; + } + } + return null; + } + + public Backpack getBackpack(OfflinePlayer player) + { + Backpack lbp = findBackpack(player); + if(lbp == null) + { + lbp = LoadBackpack(player); + if(lbp == null) + { + lbp = new Backpack(player); + } + backpacks.add(lbp); + } + return lbp; + } + + public void UnloadBackpack(Backpack backpack) + { + backpacks.remove(backpack); + } + + // DB Functions + + public void UpdatePlayer(Player player) {} + + public void SaveBackpack(Backpack backpack) {} + + public Backpack LoadBackpack(OfflinePlayer player) { return null; } +} \ No newline at end of file diff --git a/src/at/pcgamingfreaks/georgh/MinePacks/Database/Language.java b/src/at/pcgamingfreaks/georgh/MinePacks/Database/Language.java new file mode 100644 index 0000000..7562d06 --- /dev/null +++ b/src/at/pcgamingfreaks/georgh/MinePacks/Database/Language.java @@ -0,0 +1,121 @@ +/* + * Copyright (C) 2014 GeorgH93 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package at.pcgamingfreaks.georgh.MinePacks.Database; + +import java.io.File; +import java.io.IOException; + +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import com.google.common.io.Files; + +import at.pcgamingfreaks.georgh.MinePacks.MinePacks; + +public class Language +{ + private MinePacks MP; + private FileConfiguration lang; + private static final int LANG_VERSION = 1; + + public Language(MinePacks mp) + { + MP = mp; + LoadFile(); + } + + public String Get(String Option) + { + return lang.getString("Language." + Option, "§cMessage not found!"); + } + + public void Reload() + { + LoadFile(); + } + + private void LoadFile() + { + File file = new File(MP.getDataFolder() + File.separator + "Lang", MP.config.GetLanguage()+".yml"); + if(!file.exists()) + { + ExtractLangFile(file); + } + lang = YamlConfiguration.loadConfiguration(file); + UpdateLangFile(file); + } + + private void ExtractLangFile(File Target) + { + try + { + MP.saveResource("Lang" + File.separator + MP.config.GetLanguage() + ".yml", true); + } + catch(Exception ex) + { + try + { + File file_en = new File(MP.getDataFolder() + File.separator + "Lang", "en.yml"); + if(!file_en.exists()) + { + MP.saveResource("Lang" + File.separator + "en.yml", true); + } + Files.copy(file_en, Target); + } + catch (IOException e) + { + e.printStackTrace(); + } + } + } + + private boolean UpdateLangFile(File file) + { + if(lang.getInt("Version") != LANG_VERSION) + { + if(MP.config.GetLanguageUpdateMode().equalsIgnoreCase("overwrite")) + { + ExtractLangFile(file); + LoadFile(); + MP.log.info(Get("Console.LangUpdated")); + return true; + } + else + { + switch(lang.getInt("Version")) + { + case 0: + break; + default: MP.log.warning("Language File Version newer than expected!"); return false; + } + lang.set("Version", LANG_VERSION); + try + { + lang.save(file); + MP.log.info(Get("Console.LangUpdated")); + } + catch (IOException e) + { + e.printStackTrace(); + } + return true; + } + } + return false; + } +} diff --git a/src/at/pcgamingfreaks/georgh/MinePacks/Database/MySQL.java b/src/at/pcgamingfreaks/georgh/MinePacks/Database/MySQL.java new file mode 100644 index 0000000..68edcc8 --- /dev/null +++ b/src/at/pcgamingfreaks/georgh/MinePacks/Database/MySQL.java @@ -0,0 +1,286 @@ +/* + * Copyright (C) 2014 GeorgH93 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package at.pcgamingfreaks.georgh.MinePacks.Database; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.io.BukkitObjectInputStream; +import org.bukkit.util.io.BukkitObjectOutputStream; + +import at.pcgamingfreaks.georgh.MinePacks.Backpack; +import at.pcgamingfreaks.georgh.MinePacks.MinePacks; + +public class MySQL extends Database +{ + private Connection conn = null; + + private String Table_Players, Table_Backpacks; // Table Names + + private boolean UpdatePlayer; + + public MySQL(MinePacks mp) + { + super(mp); + // Load Settings + Table_Players = plugin.config.getUserTable(); + Table_Backpacks = plugin.config.getBackpackTable(); + UpdatePlayer = plugin.config.getUpdatePlayer(); + + CheckDB(); // Check Database + if(plugin.config.UseUUIDs()) + { + CheckUUIDs(); // Check if there are user accounts without UUID + } + } + + private void CheckUUIDs() + { + try + { + List converter = new ArrayList(); + Statement stmt = GetConnection().createStatement(); + ResultSet res = stmt.executeQuery("SELECT `name` FROM `" + Table_Players + "` WHERE `uuid` IS NULL"); + while(res.next()) + { + if(res.isFirst()) + { + plugin.log.info(plugin.lang.Get("Console.UpdateUUIDs")); + } + converter.add("UPDATE `" + Table_Players + "` SET `uuid`='" + UUIDConverter.getUUIDFromName(res.getString(1)) + "' WHERE `name`='" + res.getString(1).replace("\\", "\\\\").replace("'", "\\'") + "'"); + } + if(converter.size() > 0) + { + for (String string : converter) + { + stmt.execute(string); + } + plugin.log.info(String.format(plugin.lang.Get("Console.UpdatedUUIDs"),converter.size())); + } + } + catch (SQLException e) + { + e.printStackTrace(); + } + } + + private Connection GetConnection() + { + try + { + if(conn == null || conn.isClosed()) + { + conn = DriverManager.getConnection("jdbc:mysql://" + plugin.config.GetMySQLHost() + "/" + plugin.config.GetMySQLDatabase(), plugin.config.GetMySQLUser(), plugin.config.GetMySQLPassword()); + } + } + catch (SQLException e) + { + e.printStackTrace(); + } + return conn; + } + + private void CheckDB() + { + try + { + Statement stmt = GetConnection().createStatement(); + stmt.execute("CREATE TABLE IF NOT EXISTS `" + Table_Players + "` (`player_id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `name` CHAR(16) NOT NULL UNIQUE, PRIMARY KEY (`player_id`));"); + if(plugin.config.UseUUIDs()) + { + try + { + stmt.execute("ALTER TABLE `" + Table_Players + "` ADD COLUMN `uuid` CHAR(32) UNIQUE;"); + } + catch(SQLException e) + { + if(e.getErrorCode() != 1060) + { + e.printStackTrace(); + } + } + } + stmt.execute("CREATE TABLE IF NOT EXISTS `" + Table_Backpacks + "` (`owner` INT UNSIGNED NOT NULL, `itemstacks` BLOB, PRIMARY KEY (`owner`));"); + stmt.close(); + } + catch (SQLException e) + { + e.printStackTrace(); + } + } + + // Plugin Functions + public void UpdatePlayer(final Player player) + { + if(!UpdatePlayer) + { + return; + } + plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() + { + @Override + public void run() + { + try + { + PreparedStatement ps; + Connection con = DriverManager.getConnection("jdbc:mysql://" + plugin.config.GetMySQLHost() + "/" + plugin.config.GetMySQLDatabase(), plugin.config.GetMySQLUser(), plugin.config.GetMySQLPassword());; + ps = con.prepareStatement("SELECT `player_id` FROM `" + Table_Players + "` WHERE " + ((plugin.UseUUIDs) ? "`uuid`=?;" : "`name`=?;")); + if(plugin.UseUUIDs) + { + ps.setString(1, player.getUniqueId().toString().replace("-", "")); + } + else + { + ps.setString(1, player.getName()); + } + ResultSet rs = ps.executeQuery(); + if(rs.next()) + { + rs.close(); + ps.close(); + if(!plugin.UseUUIDs) + { + con.close(); + return; + } + ps = con.prepareStatement("UPDATE `" + Table_Players + "` SET `name`=? WHERE `uuid`=?;"); + ps.setString(1, player.getName()); + ps.setString(2, player.getUniqueId().toString().replace("-", "")); + } + else + { + rs.close(); + ps.close(); + ps = con.prepareStatement("INSERT INTO `" + Table_Players + "` (`name`" + ((plugin.UseUUIDs) ? ",`uuid`" : "") + ") VALUES (?" + ((plugin.UseUUIDs) ? ",?" : "") + ");"); + ps.setString(1, player.getName()); + if(plugin.UseUUIDs) + { + ps.setString(2, player.getUniqueId().toString().replace("-", "")); + } + } + ps.execute(); + ps.close(); + con.close(); + } + catch (SQLException e) + { + plugin.log.info("Failed to add user: " + player.getName()); + e.printStackTrace(); + } + }}); + } + + public void SaveBackpack(Backpack backpack) + { + try + { + // Serialising the backpack + ByteArrayOutputStream b = new ByteArrayOutputStream(); + BukkitObjectOutputStream output = new BukkitObjectOutputStream(b); + output.writeObject(backpack.getBackpack().getContents()); + PreparedStatement ps = null; // Statement Variable + // Building the mysql statement + if(backpack.getID() <= 0) + { + ps = GetConnection().prepareStatement("SELECT `player_id` FROM `" + Table_Players + "` WHERE " + ((plugin.UseUUIDs) ? "`uuid`" : "`name`")+ "=?;"); + if(plugin.UseUUIDs) + { + ps.setString(1, backpack.getOwner().getUniqueId().toString().replace("-", "")); + } + else + { + ps.setString(1, backpack.getOwner().getName()); + } + ResultSet rs = ps.executeQuery(); + if(rs.next()) + { + backpack.setID(rs.getInt(1)); + } + else + { + plugin.log.warning("Faild saving backpack for: " + backpack.getOwner().getName()); + return; + } + rs.close(); + ps.close(); + ps = GetConnection().prepareStatement("INSERT INTO `" + Table_Backpacks + "` (`owner`, `itemstacks`) VALUES (?,?);"); + ps.setInt(1, backpack.getID()); + ps.setBinaryStream(2, new ByteArrayInputStream(b.toByteArray())); + } + else + { + ps = GetConnection().prepareStatement("UPDATE `" + Table_Backpacks + "` SET `itemstacks`=? WHERE `owner`=?"); + ps.setBinaryStream(1, new ByteArrayInputStream(b.toByteArray())); + ps.setInt(2, backpack.getID()); + } + output.close(); + ps.execute(); + ps.close(); + } + catch(Exception e) + { + e.printStackTrace(); + } + } + + public Backpack LoadBackpack(OfflinePlayer player) + { + try + { + PreparedStatement ps = null; // Statement Variable + ps = GetConnection().prepareStatement("SELECT `owner`,`itemstacks` FROM `" + Table_Backpacks + "` INNER JOIN `" + Table_Players + "` ON `owner`=`player_id` WHERE " + ((plugin.UseUUIDs) ? "`uuid`" : "`name`")+ "=?;"); + if(plugin.UseUUIDs) + { + ps.setString(1, player.getUniqueId().toString().replace("-", "")); + } + else + { + ps.setString(1, player.getName()); + } + ResultSet rs = ps.executeQuery(); + if(!rs.next()) + { + return null; + } + int bpid = rs.getInt(1); + BukkitObjectInputStream bois = new BukkitObjectInputStream(rs.getBinaryStream(2)); + ItemStack[] its = (ItemStack[]) bois.readObject(); + bois.close(); + rs.close(); + ps.close(); + return new Backpack(player, its, bpid); + } + catch(Exception e) + { + e.printStackTrace(); + } + return null; + } +} \ No newline at end of file diff --git a/src/at/pcgamingfreaks/georgh/MinePacks/Database/SQLite.java b/src/at/pcgamingfreaks/georgh/MinePacks/Database/SQLite.java new file mode 100644 index 0000000..4956389 --- /dev/null +++ b/src/at/pcgamingfreaks/georgh/MinePacks/Database/SQLite.java @@ -0,0 +1,280 @@ +/* + * Copyright (C) 2014 GeorgH93 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package at.pcgamingfreaks.georgh.MinePacks.Database; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.io.BukkitObjectInputStream; +import org.bukkit.util.io.BukkitObjectOutputStream; + +import at.pcgamingfreaks.georgh.MinePacks.Backpack; +import at.pcgamingfreaks.georgh.MinePacks.MinePacks; + +public class SQLite extends Database +{ + private Connection conn = null; + + private String Table_Players, Table_Backpacks; // Table Names + + public SQLite(MinePacks mp) + { + super(mp); + // Load Settings + Table_Players = plugin.config.getUserTable(); + Table_Backpacks = plugin.config.getBackpackTable(); + + CheckDB(); // Check Database + if(plugin.config.UseUUIDs()) + { + CheckUUIDs(); // Check if there are user accounts without UUID + } + } + + private void CheckUUIDs() + { + try + { + List converter = new ArrayList(); + Statement stmt = GetConnection().createStatement(); + ResultSet res = stmt.executeQuery("SELECT `name` FROM `" + Table_Players + "` WHERE `uuid` IS NULL"); + while(res.next()) + { + if(res.isFirst()) + { + plugin.log.info(plugin.lang.Get("Console.UpdateUUIDs")); + } + converter.add("UPDATE `" + Table_Players + "` SET `uuid`='" + UUIDConverter.getUUIDFromName(res.getString(1)) + "' WHERE `name`='" + res.getString(1).replace("\\", "\\\\").replace("'", "\\'") + "'"); + } + if(converter.size() > 0) + { + for (String string : converter) + { + stmt.execute(string); + } + plugin.log.info(String.format(plugin.lang.Get("Console.UpdatedUUIDs"),converter.size())); + } + } + catch (SQLException e) + { + e.printStackTrace(); + } + } + + private Connection GetConnection() + { + try + { + if(conn == null || conn.isClosed()) + { + try + { + Class.forName("org.sqlite.JDBC"); + conn = DriverManager.getConnection("jdbc:sqlite:" + plugin.getDataFolder().getAbsolutePath() + File.separator + "backpack.db"); + } + catch (ClassNotFoundException e) + { + e.printStackTrace(); + } + + } + } + catch (SQLException e) + { + e.printStackTrace(); + } + return conn; + } + + private void CheckDB() + { + try + { + Statement stmt = GetConnection().createStatement(); + stmt.execute("CREATE TABLE IF NOT EXISTS `" + Table_Players + "` (`player_id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` CHAR(16) NOT NULL UNIQUE);"); + if(plugin.config.UseUUIDs()) + { + try + { + stmt.execute("ALTER TABLE `" + Table_Players + "` ADD COLUMN `uuid` CHAR(32) UNIQUE;"); + } + catch(SQLException e) + { + if(e.getErrorCode() != 1060) + { + e.printStackTrace(); + } + } + } + stmt.execute("CREATE TABLE IF NOT EXISTS `" + Table_Backpacks + "` (`owner` INT UNSIGNED PRIMARY KEY, `itemstacks` BLOB);"); + stmt.close(); + } + catch (SQLException e) + { + e.printStackTrace(); + } + } + + // Plugin Functions + public void UpdatePlayer(Player player) + { + try + { + PreparedStatement ps; + ps = GetConnection().prepareStatement("SELECT `player_id` FROM `" + Table_Players + "` WHERE " + ((plugin.UseUUIDs) ? "`uuid`=?;" : "`name`=?;")); + if(plugin.UseUUIDs) + { + ps.setString(1, player.getUniqueId().toString().replace("-", "")); + } + else + { + ps.setString(1, player.getName()); + } + ResultSet rs = ps.executeQuery(); + if(rs.next()) + { + rs.close(); + ps.close(); + if(!plugin.UseUUIDs) + { + return; + } + ps = GetConnection().prepareStatement("UPDATE `" + Table_Players + "` SET `name`=? WHERE `uuid`=?;"); + ps.setString(1, player.getName()); + ps.setString(2, player.getUniqueId().toString().replace("-", "")); + } + else + { + rs.close(); + ps.close(); + ps = GetConnection().prepareStatement("INSERT INTO `" + Table_Players + "` (`name`" + ((plugin.UseUUIDs) ? ",`uuid`" : "") + ") VALUES (?" + ((plugin.UseUUIDs) ? ",?" : "") + ");"); + ps.setString(1, player.getName()); + if(plugin.UseUUIDs) + { + ps.setString(2, player.getUniqueId().toString().replace("-", "")); + } + } + ps.execute(); + ps.close(); + } + catch (SQLException e) + { + plugin.log.info("Failed to add user: " + player.getName()); + e.printStackTrace(); + } + } + + public void SaveBackpack(Backpack backpack) + { + try + { + // Serialising the backpack + ByteArrayOutputStream b = new ByteArrayOutputStream(); + BukkitObjectOutputStream output = new BukkitObjectOutputStream(b); + output.writeObject(backpack.getBackpack().getContents()); + PreparedStatement ps = null; // Statement Variable + // Building the mysql statement + if(backpack.getID() <= 0) + { + ps = GetConnection().prepareStatement("SELECT `player_id` FROM `" + Table_Players + "` WHERE " + ((plugin.UseUUIDs) ? "`uuid`" : "`name`")+ "=?;"); + if(plugin.UseUUIDs) + { + ps.setString(1, backpack.getOwner().getUniqueId().toString().replace("-", "")); + } + else + { + ps.setString(1, backpack.getOwner().getName()); + } + ResultSet rs = ps.executeQuery(); + if(rs.next()) + { + backpack.setID(rs.getInt(1)); + } + else + { + plugin.log.warning("Faild saving backpack for: " + backpack.getOwner().getName()); + return; + } + rs.close(); + ps.close(); + ps = GetConnection().prepareStatement("INSERT INTO `" + Table_Backpacks + "` (`owner`, `itemstacks`) VALUES (?,?);"); + ps.setInt(1, backpack.getID()); + ps.setBytes(2, b.toByteArray()); + } + else + { + ps = GetConnection().prepareStatement("UPDATE `" + Table_Backpacks + "` SET `itemstacks`=? WHERE `owner`=?"); + ps.setBytes(1, b.toByteArray()); + ps.setInt(2, backpack.getID()); + } + output.close(); + ps.execute(); + ps.close(); + } + catch(Exception e) + { + e.printStackTrace(); + } + } + + public Backpack LoadBackpack(OfflinePlayer player) + { + try + { + PreparedStatement ps = null; // Statement Variable + ps = GetConnection().prepareStatement("SELECT `owner`,`itemstacks` FROM `" + Table_Backpacks + "` INNER JOIN `" + Table_Players + "` ON `owner`=`player_id` WHERE " + ((plugin.UseUUIDs) ? "`uuid`" : "`name`")+ "=?;"); + if(plugin.UseUUIDs) + { + ps.setString(1, player.getUniqueId().toString().replace("-", "")); + } + else + { + ps.setString(1, player.getName()); + } + ResultSet rs = ps.executeQuery(); + if(!rs.next()) + { + return null; + } + int bpid = rs.getInt(1); + BukkitObjectInputStream bois = new BukkitObjectInputStream(new ByteArrayInputStream(rs.getBytes(2))); + ItemStack[] its = (ItemStack[]) bois.readObject(); + bois.close(); + rs.close(); + ps.close(); + return new Backpack(player, its, bpid); + } + catch(Exception e) + { + e.printStackTrace(); + } + return null; + } +} \ No newline at end of file diff --git a/src/at/pcgamingfreaks/georgh/MinePacks/Database/UUIDConverter.java b/src/at/pcgamingfreaks/georgh/MinePacks/Database/UUIDConverter.java new file mode 100644 index 0000000..cffa020 --- /dev/null +++ b/src/at/pcgamingfreaks/georgh/MinePacks/Database/UUIDConverter.java @@ -0,0 +1,138 @@ +/* + * Copyright (C) 2014 GeorgH93 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package at.pcgamingfreaks.georgh.MinePacks.Database; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.Proxy; +import java.net.URL; +import java.net.URLConnection; +import java.util.Scanner; + +import net.minecraft.util.com.google.gson.Gson; + +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; + +public class UUIDConverter +{ + private static Gson gson = new Gson(); + + protected static String getNameFromUUID(String uuid) + { + String name = null; + try + { + URL url = new URL("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid); + URLConnection connection = url.openConnection(); + Scanner jsonScanner = new Scanner(connection.getInputStream(), "UTF-8"); + String json = jsonScanner.next(); + JSONParser parser = new JSONParser(); + Object obj = parser.parse(json); + name = (String) ((JSONObject) obj).get("name"); + jsonScanner.close(); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + return name; + } + + protected static String getUUIDFromName(String name) + { + try + { + ProfileData profC = new ProfileData(name); + String UUID = null; + for (int i = 1; i <= 100; i++) + { + PlayerProfile[] result = post(new URL("https://api.mojang.com/profiles/page/" + i), Proxy.NO_PROXY, gson.toJson(profC).getBytes()); + if (result.length == 0) + { + break; + } + UUID = result[0].getId(); + } + return UUID; + } + catch (Exception e) + { + e.printStackTrace(); + } + return null; + } + + private static PlayerProfile[] post(URL url, Proxy proxy, byte[] bytes) throws IOException + { + HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setDoInput(true); + connection.setDoOutput(true); + + DataOutputStream out = new DataOutputStream(connection.getOutputStream()); + out.write(bytes); + out.flush(); + out.close(); + + BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + StringBuffer response = new StringBuffer(); + String line; + while ((line = reader.readLine()) != null) + { + response.append(line); + response.append('\r'); + } + reader.close(); + return gson.fromJson(response.toString(), SearchResult.class).getProfiles(); + } + + private static class PlayerProfile + { + private String id; + public String getId() + { + return id; + } + } + + private static class SearchResult + { + private PlayerProfile[] profiles; + public PlayerProfile[] getProfiles() + { + return profiles; + } + } + + private static class ProfileData + { + @SuppressWarnings("unused") + private String name; + @SuppressWarnings("unused") + private String agent = "minecraft"; + public ProfileData(String name) + { + this.name = name; + } + } +} \ No newline at end of file diff --git a/src/at/pcgamingfreaks/georgh/MinePacks/EventListener.java b/src/at/pcgamingfreaks/georgh/MinePacks/EventListener.java new file mode 100644 index 0000000..a86d4b2 --- /dev/null +++ b/src/at/pcgamingfreaks/georgh/MinePacks/EventListener.java @@ -0,0 +1,119 @@ +/* + * Copyright (C) 2014 GeorgH93 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package at.pcgamingfreaks.georgh.MinePacks; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +public class EventListener implements Listener +{ + private MinePacks plugin; + private boolean drop_on_death; + + private String Message_OwnBPClose, Message_PlayerBPClose; + + public EventListener(MinePacks mp) + { + plugin = mp; + drop_on_death = plugin.config.getDropOnDeath(); + + Message_OwnBPClose = plugin.lang.Get("Ingame.OwnBackPackClose"); + Message_PlayerBPClose = plugin.lang.Get("Ingame.PlayerBackPackClose"); + } + + @EventHandler + public void onDeath(PlayerDeathEvent event) + { + Player player = event.getEntity(); + if (drop_on_death && !player.hasPermission("backpack.KeepOnDeath")) + { + Inventory BP = plugin.DB.getBackpack(player).getBackpack(); + for (ItemStack i : BP.getContents()) + { + if (i != null) + { + player.getWorld().dropItemNaturally(player.getLocation(), i); + BP.remove(i); + } + } + } + } + + @EventHandler + public void onClose(InventoryCloseEvent event) + { + if (event.getInventory() != null && event.getInventory().getTitle() != null && event.getPlayer() instanceof Player) + { + Backpack backpack = plugin.DB.getBackpack(event.getInventory().getTitle()); + if(backpack != null && !backpack.inUse()) + { + Player closer = (Player)event.getPlayer(); + if(backpack.canEdit(closer)) + { + plugin.DB.SaveBackpack(backpack); + } + backpack.Close(closer); + if(event.getPlayer().getName().equals(backpack.getOwner().getName())) + { + closer.sendMessage(Message_OwnBPClose); + } + else + { + closer.sendMessage(String.format(Message_PlayerBPClose, backpack.getOwner().getName())); + } + } + } + } + + @EventHandler + public void onClick(InventoryClickEvent event) + { + if (event.getInventory() != null && event.getInventory().getTitle() != null && event.getWhoClicked() instanceof Player) + { + Backpack backpack = plugin.DB.getBackpack(event.getInventory().getTitle()); + if(backpack != null && !backpack.canEdit((Player)event.getWhoClicked())) + { + event.setCancelled(true); + } + } + } + + @EventHandler + public void PlayerLoginEvent(PlayerJoinEvent event) + { + plugin.DB.UpdatePlayer(event.getPlayer()); + } + + @EventHandler + public void PlayerLeaveEvent(PlayerQuitEvent event) + { + Backpack bp = plugin.DB.getBackpack(event.getPlayer()); + if(!bp.isOpen()) + { + plugin.DB.UnloadBackpack(bp); + } + } +} \ No newline at end of file diff --git a/src/at/pcgamingfreaks/georgh/MinePacks/MinePacks.java b/src/at/pcgamingfreaks/georgh/MinePacks/MinePacks.java new file mode 100644 index 0000000..a87cd38 --- /dev/null +++ b/src/at/pcgamingfreaks/georgh/MinePacks/MinePacks.java @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2014 GeorgH93 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package at.pcgamingfreaks.georgh.MinePacks; + +import java.util.logging.Logger; + +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import at.pcgamingfreaks.georgh.MinePacks.Database.*; + +public class MinePacks extends JavaPlugin +{ + public Logger log; + public Config config; + public Language lang; + public Database DB; + public String DBType; + public boolean UseUUIDs; + + static public String BackpackTitle; + public String Message_IvalidBackpack; + + public void onEnable() + { + log = getLogger(); + config = new Config(this); + lang = new Language(this); + UseUUIDs = config.UseUUIDs(); + DBType = config.GetDatabaseType().toLowerCase(); + switch(DBType) + { + case "mysql": DB = new MySQL(this); break; + case "sqlite": + default: DB = new SQLite(this); break; + } + getCommand("backpack").setExecutor(new OnCommand(this)); + getServer().getPluginManager().registerEvents(new EventListener(this), this); + + BackpackTitle = config.getBPTitle(); + Message_IvalidBackpack = ChatColor.RED + lang.Get("Ingame.IvalidBackpack"); + log.info(lang.Get("Console.Enabled")); + } + + public void onDisable() + { + log.info(lang.Get("Console.Disabled")); + } + + public void OpenBackpack(Player opener, OfflinePlayer owener, boolean editable) + { + OpenBackpack(opener, DB.getBackpack(owener), editable); + } + + public void OpenBackpack(Player opener, Backpack backpack, boolean editable) + { + if(backpack == null) + { + opener.sendMessage(Message_IvalidBackpack); + return; + } + backpack.Open(opener, editable); + } + + public int getBackpackPermSize(Player player) + { + if(player.hasPermission("backpack.size.6")) + { + return 54; + } + else if(player.hasPermission("backpack.size.5")) + { + return 45; + } + else if(player.hasPermission("backpack.size.4")) + { + return 36; + } + else if(player.hasPermission("backpack.size.3")) + { + return 27; + } + else if(player.hasPermission("backpack.size.2")) + { + return 18; + } + else + { + return 9; + } + } +} \ No newline at end of file diff --git a/src/at/pcgamingfreaks/georgh/MinePacks/OnCommand.java b/src/at/pcgamingfreaks/georgh/MinePacks/OnCommand.java new file mode 100644 index 0000000..1a13ede --- /dev/null +++ b/src/at/pcgamingfreaks/georgh/MinePacks/OnCommand.java @@ -0,0 +1,154 @@ +/* + * Copyright (C) 2014 GeorgH93 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package at.pcgamingfreaks.georgh.MinePacks; + +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class OnCommand implements CommandExecutor +{ + private MinePacks plugin; + + public String Message_NotFromConsole, Message_NoPermission, Message_IvalidBackpack, Message_BackpackCleaned; + + public OnCommand(MinePacks mp) + { + plugin = mp; + Message_NotFromConsole = plugin.lang.Get("Console.NotFromConsole"); + Message_NoPermission = ChatColor.RED + plugin.lang.Get("Ingame.NoPermission"); + Message_IvalidBackpack = ChatColor.RED + plugin.lang.Get("Ingame.IvalidBackpack"); + Message_BackpackCleaned = ChatColor.DARK_GREEN + plugin.lang.Get("Ingame.BackpackCleaned"); + } + + @SuppressWarnings("deprecation") + @Override + public boolean onCommand(CommandSender sender, Command cmd, String arg, String[] args) + { + Player player = null; + if (sender instanceof Player) + { + player = (Player) sender; + } + else + { + sender.sendMessage(Message_NotFromConsole); + return true; + } + + if(args.length == 0) + { + // Open player backpack + if(player.hasPermission("backpack")) + { + Backpack bp = plugin.DB.getBackpack(player); + if(bp == null) + { + player.sendMessage(Message_IvalidBackpack); + return true; + } + int size = plugin.getBackpackPermSize(player); + if(size != bp.getSize()) + { + List items = bp.setSize(size); + for(ItemStack i : items) + { + if (i != null) + { + player.getWorld().dropItemNaturally(player.getLocation(), i); + } + } + } + plugin.OpenBackpack(player, bp, true); + } + else + { + player.sendMessage(Message_NoPermission); + } + } + else + { + // Subcommands + switch(args[0].toLowerCase()) + { + case "help": // Shows the help for the plugin + case "hilfe": + case "?": + if(player.hasPermission("backpack")) + { + player.sendMessage(ChatColor.GOLD + "Minepacks Help:"); + player.sendMessage(ChatColor.AQUA + "/backpack" + ChatColor.WHITE + " - " + plugin.lang.Get("Description.Backpack")); + if(player.hasPermission("backpack.clean")) + { + player.sendMessage(ChatColor.AQUA + "/backpack clean" + ChatColor.WHITE + " - " + plugin.lang.Get("Description.Clean")); + } + if(player.hasPermission("backpack.clean.other")) + { + player.sendMessage(ChatColor.AQUA + "/backpack clean " + ChatColor.WHITE + " - " + plugin.lang.Get("Description.CleanOther")); + } + if(player.hasPermission("backpack.other")) + { + player.sendMessage(ChatColor.AQUA + "/backpack " + ChatColor.WHITE + " - " + plugin.lang.Get("Description.View")); + } + } + else + { + player.sendMessage(Message_NoPermission); + } + break; + case "empty": // Removes all items from the backpack + case "clean": + case "clear": + if(player.hasPermission("backpack.clean")) + { + OfflinePlayer OP = player; + if(player.hasPermission("backpack.clean.other") && args.length == 2) + { + OP = Bukkit.getOfflinePlayer(args[1]); + } + Backpack BP = plugin.DB.getBackpack(OP); + BP.getBackpack().clear(); + player.sendMessage(Message_BackpackCleaned); + } + else + { + player.sendMessage(Message_NoPermission); + } + break; + default: // Shows the backpack of an other player + if(player.hasPermission("backpack.others")) + { + plugin.OpenBackpack(player, Bukkit.getOfflinePlayer(args[0]), player.hasPermission("backpack.others.edit")); + } + else + { + player.sendMessage(Message_NoPermission); + } + break; + } + } + return true; + } +} \ No newline at end of file