Convert to a multi-module Maven setup

This is much more user-friendly - users can either compile a specific module or create a profile to compile for the specific Minecraft versions they're looking to support. It means that it's much easier for people to continue assisting with the development of OpenInv in the future without access to every version of CB since 1.4.5.

This commit restores and updates most of the old system.
This commit is contained in:
Jikoo 2016-11-25 08:01:44 -05:00
parent b76440ab9a
commit 3bf7225712
40 changed files with 1088 additions and 196 deletions

38
plugin/pom.xml Normal file
View file

@ -0,0 +1,38 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinv</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>openinvplugin</artifactId>
<name>OpenInvPlugin</name>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<!-- Really should use 1.4.5-R1.0, but the InventoryDragEvent doesn't exist. TODO separate module? -->
<version>1.11-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvinternal</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>

View file

@ -0,0 +1,163 @@
package com.lishid.openinv;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import com.lishid.openinv.utils.UUIDUtils;
public class ConfigUpdater {
private final OpenInv plugin;
private static final int CONFIG_VERSION = 2;
public ConfigUpdater(OpenInv plugin) {
this.plugin = plugin;
}
private int getConfigVersion() {
return plugin.getConfig().getInt("config-version", 1);
}
private boolean isConfigOutdated() {
return getConfigVersion() < CONFIG_VERSION;
}
public void checkForUpdates() {
if (isConfigOutdated()) {
plugin.getLogger().info("[Config] Update found! Performing update...");
performUpdate();
} else {
plugin.getLogger().info("[Config] Update not required.");
}
}
private void performUpdate() {
// Update according to the right version
switch (getConfigVersion()) {
case 1:
updateConfig1To2();
break;
}
}
private void updateConfig1To2() {
FileConfiguration config = plugin.getConfig();
// Backup the old config file
File configFile = new File(plugin.getDataFolder(), "config.yml");
File oldConfigFile = new File(plugin.getDataFolder(), "config_old.yml");
configFile.renameTo(oldConfigFile);
if (configFile.exists()) {
configFile.delete();
}
plugin.getLogger().info("[Config] Backup of old config.yml file created.");
// Get the old config settings
int itemOpenInvItemId = config.getInt("ItemOpenInvItemID", 280);
boolean notifySilentChest = config.getBoolean("NotifySilentChest", true);
boolean notifyAnyChest = config.getBoolean("NotifyAnyChest", true);
Map<UUID, Boolean> anyChestToggles = null;
Map<UUID, Boolean> itemOpenInvToggles = null;
Map<UUID, Boolean> silentChestToggles = null;
if (config.isSet("AnyChest")) {
anyChestToggles = updateToggles("AnyChest");
}
if (config.isSet("ItemOpenInv")) {
itemOpenInvToggles = updateToggles("ItemOpenInv");
}
if (config.isSet("SilentChest")) {
silentChestToggles = updateToggles("SilentChest");
}
// Clear the old config
for (String key : config.getKeys(false)) {
config.set(key, null);
}
// Set the new config options
plugin.saveDefaultConfig();
plugin.reloadConfig();
config = plugin.getConfig(); // Refresh the referenced plugin config
config.set("config-version", 2);
config.set("items.open-inv", getMaterialById(itemOpenInvItemId).toString());
config.set("notify.any-chest", notifyAnyChest);
config.set("notify.silent-chest", notifySilentChest);
if (anyChestToggles != null && !anyChestToggles.isEmpty()) {
for (Map.Entry<UUID, Boolean> entry : anyChestToggles.entrySet()) {
config.set("toggles.any-chest." + entry.getKey(), entry.getValue());
}
}
if (itemOpenInvToggles != null && !itemOpenInvToggles.isEmpty()) {
for (Map.Entry<UUID, Boolean> entry : itemOpenInvToggles.entrySet()) {
config.set("toggles.items.open-inv." + entry.getKey(), entry.getValue());
}
}
if (silentChestToggles != null && !silentChestToggles.isEmpty()) {
for (Map.Entry<UUID, Boolean> entry : silentChestToggles.entrySet()) {
config.set("toggles.silent-chest." + entry.getKey(), entry.getValue());
}
}
// Save the new config
plugin.saveConfig();
plugin.getLogger().info("[Config] Update complete.");
}
private Map<UUID, Boolean> updateToggles(String sectionName) {
Map<UUID, Boolean> toggles = new HashMap<UUID, Boolean>();
ConfigurationSection section = plugin.getConfig().getConfigurationSection(sectionName);
Set<String> keys = section.getKeys(false);
if (keys == null || keys.isEmpty()) {
return null;
}
int total = keys.size();
int converted = 0;
for (String playerName : keys) {
UUID uuid = UUIDUtils.getPlayerUUID(playerName);
if (uuid != null) {
boolean toggled = section.getBoolean(playerName + ".toggle", false);
toggles.put(uuid, toggled);
converted++;
}
}
plugin.getLogger().info("[Config] Converted (" + converted + "/" + total + ") " + sectionName + " toggle player usernames to UUIDs.");
return toggles;
}
@SuppressWarnings("deprecation")
private Material getMaterialById(int id) {
Material material = Material.getMaterial(id);
if (material == null) {
material = Material.STICK;
}
return material;
}
}

View file

