1
0
mirror of https://github.com/nkomarn/harbor.git synced 2024-06-26 14:54:46 +02:00

Fix bed entry/updating when players leave.

This commit is contained in:
Mykyta Komarn 2019-04-01 16:03:29 -07:00
parent 4cc227f9fe
commit 7283fa8000
13 changed files with 318 additions and 43 deletions

View File

@ -7,16 +7,16 @@
# An open-source project by Mykyta (TechToolbox)
# https://mykyta.tk/
#
# Ahoy, matey! You've arrived at the configuration file, where things get scary.
# Ahoy, matey! You've arrived at the configuration file, where things get a bit scary.
# Every single thing within this plugin is customizable (at least I tried to make it that way),
# so every message and plugin module can be modified here. If you would like to report a bug
# or suggest a feature, make sure to add an issue on the GitHub page for this plugin!
# GitHub URL: https://github.com/nkomarn/Harbor/issues
values:
# How often to run the clock task (used to detect many things, such as AFK, and to time actionbar)
# If your server is relatively slower, increase this value
check: 1
# How often to run the clock task (used to detect sleep, AFK players, time actionbar, etc.)
# Lower this value for relatively slow servers
clock: 1
# Percent of players that need to sleep to skip night (must be between 0 to 100)
percent: 50
# Time that it takes to be considered AFK (in minutes)
@ -26,7 +26,7 @@ features:
# Toggle night skipping feature. Configure amount of players needed to skip above (percent)
skip: true
# Clear weather when skipping night
clearWeather: true
weather: true
# Toggle exclusion of operators/players with permission "harbor.bypass" from sleep count
bypass: false
# Toggle exclusion of players in creative and spectator mode
@ -90,6 +90,10 @@ messages:
# Sent when command argument isn't recognized
unrecognized: "&7Not recognized."
gui:
# Title for menu that shows when a player executes /sleeping
sleeping: "Sleeping players"
# Version identifier (do not change)
version: 1.5
debug: true

View File

