Continue changes for V2

This commit is contained in:
GeorgH93 2016-12-19 22:06:08 +01:00
parent 079003cbb8
commit 329ef26cb6
31 changed files with 1290 additions and 397 deletions

13
pom.xml
View File

@ -29,6 +29,12 @@
<distribution>repo</distribution> <distribution>repo</distribution>
</license> </license>
</licenses> </licenses>
<properties>
<author>GeorgH93</author>
<website>http://dev.bukkit.org/bukkit-plugins/minepacks/</website>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<repositories> <repositories>
<repository> <repository>
@ -50,16 +56,11 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>at.pcgamingfreaks</groupId> <groupId>at.pcgamingfreaks</groupId>
<artifactId>Bukkit_Bungee_PluginLib</artifactId> <artifactId>PluginLib</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
</dependency> </dependency>
</dependencies> </dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<build> <build>
<defaultGoal>clean install</defaultGoal> <defaultGoal>clean install</defaultGoal>
<sourceDirectory>src</sourceDirectory> <sourceDirectory>src</sourceDirectory>

View File

@ -18,8 +18,6 @@ command_cooldown: -1
# Defines if the content of the backpack get droped on the death of a player. # Defines if the content of the backpack get droped on the death of a player.
# If enabled, it can be disabled for individual players with the "backpack.KeepOnDeath" permission. # If enabled, it can be disabled for individual players with the "backpack.KeepOnDeath" permission.
drop_on_death: true drop_on_death: true
# Defines if the message that the backpack has been closed should be shown
show_close_message: false
# Defines the max amount of colums for a backpack # Defines the max amount of colums for a backpack
max_size: 6 max_size: 6
@ -46,7 +44,6 @@ Database:
# If you would like to use UUIDs, it is recomendet not to change this setting unless you know what you are doing! # If you would like to use UUIDs, it is recomendet not to change this setting unless you know what you are doing!
# true: Only to use if your server is running in online mode and your minecraft version is 1.7.5 or newer # true: Only to use if your server is running in online mode and your minecraft version is 1.7.5 or newer
# false: In offline mode or for minecraft version below 1.7.5 # false: In offline mode or for minecraft version below 1.7.5
# Should be configured automaticaly based on your minecraft version and online mode settings
# If you are using BungeeCord please set this setting based on your BungeeCord's online mode!!! # If you are using BungeeCord please set this setting based on your BungeeCord's online mode!!!
UseUUIDs: true UseUUIDs: true
# Defines the storage format for UUIDs for compatibility with other plugins (shared tables) # Defines the storage format for UUIDs for compatibility with other plugins (shared tables)
@ -54,7 +51,7 @@ Database:
# false: format: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # false: format: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
UseUUIDSeparators: false UseUUIDSeparators: false
# Settings only for MySQL # Settings only for MySQL
MySQL: SQL:
Host: localhost:3306 Host: localhost:3306
Database: minecraft Database: minecraft
User: minecraft User: minecraft
@ -83,6 +80,30 @@ Database:
ItemStacks: itemstacks ItemStacks: itemstacks
Version: version Version: version
LastUpdate: lastupdate LastUpdate: lastupdate
# Settings controlling the cache behavior of the plugin. You may can optimize it a little bit depending on your player count, ram or cpu bottelnecks.
Cache:
UnCache:
# The strategie used to uncache offlien players. Options
# interval (offline players get uncached every x seconds)
# intervalChecked (like interval, but also ensures that the player is already offline for atleast the interval time, add's a cpu overhead)
# ondisconnect (player instantly gets uncahed as sone as he disconnects, may adds overhead if other plugins try to access the player data when they go offline, also it may be problematic for players with unstabel connections)
# ondisconnectdelayed (player gets uncached x seconds after he went offline, adds overhead on disconnect, you shouldn't use this with a lot of players joining and leaving.)
Strategie: interval
# Used for the interval based uncaching algorithems. Also used as delay for ondisconnectdelayed. Value in seconds. Default: 600 = 10 minutes
Interval: 600
Delay: 600
Shulkerboxes:
# This setting controlles whether players can put shulkerboxes into their backpacks.
PreventInBackpack: true
# This setting allows to disable shulkerboxes alltogether. Players won't be able to craft or use them.
DisableShulkerboxes: false
# This settings controlles how existing shulkerboxes are handeled if they are disabled.
Existing:
# Every existing shunkbox will be removed when a player tries to interact with it. The content will be lost.
Remove: false
# Every existing shunkbox will be destroyed when a player tries to interact with it. The content will be droped to the ground.
Destroy: false
# Enables/Disables the auto-update function of the plugin. # Enables/Disables the auto-update function of the plugin.
auto-update: true auto-update: true

View File

@ -2,11 +2,14 @@ Language:
NotFromConsole: "&cDieser Befehl kann nicht in der Console ausgeführt werden." NotFromConsole: "&cDieser Befehl kann nicht in der Console ausgeführt werden."
Ingame: Ingame:
NoPermission: "Dir fehlen die Rechte dafür." NoPermission: "Dir fehlen die Rechte dafür."
OwnBackPackClose: "Rucksack geschlossen." OwnBackpackClose: "Rucksack geschlossen."
PlayerBackPackClose: "%s's Rucksack geschlossen." #Parameter: {OwnerName}, {OwnerDisplayName}
PlayerBackpackClose: "{OwnerName}'s Rucksack geschlossen."
InvalidBackpack: "Rucksack fehlerhaft." InvalidBackpack: "Rucksack fehlerhaft."
BackpackCleaned: "Rucksack gelehrt." BackpackCleaned: "Rucksack gelehrt."
Cooldown: "&2Bitte warte kurz bis du deinen Rucksack wieder öffnest." Cooldown: "&2Bitte warte kurz bis du deinen Rucksack wieder öffnest."
Shulkerboxes:
NotAllowedInBackpack: "&cShulkerboxes sind im Rucksack nicht erlaubt."
Commands: Commands:
Description: Description:
Backpack: "Öffent deinen Rucksack." Backpack: "Öffent deinen Rucksack."

View File

@ -2,11 +2,14 @@ Language:
NotFromConsole: "&cCommand not useable from console." NotFromConsole: "&cCommand not useable from console."
Ingame: Ingame:
NoPermission: "&cYou don't have the Permission to do that." NoPermission: "&cYou don't have the Permission to do that."
OwnBackPackClose: "Backpack closed!" OwnBackpackClose: "Backpack closed!"
PlayerBackPackClose: "%s's backpack closed!" #Parameter: {OwnerName}, {OwnerDisplayName}
PlayerBackpackClose: "{OwnerName}'s backpack closed!"
InvalidBackpack: "Invalid backpack." InvalidBackpack: "Invalid backpack."
BackpackCleaned: "Backpack cleaned." BackpackCleaned: "Backpack cleaned."
Cooldown: "&2Please wait till you reopen your backpack." Cooldown: "&2Please wait till you reopen your backpack."
Shulkerboxes:
NotAllowedInBackpack: "&cShulkerboxes are not allowed in the backpack."
Commands: Commands:
Description: Description:
Backpack: "Opens your backpack." Backpack: "Opens your backpack."

View File

@ -1,7 +1,7 @@
name: Minepacks name: ${project.name}
author: GeorgH93 author: ${author}
website: http://dev.bukkit.org/bukkit-plugins/minepacks/ website: ${website}
main: at.pcgamingfreaks.Minepacks.Minepacks main: at.pcgamingfreaks.Minepacks.Bukkit.Minepacks
description: ${project.description} description: ${project.description}
version: ${project.version} version: ${project.version}
depend: [PCGF_MC_Plugin_Lib] depend: [PCGF_MC_Plugin_Lib]
@ -18,7 +18,7 @@ permissions:
backpack.size.6: true backpack.size.6: true
backpack.others: true backpack.others: true
backpack.others.edit: true backpack.others.edit: true
backpack.KeepOnDeath: true backpack.keepOnDeath: true
backpack.clean: true backpack.clean: true
backpack.clean.other: true backpack.clean.other: true
backpack.noCooldown: true backpack.noCooldown: true
@ -76,7 +76,7 @@ permissions:
default: op default: op
children: children:
backpack.others: true backpack.others: true
backpack.KeepOnDeath: backpack.keepOnDeath:
description: Allows the player to keep their items in their backpack on death. description: Allows the player to keep their items in their backpack on death.
default: op default: op
backpack.noCooldown: backpack.noCooldown:

View File

@ -0,0 +1,80 @@
/*
* Copyright (C) 2016 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 <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks.Bukkit.API;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryHolder;
import org.jetbrains.annotations.NotNull;
public interface Backpack extends InventoryHolder
{
/**
* Gets the owner of the backpack.
*
* @return The owner of the backpack;
*/
@NotNull OfflinePlayer getOwner();
/**
* Let a given player open this backpack.
*
* @param player The player who opens the backpack.
* @param editable Defines if the player who has opened the backpack can change the items inside.
*/
void open(@NotNull Player player, boolean editable);
/**
* Checks if the backpack is currently opened by a player.
*
* @return True if the backpack is open, false if not.
*/
boolean isOpen();
/**
* Checks if a player can change the content of the backpack.
*
* @param player The player to be checked.
* @return True if he can change the content, false if not.
*/
boolean canEdit(@NotNull Player player);
/**
* Gets the size of the backpack.
*
* @return The size of the backpack.
*/
int getSize();
/**
* Checks if the backpack has changed since it was last saved.
*
* @return True if it has been changed, false if not.
*/
boolean hasChanged();
/**
* Marks that the content of the backpack a changed. It will be saved when the next player closes the backpack or before it gets removed from the cache.
*/
void setChanged();
/**
* Forces the backpack to be saved
*/
void save();
}

View File