@ -0,0 +1,153 @@
package com.lishid.openinv;
import org.bukkit.Material;
import org.bukkit.entity.Player;
public class Configuration {
private final OpenInv plugin;
private Material openInvItem;
private boolean notifySilentChest;
private boolean notifyAnyChest;
public Configuration(OpenInv plugin) {
this.plugin = plugin;
// Check for config updates
ConfigUpdater configUpdater = new ConfigUpdater(plugin);
configUpdater.checkForUpdates();
// Load the config settings
load();
}
/**
* Loads OpenInv's config settings.
*/
public void load() {
// OpenInv Item
if (!plugin.getConfig().isSet("items.open-inv")) {
saveToConfig("items.open-inv", "STICK");
}
String itemName = plugin.getConfig().getString("items.open-inv", "STICK");
Material material = Material.getMaterial(itemName);
if (material == null) {
plugin.getLogger().warning("OpenInv item '" + itemName + "' does not match to a valid item. Defaulting to stick.");
material = Material.STICK;
}
openInvItem = material;
// Other Values
notifySilentChest = plugin.getConfig().getBoolean("notify.silent-chest", true);
notifyAnyChest = plugin.getConfig().getBoolean("notify.any-chest", true);
}
/**
* Reloads OpenInv's config settings.
*/
public void reload() {
load();
}
/**
* Saves a value to the plugin config at the specified path.
*
* @param path the path to set the value to
* @param value the value to set to the path
*/
private void saveToConfig(String path, Object value) {
plugin.getConfig().set(path, value);
plugin.saveConfig();
}
/**
* Returns the OpenInv item Material.
*
* @return the OpenInv item Material
*/
public Material getOpenInvItem() {
return openInvItem;
}
/**
* Returns whether or not notify silent chest is enabled.
*
* @return true if notify silent chest is enabled; false otherwise
*/
public boolean notifySilentChest() {
return notifySilentChest;
}
/**
* Returns whether or not notify any chest is enabled.
*
* @return true if notify any chest is enabled; false otherwise
*/
public boolean notifyAnyChest() {
return notifyAnyChest;
}
/**
* Returns a player's item OpenInv status.
*
* @param player the player to get the item OpenInv status of
* @return the player's item OpenInv status
*/
public boolean getPlayerItemOpenInvStatus(Player player) {
return plugin.getConfig().getBoolean("toggles.items.open-inv." + player.getUniqueId(), false);
}
/**
* Returns a player's any chest status.
*
* @param player the player to get the any chest status of
* @return the player's any chest status
*/
public boolean getPlayerAnyChestStatus(Player player) {
return plugin.getConfig().getBoolean("toggles.any-chest." + player.getUniqueId(), true);
}
/**
* Sets a player's any chest status.
*
* @param player the player to set the any chest status of
* @param status the status to set with
*/
public void setPlayerAnyChestStatus(Player player, boolean status) {
saveToConfig("toggles.any-chest." + player.getUniqueId(), status);
}
/**
* Sets a player's item OpenInv status.
*
* @param player the player to set the item OpenInv status of
* @param status the status to set with
*/
public void setPlayerItemOpenInvStatus(Player player, boolean status) {
saveToConfig("toggles.items.open-inv." + player.getUniqueId(), status);
}
/**
* Returns a player's silent chest status.
*
* @param player the player to get the silent chest status of
* @return the player's silent chest status
*/
public boolean getPlayerSilentChestStatus(Player player) {
return plugin.getConfig().getBoolean("toggles.silent-chest." + player.getUniqueId(), false);
}
/**
* Sets a player's silent chest status.
*
* @param player the player to set the silent chest status of
* @param status the status to set with
*/
public void setPlayerSilentChestStatus(Player player, boolean status) {
saveToConfig("toggles.silent-chest." + player.getUniqueId(), status);
}
}

View file