@ -1,9 +1,12 @@
package mykyta.Harbor;
package mykyta.Harbor.Commands;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import mykyta.Harbor.Config;
import mykyta.Harbor.Util;
public class Command implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, org.bukkit.command.Command command, String label, String[] args) {

View File

@ -14,6 +14,9 @@ import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import mykyta.Harbor.Config;
import mykyta.Harbor.EncodingUtils;
import mykyta.Harbor.GUI;
import mykyta.Harbor.Util;
public class Sleeping implements CommandExecutor {
@ -22,11 +25,13 @@ public class Sleeping implements CommandExecutor {
if (sender instanceof Player) {
Player player = (Player) sender;
World world = player.getWorld();
Inventory gui = Bukkit.createInventory(player, 9, "Sleeping players");
Config config = new Config();
String title = config.getString("gui.sleeping") + " " + EncodingUtils.encodeString("{'GUIType': 'SLEEPING'}");
Inventory gui = Bukkit.createInventory(player, 9, title);
ArrayList<Player> sleeping = Util.sleeping.get(world);
if (sleeping.size() > 0) sleeping.forEach(p -> {
ItemStack item = new ItemStack(Material.LEGACY_SKULL_ITEM, 1, (short) 3);
ItemStack item = new ItemStack(Material.LEGACY_SKULL_ITEM, 1, (short) 3); //FIXME deprecated
SkullMeta skull = (SkullMeta) item.getItemMeta();
skull.setDisplayName(p.getName());
/*ArrayList<String> lore = new ArrayList<String>();

View File

@ -0,0 +1,130 @@
package mykyta.Harbor;
import java.nio.charset.Charset;
import org.bukkit.ChatColor;
/**
* Utility to hide data using encoding with ChatColor
* @see https://gist.github.com/filoghost/f53ecb7b014c40b66bdc
*/
public class EncodingUtils {
// String constants.
private static final String SEQUENCE_HEADER = "" + ChatColor.RESET + ChatColor.BOLD + ChatColor.RESET;
private static final String SEQUENCE_FOOTER = "" + ChatColor.RESET + ChatColor.STRIKETHROUGH + ChatColor.RESET;
public static String encodeString(String hiddenString) {
return quote(stringToColors(hiddenString));
}
public static boolean hasHiddenString(String input) {
if (input == null) return false;
return input.indexOf(SEQUENCE_HEADER) > -1 && input.indexOf(SEQUENCE_FOOTER) > -1;
}
public static String extractHiddenString(String input) {
return colorsToString(extract(input));
}
public static String replaceHiddenString(String input, String hiddenString) {
if (input == null) return null;
int start = input.indexOf(SEQUENCE_HEADER);
int end = input.indexOf(SEQUENCE_FOOTER);
if (start < 0 || end < 0) {
return null;
}
return input.substring(0, start + SEQUENCE_HEADER.length()) + stringToColors(hiddenString) + input.substring(end, input.length());
}
/**
* Internal stuff.
*/
private static String quote(String input) {
if (input == null) return null;
return SEQUENCE_HEADER + input + SEQUENCE_FOOTER;
}
private static String extract(String input) {
if (input == null) return null;
int start = input.indexOf(SEQUENCE_HEADER);
int end = input.indexOf(SEQUENCE_FOOTER);
if (start < 0 || end < 0) {
return null;
}
return input.substring(start + SEQUENCE_HEADER.length(), end);
}
private static String stringToColors(String normal) {
if (normal == null) return null;
byte[] bytes = normal.getBytes(Charset.forName("UTF-8"));
char[] chars = new char[bytes.length * 4];
for (int i = 0; i < bytes.length; i++) {
char[] hex = byteToHex(bytes[i]);
chars[i * 4] = ChatColor.COLOR_CHAR;
chars[i * 4 + 1] = hex[0];
chars[i * 4 + 2] = ChatColor.COLOR_CHAR;
chars[i * 4 + 3] = hex[1];
}
return new String(chars);
}
private static String colorsToString(String colors) {
if (colors == null) return null;
colors = colors.toLowerCase().replace("" + ChatColor.COLOR_CHAR, "");
if (colors.length() % 2 != 0) {
colors = colors.substring(0, (colors.length() / 2) * 2);
}
char[] chars = colors.toCharArray();
byte[] bytes = new byte[chars.length / 2];
for (int i = 0; i < chars.length; i += 2) {
bytes[i / 2] = hexToByte(chars[i], chars[i + 1]);
}
return new String(bytes, Charset.forName("UTF-8"));
}
private static int hexToUnsignedInt(char c) {
if (c >= '0' && c <= '9') {
return c - 48;
} else if (c >= 'a' && c <= 'f') {
return c - 87;
} else {
throw new IllegalArgumentException("Invalid hex char: out of range");
}
}
private static char unsignedIntToHex(int i) {
if (i >= 0 && i <= 9) {
return (char) (i + 48);
} else if (i >= 10 && i <= 15) {
return (char) (i + 87);
} else {
throw new IllegalArgumentException("Invalid hex int: out of range");
}
}
private static byte hexToByte(char hex1, char hex0) {
return (byte) (((hexToUnsignedInt(hex1) << 4) | hexToUnsignedInt(hex0)) + Byte.MIN_VALUE);
}
private static char[] byteToHex(byte b) {
int unsignedByte = (int) b - Byte.MIN_VALUE;
return new char[]{unsignedIntToHex((unsignedByte >> 4) & 0xf), unsignedIntToHex(unsignedByte & 0xf)};
}
}

View File

@ -29,45 +29,27 @@ public class BedEnter implements Listener {
}
if (event.getBedEnterResult() == BedEnterResult.OK) {
World world = event.getPlayer().getWorld();
ArrayList<Player> included = util.getIncluded(world);
int excluded = world.getPlayers().size() - included.size();
World w = event.getPlayer().getWorld();
ArrayList<Player> included = util.getIncluded(w);
int excluded = w.getPlayers().size() - included.size();
// Increment the sleeping count TODO bypass stuff
if (included.contains(event.getPlayer())) {
util.add(world, event.getPlayer());
util.add(w, event.getPlayer());
// Send a chat message when a player is sleeping
if (config.getBoolean("messages.chat.chat") && (config.getString("messages.chat.sleeping").length() != 0)) {
Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.chat.sleeping")
.replace("[sleeping]", String.valueOf(util.getSleeping(world))))
.replace("[sleeping]", String.valueOf(util.getSleeping(w))))
.replace("[online]", String.valueOf(included.size()))
.replace("[player]", event.getPlayer().getName())
.replace("[needed]", String.valueOf(util.getNeeded(world) - excluded)));
.replace("[needed]", String.valueOf(util.getNeeded(w) - excluded)));
}
}
else if (config.getString("messages.chat.bypass").length() != 0) event.getPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.chat.bypass")));
// Skip night if threshold is reached
if (config.getBoolean("features.skip") && (util.getNeeded(world) - excluded) == 0) {
Bukkit.getServer().getWorld(event.getPlayer().getWorld().getName()).setTime(1000L);
// Clear weather when it turns day
if (config.getBoolean("features.clearWeather")) {
event.getPlayer().getWorld().setStorm(false);
event.getPlayer().getWorld().setThundering(false);
}
// Send a chat message when night is skipped
if (config.getBoolean("messages.chat.chat") && (config.getString("messages.chat.skipped").length() != 0)) Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.chat.skipped")));
// Display title messages
if (config.getBoolean("features.title")) {
for (Player p : event.getPlayer().getWorld().getPlayers()) {
util.sendTitle(p, config.getString("messages.title.morning.top"), config.getString("messages.title.morning.bottom"));
}
}
}
// Skip night if possible
util.skip(w, excluded, util.getNeeded(w));
}
}
}