@ -0,0 +1,25 @@
/*
* Copyright (C) 2016 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 <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks.Bukkit.API;
public interface Callback<T>
{
void onResult(T done);
void onFail();
}

View File

@ -0,0 +1,80 @@
/*
* Copyright (C) 2016 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 <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks.Bukkit.API;
import at.pcgamingfreaks.Version;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public interface MinepacksPlugin
{
/**
* Let a given player open the backpack of an other player.
*
* @param opener The player who opens the backpack.
* @param owner The owner of the backpack that should be opened.
* @param editable Defines if the player who has opened the backpack can change the items inside.
*/
void openBackpack(@NotNull final Player opener, @NotNull final OfflinePlayer owner, final boolean editable);
/**
* Let a given player open a given {@link at.pcgamingfreaks.Minepacks.Bukkit.Backpack}.
*
* @param opener The player who opens the backpack.
* @param backpack The backpack to be opened. null will result in an error message for the player.
* @param editable Defines if the player who has opened the backpack can change the items inside.
*/
void openBackpack(@NotNull final Player opener, @Nullable final at.pcgamingfreaks.Minepacks.Bukkit.Backpack backpack, boolean editable);
/**
* Retrieves the backpack for a given player.
* This method runs sync! If the requested backpack is not in the cache it will block you server! Use with extreme care!
*
* @param owner The player who's backpack should be retrieved.
* @return The backpack of the given player.
*/
@Nullable at.pcgamingfreaks.Minepacks.Bukkit.Backpack getBackpack(@NotNull final OfflinePlayer owner);
/**
* Retrieves the backpack for a given player.
* This method only returns a backpack if it is in the cache.
*
* @param owner The player who's backpack should be retrieved.
* @return The backpack of the given player. null if the backpack is in the cache.
*/
@Nullable at.pcgamingfreaks.Minepacks.Bukkit.Backpack getBackpackCachedOnly(@NotNull final OfflinePlayer owner);
/**
* Retrieves the backpack for a given player.
* This method runs async! The result will be delivered with a callback.
*
* @param owner The player who's backpack should be retrieved.
* @param callback The callback delivering the result of the request.
*/
void getBackpack(@NotNull final OfflinePlayer owner, @NotNull final Callback<at.pcgamingfreaks.Minepacks.Bukkit.Backpack> callback);
/**
* Gets the currently running {@link Version} of the plugin.
*
* @return The currently running version of the plugin.
*/
Version getVersion();
}

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2014-2016 GeorgH93 * Copyright (C) 2016 GeorgH93
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -15,7 +15,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package at.pcgamingfreaks.Minepacks; package at.pcgamingfreaks.Minepacks.Bukkit;
import at.pcgamingfreaks.Bukkit.NMSReflection; import at.pcgamingfreaks.Bukkit.NMSReflection;
import at.pcgamingfreaks.StringUtils; import at.pcgamingfreaks.StringUtils;
@ -31,20 +31,20 @@
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
public class Backpack implements InventoryHolder public class Backpack implements at.pcgamingfreaks.Minepacks.Bukkit.API.Backpack
{ {
private final static Method METHOD_GET_INVENTORY = NMSReflection.getOBCMethod("inventory.CraftInventory", "getInventory"); private final static Method METHOD_GET_INVENTORY = NMSReflection.getOBCMethod("inventory.CraftInventory", "getInventory");
private final static Field FIELD_TITLE = NMSReflection.getOBCField("inventory.CraftInventoryCustom$MinecraftInventory", "title"); private final static Field FIELD_TITLE = NMSReflection.getOBCField("inventory.CraftInventoryCustom$MinecraftInventory", "title");
private OfflinePlayer owner; private final OfflinePlayer owner;
private HashMap<Player, Boolean> opened = new HashMap<>(); private final String titleOther;
private final HashMap<Player, Boolean> opened = new HashMap<>();
private Inventory bp; private Inventory bp;
private int size, ownerID; private int size, ownerID;
private final String titleOther; private boolean hasChanged;
private boolean inWork, hasChanged;
public Backpack(OfflinePlayer owner) public Backpack(OfflinePlayer owner)
{ {
@ -63,7 +63,6 @@ public Backpack(OfflinePlayer owner, int Size, int ID)
bp = Bukkit.createInventory(this, Size, titleOther); bp = Bukkit.createInventory(this, Size, titleOther);
size = Size; size = Size;
ownerID = ID; ownerID = ID;
inWork = false;
} }
public Backpack(OfflinePlayer owner, ItemStack[] backpack, int ID) public Backpack(OfflinePlayer owner, ItemStack[] backpack, int ID)
@ -81,13 +80,15 @@ public void setOwnerID(int id)
{ {
ownerID = id; ownerID = id;
} }
public OfflinePlayer getOwner() @Override
public @NotNull OfflinePlayer getOwner()
{ {
return owner; return owner;
} }
public void open(Player p, boolean editable) @Override
public void open(@NotNull Player p, boolean editable)
{ {
if(owner.isOnline()) if(owner.isOnline())
{ {
@ -112,7 +113,7 @@ public void open(Player p, boolean editable)
// It's not perfect, but it is the only way of doing this. // It's not perfect, but it is the only way of doing this.
// This sets the title of the inventory based on the person who is opening it. // This sets the title of the inventory based on the person who is opening it.
// The owner will se an other title then everyone else. // The owner will see an other title then everyone else.
// This way we can add owner name to the tile for everyone else. // This way we can add owner name to the tile for everyone else.
try try
{ {
@ -131,23 +132,20 @@ public void close(Player p)
{ {
opened.remove(p); opened.remove(p);
} }
@Override
public boolean isOpen() public boolean isOpen()
{ {
return !opened.isEmpty(); return !opened.isEmpty();
} }
public boolean canEdit(Player p) @Override
public boolean canEdit(@NotNull Player player)
{ {
return opened.containsKey(p) && opened.get(p); return opened.containsKey(player) && opened.get(player);
}
public boolean inUse()
{
return inWork;
} }
@SuppressWarnings("unused") @Override
public int getSize() public int getSize()
{ {
return size; return size;
@ -155,7 +153,6 @@ public int getSize()
public List<ItemStack> setSize(int newSize) public List<ItemStack> setSize(int newSize)
{ {
inWork = true;
for(Entry<Player, Boolean> e : opened.entrySet()) for(Entry<Player, Boolean> e : opened.entrySet())
{ {
e.getKey().closeInventory(); e.getKey().closeInventory();
@ -196,37 +193,33 @@ public List<ItemStack> setSize(int newSize)
{ {
e.getKey().openInventory(bp); e.getKey().openInventory(bp);
} }
inWork = false;
return removedItems; return removedItems;
} }
/**
* Get the object's inventory.
*
* @return The inventory.
*/
@Override @Override
public Inventory getInventory() public Inventory getInventory()
{ {
return bp; return bp;
} }
@SuppressWarnings("unused") @Override
public boolean hasChanged() public boolean hasChanged()
{ {
return hasChanged; return hasChanged;
} }
@Override
public void setChanged() public void setChanged()
{ {
hasChanged = true; hasChanged = true;
} }
@Override
public void save() public void save()
{ {
if(hasChanged) if(hasChanged())
{ {
Minepacks.getInstance().DB.saveBackpack(this); Minepacks.getInstance().getDb().saveBackpack(this);
hasChanged = false; hasChanged = false;
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2014-2016 GeorgH93 * Copyright (C) 2016 GeorgH93
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -15,7 +15,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package at.pcgamingfreaks.Minepacks.Database; package at.pcgamingfreaks.Minepacks.Bukkit.Database;
import at.pcgamingfreaks.Bukkit.Configuration; import at.pcgamingfreaks.Bukkit.Configuration;
@ -46,10 +46,16 @@ protected void doUpgrade(at.pcgamingfreaks.Configuration oldConfig)
Set<String> keys = oldConfig.getConfig().getKeys(); Set<String> keys = oldConfig.getConfig().getKeys();
for(String key : keys) for(String key : keys)
{ {
if(key.equals("UseUUIDs") || key.equals("Version") || (key.equals("BackpackTitle") && oldConfig.getVersion() < 11)) continue; String newKey = key;
if(key.equals("Version")) continue;
if(oldConfig.getVersion() < 11)
{
if(key.equals("UseUUIDs") || key.equals("BackpackTitle")) continue;
newKey = key.replace(".MySQL.", ".SQL.");
}
try try
{ {
config.set(key, oldConfig.getConfig().getString(key)); config.set(newKey, oldConfig.getConfig().getString(key));
} }
catch(Exception e) catch(Exception e)
{ {
@ -62,10 +68,6 @@ protected void doUpgrade(at.pcgamingfreaks.Configuration oldConfig)
{ {
config.set("Database.UseUUIDs", oldConfig.getConfig().getBoolean("UseUUIDs", true)); config.set("Database.UseUUIDs", oldConfig.getConfig().getBoolean("UseUUIDs", true));
} }
else
{
config.set("Database.UseUUIDs", Bukkit.getServer().getOnlineMode() && isBukkitVersionUUIDCompatible());
}
} }
if(oldConfig.getVersion() < 11) if(oldConfig.getVersion() < 11)
{ {
@ -73,7 +75,8 @@ protected void doUpgrade(at.pcgamingfreaks.Configuration oldConfig)
} }
} }
// Getter //region getter
//region Database getter
public int getAutoCleanupMaxInactiveDays() public int getAutoCleanupMaxInactiveDays()
{ {
return config.getInt("Database.AutoCleanup.MaxInactiveDays", -1); return config.getInt("Database.AutoCleanup.MaxInactiveDays", -1);
@ -86,27 +89,27 @@ public String getDatabaseType()
public String getMySQLHost() public String getMySQLHost()
{ {
return config.getString("Database.MySQL.Host", "localhost"); return config.getString("Database.SQL.Host", "localhost");
} }
public String getMySQLDatabase() public String getMySQLDatabase()
{ {
return config.getString("Database.MySQL.Database", "minecraft"); return config.getString("Database.SQL.Database", "minecraft");
} }
public String getMySQLUser() public String getMySQLUser()
{ {
return config.getString("Database.MySQL.User", "minecraft"); return config.getString("Database.SQL.User", "minecraft");
} }
public String getMySQLPassword() public String getMySQLPassword()
{ {
return config.getString("Database.MySQL.Password", ""); return config.getString("Database.SQL.Password", "");
} }
public int getMySQLMaxConnections() public int getMySQLMaxConnections()
{ {
return config.getInt("Database.MySQL.MaxConnections", 4); return config.getInt("Database.SQL.MaxConnections", 4);
} }
public String getUserTable() public String getUserTable()
@ -139,6 +142,22 @@ public boolean getUseUUIDSeparators()
return config.getBoolean("Database.UseUUIDSeparators", false); return config.getBoolean("Database.UseUUIDSeparators", false);
} }
public String getUnCacheStrategie()
{
return config.getString("Database.Cache.UnCache.Strategie", "interval").toLowerCase();
}
public long getUnCacheInterval()
{
return config.getLong("Database.Cache.UnCache.Interval", 600) * 20L;
}
public long getUnCacheDelay()
{
return config.getLong("Database.Cache.UnCache.Delay", 600) * 20L;
}
//endregion
public String getBPTitleOther() public String getBPTitleOther()
{ {
return ChatColor.translateAlternateColorCodes('&', config.getString("BackpackTitleOther", "{OwnerName} Backpack").replaceAll("%", "%%").replaceAll("\\{OwnerName\\}", "%s")); return ChatColor.translateAlternateColorCodes('&', config.getString("BackpackTitleOther", "{OwnerName} Backpack").replaceAll("%", "%%").replaceAll("\\{OwnerName\\}", "%s"));
@ -169,11 +188,7 @@ public int getCommandCooldown()
return config.getInt("command_cooldown", -1) * 1000; return config.getInt("command_cooldown", -1) * 1000;
} }
public boolean getShowCloseMessage() //region Full inventory handling
{
return config.getBoolean("show_close_message", true);
}
public boolean getFullInvCollect() public boolean getFullInvCollect()
{ {
return config.getBoolean("full_inventory.collect_items", false); return config.getBoolean("full_inventory.collect_items", false);
@ -188,4 +203,28 @@ public double getFullInvRadius()
{ {
return config.getDouble("full_inventory.collect_radius", 1.5); // in blocks return config.getDouble("full_inventory.collect_radius", 1.5); // in blocks
} }
//endregion
//region Shulkerboxes
public boolean getShulkerboxesPreventInBackpack()
{
return config.getBoolean("Shulkerboxes.PreventInBackpack", true);
}
public boolean getShulkerboxesDisableShulkerboxes()
{
return config.getBoolean("Shulkerboxes.DisableShulkerboxes", false);
}
public boolean getShulkerboxesExistingRemove()
{
return config.getBoolean("Shulkerboxes.Existing.Remove", true);
}
public boolean getShulkerboxesExistingDestroy()
{
return config.getBoolean("Shulkerboxes.Existing.Destroy", true);
}
//endregion
//endregion
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2014-2016 GeorgH93 * Copyright (C) 2016 GeorgH93
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -15,25 +15,36 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package at.pcgamingfreaks.Minepacks.Database; package at.pcgamingfreaks.Minepacks.Bukkit.Database;
import at.pcgamingfreaks.Minepacks.Backpack; import at.pcgamingfreaks.Minepacks.Bukkit.API.Callback;
import at.pcgamingfreaks.Minepacks.Minepacks; import at.pcgamingfreaks.Minepacks.Bukkit.Backpack;
import at.pcgamingfreaks.Minepacks.Bukkit.Database.UnCacheStrategies.UnCacheStrategie;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap; import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Database public class Database implements Listener
{ {
protected static final String START_UUID_UPDATE = "Start updating database to UUIDs ...", UUIDS_UPDATED = "Updated %d accounts to UUIDs."; protected static final String START_UUID_UPDATE = "Start updating database to UUIDs ...", UUIDS_UPDATED = "Updated %d accounts to UUIDs.";
protected Minepacks plugin; protected final Minepacks plugin;
protected final InventorySerializer itsSerializer = new InventorySerializer();
protected boolean useUUIDs, useUUIDSeparators; protected boolean useUUIDs, useUUIDSeparators;
protected long maxAge; protected long maxAge;
protected InventorySerializer itsSerializer = new InventorySerializer(); private final Map<OfflinePlayer, Backpack> backpacks = new ConcurrentHashMap<>();
private HashMap<OfflinePlayer, Backpack> backpacks = new HashMap<>(); private final UnCacheStrategie unCacheStrategie;
public Database(Minepacks mp) public Database(Minepacks mp)
{ {
@ -41,22 +52,37 @@ public Database(Minepacks mp)
useUUIDSeparators = plugin.config.getUseUUIDSeparators(); useUUIDSeparators = plugin.config.getUseUUIDSeparators();
useUUIDs = plugin.config.getUseUUIDs(); useUUIDs = plugin.config.getUseUUIDs();
maxAge = plugin.config.getAutoCleanupMaxInactiveDays(); maxAge = plugin.config.getAutoCleanupMaxInactiveDays();
unCacheStrategie = UnCacheStrategie.getUnCacheStrategie(this);
}
public void init()
{
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
public void close()
{
HandlerList.unregisterAll(this);
unCacheStrategie.close();
} }
public static Database getDatabase(Minepacks Plugin) public static Database getDatabase(Minepacks Plugin)
{ {
Database database;
switch(Plugin.config.getDatabaseType().toLowerCase()) switch(Plugin.config.getDatabaseType().toLowerCase())
{ {
case "mysql": case "mysql":
return new MySQL(Plugin); database = new MySQL(Plugin); break;
case "flat": case "flat":
case "file": case "file":
case "files": case "files":
return new Files(Plugin); database = new Files(Plugin); break;
case "sqlite": case "sqlite":
default: default:
return new SQLite(Plugin); database = new SQLite(Plugin);
} }
database.init();
return database;
} }
protected String getPlayerNameOrUUID(OfflinePlayer player) protected String getPlayerNameOrUUID(OfflinePlayer player)
@ -80,12 +106,16 @@ protected String getPlayerFormattedUUID(OfflinePlayer player)
return null; return null;
} }
public Backpack getBackpack(OfflinePlayer player) public @NotNull Collection<Backpack> getLoadedBackpacks()
{
return backpacks.values();
}
public @Nullable Backpack getBackpack(@Nullable OfflinePlayer player)
{ {
return (player == null) ? null : backpacks.get(player); return (player == null) ? null : backpacks.get(player);
} }
@SuppressWarnings("unused")
public Backpack getBackpack(OfflinePlayer player, boolean loadedOnly) public Backpack getBackpack(OfflinePlayer player, boolean loadedOnly)
{ {
if(player == null) if(player == null)
@ -164,9 +194,13 @@ public void onFail()
} }
} }
// DB Functions @EventHandler
public void close() { } public void onPlayerLoginEvent(PlayerJoinEvent event)
{
updatePlayerAndLoadBackpack(event.getPlayer());
}
// DB Functions
public void updatePlayerAndLoadBackpack(Player player) public void updatePlayerAndLoadBackpack(Player player)
{ {
updatePlayer(player); updatePlayer(player);
@ -191,11 +225,4 @@ protected void loadBackpack(final OfflinePlayer player, final Callback<Backpack>
callback.onResult(loadedBackpack); callback.onResult(loadedBackpack);
} }
} }
public interface Callback<T>
{
void onResult(T done);
void onFail();
}
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2014-2016 GeorgH93 * Copyright (C) 2016 GeorgH93
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -15,7 +15,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package at.pcgamingfreaks.Minepacks.Database; package at.pcgamingfreaks.Minepacks.Bukkit.Database;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@ -25,12 +25,11 @@
import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileFilter;
import at.pcgamingfreaks.Minepacks.Bukkit.Backpack;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import at.pcgamingfreaks.UUIDConverter; import at.pcgamingfreaks.UUIDConverter;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import at.pcgamingfreaks.Minepacks.Backpack;
import at.pcgamingfreaks.Minepacks.Minepacks;
public class Files extends Database public class Files extends Database
{ {
private static final String EXT = ".backpack", EXT_REGEX = "\\.backpack"; private static final String EXT = ".backpack", EXT_REGEX = "\\.backpack";

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2014-2016 GeorgH93 * Copyright (C) 2016 GeorgH93
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -15,7 +15,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package at.pcgamingfreaks.Minepacks.Database; package at.pcgamingfreaks.Minepacks.Bukkit.Database;
import at.pcgamingfreaks.Bukkit.ItemStackSerializer.BukkitItemStackSerializer; import at.pcgamingfreaks.Bukkit.ItemStackSerializer.BukkitItemStackSerializer;
import at.pcgamingfreaks.Bukkit.ItemStackSerializer.ItemStackSerializer; import at.pcgamingfreaks.Bukkit.ItemStackSerializer.ItemStackSerializer;
@ -65,6 +65,7 @@ public ItemStack[] deserialize(byte[] data)
public ItemStack[] deserialize(byte[] data, int usedSerializer) public ItemStack[] deserialize(byte[] data, int usedSerializer)
{ {
if(data == null) return null;
switch(usedSerializer) switch(usedSerializer)
{ {
case 0: return baseItemStackSerializer.deserialize(data); case 0: return baseItemStackSerializer.deserialize(data);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2014-2016 GeorgH93 * Copyright (C) 2016 GeorgH93
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -15,7 +15,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package at.pcgamingfreaks.Minepacks.Database; package at.pcgamingfreaks.Minepacks.Bukkit.Database;
import at.pcgamingfreaks.yaml.YAML; import at.pcgamingfreaks.yaml.YAML;
@ -62,11 +62,12 @@ protected void doUpgrade(at.pcgamingfreaks.Language oldLang)
} }
break; break;
case "Ingame": case "Ingame":
helper = keys[0] + "." + keys[1] + ".";
switch(keys[2]) switch(keys[2])
{ {
case "NoPermission": advancedConverter.put(key, ChatColor.RED + oldYAML.getString(key)); break; case "NoPermission": advancedConverter.put(key, ChatColor.RED + oldYAML.getString(key)); break;
case "OwnBackPackClose": simpleConverter.put(key, key); break; case "OwnBackPackClose": simpleConverter.put(helper + "OwnBackpackClose", key); break;
case "PlayerBackPackClose": simpleConverter.put(key, key); break; case "PlayerBackPackClose": advancedConverter.put(helper + "PlayerBackpackClose", oldYAML.getString(key).replace("%s", "{OwnerName}")); break;
case "InvalidBackpack": simpleConverter.put(key, key); break; case "InvalidBackpack": simpleConverter.put(key, key); break;
case "BackpackCleaned": simpleConverter.put(key, key); break; case "BackpackCleaned": simpleConverter.put(key, key); break;
case "Cooldown": advancedConverter.put(key, ChatColor.DARK_GREEN + oldYAML.getString(key)); break; case "Cooldown": advancedConverter.put(key, ChatColor.DARK_GREEN + oldYAML.getString(key)); break;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2014-2016 GeorgH93 * Copyright (C) 2016 GeorgH93
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -15,9 +15,9 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package at.pcgamingfreaks.Minepacks.Database; package at.pcgamingfreaks.Minepacks.Bukkit.Database;
import at.pcgamingfreaks.Minepacks.Minepacks; import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariConfig;
@ -49,7 +49,7 @@ protected HikariConfig getPoolConfig()
protected void updateQuerysForDialect() protected void updateQuerysForDialect()
{ {
queryDeleteOldBackpacks = "DELETE FROM `{TableBackpacks}` WHERE `{FieldBPLastUpdate}` + INTERVAL {VarMaxAge} day < NOW()"; queryDeleteOldBackpacks = "DELETE FROM `{TableBackpacks}` WHERE `{FieldBPLastUpdate}` + INTERVAL {VarMaxAge} day < NOW()";
queryUpdateBP = queryUpdateBP.replaceAll("\\{NOW\\}", "NOW()"); queryUpdateBp = queryUpdateBp.replaceAll("\\{NOW\\}", "NOW()");
} }
@Override @Override
@ -60,36 +60,36 @@ protected void checkDB()
ResultSet res; ResultSet res;
if(useUUIDs) if(useUUIDs)
{ {
stmt.execute("CREATE TABLE IF NOT EXISTS `" + tablePlayers + "` (`" + fieldPlayerID + "` INT UNSIGNED NOT NULL AUTO_INCREMENT,`" + fieldName + "` CHAR(16) NOT NULL,`" + fieldUUID + "` CHAR(36) UNIQUE, PRIMARY KEY (`" + fieldPlayerID + "`));"); stmt.execute("CREATE TABLE IF NOT EXISTS `" + tablePlayers + "` (`" + fieldPlayerID + "` INT UNSIGNED NOT NULL AUTO_INCREMENT,`" + fieldPlayerName + "` CHAR(16) NOT NULL,`" + fieldPlayerUUID + "` CHAR(36) UNIQUE, PRIMARY KEY (`" + fieldPlayerID + "`));");
res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + tablePlayers + "' AND COLUMN_NAME = '" + fieldUUID + "';"); res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + tablePlayers + "' AND COLUMN_NAME = '" + fieldPlayerUUID + "';");
if(!res.next()) if(!res.next())
{ {
stmt.execute("ALTER TABLE `" + tablePlayers + "` ADD COLUMN `" + fieldUUID + "` CHAR(36) UNIQUE;"); stmt.execute("ALTER TABLE `" + tablePlayers + "` ADD COLUMN `" + fieldPlayerUUID + "` CHAR(36) UNIQUE;");
} }
res.close(); res.close();
res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + tablePlayers + "' AND COLUMN_NAME = '" + fieldName + "' AND COLUMN_KEY='UNI';"); res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + tablePlayers + "' AND COLUMN_NAME = '" + fieldPlayerName + "' AND COLUMN_KEY='UNI';");
if(res.next()) if(res.next())
{ {
stmt.execute("ALTER TABLE `" + tablePlayers + "` DROP INDEX `" + fieldName + "_UNIQUE`;"); stmt.execute("ALTER TABLE `" + tablePlayers + "` DROP INDEX `" + fieldPlayerName + "_UNIQUE`;");
} }
res.close(); res.close();
if(useUUIDSeparators) if(useUUIDSeparators)
{ {
res = stmt.executeQuery("SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + tablePlayers + "' AND COLUMN_NAME = '" + fieldUUID + "';"); res = stmt.executeQuery("SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + tablePlayers + "' AND COLUMN_NAME = '" + fieldPlayerUUID + "';");
if(res.next() && res.getInt(1) < 36) if(res.next() && res.getInt(1) < 36)
{ {
stmt.execute("ALTER TABLE `" + tablePlayers + "` MODIFY `" + fieldUUID + "` CHAR(36) UNIQUE;"); stmt.execute("ALTER TABLE `" + tablePlayers + "` MODIFY `" + fieldPlayerUUID + "` CHAR(36) UNIQUE;");
} }
res.close(); res.close();
} }
} }
else else
{ {
stmt.execute("CREATE TABLE IF NOT EXISTS `" + tablePlayers + "` (`" + fieldPlayerID + "` INT UNSIGNED NOT NULL AUTO_INCREMENT,`" + fieldName + "` CHAR(16) NOT NULL, PRIMARY KEY (`" + fieldPlayerID + "`));"); stmt.execute("CREATE TABLE IF NOT EXISTS `" + tablePlayers + "` (`" + fieldPlayerID + "` INT UNSIGNED NOT NULL AUTO_INCREMENT,`" + fieldPlayerName + "` CHAR(16) NOT NULL, PRIMARY KEY (`" + fieldPlayerID + "`));");
res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + tablePlayers + "' AND COLUMN_NAME = '" + fieldName + "' AND COLUMN_KEY='UNI';"); res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + tablePlayers + "' AND COLUMN_NAME = '" + fieldPlayerName + "' AND COLUMN_KEY='UNI';");
if(!res.next()) if(!res.next())
{ {
stmt.execute("ALTER TABLE `" + tablePlayers + "` ADD UNIQUE INDEX `" + fieldName + "_UNIQUE` (`" + fieldName + "` ASC);"); stmt.execute("ALTER TABLE `" + tablePlayers + "` ADD UNIQUE INDEX `" + fieldPlayerName + "_UNIQUE` (`" + fieldPlayerName + "` ASC);");
} }
res.close(); res.close();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2014-2016 GeorgH93 * Copyright (C) 2016 GeorgH93
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -15,10 +15,12 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package at.pcgamingfreaks.Minepacks.Database; package at.pcgamingfreaks.Minepacks.Bukkit.Database;
import at.pcgamingfreaks.Minepacks.Backpack; import at.pcgamingfreaks.Database.DBTools;
import at.pcgamingfreaks.Minepacks.Minepacks; import at.pcgamingfreaks.Minepacks.Bukkit.API.Callback;
import at.pcgamingfreaks.Minepacks.Bukkit.Backpack;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import at.pcgamingfreaks.UUIDConverter; import at.pcgamingfreaks.UUIDConverter;
import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariConfig;
@ -37,8 +39,8 @@ public abstract class SQL extends Database
private HikariDataSource dataSource; private HikariDataSource dataSource;
protected String tablePlayers, tableBackpacks; // Table Names protected String tablePlayers, tableBackpacks; // Table Names
protected String fieldName, fieldPlayerID, fieldUUID, fieldBpOwner, fieldBpIts, fieldBpVersion, fieldBpLastUpdate; // Table Fields protected String fieldPlayerName, fieldPlayerID, fieldPlayerUUID, fieldBpOwner, fieldBpIts, fieldBpVersion, fieldBpLastUpdate; // Table Fields
protected String queryUpdatePlayerAdd, queryGetPlayerID, queryInsertBP, queryUpdateBP, queryGetBP, queryDeleteOldBackpacks, queryGetUnsetOrInvalidUUIDs, queryFixUUIDs; // DB Querys protected String queryUpdatePlayerAdd, queryGetPlayerID, queryInsertBp, queryUpdateBp, queryGetBP, queryDeleteOldBackpacks, queryGetUnsetOrInvalidUUIDs, queryFixUUIDs; // DB Querys
protected boolean updatePlayer; protected boolean updatePlayer;
public SQL(Minepacks mp) public SQL(Minepacks mp)
@ -82,8 +84,8 @@ protected void loadSettings()
tablePlayers = plugin.config.getUserTable(); tablePlayers = plugin.config.getUserTable();
tableBackpacks = plugin.config.getBackpackTable(); tableBackpacks = plugin.config.getBackpackTable();
fieldPlayerID = plugin.config.getDBFields("User.Player_ID"); fieldPlayerID = plugin.config.getDBFields("User.Player_ID");
fieldName = plugin.config.getDBFields("User.Name"); fieldPlayerName = plugin.config.getDBFields("User.Name");
fieldUUID = plugin.config.getDBFields("User.UUID"); fieldPlayerUUID = plugin.config.getDBFields("User.UUID");
fieldBpOwner = plugin.config.getDBFields("Backpack.Owner_ID"); fieldBpOwner = plugin.config.getDBFields("Backpack.Owner_ID");
fieldBpIts = plugin.config.getDBFields("Backpack.ItemStacks"); fieldBpIts = plugin.config.getDBFields("Backpack.ItemStacks");
fieldBpVersion = plugin.config.getDBFields("Backpack.Version"); fieldBpVersion = plugin.config.getDBFields("Backpack.Version");
@ -94,6 +96,7 @@ protected void loadSettings()
@Override @Override
public void close() public void close()
{ {
super.close();
dataSource.close(); dataSource.close();
} }
@ -120,12 +123,12 @@ public UpdateData(String uuid, int id)
{ {
if(res.isFirst()) if(res.isFirst())
{ {
plugin.log.info(START_UUID_UPDATE); plugin.getLogger().info(START_UUID_UPDATE);
} }
String uuid = res.getString(fieldUUID); String uuid = res.getString(fieldPlayerUUID);
if(uuid == null) if(uuid == null)
{ {
toConvert.put(res.getString(fieldName).toLowerCase(), new UpdateData(null, res.getInt(fieldPlayerID))); toConvert.put(res.getString(fieldPlayerName).toLowerCase(), new UpdateData(null, res.getInt(fieldPlayerID)));
} }
else else
{ {
@ -156,7 +159,7 @@ public UpdateData(String uuid, int id)
ps.executeBatch(); ps.executeBatch();
} }
} }
plugin.log.info(String.format(UUIDS_UPDATED, toUpdate.size())); plugin.getLogger().info(String.format(UUIDS_UPDATED, toUpdate.size()));
} }
} }
catch(SQLException e) catch(SQLException e)
@ -188,13 +191,13 @@ protected final void buildQuerys()
queryGetPlayerID = "SELECT `{FieldPlayerID}` FROM `{TablePlayers}` WHERE `{FieldName}`=?;"; queryGetPlayerID = "SELECT `{FieldPlayerID}` FROM `{TablePlayers}` WHERE `{FieldName}`=?;";
queryGetBP += "`{FieldName}`=?;"; queryGetBP += "`{FieldName}`=?;";
} }
queryInsertBP = "INSERT INTO `{TableBackpacks}` (`{FieldBPOwner}`,`{FieldBPITS}`,`{FieldBPVersion}`) VALUES (?,?,?);"; queryInsertBp = "INSERT INTO `{TableBackpacks}` (`{FieldBPOwner}`,`{FieldBPITS}`,`{FieldBPVersion}`) VALUES (?,?,?);";
queryUpdateBP = "UPDATE `{TableBackpacks}` SET `{FieldBPITS}`=?,`{FieldBPVersion}`=?"; queryUpdateBp = "UPDATE `{TableBackpacks}` SET `{FieldBPITS}`=?,`{FieldBPVersion}`=?";
if(maxAge > 0) if(maxAge > 0)
{ {
queryUpdateBP += ",`{FieldBPLastUpdate}`={NOW}"; queryUpdateBp += ",`{FieldBPLastUpdate}`={NOW}";
} }
queryUpdateBP += " WHERE `{FieldBPOwner}`=?;"; queryUpdateBp += " WHERE `{FieldBPOwner}`=?;";
queryDeleteOldBackpacks = "DELETE FROM `{TableBackpacks}` WHERE `{FieldBPLastUpdate}` < DATE('now', '-{VarMaxAge} days')"; queryDeleteOldBackpacks = "DELETE FROM `{TableBackpacks}` WHERE `{FieldBPLastUpdate}` < DATE('now', '-{VarMaxAge} days')";
if(useUUIDSeparators) if(useUUIDSeparators)
{ {
@ -208,19 +211,32 @@ protected final void buildQuerys()
updateQuerysForDialect(); updateQuerysForDialect();
setTableAndFieldNames();
}
protected void setTableAndFieldNames()
{
// Replace the table and filed names with the names from the config // Replace the table and filed names with the names from the config
queryUpdatePlayerAdd = queryUpdatePlayerAdd.replaceAll("\\{TablePlayers\\}", tablePlayers).replaceAll("\\{FieldName\\}", fieldName).replaceAll("\\{FieldUUID\\}", fieldUUID).replaceAll("\\{FieldPlayerID\\}", fieldPlayerID); queryUpdatePlayerAdd = replacePlaceholders(queryUpdatePlayerAdd);
queryGetPlayerID = queryGetPlayerID.replaceAll("\\{TablePlayers\\}", tablePlayers).replaceAll("\\{FieldName\\}", fieldName).replaceAll("\\{FieldUUID\\}", fieldUUID).replaceAll("\\{FieldPlayerID\\}", fieldPlayerID); queryGetPlayerID = replacePlaceholders(queryGetPlayerID);
queryGetBP = queryGetBP.replaceAll("\\{FieldBPOwner\\}", fieldBpOwner).replaceAll("\\{FieldBPITS\\}", fieldBpIts).replaceAll("\\{FieldBPVersion\\}", fieldBpVersion).replaceAll("\\{TableBackpacks\\}", tableBackpacks).replaceAll("\\{TablePlayers\\}", tablePlayers).replaceAll("\\{FieldPlayerID\\}", fieldPlayerID).replaceAll("\\{FieldName\\}", fieldName).replaceAll("\\{FieldUUID\\}", fieldUUID); queryGetBP = replacePlaceholders(queryGetBP);
queryInsertBP = queryInsertBP.replaceAll("\\{TableBackpacks\\}", tableBackpacks).replaceAll("\\{FieldBPOwner\\}", fieldBpOwner).replaceAll("\\{FieldBPITS\\}", fieldBpIts).replaceAll("\\{FieldBPVersion\\}", fieldBpVersion).replaceAll("\\{FieldBPLastUpdate\\}", fieldBpLastUpdate); queryInsertBp = replacePlaceholders(queryInsertBp);
queryUpdateBP = queryUpdateBP.replaceAll("\\{TableBackpacks\\}", tableBackpacks).replaceAll("\\{FieldBPOwner\\}", fieldBpOwner).replaceAll("\\{FieldBPITS\\}", fieldBpIts).replaceAll("\\{FieldBPVersion\\}", fieldBpVersion).replaceAll("\\{FieldBPLastUpdate\\}", fieldBpLastUpdate); queryUpdateBp = replacePlaceholders(queryUpdateBp);
queryDeleteOldBackpacks = queryDeleteOldBackpacks.replaceAll("\\{TableBackpacks\\}", tableBackpacks).replaceAll("\\{FieldBPLastUpdate\\}", fieldBpLastUpdate).replaceAll("\\{VarMaxAge\\}", maxAge + ""); queryFixUUIDs = replacePlaceholders(queryFixUUIDs);
queryGetUnsetOrInvalidUUIDs = queryGetUnsetOrInvalidUUIDs.replaceAll("\\{TablePlayers\\}", tablePlayers).replaceAll("\\{FieldName\\}", fieldName).replaceAll("\\{FieldUUID\\}", fieldUUID).replaceAll("\\{FieldPlayerID\\}", fieldPlayerID); queryDeleteOldBackpacks = replacePlaceholders(queryDeleteOldBackpacks.replaceAll("\\{VarMaxAge}", maxAge + ""));
queryFixUUIDs = queryFixUUIDs.replaceAll("\\{TablePlayers\\}", tablePlayers).replaceAll("\\{FieldUUID\\}", fieldUUID).replaceAll("\\{FieldPlayerID\\}", fieldPlayerID); queryGetUnsetOrInvalidUUIDs = replacePlaceholders(queryGetUnsetOrInvalidUUIDs);
} }
protected abstract void updateQuerysForDialect(); protected abstract void updateQuerysForDialect();
protected String replacePlaceholders(String query)
{
return query.replaceAll("(\\{\\w+})", "`$1`").replaceAll("`(\\{\\w+})`_(\\w+)", "`$1_$2`").replaceAll("fk_`(\\{\\w+})`_`(\\{\\w+})`_`(\\{\\w+})`", "`fk_$1_$2_$3`") // Fix name formatting
.replaceAll("\\{TablePlayers}", tablePlayers).replaceAll("\\{FieldName}", fieldPlayerName).replaceAll("\\{FieldUUID}", fieldPlayerUUID).replaceAll("\\{FieldPlayerID}", fieldPlayerID) // Players
.replaceAll("\\{TableBackpacks}", tableBackpacks).replaceAll("\\{FieldBPOwner}", fieldBpOwner).replaceAll("\\{FieldBPITS}", fieldBpIts) // Backpacks
.replaceAll("\\{FieldBPVersion}", fieldBpVersion).replaceAll("\\{FieldBPLastUpdate}", fieldBpLastUpdate); // Backpacks
}
protected void runStatementAsync(final String query, final Object... args) protected void runStatementAsync(final String query, final Object... args)
{ {
Bukkit.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() Bukkit.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable()
@ -289,6 +305,7 @@ public void run()
if(rs.next()) if(rs.next())
{ {
newID = rs.getInt(1); newID = rs.getInt(1);
DBTools.runStatement(connection, queryInsertBp, data, usedSerializer, id);
plugin.getServer().getScheduler().runTask(plugin, new Runnable() plugin.getServer().getScheduler().runTask(plugin, new Runnable()
{ {
@Override @Override
@ -300,32 +317,14 @@ public void run()
} }
else else
{ {
newID = -1; plugin.getLogger().warning("Failed saving backpack for: " + name + " (Unable to get players ID from database)");
} }
} }
} }
if(newID <= 0)
{
plugin.log.warning("Failed saving backpack for: " + name + " (Unable to get players ID from database)");
return;
}
try(PreparedStatement ps = connection.prepareStatement(queryInsertBP))
{
ps.setInt(1, newID);
ps.setBytes(2, data);
ps.setInt(3, usedSerializer);
ps.execute();
}
} }
else else
{ {
try(PreparedStatement ps = connection.prepareStatement(queryUpdateBP)) DBTools.runStatement(connection, queryUpdateBp, data, usedSerializer, id);
{
ps.setBytes(1, data);
ps.setInt(2, usedSerializer);
ps.setInt(3, id);
ps.execute();
}
} }
} }
catch(SQLException e) catch(SQLException e)
@ -369,7 +368,7 @@ public void run()
@Override @Override
public void run() public void run()
{ {
ItemStack[] its = (data != null) ? itsSerializer.deserialize(data, version) : null; ItemStack[] its = itsSerializer.deserialize(data, version);
if(its != null) if(its != null)
{ {
callback.onResult(new Backpack(player, its, bpID)); callback.onResult(new Backpack(player, its, bpID));
@ -384,7 +383,7 @@ public void run()
catch(SQLException e) catch(SQLException e)
{ {
e.printStackTrace(); e.printStackTrace();
callback.onFail(); callback.onFail(); //TODO sync with main thread
} }
} }
}); });

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2014-2016 GeorgH93 * Copyright (C) 2016 GeorgH93
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -15,9 +15,9 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package at.pcgamingfreaks.Minepacks.Database; package at.pcgamingfreaks.Minepacks.Bukkit.Database;
import at.pcgamingfreaks.Minepacks.Minepacks; import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariConfig;
@ -42,8 +42,8 @@ protected void loadSettings()
{ {
// Set table and field names to fixed values to prevent users from destroying old databases. // Set table and field names to fixed values to prevent users from destroying old databases.
fieldPlayerID = "player_id"; fieldPlayerID = "player_id";
fieldName = "name"; fieldPlayerName = "name";
fieldUUID = "uuid"; fieldPlayerUUID = "uuid";
fieldBpOwner = "owner"; fieldBpOwner = "owner";
//noinspection SpellCheckingInspection //noinspection SpellCheckingInspection
fieldBpIts = "itemstacks"; fieldBpIts = "itemstacks";
@ -80,10 +80,10 @@ protected void updateQuerysForDialect()
{ {
if(maxAge > 0) if(maxAge > 0)
{ {
queryInsertBP = queryInsertBP.replaceAll("\\) VALUES \\(\\?,\\?,\\?", "{FieldBPLastUpdate}) VALUES (?,?,?,DATE('now')"); queryInsertBp = queryInsertBp.replaceAll("\\) VALUES \\(\\?,\\?,\\?", "{FieldBPLastUpdate}) VALUES (?,?,?,DATE('now')");
} }
queryDeleteOldBackpacks = "DELETE FROM `{TableBackpacks}` WHERE `{FieldBPLastUpdate}` < DATE('now', '-{VarMaxAge} days')"; queryDeleteOldBackpacks = "DELETE FROM `{TableBackpacks}` WHERE `{FieldBPLastUpdate}` < DATE('now', '-{VarMaxAge} days')";
queryUpdateBP = queryUpdateBP.replaceAll("\\{NOW\\}", "DATE('now')"); queryUpdateBp = queryUpdateBp.replaceAll("\\{NOW\\}", "DATE('now')");
if(useUUIDs) if(useUUIDs)
{ {
queryUpdatePlayerAdd = "INSERT OR IGNORE INTO `{TablePlayers}` (`{FieldName}`,`{FieldUUID}`) VALUES (?,?);"; queryUpdatePlayerAdd = "INSERT OR IGNORE INTO `{TablePlayers}` (`{FieldName}`,`{FieldUUID}`) VALUES (?,?);";
@ -94,6 +94,7 @@ protected void updateQuerysForDialect()
} }
} }
@SuppressWarnings("SqlResolve")
@Override @Override
protected void checkDB() protected void checkDB()
{ {
@ -122,9 +123,7 @@ protected void checkDB()
rs.next(); rs.next();
stmt.execute("ALTER TABLE `backpacks` ADD COLUMN `lastupdate` DATE DEFAULT '" + rs.getString(1) + "';"); stmt.execute("ALTER TABLE `backpacks` ADD COLUMN `lastupdate` DATE DEFAULT '" + rs.getString(1) + "';");
} }
catch(SQLException ignored) catch(SQLException ignored) {}
{
}
} }
} }
catch(SQLException e) catch(SQLException e)
@ -143,7 +142,7 @@ public void updatePlayer(final Player player)
public void run() public void run()
{ {
runStatement(queryUpdatePlayerAdd, player.getName(), getPlayerFormattedUUID(player)); runStatement(queryUpdatePlayerAdd, player.getName(), getPlayerFormattedUUID(player));
runStatement("UPDATE `" + tablePlayers + "` SET `" + fieldName + "`=? WHERE `" + fieldUUID + "`=?;", player.getName(), getPlayerFormattedUUID(player)); runStatement("UPDATE `" + tablePlayers + "` SET `" + fieldPlayerName + "`=? WHERE `" + fieldPlayerUUID + "`=?;", player.getName(), getPlayerFormattedUUID(player));
} }
}); });
} }

View File

@ -0,0 +1,54 @@
/*
* Copyright (C) 2016 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 <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks.Bukkit.Database.UnCacheStrategies;
import at.pcgamingfreaks.Minepacks.Bukkit.Backpack;
import at.pcgamingfreaks.Minepacks.Bukkit.Database.Database;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import org.bukkit.Bukkit;
public class Interval extends UnCacheStrategie implements Runnable
{
private final int taskID;
public Interval(Database cache)
{
super(cache);
taskID = Bukkit.getScheduler().scheduleSyncRepeatingTask(Minepacks.getInstance(), this, Minepacks.getInstance().getConfiguration().getUnCacheDelay(), Minepacks.getInstance().getConfiguration().getUnCacheInterval());
}
@Override
public void run()
{
for(Backpack backpack : cache.getLoadedBackpacks())
{
if(!backpack.getOwner().isOnline() && !backpack.isOpen())
{
this.cache.unloadBackpack(backpack);
}
}
}
@Override
public void close()
{
Bukkit.getScheduler().cancelTask(taskID);
super.close();
}
}

View File

@ -0,0 +1,58 @@
/*
* Copyright (C) 2016 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 <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks.Bukkit.Database.UnCacheStrategies;
import at.pcgamingfreaks.Minepacks.Bukkit.Backpack;
import at.pcgamingfreaks.Minepacks.Bukkit.Database.Database;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import org.bukkit.Bukkit;
public class IntervalChecked extends UnCacheStrategie implements Runnable
{
private final long delay;
private final int taskID;
public IntervalChecked(Database cache)
{
super(cache);
long delay = Minepacks.getInstance().getConfiguration().getUnCacheDelay();
taskID = Bukkit.getScheduler().scheduleSyncRepeatingTask(Minepacks.getInstance(), this, delay, Minepacks.getInstance().getConfiguration().getUnCacheInterval());
this.delay = delay * 50L;
}
@Override
public void run()
{
long currentTime = System.currentTimeMillis() - delay;
for(Backpack backpack : cache.getLoadedBackpacks())
{
if(!backpack.getOwner().isOnline() && backpack.getOwner().getPlayer().getLastPlayed() < currentTime && !backpack.isOpen())
{
this.cache.unloadBackpack(backpack);
}
}
}
@Override
public void close()
{
Bukkit.getScheduler().cancelTask(taskID);
super.close();
}
}

View File

@ -0,0 +1,55 @@
/*
* Copyright (C) 2016 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 <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks.Bukkit.Database.UnCacheStrategies;
import at.pcgamingfreaks.Minepacks.Bukkit.Backpack;
import at.pcgamingfreaks.Minepacks.Bukkit.Database.Database;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
public class OnDisconnect extends UnCacheStrategie implements Listener
{
public OnDisconnect(Database cache)
{
super(cache);
Bukkit.getPluginManager().registerEvents(this, Minepacks.getInstance());
}
@EventHandler(priority = EventPriority.MONITOR)
public void playerLeaveEvent(PlayerQuitEvent event)
{
Backpack backpack = cache.getBackpack(event.getPlayer());
if(backpack != null && !backpack.isOpen())
{
backpack.save();
cache.unloadBackpack(backpack);
}
}
@Override
public void close()
{
HandlerList.unregisterAll(this);
}
}

View File

@ -0,0 +1,73 @@
/*
* Copyright (C) 2016 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 <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks.Bukkit.Database.UnCacheStrategies;
import at.pcgamingfreaks.Minepacks.Bukkit.Backpack;
import at.pcgamingfreaks.Minepacks.Bukkit.Database.Database;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.scheduler.BukkitRunnable;
public class OnDisconnectDelayed extends UnCacheStrategie implements Listener
{
private final long delay;
public OnDisconnectDelayed(Database cache)
{
super(cache);
delay = Minepacks.getInstance().getConfiguration().getUnCacheDelay();
Bukkit.getPluginManager().registerEvents(this, Minepacks.getInstance());
}
@EventHandler(priority = EventPriority.MONITOR)
public void playerLeaveEvent(PlayerQuitEvent event)
{
final Backpack backpack = cache.getBackpack(event.getPlayer());
if(backpack != null) // We only uncache unmarried player.
{
new BukkitRunnable()
{
@Override
public void run()
{
if(!backpack.isOpen())
{
backpack.save();
cache.unloadBackpack(backpack);
}
else
{
this.runTaskLater(Minepacks.getInstance(), delay);
}
}
}.runTaskLater(Minepacks.getInstance(), delay);
}
}
@Override
public void close()
{
HandlerList.unregisterAll(this);
}
}

View File

@ -0,0 +1,47 @@
/*
* Copyright (C) 2016 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 <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks.Bukkit.Database.UnCacheStrategies;
import at.pcgamingfreaks.Minepacks.Bukkit.Database.Database;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
public abstract class UnCacheStrategie
{
protected Database cache;
public UnCacheStrategie(Database cache)
{
this.cache = cache;
}
public static UnCacheStrategie getUnCacheStrategie(Database cache)
{
switch(Minepacks.getInstance().getConfiguration().getUnCacheStrategie())
{
case "ondisconnect": return new OnDisconnect(cache);
case "ondisconnectdelayed": return new OnDisconnectDelayed(cache);
case "intervalChecked": return new IntervalChecked(cache);
case "interval": default: return new Interval(cache);
}
}
public void close()
{
cache = null;
}
}

View File

@ -1,21 +1,21 @@
/* /*
* Copyright (C) 2014-2016 GeorgH93 * Copyright (C) 2016 GeorgH93
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package at.pcgamingfreaks.Minepacks; package at.pcgamingfreaks.Minepacks.Bukkit;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
@ -35,7 +35,7 @@ public class ItemsCollector extends BukkitRunnable
public ItemsCollector(Minepacks plugin) public ItemsCollector(Minepacks plugin)
{ {
this.plugin = plugin; this.plugin = plugin;
radius = this.plugin.config.getFullInvRadius(); this.radius = plugin.config.getFullInvRadius();
} }
@Override @Override
@ -46,7 +46,7 @@ public void run()
if(player.getInventory().firstEmpty() == -1 && player.hasPermission("backpack") && player.hasPermission("backpack.fullpickup")) if(player.getInventory().firstEmpty() == -1 && player.hasPermission("backpack") && player.hasPermission("backpack.fullpickup"))
{ {
// Only check loaded backpacks (loading them would take to much time for a repeating task, the will be loaded async soon enough) // Only check loaded backpacks (loading them would take to much time for a repeating task, the will be loaded async soon enough)
Backpack backpack = plugin.DB.getBackpack(player); Backpack backpack = plugin.getBackpackCachedOnly(player);
if(backpack == null) if(backpack == null)
{ {
continue; continue;

View File

@ -0,0 +1,152 @@
/*
* Copyright (C) 2016 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 <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks.Bukkit.Listener;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.*;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.inventory.*;
public class DisableShulkerboxes extends ShulkerboxesListener implements Listener
{
public DisableShulkerboxes(final Minepacks plugin)
{
super(plugin);
}
@EventHandler(ignoreCancelled = true)
public void onCraft(CraftItemEvent event)
{
if(event.getCurrentItem() != null && SHULKER_BOX_MATERIALS.contains(event.getCurrentItem().getType()))
{
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event)
{
if(event.getCurrentItem() != null && SHULKER_BOX_MATERIALS.contains(event.getCurrentItem().getType()))
{
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onInventoryOpen(InventoryOpenEvent event)
{
if(event.getInventory().getHolder().getClass().getName().toLowerCase().contains("shulker"))
{
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onItemMove(InventoryMoveItemEvent event)
{
if(SHULKER_BOX_MATERIALS.contains(event.getItem().getType()))
{
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onItemMove(InventoryDragEvent event)
{
if(SHULKER_BOX_MATERIALS.contains(event.getCursor().getType()))
{
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPickup(InventoryPickupItemEvent event)
{
if(SHULKER_BOX_MATERIALS.contains(event.getItem().getItemStack().getType()))
{
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onItemSpawn(ItemSpawnEvent event)
{
if(SHULKER_BOX_MATERIALS.contains(event.getEntity().getItemStack().getType()))
{
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event)
{
if(SHULKER_BOX_MATERIALS.contains(event.getBlockPlaced().getType()))
{
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event)
{
if(SHULKER_BOX_MATERIALS.contains(event.getBlock().getType()))
{
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockIgnite(BlockIgniteEvent event)
{
if(SHULKER_BOX_MATERIALS.contains(event.getBlock().getType()))
{
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockCanBuild(BlockCanBuildEvent event)
{
if(SHULKER_BOX_MATERIALS.contains(event.getBlock().getType()))
{
event.setBuildable(false);
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockDispense(BlockDispenseEvent event)
{
if(SHULKER_BOX_MATERIALS.contains(event.getBlock().getType()))
{
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockBreak(BlockMultiPlaceEvent event)
{
if(SHULKER_BOX_MATERIALS.contains(event.getBlock().getType()))
{
event.setCancelled(true);
}
}
}

View File

@ -0,0 +1,69 @@
/*
* Copyright (C) 2016 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 <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks.Bukkit.Listener;
import at.pcgamingfreaks.Minepacks.Bukkit.API.Callback;
import at.pcgamingfreaks.Minepacks.Bukkit.Backpack;
import at.pcgamingfreaks.Minepacks.Bukkit.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.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
public class DropOnDeath implements Listener
{
private final Minepacks plugin;
public DropOnDeath(Minepacks plugin)
{
this.plugin = plugin;
}
@EventHandler
public void onDeath(PlayerDeathEvent event)
{
final Player player = event.getEntity();
if (!player.hasPermission("backpack.keepOnDeath"))
{
plugin.getBackpack(player, new Callback<Backpack>()
{
@Override
public void onResult(Backpack backpack)
{
Inventory backpackInventory = backpack.getInventory();
for(ItemStack i : backpackInventory.getContents())
{
if(i != null)
{
player.getWorld().dropItemNaturally(player.getLocation(), i);
backpackInventory.remove(i);
backpack.setChanged();
}
}
backpack.save();
}
@Override
public void onFail() {}
});
}
}
}

View File

@ -0,0 +1,95 @@
/*
* Copyright (C) 2016 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 <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks.Bukkit.Listener;
import at.pcgamingfreaks.Bukkit.Message.Message;
import at.pcgamingfreaks.Minepacks.Bukkit.Backpack;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerQuitEvent;
public class EventListener implements Listener
{
private Minepacks plugin;
private Message messageOwnBackpackClose, messageOtherBackpackClose;
public EventListener(Minepacks mp)
{
plugin = mp;
messageOwnBackpackClose = plugin.lang.getMessage("Ingame.OwnBackPackClose");
messageOtherBackpackClose = plugin.lang.getMessage("Ingame.PlayerBackPackClose").replaceAll("\\{OwnerName\\}", "%1\\$s").replaceAll("\\{OwnerDisplayName\\}", "%2\\$s");
}
@EventHandler
public void onClose(InventoryCloseEvent event)
{
if (event.getInventory() != null && event.getInventory().getHolder() instanceof Backpack && event.getPlayer() instanceof Player)
{
Backpack backpack = (Backpack)event.getInventory().getHolder();
Player closer = (Player)event.getPlayer();
if(backpack.canEdit(closer))
{
backpack.save();
}
backpack.close(closer);
if(event.getPlayer().getUniqueId().equals(backpack.getOwner().getUniqueId()))
{
messageOwnBackpackClose.send(closer);
}
else
{
OfflinePlayer owner = backpack.getOwner();
messageOtherBackpackClose.send(closer, owner.getName(), owner.isOnline() ? owner.getPlayer().getDisplayName() : ChatColor.GRAY + owner.getName());
}
}
}
@EventHandler
public void onClick(InventoryClickEvent event)
{
if (event.getInventory() != null && event.getInventory().getHolder() instanceof Backpack && event.getWhoClicked() instanceof Player)
{
Backpack backpack = (Backpack) event.getInventory().getHolder();
if(!backpack.canEdit((Player)event.getWhoClicked()))
{
event.setCancelled(true);
}
else
{
backpack.setChanged();
}
}
}
@EventHandler
public void onPlayerLeaveEvent(PlayerQuitEvent event)
{
if(plugin.cooldowns.containsKey(event.getPlayer()))
{
plugin.cooldowns.remove(event.getPlayer());
}
}
}

View File

@ -0,0 +1,59 @@
/*
* Copyright (C) 2016 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 <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks.Bukkit.Listener;
import at.pcgamingfreaks.Bukkit.Message.Message;
import at.pcgamingfreaks.Minepacks.Bukkit.API.Backpack;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
public class PreventShulkerboxesInBackpack extends ShulkerboxesListener implements Listener
{
private final Message messageNotAllowedInBackpack;
public PreventShulkerboxesInBackpack(final Minepacks plugin)
{
super(plugin);
messageNotAllowedInBackpack = plugin.lang.getMessage("Ingame.Shulkerboxes.NotAllowedInBackpack");
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onItemMove(InventoryMoveItemEvent event)
{
if(event.getDestination().getHolder() instanceof Backpack && SHULKER_BOX_MATERIALS.contains(event.getItem().getType()))
{
//TODO get player and send him a message
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onItemMove(InventoryDragEvent event)
{
if(event.getInventory().getHolder() instanceof Backpack && SHULKER_BOX_MATERIALS.contains(event.getCursor().getType()))
{
//TODO get player and send him a message
event.setCancelled(true);
}
}
}

View File

@ -0,0 +1,57 @@
/*
* Copyright (C) 2016 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 <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks.Bukkit.Listener;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import org.bukkit.Material;
import java.util.HashSet;
import java.util.Set;
class ShulkerboxesListener
{
protected static final Set<Material> SHULKER_BOX_MATERIALS = new HashSet<>();
protected final Minepacks plugin;
static
{
SHULKER_BOX_MATERIALS.add(Material.BLACK_SHULKER_BOX);
SHULKER_BOX_MATERIALS.add(Material.BLUE_SHULKER_BOX);
SHULKER_BOX_MATERIALS.add(Material.SILVER_SHULKER_BOX);
SHULKER_BOX_MATERIALS.add(Material.BROWN_SHULKER_BOX);
SHULKER_BOX_MATERIALS.add(Material.CYAN_SHULKER_BOX);
SHULKER_BOX_MATERIALS.add(Material.GREEN_SHULKER_BOX);
SHULKER_BOX_MATERIALS.add(Material.GRAY_SHULKER_BOX);
SHULKER_BOX_MATERIALS.add(Material.LIGHT_BLUE_SHULKER_BOX);
SHULKER_BOX_MATERIALS.add(Material.LIME_SHULKER_BOX);
SHULKER_BOX_MATERIALS.add(Material.MAGENTA_SHULKER_BOX);
SHULKER_BOX_MATERIALS.add(Material.ORANGE_SHULKER_BOX);
SHULKER_BOX_MATERIALS.add(Material.PINK_SHULKER_BOX);
SHULKER_BOX_MATERIALS.add(Material.PURPLE_SHULKER_BOX);
SHULKER_BOX_MATERIALS.add(Material.RED_SHULKER_BOX);
SHULKER_BOX_MATERIALS.add(Material.WHITE_SHULKER_BOX);
SHULKER_BOX_MATERIALS.add(Material.YELLOW_SHULKER_BOX);
}
protected ShulkerboxesListener(Minepacks plugin)
{
this.plugin = plugin;
}
}

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2014-2016 GeorgH93 * Copyright (C) 2016 GeorgH93
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -15,39 +15,50 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package at.pcgamingfreaks.Minepacks; package at.pcgamingfreaks.Minepacks.Bukkit;
import at.pcgamingfreaks.Bukkit.MCVersion; import at.pcgamingfreaks.Bukkit.MCVersion;
import at.pcgamingfreaks.Bukkit.Message.Message;
import at.pcgamingfreaks.Bukkit.Updater; import at.pcgamingfreaks.Bukkit.Updater;
import at.pcgamingfreaks.Bukkit.Utils; import at.pcgamingfreaks.Bukkit.Utils;
import at.pcgamingfreaks.ConsoleColor; import at.pcgamingfreaks.ConsoleColor;
import at.pcgamingfreaks.Minepacks.Database.Config; import at.pcgamingfreaks.Minepacks.Bukkit.API.Callback;
import at.pcgamingfreaks.Minepacks.Database.Database; import at.pcgamingfreaks.Minepacks.Bukkit.API.MinepacksPlugin;
import at.pcgamingfreaks.Minepacks.Database.Language; import at.pcgamingfreaks.Minepacks.Bukkit.Database.Config;
import at.pcgamingfreaks.Minepacks.Bukkit.Database.Language;
import at.pcgamingfreaks.Minepacks.Bukkit.Listener.DisableShulkerboxes;
import at.pcgamingfreaks.Minepacks.Bukkit.Database.Database;
import at.pcgamingfreaks.Minepacks.Bukkit.Listener.DropOnDeath;
import at.pcgamingfreaks.Minepacks.Bukkit.Listener.EventListener;
import at.pcgamingfreaks.Minepacks.Bukkit.Listener.PreventShulkerboxesInBackpack;
import at.pcgamingfreaks.StringUtils; import at.pcgamingfreaks.StringUtils;
import at.pcgamingfreaks.Version;
import org.apache.commons.lang3.Validate;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.ServicePriority; import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap; import java.util.HashMap;
import java.util.logging.Logger;
public class Minepacks extends JavaPlugin public class Minepacks extends JavaPlugin implements MinepacksPlugin
{ {
private static Version version = new Version("2.0-SNAPSHOT");
private static Minepacks instance = null; private static Minepacks instance = null;
public Logger log;
public Config config; public Config config;
public Language lang; public Language lang;
public Database DB; private Database database;
public HashMap<Player, Long> cooldowns = new HashMap<>(); public HashMap<Player, Long> cooldowns = new HashMap<>();
public String backpackTitleOther, backpackTitle; public String backpackTitleOther, backpackTitle;
public String messageInvalidBackpack; public Message messageNoPermission, messageInvalidBackpack;
private int maxSize; private int maxSize;
@ -56,12 +67,17 @@ public static Minepacks getInstance()
return instance; return instance;
} }
@Override
public Version getVersion()
{
return version;
}
@Override @Override
public void onEnable() public void onEnable()
{ {
log = getLogger(); Utils.warnOnJava_1_7(getLogger());
Utils.warnOnJava_1_7(log); version = new Version(getDescription().getVersion());
instance = this;
//region Check compatibility with used minecraft version //region Check compatibility with used minecraft version
if(MCVersion.is(MCVersion.UNKNOWN) || MCVersion.isNewerThan(MCVersion.MC_NMS_1_11_R1)) if(MCVersion.is(MCVersion.UNKNOWN) || MCVersion.isNewerThan(MCVersion.MC_NMS_1_11_R1))
{ {
@ -72,12 +88,20 @@ public void onEnable()
return; return;
} }
//endregion //endregion
instance = this;
config = new Config(this); config = new Config(this);
lang = new Language(this); lang = new Language(this);
lang.load(config.getLanguage(), config.getLanguageUpdateMode()); lang.load(config.getLanguage(), config.getLanguageUpdateMode());
DB = Database.getDatabase(this); database = Database.getDatabase(this);
getCommand("backpack").setExecutor(new OnCommand(this)); getCommand("backpack").setExecutor(new OnCommand(this));
getServer().getPluginManager().registerEvents(new EventListener(this), this);
//region register events
PluginManager pluginManager = getServer().getPluginManager();
pluginManager.registerEvents(new EventListener(this), this);
if(config.getDropOnDeath()) pluginManager.registerEvents(new DropOnDeath(this), this);
if(config.getShulkerboxesPreventInBackpack()) pluginManager.registerEvents(new PreventShulkerboxesInBackpack(this), this);
if(config.getShulkerboxesDisableShulkerboxes()) pluginManager.registerEvents(new DisableShulkerboxes(this), this);
//endregion
if(config.getFullInvCollect()) if(config.getFullInvCollect())
{ {
@ -87,17 +111,17 @@ public void onEnable()
maxSize = config.getBackpackMaxSize(); maxSize = config.getBackpackMaxSize();
backpackTitleOther = config.getBPTitleOther(); backpackTitleOther = config.getBPTitleOther();
backpackTitle = StringUtils.limitLength(config.getBPTitle(), 32); backpackTitle = StringUtils.limitLength(config.getBPTitle(), 32);
messageInvalidBackpack = lang.getTranslated("Ingame.InvalidBackpack"); messageNoPermission = lang.getMessage("Ingame.NoPermission");
messageInvalidBackpack = lang.getMessage("Ingame.InvalidBackpack");
getServer().getServicesManager().register(Minepacks.class, this, this, ServicePriority.Normal); getServer().getServicesManager().register(Minepacks.class, this, this, ServicePriority.Normal);
if(config.getAutoUpdate()) // Lets check for updates if(config.getAutoUpdate()) // Lets check for updates
{ {
log.info("Checking for updates ..."); getLogger().info("Checking for updates ...");
Updater updater = new Updater(this, this.getFile(), true, 83445); // Create a new updater with dev.bukkit.org as update provider Updater updater = new Updater(this, this.getFile(), true, 83445); // Create a new updater with dev.bukkit.org as update provider
updater.update(); // Starts the update updater.update(); // Starts the update
} }
StringUtils.getPluginEnabledMessage(getDescription().getName());
log.info(lang.get(ConsoleColor.GREEN + "Minepacks has been enabled! " + ConsoleColor.YELLOW + ":)"));
} }
@Override @Override
@ -106,32 +130,41 @@ public void onDisable()
Updater updater = null; Updater updater = null;
if(config.getAutoUpdate()) // Lets check for updates if(config.getAutoUpdate()) // Lets check for updates
{ {
log.info("Checking for updates ..."); getLogger().info("Checking for updates ...");
updater = new Updater(this, this.getFile(), true, 83445); // Create a new updater with dev.bukkit.org as update provider updater = new Updater(this, this.getFile(), true, 83445); // Create a new updater with dev.bukkit.org as update provider
updater.update(); // Starts the update, if there is a new update available it will download while we close the rest updater.update(); // Starts the update, if there is a new update available it will download while we close the rest
} }
getServer().getScheduler().cancelTasks(this); // Stop the listener, we don't need them any longer getServer().getScheduler().cancelTasks(this); // Stop the listener, we don't need them any longer
DB.close(); // Close the DB connection, we won't need them any longer database.close(); // Close the DB connection, we won't need them any longer
if(updater != null) updater.waitForAsyncOperation(); // The update can download while we kill the listeners and close the DB connections
instance = null; instance = null;
log.info(lang.get(ConsoleColor.RED + "Minepacks has been disabled. " + ConsoleColor.YELLOW + ":)")); if(updater != null) updater.waitForAsyncOperation(); // The update can download while we kill the listeners and close the DB connections
StringUtils.getPluginDisabledMessage(getDescription().getName());
} }
public void warnOnVersionIncompatibility(String version) public void warnOnVersionIncompatibility(String version)
{ {
log.warning(ConsoleColor.RED + "################################" + ConsoleColor.RESET); getLogger().warning(ConsoleColor.RED + "################################" + ConsoleColor.RESET);
log.warning(ConsoleColor.RED + String.format("Your minecraft version (MC %1$s) is currently not compatible with this plugins version (%2$s). Please check for updates!", version, getDescription().getVersion()) + ConsoleColor.RESET); getLogger().warning(ConsoleColor.RED + String.format("Your minecraft version (MC %1$s) is currently not compatible with this plugins version (%2$s). " +
log.warning(ConsoleColor.RED + "################################" + ConsoleColor.RESET); "Please check for updates!", version, getDescription().getVersion()) + ConsoleColor.RESET);
getLogger().warning(ConsoleColor.RED + "################################" + ConsoleColor.RESET);
Utils.blockThread(5); Utils.blockThread(5);
} }
public void openBackpack(final Player opener, OfflinePlayer owner, final boolean editable) public Config getConfiguration()
{ {
if(owner == null) return config;
{ }
return;
} public Database getDb()
DB.getBackpack(owner, new Database.Callback<Backpack>() {
return database;
}
@Override
public void openBackpack(@NotNull final Player opener, @NotNull final OfflinePlayer owner, final boolean editable)
{
Validate.notNull(owner);
database.getBackpack(owner, new Callback<Backpack>()
{ {
@Override @Override
public void onResult(Backpack backpack) public void onResult(Backpack backpack)
@ -144,16 +177,36 @@ public void onFail() {}
}); });
} }
public void openBackpack(Player opener, Backpack backpack, boolean editable) @Override
public void openBackpack(@NotNull final Player opener, @Nullable final Backpack backpack, boolean editable)
{ {
Validate.notNull(opener);
if(backpack == null) if(backpack == null)
{ {
opener.sendMessage(messageInvalidBackpack); messageInvalidBackpack.send(opener);
return; return;
} }
backpack.open(opener, editable); backpack.open(opener, editable);
} }
@Override
public @Nullable Backpack getBackpack(@NotNull OfflinePlayer owner)
{
return database.getBackpack(owner, false);
}
@Override
public @Nullable Backpack getBackpackCachedOnly(@NotNull OfflinePlayer owner)
{
return database.getBackpack(owner);
}
@Override
public void getBackpack(@NotNull OfflinePlayer owner, @NotNull Callback<Backpack> callback)
{
database.getBackpack(owner, callback);
}
public int getBackpackPermSize(Player player) public int getBackpackPermSize(Player player)
{ {
for(int i = maxSize; i > 1; i--) for(int i = maxSize; i > 1; i--)

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2014-2016 GeorgH93 * Copyright (C) 2016 GeorgH93
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -15,11 +15,11 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package at.pcgamingfreaks.Minepacks; package at.pcgamingfreaks.Minepacks.Bukkit;
import java.util.Date; import at.pcgamingfreaks.Bukkit.Message.Message;
import at.pcgamingfreaks.Minepacks.Bukkit.API.Callback;
import at.pcgamingfreaks.Minepacks.Database.Database;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
@ -28,21 +28,22 @@
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.Date;
public class OnCommand implements CommandExecutor public class OnCommand implements CommandExecutor
{ {
private Minepacks plugin; private Minepacks plugin;
public String Message_NotFromConsole, Message_NoPermission, Message_BackpackCleaned, Message_Cooldown; public Message messageNotFromConsole, messageBackpackCleaned, messageCooldown;
public int cooldown; public final int cooldown;
public OnCommand(Minepacks mp) public OnCommand(Minepacks mp)
{ {
plugin = mp; plugin = mp;
Message_NotFromConsole = plugin.lang.getTranslated("NotFromConsole"); messageNotFromConsole = plugin.lang.getMessage("NotFromConsole");
Message_NoPermission = plugin.lang.getTranslated("Ingame.NoPermission"); messageBackpackCleaned = plugin.lang.getMessage("Ingame.BackpackCleaned");
Message_BackpackCleaned = plugin.lang.getTranslated("Ingame.BackpackCleaned"); messageCooldown = plugin.lang.getMessage("Ingame.Cooldown");
Message_Cooldown = plugin.lang.getTranslated("Ingame.Cooldown");
cooldown = plugin.config.getCommandCooldown(); cooldown = plugin.config.getCommandCooldown();
} }
@ -57,7 +58,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String arg, String[]
} }
else else
{ {
sender.sendMessage(Message_NotFromConsole); messageNotFromConsole.send(sender);
return true; return true;
} }
if(args.length == 0) if(args.length == 0)
@ -71,7 +72,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String arg, String[]
{ {
if(((new Date()).getTime() - plugin.cooldowns.get(player)) < cooldown) if(((new Date()).getTime() - plugin.cooldowns.get(player)) < cooldown)
{ {
sender.sendMessage(Message_Cooldown); messageCooldown.send(sender);
return true; return true;
} }
} }
@ -81,7 +82,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String arg, String[]
} }
else else
{ {
player.sendMessage(Message_NoPermission); plugin.messageNoPermission.send(player);
} }
} }
else else
@ -111,7 +112,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String arg, String[]
} }
else else
{ {
player.sendMessage(Message_NoPermission); plugin.messageNoPermission.send(player);
} }
break; break;
case "empty": // Removes all items from the backpack case "empty": // Removes all items from the backpack
@ -120,7 +121,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String arg, String[]
if(player.hasPermission("backpack.clean")) if(player.hasPermission("backpack.clean"))
{ {
final OfflinePlayer OP = (args.length == 2 && player.hasPermission("backpack.clean.other")) ? Bukkit.getOfflinePlayer(args[1]) : player; final OfflinePlayer OP = (args.length == 2 && player.hasPermission("backpack.clean.other")) ? Bukkit.getOfflinePlayer(args[1]) : player;
plugin.DB.getBackpack(OP, new Database.Callback<Backpack>() plugin.getBackpack(OP, new Callback<Backpack>()
{ {
@Override @Override
public void onResult(Backpack backpack) public void onResult(Backpack backpack)
@ -129,24 +130,24 @@ public void onResult(Backpack backpack)
{ {
backpack.getInventory().clear(); backpack.getInventory().clear();
backpack.save(); backpack.save();
player.sendMessage(Message_BackpackCleaned); messageBackpackCleaned.send(player);
} }
else else
{ {
player.sendMessage(plugin.messageInvalidBackpack); plugin.messageInvalidBackpack.send(player);
} }
} }
@Override @Override
public void onFail() public void onFail()
{ {
player.sendMessage(plugin.messageInvalidBackpack); plugin.messageInvalidBackpack.send(player);
} }
}); });
} }
else else
{ {
player.sendMessage(Message_NoPermission); plugin.messageNoPermission.send(player);
} }
break; break;
default: // Shows the backpack of an other player default: // Shows the backpack of an other player
@ -156,7 +157,7 @@ public void onFail()
} }
else else
{ {
player.sendMessage(Message_NoPermission); plugin.messageNoPermission.send(player);
} }
break; break;
} }

View File

@ -1,151 +0,0 @@
/*
* Copyright (C) 2014-2016 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 <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks;
import at.pcgamingfreaks.Minepacks.Database.Database;
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, showCloseMessageOwn, showCloseMessageOther;
private String messageOwnBPClose, messagePlayerBPClose;
public EventListener(Minepacks mp)
{
plugin = mp;
drop_on_death = plugin.config.getDropOnDeath();
messageOwnBPClose = plugin.lang.getTranslated("Ingame.OwnBackPackClose");
messagePlayerBPClose = plugin.lang.getTranslated("Ingame.PlayerBackPackClose");
showCloseMessageOther = messagePlayerBPClose != null && plugin.config.getShowCloseMessage();
showCloseMessageOwn = messageOwnBPClose != null && plugin.config.getShowCloseMessage();
}
@EventHandler
public void onDeath(PlayerDeathEvent event)
{
final Player player = event.getEntity();
if (drop_on_death && !player.hasPermission("backpack.KeepOnDeath"))
{
plugin.DB.getBackpack(player, new Database.Callback<Backpack>()
{
@Override
public void onResult(Backpack backpack)
{
Inventory backpackInventory = backpack.getInventory();
for(ItemStack i : backpackInventory.getContents())
{
if(i != null)
{
player.getWorld().dropItemNaturally(player.getLocation(), i);
backpackInventory.remove(i);
backpack.setChanged();
}
}
backpack.save(); // We have to save it now!
}
@Override
public void onFail()
{
}
});
}
}
@EventHandler
public void onClose(InventoryCloseEvent event)
{
if (event.getInventory() != null && event.getInventory().getHolder() instanceof Backpack && event.getPlayer() instanceof Player)
{
Backpack backpack = (Backpack)event.getInventory().getHolder();
if(!backpack.inUse())
{
Player closer = (Player)event.getPlayer();
if(backpack.canEdit(closer))
{
backpack.save();
}
backpack.close(closer);
if(event.getPlayer().getName().equals(backpack.getOwner().getName()))
{
if(showCloseMessageOwn)
{
closer.sendMessage(messageOwnBPClose);
}
}
else
{
if(showCloseMessageOther)
{
closer.sendMessage(String.format(messagePlayerBPClose, backpack.getOwner().getName()));
}
}
}
}
}
@EventHandler
public void onClick(InventoryClickEvent event)
{
if (event.getInventory() != null && event.getInventory().getHolder() instanceof Backpack && event.getWhoClicked() instanceof Player)
{
Backpack backpack = (Backpack) event.getInventory().getHolder();
if(!backpack.canEdit((Player)event.getWhoClicked()))
{
event.setCancelled(true);
}
else
{
backpack.setChanged();
}
}
}
@EventHandler
public void onPlayerLoginEvent(PlayerJoinEvent event)
{
plugin.DB.updatePlayerAndLoadBackpack(event.getPlayer());
}
@EventHandler
public void onPlayerLeaveEvent(PlayerQuitEvent event)
{
Backpack backpack = plugin.DB.getBackpack(event.getPlayer());
if(backpack != null && !backpack.isOpen())
{
backpack.save();
plugin.DB.unloadBackpack(backpack);
}
if(plugin.cooldowns.containsKey(event.getPlayer()))
{
plugin.cooldowns.remove(event.getPlayer());
}
}
}