@ -0,0 +1,270 @@
/*
* Copyright (C) 2011-2016 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 com.lishid.openinv;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import com.lishid.openinv.commands.AnyChestCommand;
import com.lishid.openinv.commands.OpenEnderCommand;
import com.lishid.openinv.commands.OpenInvCommand;
import com.lishid.openinv.commands.SearchEnderCommand;
import com.lishid.openinv.commands.SearchInvCommand;
import com.lishid.openinv.commands.SilentChestCommand;
import com.lishid.openinv.commands.ToggleOpenInvCommand;
import com.lishid.openinv.internal.IAnySilentChest;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.internal.InternalAccessor;
import com.lishid.openinv.listeners.OpenInvEntityListener;
import com.lishid.openinv.listeners.OpenInvInventoryListener;
import com.lishid.openinv.listeners.OpenInvPlayerListener;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permissible;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class OpenInv extends JavaPlugin {
private final Map<UUID, ISpecialPlayerInventory> inventories = new HashMap<UUID, ISpecialPlayerInventory>();
private final Map<UUID, ISpecialEnderChest> enderChests = new HashMap<UUID, ISpecialEnderChest>();
private Configuration configuration;
private InternalAccessor accessor;
private IPlayerDataManager playerLoader;
private IInventoryAccess inventoryAccess;
private IAnySilentChest anySilentChest;
@Override
public void onEnable() {
// Save the default config.yml if it doesn't already exist
saveDefaultConfig();
// Config
configuration = new Configuration(this);
PluginManager pm = getServer().getPluginManager();
// Version check
if (!accessor.initialize(getServer())) {
getLogger().info("Your version of CraftBukkit (" + accessor.getVersion() + ") is not supported.");
getLogger().info("Please look for an updated version of OpenInv.");
pm.disablePlugin(this);
return;
}
playerLoader = accessor.newPlayerDataManager();
inventoryAccess = accessor.newInventoryAccess();
anySilentChest = accessor.newAnySilentChest();
// Register the plugin's events
pm.registerEvents(new OpenInvPlayerListener(this), this);
pm.registerEvents(new OpenInvEntityListener(this), this);
pm.registerEvents(new OpenInvInventoryListener(this), this);
// Register the plugin's commands
getCommand("openinv").setExecutor(new OpenInvCommand(this));
getCommand("openender").setExecutor(new OpenEnderCommand(this));
getCommand("searchinv").setExecutor(new SearchInvCommand(this));
getCommand("searchender").setExecutor(new SearchEnderCommand());
getCommand("toggleopeninv").setExecutor(new ToggleOpenInvCommand(this));
getCommand("anychest").setExecutor(new AnyChestCommand(this));
getCommand("silentchest").setExecutor(new SilentChestCommand(this));
}
/**
* Returns the plugin Configuration.
*
* @return the plugin Configuration
*/
public Configuration getConfiguration() {
return configuration;
}
/**
* Returns an instance of PlayerDataManager.
*
* @return an instance of PlayerDataManager
*/
public IPlayerDataManager getPlayerLoader() {
return playerLoader;
}
/**
* Returns an instance of InventoryAccess.
*
* @return an instance of InventoryAccess
*/
public IInventoryAccess getInventoryAccess() {
return inventoryAccess;
}
/**
* Returns an instance of AnySilentChest.
*
* @return an instance of AnySilentChest
*/
public IAnySilentChest getAnySilentChest() {
return anySilentChest;
}
/**
* Returns a player's SpecialPlayerInventory.
*
* @param player the player to get the SpecialPlayerInventory of
* @param createIfNull whether or not to create it if it doesn't exist
* @return the player's SpecialPlayerInventory or null
*/
public ISpecialPlayerInventory getPlayerInventory(Player player, boolean createIfNull) {
ISpecialPlayerInventory inventory = inventories.get(player.getUniqueId());
if (inventory == null && createIfNull) {
inventory = accessor.newSpecialPlayerInventory(player, !player.isOnline());
inventories.put(player.getUniqueId(), inventory);
}
return inventory;
}
/**
* Returns a player's SpecialEnderChest.
*
* @param player the player to get the SpecialEnderChest of
* @param createIfNull whether or not to create it if it doesn't exist
* @return the player's SpecialEnderChest or null
*/
public ISpecialEnderChest getPlayerEnderChest(Player player, boolean createIfNull) {
ISpecialEnderChest enderChest = enderChests.get(player.getUniqueId());
if (enderChest == null && createIfNull) {
enderChest = accessor.newSpecialEnderChest(player, player.isOnline());
enderChests.put(player.getUniqueId(), enderChest);
}
return enderChest;
}
/**
* Removes a player's loaded inventory if it exists.
*
* @param player the player to remove the loaded inventory of
*/
public void removeLoadedInventory(Player player) {
if (inventories.containsKey(player.getUniqueId())) {
inventories.remove(player.getUniqueId());
}
}
/**
* Removes a player's loaded ender chest if it exists.
*
* @param player the player to remove the loaded ender chest of
*/
public void removeLoadedEnderChest(Player player) {
if (enderChests.containsKey(player.getUniqueId())) {
enderChests.remove(player.getUniqueId());
}
}
/**
* Logs a message to console.
*
* @param text the message to log
*/
public void log(String text) {
getLogger().info(text);
}
/**
* Logs a Throwable to console.
*
* @param e the Throwable to log
*/
public void log(Throwable e) {
getLogger().severe(e.toString());
e.printStackTrace();
}
/**
* Sends an OpenInv message to a player.
*
* @param sender the CommandSender to message
* @param message the message to send
*/
public static void sendMessage(CommandSender sender, String message) {
sender.sendMessage(ChatColor.AQUA + "[OpenInv] " + ChatColor.WHITE + message);
}
/**
* Outputs OpenInv help information to a CommandSender.
*
* @param sender the CommandSender to show help to
*/
public static void showHelp(CommandSender sender) {
sender.sendMessage(ChatColor.GREEN + "/openinv <player> - Opens a player's inventory.");
sender.sendMessage(ChatColor.GREEN + " (aliases: oi, inv, open)");
sender.sendMessage(ChatColor.GREEN + "/openender <player> - Opens a player's ender chest.");
sender.sendMessage(ChatColor.GREEN + " (aliases: oe)");
sender.sendMessage(ChatColor.GREEN + "/searchinv <item> [minAmount] -");
sender.sendMessage(ChatColor.GREEN + " Searches and lists players that have a specific item in their inventory.");
sender.sendMessage(ChatColor.GREEN + " (aliases: si)");
sender.sendMessage(ChatColor.GREEN + "/searchender <item> [minAmount] -");
sender.sendMessage(ChatColor.GREEN + " Searches and lists players that have a specific item in their ender chest.");
sender.sendMessage(ChatColor.GREEN + " (aliases: se)");
sender.sendMessage(ChatColor.GREEN + "/toggleopeninv - Toggles the item openinv function.");
sender.sendMessage(ChatColor.GREEN + " (aliases: toi, toggleoi, toggleinv)");
sender.sendMessage(ChatColor.GREEN + "/anychest - Toggles the any chest function.");
sender.sendMessage(ChatColor.GREEN + " (aliases: ac)");
sender.sendMessage(ChatColor.GREEN + "/silentchest - Toggles the silent chest function.");
sender.sendMessage(ChatColor.GREEN + " (aliases: sc, silent)");
}
/**
* Returns whether or not a player has a permission.
*
* @param player the player to check
* @param permission the permission node to check for
* @return true if the player has the permission; false otherwise
*/
public static boolean hasPermission(Permissible player, String permission) {
String[] parts = permission.split("\\.");
String perm = "";
for (int i = 0; i < parts.length; i++) {
if (player.hasPermission(perm + "*")) {
return true;
}
perm += parts[i] + ".";
}
return player.hasPermission(permission);
}
}

View file

@ -0,0 +1,19 @@
package com.lishid.openinv;
public final class Permissions {
private Permissions() {}
public static final String PERM_OPENINV = "OpenInv.openinv";
public static final String PERM_OVERRIDE = "OpenInv.override";
public static final String PERM_EXEMPT = "OpenInv.exempt";
public static final String PERM_CROSSWORLD = "OpenInv.crossworld";
public static final String PERM_SILENT = "OpenInv.silent";
public static final String PERM_ANYCHEST = "OpenInv.anychest";
public static final String PERM_ENDERCHEST = "OpenInv.openender";
public static final String PERM_ENDERCHEST_ALL = "OpenInv.openenderall";
public static final String PERM_SEARCH = "OpenInv.search";
public static final String PERM_EDITINV = "OpenInv.editinv";
public static final String PERM_EDITENDER = "OpenInv.editender";
public static final String PERM_OPENSELF = "OpenInv.openself";
}