View File

@ -0,0 +1,35 @@
package mykyta.Harbor.Events;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import mykyta.Harbor.EncodingUtils;
import mykyta.Harbor.GUI;
import mykyta.Harbor.Util;
import mykyta.Harbor.GUI.GUIType;
public class GUIClick implements Listener {
@EventHandler
public void onGUIClick(InventoryClickEvent event) {
String title = event.getInventory().getName();
if (EncodingUtils.hasHiddenString(title)) {
// Extract hidden data
String raw = EncodingUtils.extractHiddenString(title);
JSONParser parser = new JSONParser();
JSONObject json = new JSONObject();
try {json = (JSONObject) parser.parse(raw);}
catch (Exception e) {if (Util.debug) e.printStackTrace();}
String type = json.get("GUIType").toString();
System.out.println("type");
if (type.equals("SLEEPING")) {
event.setCancelled(true);
return;
}
}
else System.out.println("asdfasd");;
}
}

View File

@ -0,0 +1,12 @@
package mykyta.Harbor.Events;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryDragEvent;
public class GUIDrag implements Listener {
@EventHandler
public void onGUIDrag(InventoryDragEvent event) {
}
}

View File

@ -16,9 +16,8 @@ public class PlayerJoin implements Listener {
Util util = new Util();
String json = "[{\"text\":\"[prefix]§7Hey there, Harbor [version] was released! \"},{\"text\":\"§7§oClick §7§ome §7§oto §7§oupdate!\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/harbor update\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"§a§l↑ §7Update Harbor.\"}}]";
if (event.getPlayer().isOp() && updater.check()) util.sendJSONMessage(event.getPlayer(), json.replace("[version]", updater.getLatest()).replace("[prefix]", config.getString("messages.miscellaneous.prefix")).replace("&", "§"));
if (event.getPlayer().isOp() && updater.check() && config.getBoolean("features.notifier")) util.sendJSONMessage(event.getPlayer(), json.replace("[version]", updater.getLatest()).replace("[prefix]", config.getString("messages.miscellaneous.prefix")).replace("&", "§"));
// Add activity entry
Util.activity.put(event.getPlayer(), System.currentTimeMillis());
}
}

View File

@ -0,0 +1,18 @@
package mykyta.Harbor.Events;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
import mykyta.Harbor.Util;
public class PlayerLeave implements Listener {
@EventHandler
public void onPlayerLeave(PlayerQuitEvent event) {
Util util = new Util();
World w = event.getPlayer().getWorld();
int excluded = (w.getPlayers().size() - 1) - (util.getIncluded(w).size() - 1);
util.skip(event.getPlayer().getWorld(), excluded, util.getNeededDecremented(w));
}
}

View File

@ -0,0 +1,43 @@
package mykyta.Harbor;
import org.bukkit.Bukkit;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
/**
* A custom Inventory wrapper for Harbor GUIs
* @see https://www.spigotmc.org/threads/custom-inventory-types.150414/
*/
public class GUI {
//TODO ADD JAVADOC COMMENTS ALL OVER THIS FILE
public enum GUIType {
SLEEPING, BLACKLIST
}
private final Inventory inventory;
private final GUIType type;
public GUI(Inventory inventory, GUIType type) {
this.inventory = inventory;
this.type = type;
}
public GUI(int size, String name, GUIType type) {
this.inventory = Bukkit.createInventory(null, size, name);
this.type = type;
}
public Inventory getInventory() {
return this.inventory;
}
public GUIType getType() {
return this.type;
}
public void setItem(int slot, ItemStack itemstack) {
this.inventory.setItem(slot, itemstack);
}
}

View File

@ -9,11 +9,15 @@ import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import mykyta.Harbor.Commands.Command;
import mykyta.Harbor.Commands.Sleeping;
import mykyta.Harbor.Events.BedEnter;
import mykyta.Harbor.Events.BedLeave;
import mykyta.Harbor.Events.GUIClick;
import mykyta.Harbor.Events.GUIDrag;
import mykyta.Harbor.Events.Move;
import mykyta.Harbor.Events.PlayerJoin;
import mykyta.Harbor.Events.PlayerLeave;
public class Harbor extends JavaPlugin {
private Logger log = Bukkit.getLogger();
@ -29,24 +33,23 @@ public class Harbor extends JavaPlugin {
Bukkit.getPluginManager().registerEvents(new BedEnter(), this);
Bukkit.getPluginManager().registerEvents(new BedLeave(), this);
Bukkit.getPluginManager().registerEvents(new Move(), this);
if (config.getBoolean("features.notifier")) Bukkit.getPluginManager().registerEvents(new PlayerJoin(), this);
Bukkit.getPluginManager().registerEvents(new GUIClick(), this);
Bukkit.getPluginManager().registerEvents(new GUIDrag(), this);
Bukkit.getPluginManager().registerEvents(new PlayerJoin(), this);
Bukkit.getPluginManager().registerEvents(new PlayerLeave(), this);
util.setupNMS();
// Enable debugging if set in configuration
if (this.getConfig().getBoolean("debug")) Util.debug = true;
// Start timer task
Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Task(), 0L, config.getInteger("values.check") * 20);
Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Task(), 0L, config.getInteger("values.clock") * 20);
// Check for updates
if (this.getConfig().getBoolean("features.notifier")) {
if (Util.debug) Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.miscellaneous.prefix")) + "Checking for new updates...");
updater.check();
}
// TODO "Damage" players to kick them out of bed (reset counter)--- may not need to do cause of new system
// FIXME Initialize HashMap items for every world
for (World w : Bukkit.getServer().getWorlds()) {

View File

@ -1,5 +1,6 @@
package mykyta.Harbor;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.bukkit.Bukkit;
@ -25,6 +26,7 @@ public class Task implements Runnable {
}
}
/*
// TODO if player hasnt moved for x minutes then put in afk
Bukkit.getServer().getWorlds().forEach(w -> {
w.getPlayers().forEach(p -> {
@ -34,7 +36,7 @@ public class Task implements Runnable {
System.out.println(p.getName() + " is AFK.");
}
});
});
});*/
}
/* @Override

View File

@ -79,6 +79,14 @@ public class Util {
public int getNeeded(World world) {
return Math.max(0, (int) Math.ceil(world.getPlayers().size() * (config.getDouble("values.percent") / 100) - this.getSleeping(world)));
}
/**
* Fetch the amount of players needed to skip night (minus one)
* @param world World to fetch count for
*/
public int getNeededDecremented(World world) {
return Math.max(0, (int) Math.ceil((world.getPlayers().size() - 1) * (config.getDouble("values.percent") / 100) - this.getSleeping(world)));
}
/**
* Fetch the included players in a world
@ -163,4 +171,35 @@ public class Util {
public void sendTitle(Player player, String top, String bottom) {
nms.sendTitle(player, top, bottom);
}
/**
* Skips the night in the specified world (if possible)
* @param World to return value for
*/
public void skip(World w, int excluded, int needed) {
System.out.println("needed: "+ needed);
System.out.println("Exclkuded: " + excluded);
System.out.println("difference: " + (needed - excluded));
if (config.getBoolean("features.skip") && (needed - excluded) == 0) {
System.out.println("set time");
w.setTime(1000L);
// Set weather to clear
if (config.getBoolean("features.weather")) {
w.setStorm(false);
w.setThundering(false);
}
// Display messages
if (config.getBoolean("messages.chat.chat") && (config.getString("messages.chat.skipped").length() != 0)) Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.chat.skipped")));
if (config.getBoolean("features.title")) {
System.out.println("sent message");
w.getPlayers().forEach(p -> {
this.sendTitle(p, config.getString("messages.title.morning.top"), config.getString("messages.title.morning.bottom"));
});
}
}
}
}