View file

@ -0,0 +1,72 @@
/*
* Copyright (C) 2011-2016 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 com.lishid.openinv.commands;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.Permissions;
import com.lishid.openinv.Configuration;
public class AnyChestCommand implements CommandExecutor {
private final OpenInv plugin;
private final Configuration configuration;
public AnyChestCommand(OpenInv plugin) {
this.plugin = plugin;
configuration = plugin.getConfiguration();
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equalsIgnoreCase("anychest")) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You can't use this command from the console.");
return true;
}
if (!OpenInv.hasPermission(sender, Permissions.PERM_ANYCHEST)) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use any chest.");
return true;
}
Player player = (Player) sender;
if (args.length > 0) {
if (args[0].equalsIgnoreCase("check")) {
String status = configuration.getPlayerAnyChestStatus(player) ? ChatColor.GREEN + "ON" : ChatColor.RED + "OFF";
OpenInv.sendMessage(player, "Any Chest is " + status + ChatColor.RESET + ".");
return true;
}
}
configuration.setPlayerAnyChestStatus(player, !configuration.getPlayerAnyChestStatus(player));
String status = configuration.getPlayerAnyChestStatus(player) ? ChatColor.GREEN + "ON" : ChatColor.RED + "OFF";
OpenInv.sendMessage(player, "Any Chest is now " + status + ChatColor.RESET + ".");
return true;
}
return false;
}
}

View file

@ -0,0 +1,161 @@
/*
* Copyright (C) 2011-2016 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 com.lishid.openinv.commands;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.Permissions;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.utils.UUIDUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class OpenEnderCommand implements CommandExecutor {
private final OpenInv plugin;
private final Map<UUID, UUID> openEnderHistory = new ConcurrentHashMap<UUID, UUID>();
public OpenEnderCommand(OpenInv plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equalsIgnoreCase("openender")) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You can't use this command from the console.");
return true;
}
if (!OpenInv.hasPermission(sender, Permissions.PERM_ENDERCHEST)) {
sender.sendMessage(ChatColor.RED + "You do not have permission to access player ender chests.");
return true;
}
if (args.length > 0 && args[0].equalsIgnoreCase("?")) {
OpenInv.showHelp(sender);
return true;
}
final Player player = (Player) sender;
// History management
UUID history = openEnderHistory.get(player.getUniqueId());
if (history == null) {
history = player.getUniqueId();
openEnderHistory.put(player.getUniqueId(), history);
}
final UUID uuid;
// Read from history if target is not named
if (args.length < 1) {
if (history != null) {
uuid = history;
} else {
sender.sendMessage(ChatColor.RED + "OpenEnder history is empty!");
return true;
}
}
else {
uuid = UUIDUtils.getPlayerUUID(args[0]);
if (uuid == null) {
player.sendMessage(ChatColor.RED + "Player not found!");
return true;
}
}
final UUID playerUUID = player.getUniqueId();
Player target = Bukkit.getPlayer(uuid);
if (target == null) {
// Targeted player was not found online, start asynchronous lookup in files
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
// Try loading the player's data asynchronously
final Player target = plugin.getPlayerLoader().loadPlayer(uuid);
if (target == null) {
player.sendMessage(ChatColor.RED + "Player not found!");
return;
}
// Open target's inventory synchronously
Bukkit.getScheduler().runTask(plugin, new Runnable() {
@Override
public void run() {
Player player = Bukkit.getPlayer(playerUUID);
// If sender is no longer online after loading the target, abort!
if (player == null) {
return;
}
openInventory(player, target);
}
});
}
});
} else {
openInventory(player, target);
}
return true;
}
return false;
}
private void openInventory(Player player, Player target) {
// Null target check
if (target == null) {
player.sendMessage(ChatColor.RED + "Player not found!");
return;
}
// Permissions checks
if (target != player && !OpenInv.hasPermission(player, Permissions.PERM_ENDERCHEST_ALL)) {
player.sendMessage(ChatColor.RED + "You do not have permission to access other player's ender chests.");
return;
}
if (!OpenInv.hasPermission(player, Permissions.PERM_OVERRIDE) && OpenInv.hasPermission(target, Permissions.PERM_EXEMPT)) {
player.sendMessage(ChatColor.RED + target.getDisplayName() + "'s ender chest is protected!");
return;
}
// Crossworld check
if ((!OpenInv.hasPermission(player, Permissions.PERM_CROSSWORLD) && !OpenInv.hasPermission(player, Permissions.PERM_OVERRIDE)) && target.getWorld() != player.getWorld()) {
player.sendMessage(ChatColor.RED + target.getDisplayName() + " is not in your world!");
return;
}
// Record the target
openEnderHistory.put(player.getUniqueId(), target.getUniqueId());
// Get the inventory and open it
ISpecialEnderChest enderChest = plugin.getPlayerEnderChest(target, true);
player.openInventory(enderChest.getBukkitInventory());
}
}

View file

@ -0,0 +1,156 @@
/*
* Copyright (C) 2011-2016 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 com.lishid.openinv.commands;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.Permissions;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.utils.UUIDUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class OpenInvCommand implements CommandExecutor {
private final OpenInv plugin;
private final Map<UUID, UUID> openInvHistory = new ConcurrentHashMap<UUID, UUID>();
public OpenInvCommand(OpenInv plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equalsIgnoreCase("openinv")) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You can't use this command from the console.");
return true;
}
if (!OpenInv.hasPermission(sender, Permissions.PERM_OPENINV)) {
sender.sendMessage(ChatColor.RED + "You do not have permission to access player inventories.");
return true;
}
if (args.length > 0 && args[0].equalsIgnoreCase("?")) {
OpenInv.showHelp(sender);
return true;
}
final Player player = (Player) sender;
// History management
UUID history = openInvHistory.get(player.getUniqueId());
if (history == null) {
history = player.getUniqueId();
openInvHistory.put(player.getUniqueId(), history);
}
final UUID uuid;
// Read from history if target is not named
if (args.length < 1) {
uuid = history;
} else {
uuid = UUIDUtils.getPlayerUUID(args[0]);
if (uuid == null) {
player.sendMessage(ChatColor.RED + "Player not found!");
return true;
}
}
final UUID playerUUID = player.getUniqueId();
Player target = Bukkit.getPlayer(uuid);
if (target == null) {
// Targeted player was not found online, start asynchronous lookup in files
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
// Try loading the player's data asynchronously
final Player target = plugin.getPlayerLoader().loadPlayer(uuid);
if (target == null) {
player.sendMessage(ChatColor.RED + "Player not found!");
return;
}
// Open target's inventory synchronously
Bukkit.getScheduler().runTask(plugin, new Runnable() {
@Override
public void run() {
Player player = Bukkit.getPlayer(playerUUID);
// If sender is no longer online after loading the target, abort!
if (player == null) {
return;
}
openInventory(player, target);
}
});
}
});
} else {
openInventory(player, target);
}
return true;
}
return false;
}
private void openInventory(Player player, Player target) {
// Null target check
if (target == null) {
player.sendMessage(ChatColor.RED + "Player not found!");
return;
}
// Permissions checks
if (!OpenInv.hasPermission(player, Permissions.PERM_OVERRIDE) && OpenInv.hasPermission(target, Permissions.PERM_EXEMPT)) {
player.sendMessage(ChatColor.RED + target.getDisplayName() + "'s inventory is protected!");
return;
}
// Crossworld check
if ((!OpenInv.hasPermission(player, Permissions.PERM_CROSSWORLD) && !OpenInv.hasPermission(player, Permissions.PERM_OVERRIDE)) && target.getWorld() != player.getWorld()) {
player.sendMessage(ChatColor.RED + target.getDisplayName() + " is not in your world!");
return;
}
// Self-open check
if (!OpenInv.hasPermission(player, Permissions.PERM_OPENSELF) && target.equals(player)) {
player.sendMessage(ChatColor.RED + "You're not allowed to openinv yourself.");
return;
}
// Record the target
openInvHistory.put(player.getUniqueId(), target.getUniqueId());
// Get the inventory and open it
ISpecialPlayerInventory inventory = plugin.getPlayerInventory(target, true);
player.openInventory(inventory.getBukkitInventory());
}
}

View file

@ -0,0 +1,66 @@
package com.lishid.openinv.commands;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.Permissions;
public class SearchEnderCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equalsIgnoreCase("searchender")) {
if (sender instanceof Player) {
if (!OpenInv.hasPermission(sender, Permissions.PERM_SEARCH)) {
sender.sendMessage(ChatColor.RED + "You do not have permission to search player ender chests.");
return true;
}
}
Material material = null;
int count = 1;
if (args.length >= 1) {
String[] gData;
gData = args[0].split(":");
material = Material.matchMaterial(gData[0]);
}
if (args.length >= 2) {
try {
count = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "'" + args[1] + "' is not a number!");
return false;
}
}
if (material == null) {
sender.sendMessage(ChatColor.RED + "Unknown item.");
return false;
}
StringBuilder sb = new StringBuilder();
for (Player onlinePlayer : Bukkit.getServer().getOnlinePlayers()) {
if (onlinePlayer.getEnderChest().contains(material, count)) {
sb.append(onlinePlayer.getName());
sb.append(" ");
}
}
String playerList = sb.toString();
sender.sendMessage("Players with the item " + ChatColor.GRAY + material.toString() + ChatColor.RESET + " in their ender chest: " + playerList);
return true;
}
return false;
}
}

View file

@ -0,0 +1,88 @@
/*
* Copyright (C) 2011-2016 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 com.lishid.openinv.commands;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.Permissions;
public class SearchInvCommand implements CommandExecutor {
private final OpenInv plugin;
public SearchInvCommand(OpenInv plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equalsIgnoreCase("searchinv")) {
if (sender instanceof Player) {
if (!OpenInv.hasPermission(sender, Permissions.PERM_SEARCH)) {
sender.sendMessage(ChatColor.RED + "You do not have permission to search player inventories.");
return true;
}
}
Material material = null;
int count = 1;
if (args.length >= 1) {
String[] gData;
gData = args[0].split(":");
material = Material.matchMaterial(gData[0]);
}
if (args.length >= 2) {
try {
count = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "'" + args[1] + "' is not a number!");
return false;
}
}
if (material == null) {
sender.sendMessage(ChatColor.RED + "Unknown item.");
return false;
}
StringBuilder sb = new StringBuilder();
for (Player onlinePlayer : Bukkit.getServer().getOnlinePlayers()) {
if (onlinePlayer.getInventory().contains(material, count)) {
sb.append(onlinePlayer.getName());
sb.append(" ");
}
}
String playerList = sb.toString();
sender.sendMessage("Players with the item " + ChatColor.GRAY + material.toString() + ChatColor.RESET + " in their inventory: " + playerList);
return true;
}
return false;
}
}

View file

@ -0,0 +1,72 @@
/*
* Copyright (C) 2011-2016 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 com.lishid.openinv.commands;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.Permissions;
import com.lishid.openinv.Configuration;
public class SilentChestCommand implements CommandExecutor {
private final OpenInv plugin;
private final Configuration configuration;
public SilentChestCommand(OpenInv plugin) {
this.plugin = plugin;
configuration = plugin.getConfiguration();
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equalsIgnoreCase("silentchest")) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You can't use this command from the console.");
return true;
}
if (!OpenInv.hasPermission(sender, Permissions.PERM_SILENT)) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use silent chest.");
return true;
}
Player player = (Player) sender;
if (args.length > 0) {
if (args[0].equalsIgnoreCase("check")) {
String status = configuration.getPlayerSilentChestStatus(player) ? ChatColor.GREEN + "ON" : ChatColor.RED + "OFF";
OpenInv.sendMessage(player, "Silent Chest is " + status + ChatColor.RESET + ".");
return true;
}
}
configuration.setPlayerSilentChestStatus(player, !configuration.getPlayerSilentChestStatus(player));
String status = configuration.getPlayerSilentChestStatus(player) ? ChatColor.GREEN + "ON" : ChatColor.RED + "OFF";
OpenInv.sendMessage(player, "Silent Chest is now " + status + ChatColor.RESET + ".");
return true;
}
return false;
}
}

View file

@ -0,0 +1,72 @@
/*
* Copyright (C) 2011-2016 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 com.lishid.openinv.commands;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.Permissions;
import com.lishid.openinv.Configuration;
public class ToggleOpenInvCommand implements CommandExecutor {
private final OpenInv plugin;
private final Configuration configuration;
public ToggleOpenInvCommand(OpenInv plugin) {
this.plugin = plugin;
configuration = plugin.getConfiguration();
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equalsIgnoreCase("toggleopeninv")) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You can't use this command from the console.");
return true;
}
if (!OpenInv.hasPermission(sender, Permissions.PERM_OPENINV)) {
sender.sendMessage(ChatColor.RED + "You do not have permission to access player inventories.");
return true;
}
Player player = (Player) sender;
if (args.length > 0) {
if (args[0].equalsIgnoreCase("check")) {
String status = configuration.getPlayerItemOpenInvStatus(player) ? ChatColor.GREEN + "ON" : ChatColor.RED + "OFF";
OpenInv.sendMessage(player, "OpenInv with " + ChatColor.GRAY + configuration.getOpenInvItem() + ChatColor.RESET + status + ChatColor.RESET + ".");
return true;
}
}
configuration.setPlayerItemOpenInvStatus(player, !configuration.getPlayerItemOpenInvStatus(player));
String status = configuration.getPlayerItemOpenInvStatus(player) ? ChatColor.GREEN + "ON" : ChatColor.RED + "OFF";
OpenInv.sendMessage(player, "OpenInv with " + ChatColor.GRAY + configuration.getOpenInvItem() + ChatColor.RESET + " is now " + status + ChatColor.RESET + ".");
return true;
}
return false;
}
}

View file

@ -0,0 +1,64 @@
/*
* Copyright (C) 2011-2016 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 com.lishid.openinv.listeners;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.Permissions;
import com.lishid.openinv.Configuration;
public class OpenInvEntityListener implements Listener {
private final OpenInv plugin;
private final Configuration configuration;
public OpenInvEntityListener(OpenInv plugin) {
this.plugin = plugin;
configuration = plugin.getConfiguration();
}
@EventHandler(priority = EventPriority.LOWEST)
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
if (!(attacker instanceof Player) || !(defender instanceof Player)) {
return;
}
Player player = (Player) attacker;
if (player.getInventory().getItemInMainHand().getType() == configuration.getOpenInvItem()) {
if (!configuration.getPlayerItemOpenInvStatus(player) || !OpenInv.hasPermission(player, Permissions.PERM_OPENINV)) {
return;
}
Player target = (Player) defender;
event.setDamage(0);
event.setCancelled(true);
player.performCommand("openinv " + target.getName());
}
}
}

View file

@ -0,0 +1,44 @@
/*
* Copyright (C) 2011-2016 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 com.lishid.openinv.listeners;
import org.bukkit.entity.HumanEntity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import com.lishid.openinv.OpenInv;
public class OpenInvInventoryListener implements Listener {
private final OpenInv plugin;
public OpenInvInventoryListener(OpenInv plugin) {
this.plugin = plugin;
}
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
Inventory inventory = event.getInventory();
HumanEntity player = event.getWhoClicked();
if (!plugin.getInventoryAccess().check(inventory, player)) {
event.setCancelled(true);
}
}
}

View file

@ -0,0 +1,178 @@
/*
* Copyright (C) 2011-2016 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 com.lishid.openinv.listeners;
import com.lishid.openinv.Configuration;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.Permissions;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Chest;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.scheduler.BukkitRunnable;
public class OpenInvPlayerListener implements Listener {
private final OpenInv plugin;
private final Configuration configuration;
public OpenInvPlayerListener(OpenInv plugin) {
this.plugin = plugin;
configuration = plugin.getConfiguration();
}
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerJoin(PlayerJoinEvent event) {
final Player player = event.getPlayer();
new BukkitRunnable() {
@Override
public void run() {
if (!player.isOnline()) {
return;
}
ISpecialPlayerInventory inventory = plugin.getPlayerInventory(player, false);
if (inventory != null) {
inventory.playerOnline(player);
player.updateInventory();
}
ISpecialEnderChest enderChest = plugin.getPlayerEnderChest(player, false);
if (enderChest != null) {
enderChest.playerOnline(player);
}
}
}.runTask(plugin);
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
ISpecialPlayerInventory inventory = plugin.getPlayerInventory(player, false);
if (inventory != null) {
inventory.playerOffline();
if (inventory.isInUse()) {
plugin.removeLoadedInventory(event.getPlayer());
}
}
ISpecialEnderChest enderChest = plugin.getPlayerEnderChest(player, false);
if (enderChest != null) {
enderChest.playerOffline();
if (!enderChest.isInUse()) {
plugin.removeLoadedEnderChest(event.getPlayer());
}
}
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
if (player.isSneaking()) {
return;
}
Action action = event.getAction();
Block block = event.getClickedBlock();
switch (action) {
case RIGHT_CLICK_BLOCK:
if (event.useInteractedBlock() == Result.DENY) {
return;
}
// Ender Chests
if (block.getType() == Material.ENDER_CHEST) {
if (OpenInv.hasPermission(player, Permissions.PERM_SILENT) && configuration.getPlayerSilentChestStatus(player)) {
event.setCancelled(true);
player.openInventory(player.getEnderChest());
return;
}
}
// Chests
if (block.getState() instanceof Chest) {
boolean silentChest = false;
boolean anyChest = false;
int x = block.getX();
int y = block.getY();
int z = block.getZ();
if (OpenInv.hasPermission(player, Permissions.PERM_SILENT) && configuration.getPlayerSilentChestStatus(player)) {
silentChest = true;
}
if (OpenInv.hasPermission(player, Permissions.PERM_ANYCHEST) && configuration.getPlayerAnyChestStatus(player)) {
try {
anyChest = plugin.getAnySilentChest().isAnyChestNeeded(player, x, y, z);
} catch (Exception e) {
player.sendMessage(ChatColor.RED + "Error while executing openinv. Unsupported CraftBukkit.");
e.printStackTrace();
}
}
// If the anyChest or silentChest is active
if (anyChest || silentChest) {
if (!plugin.getAnySilentChest().activateChest(player, anyChest, silentChest, x, y, z)) {
event.setCancelled(true);
}
}
return;
}
// Signs
if (block.getState() instanceof Sign) {
try {
Sign sign = (Sign) block.getState();
if (OpenInv.hasPermission(player, Permissions.PERM_OPENINV) && sign.getLine(0).equalsIgnoreCase("[openinv]")) {
String text = sign.getLine(1).trim() + sign.getLine(2).trim() + sign.getLine(3).trim();
player.performCommand("openinv " + text);
}
} catch (Exception e) {
player.sendMessage(ChatColor.RED + "An internal error occured.");
e.printStackTrace();
}
return;
}
case RIGHT_CLICK_AIR:
// OpenInv item
if (player.getInventory().getItemInMainHand().getType() == configuration.getOpenInvItem() && configuration.getPlayerItemOpenInvStatus(player) && OpenInv.hasPermission(player, Permissions.PERM_OPENINV)) {
player.performCommand("openinv");
}
}
}
}

View file

@ -0,0 +1,160 @@
package com.lishid.openinv.util;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
/**
* A minimal time-based cache implementation backed by a HashMap and TreeMultimap.
*
* @author Jikoo
*/
public class Cache<K, V> {
private final Map<K, V> internal;
private final Multimap<Long, K> expiry;
private final long retention;
private final Function<V> inUseCheck, postRemoval;
/**
* Constructs a Cache with the specified retention duration, in use function, and post-removal function.
*
* @param retention duration after which keys are automatically invalidated if not in use
* @param inUseCheck Function used to check if a key is considered in use
* @param postRemoval Function used to perform any operations required when a key is invalidated
*/
public Cache(long retention, Function<V> inUseCheck, Function<V> postRemoval) {
this.internal = new HashMap<K, V>();
this.expiry = TreeMultimap.create(new Comparator<Long>() {
@Override
public int compare(Long long1, Long long2) {
return long1.compareTo(long2);
}
},
new Comparator<K>() {
@Override
public int compare(K k1, K k2) {
return 0;
}
});
this.retention = retention;
this.inUseCheck = inUseCheck;
this.postRemoval = postRemoval;
}
/**
* Set a key and value pair. Keys are unique. Using an existing key will cause the old value to
* be overwritten and the expiration timer to be reset.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
*/
public void put(K key, V value) {
// Invalidate key - runs lazy check and ensures value won't be cleaned up early
invalidate(key);
internal.put(key, value);
expiry.put(System.currentTimeMillis() + retention, key);
}
/**
* Returns the value to which the specified key is mapped, or null if no value is mapped for the key.
*
* @param key the key whose associated value is to be returned
* @return the value to which the specified key is mapped, or null if no value is mapped for the key
*/
public V get(K key) {
// Run lazy check to clean cache
lazyCheck();
return internal.get(key);
}
/**
* Returns true if the specified key is mapped to a value.
*
* @param key key to check if a mapping exists for
* @return true if a mapping exists for the specified key
*/
public boolean containsKey(K key) {
// Run lazy check to clean cache
lazyCheck();
return internal.containsKey(key);
}
/**
* Forcibly invalidates a key, even if it is considered to be in use.
*
* @param key key to invalidate
*/
public void invalidate(K key) {
// Run lazy check to clean cache
lazyCheck();
if (!internal.containsKey(key)) {
// Value either not present or cleaned by lazy check. Either way, we're good
return;
}
// Remove stored object
internal.remove(key);
// Remove expiration entry - prevents more work later, plus prevents issues with values invalidating early
for (Iterator<Map.Entry<Long, K>> iterator = expiry.entries().iterator(); iterator.hasNext();) {
if (key.equals(iterator.next().getValue())) {
iterator.remove();
break;
}
}
}
/**
* Forcibly invalidates all keys, even if they are considered to be in use.
*/
public void invalidateAll() {
for (V value : internal.values()) {
postRemoval.run(value);
}
expiry.clear();
internal.clear();
}
/**
* Invalidate all expired keys that are not considered in use. If a key is expired but is
* considered in use by the provided Function, its expiration time is reset.
*/
private void lazyCheck() {
long now = System.currentTimeMillis();
long nextExpiry = now + retention;
for (Iterator<Map.Entry<Long, K>> iterator = expiry.entries().iterator(); iterator.hasNext();) {
Map.Entry<Long, K> entry = iterator.next();
if (entry.getKey() > now) {
break;
}
iterator.remove();
if (inUseCheck.run(internal.get(entry.getValue()))) {
expiry.put(nextExpiry, entry.getValue());
continue;
}
V value = internal.remove(entry.getValue());
if (value == null) {
continue;
}
postRemoval.run(value);
}
}
}

View file

@ -0,0 +1,12 @@
package com.lishid.openinv.util;
/**
* Abstraction for some simple cache calls.
*
* @author Jikoo
*/
public abstract class Function<V> {
public abstract boolean run(V value);
}

View file

@ -0,0 +1,108 @@
package com.lishid.openinv.utils;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.Callable;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.google.common.collect.ImmutableList;
public class UUIDFetcher implements Callable<Map<String, UUID>> {
private static final double PROFILES_PER_REQUEST = 100;
private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft";
private final JSONParser jsonParser = new JSONParser();
private final List<String> names;
private final boolean rateLimiting;
public UUIDFetcher(List<String> names, boolean rateLimiting) {
this.names = ImmutableList.copyOf(names);
this.rateLimiting = rateLimiting;
}
public UUIDFetcher(List<String> names) {
this(names, true);
}
@Override
public Map<String, UUID> call() throws Exception {
Map<String, UUID> uuidMap = new HashMap<String, UUID>();
int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST);
for (int i = 0; i < requests; i++) {
HttpURLConnection connection = createConnection();
String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size())));
writeBody(connection, body);
JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
for (Object profile : array) {
JSONObject jsonProfile = (JSONObject) profile;
String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name");
UUID uuid = UUIDFetcher.getUUID(id);
uuidMap.put(name.toLowerCase(), uuid);
}
if (rateLimiting && i != requests - 1) {
Thread.sleep(100L);
}
}
return uuidMap;
}
private static void writeBody(HttpURLConnection connection, String body) throws Exception {
OutputStream stream = connection.getOutputStream();
stream.write(body.getBytes());
stream.flush();
stream.close();
}
private static HttpURLConnection createConnection() throws Exception {
URL url = new URL(PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
return connection;
}
private static UUID getUUID(String id) {
return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" +id.substring(20, 32));
}
public static byte[] toBytes(UUID uuid) {
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
byteBuffer.putLong(uuid.getMostSignificantBits());
byteBuffer.putLong(uuid.getLeastSignificantBits());
return byteBuffer.array();
}
public static UUID fromBytes(byte[] array) {
if (array.length != 16) {
throw new IllegalArgumentException("Illegal byte array length: " + array.length);
}
ByteBuffer byteBuffer = ByteBuffer.wrap(array);
long mostSignificant = byteBuffer.getLong();
long leastSignificant = byteBuffer.getLong();
return new UUID(mostSignificant, leastSignificant);
}
public static UUID getUUIDOf(String name) throws Exception {
return new UUIDFetcher(Arrays.asList(name)).call().get(name);
}
}

View file

@ -0,0 +1,81 @@
package com.lishid.openinv.utils;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
public final class UUIDUtils {
private UUIDUtils() {}
private static Player getPlayer(String name) {
Validate.notNull(name, "Name cannot be null");
Player found = null;
String lowerName = name.toLowerCase();
int delta = Integer.MAX_VALUE;
Collection<? extends Player> players = Bukkit.getOnlinePlayers();
for (Player player : players) {
if (player.getName().toLowerCase().startsWith(lowerName)) {
int curDelta = player.getName().length() - lowerName.length();
if (curDelta < delta) {
found = player;
delta = curDelta;
}
if (curDelta == 0) break;
}
}
return found;
}
@SuppressWarnings("deprecation")
private static UUID getUUIDLocally(String name) {
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(name);
return offlinePlayer.hasPlayedBefore() ? offlinePlayer.getUniqueId() : null;
}
/**
* Returns the UUID of a player by their name.
*
* @param name the name of the player to get the UUID of
* @return the player's UUID or null
*/
public static UUID getPlayerUUID(String name) {
UUID uuid;
Player player = getPlayer(name);
if (player != null) {
uuid = player.getUniqueId();
} else {
if (Bukkit.getServer().getOnlineMode()) {
if (!Bukkit.getServer().isPrimaryThread()) {
UUIDFetcher fetcher = new UUIDFetcher(Arrays.asList(name));
Map<String, UUID> response;
try {
response = fetcher.call();
uuid = response.get(name.toLowerCase());
} catch (Exception e) {
uuid = getUUIDLocally(name);
}
} else {
uuid = getUUIDLocally(name);
}
} else {
uuid = getUUIDLocally(name);
}
}
return uuid;
}
}

View file

@ -0,0 +1,6 @@
config-version: 2
notify:
any-chest: true
silent-chest: true
items:
open-inv: STICK

View file

@ -0,0 +1,45 @@
name: OpenInv
main: com.lishid.openinv.OpenInv
version: ${openinv.version}
author: lishid
authors: [ShadowRanger]
description: >
This plugin allows you to open a player's inventory as a chest and interact with it in real time.
commands:
openinv:
aliases: [oi, inv, open]
description: Opens a player's inventory.
usage: |
/<command> - Opens last person's inventory.
/<command> <player> - Opens a player's inventory.
openender:
aliases: [oe]
description: Opens a player's ender chest.
usage: |
/<command> - Opens last person's ender chest.
/<command> <player> - Opens a player's ender chest.
searchinv:
aliases: [si]
description: Searches and lists players that have a specific item in their inventory.
usage: |
/<command> <item> [minAmount] - Item can be the Item ID or the CraftBukkit Item Name, minAmount is the minimum amount to be considered.
searchender:
aliases: [se]
description: Searches and lists players that have a specific item in their ender chest.
usage: |
/<command> <item> [minAmount] - Item can be the Item ID or the CraftBukkit Item Name, minAmount is the minimum amount to be considered.
toggleopeninv:
aliases: [toi, toggleoi, toggleinv]
description: Toggles the item openinv function.
usage: |
/<command> [check] - Checks whether item openinv is enabled.
anychest:
aliases: [ac]
description: Toggles the any chest function, which allows opening of blocked chests.
usage: |
/<command> [check] - Checks whether any chest is enabled.
silentchest:
aliases: [sc, silent]
description: Toggles the silent chest function, which hides the animation of a chest when opened or closed, and suppresses the sound.
usage: |
/<command> [check] - Checks whether silent chest is enabled.