1
0
mirror of https://github.com/nkomarn/harbor.git synced 2024-12-24 09:17:34 +01:00

More bug squashing

This commit is contained in:
Mykyta Komarn 2019-04-02 12:12:03 -07:00
parent 692480daec
commit 234c406b40
14 changed files with 120 additions and 315 deletions

View File

@ -4,6 +4,7 @@ main: mykyta.Harbor.Harbor
description: Ahoy, matey! Harbor is a Spigot plugin that redefines how sleep works in your server, making it easier for all the online players to get in bed quick and skip through the night! description: Ahoy, matey! Harbor is a Spigot plugin that redefines how sleep works in your server, making it easier for all the online players to get in bed quick and skip through the night!
author: Mykyta (TechToolbox) author: Mykyta (TechToolbox)
website: https://mykyta.tk website: https://mykyta.tk
api-version: 1.13
commands: commands:
harbor: harbor:

View File

@ -15,10 +15,13 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.inventory.meta.SkullMeta;
import mykyta.Harbor.Config; import mykyta.Harbor.Config;
import mykyta.Harbor.EncodingUtils;
import mykyta.Harbor.Util; import mykyta.Harbor.Util;
public class Sleeping implements CommandExecutor { public class Sleeping implements CommandExecutor {
private Inventory gui;
@SuppressWarnings("deprecation")
@Override @Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (sender instanceof Player) { if (sender instanceof Player) {
@ -26,19 +29,19 @@ public class Sleeping implements CommandExecutor {
World world = player.getWorld(); World world = player.getWorld();
Config config = new Config(); Config config = new Config();
ArrayList<Player> sleeping = Util.sleeping.get(world); ArrayList<Player> sleeping = Util.sleeping.get(world);
int slots = (((sleeping.size()) % 9)) * 9; //FIXME bad brok bad int slots = Math.min(54, ((sleeping.size() - 1) / 9 + 1) * 9);
System.out.println(slots); gui = Bukkit.createInventory(player, slots, config.getString("gui.sleeping"));
Inventory gui = Bukkit.createInventory(player, slots, config.getString("gui.sleeping"));
if (sleeping.size() > 0) sleeping.forEach(p -> { if (sleeping.size() > 0) sleeping.forEach(p -> {
ItemStack item = new ItemStack(Material.LEGACY_SKULL_ITEM, 1, (short) 3); //FIXME deprecated ItemStack item = new ItemStack(Material.PLAYER_HEAD, 1);
SkullMeta skull = (SkullMeta) item.getItemMeta(); SkullMeta meta = (SkullMeta) item.getItemMeta();
skull.setDisplayName(p.getName()); meta.setDisplayName(ChatColor.GRAY + p.getName());
/*ArrayList<String> lore = new ArrayList<String>(); /*ArrayList<String> lore = new ArrayList<String>();
lore.add("Custom head"); lore.add("Custom head");
skull.setLore(lore); skull.setLore(lore);
*/ */
skull.setOwner(p.getName()); meta.setOwner(p.getName());
item.setItemMeta(skull); item.setItemMeta(meta);
gui.setItem(sleeping.indexOf(p), item); gui.setItem(sleeping.indexOf(p), item);
}); });
@ -62,11 +65,6 @@ public class Sleeping implements CommandExecutor {
else Bukkit.getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.miscellaneous.prefix") + "There aren't any currently sleeping players in &o" + args[0] + "&r.")); else Bukkit.getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.miscellaneous.prefix") + "There aren't any currently sleeping players in &o" + args[0] + "&r."));
} }
} }
/*
StringBuilder sb = new StringBuilder();
ArrayList<Player> sleeping = Util.sleeping.get(w);
Bukkit.getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.miscellaneous.prefix")));
*/
} }
return true; return true;
} }

View File

@ -3,11 +3,15 @@ package mykyta.Harbor;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.ConsoleCommandSender;
public class Config { public class Config {
private Logger log = Bukkit.getLogger(); private Logger log = Bukkit.getLogger();
private String error = "An error occured while trying to read the configuration. The plugin may not function correctly as a result."; private Config config = new Config();
private String error = "An error occured while trying to read the configuration. Harbor may not function correctly as a result.";
private static Harbor harbor; private static Harbor harbor;
private ConsoleCommandSender c = Bukkit.getServer().getConsoleSender();
/** /**
* Sets main class instance for accessing configuration * Sets main class instance for accessing configuration
@ -22,8 +26,8 @@ public class Config {
* @param e Exception generated from reading configuration * @param e Exception generated from reading configuration
*/ */
private void error(Exception e) { private void error(Exception e) {
log.severe(error); c.sendMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.miscellaneous.prefix") + error));
if (Util.debug) System.err.println(e); if (Util.debug) e.printStackTrace();
} }
/** /**

View File

@ -1,130 +0,0 @@
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

@ -30,26 +30,26 @@ public class BedEnter implements Listener {
} }
if (event.getBedEnterResult() == BedEnterResult.OK) { if (event.getBedEnterResult() == BedEnterResult.OK) {
World w = event.getPlayer().getWorld(); Player p = event.getPlayer();
ArrayList<Player> included = util.getIncluded(w); World w = p.getWorld();
int excluded = w.getPlayers().size() - included.size(); ArrayList<Player> excluded = util.getExcluded(w);
if (included.contains(event.getPlayer())) { if (!excluded.contains(p)) {
util.add(w, event.getPlayer()); util.add(w, p);
// Chat messages // Chat messages
if (config.getBoolean("messages.chat.chat") && (config.getString("messages.chat.sleeping").length() != 0)) { if (config.getBoolean("messages.chat.chat") && (config.getString("messages.chat.sleeping").length() != 0)) {
Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.chat.sleeping") Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.chat.sleeping")
.replace("[sleeping]", String.valueOf(util.getSleeping(w)))) .replace("[sleeping]", String.valueOf(util.getSleeping(w))))
.replace("[online]", String.valueOf(included.size())) .replace("[online]", String.valueOf(util.getOnline(w) - excluded.size()))
.replace("[player]", event.getPlayer().getName()) .replace("[player]", p.getName())
.replace("[needed]", String.valueOf(util.getNeeded(w) - excluded))); .replace("[needed]", String.valueOf(util.getNeeded(w) - excluded.size())));
} }
// Skip night if possible // Skip night if possible
util.skip(w, excluded, util.getNeeded(w)); util.skip(w);
} }
else if (config.getString("messages.chat.bypass").length() != 0) event.getPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.chat.bypass"))); else if (config.getString("messages.chat.bypass").length() != 0) p.sendMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.chat.bypass")));
} }
} }
} }

View File

@ -19,23 +19,23 @@ public class BedLeave implements Listener {
public void onPlayerBedLeave(PlayerBedLeaveEvent event) { public void onPlayerBedLeave(PlayerBedLeaveEvent event) {
Util util = new Util(); Util util = new Util();
Config config = new Config(); Config config = new Config();
World w = event.getPlayer().getWorld(); Player p = event.getPlayer();
World w = p.getWorld();
ArrayList<Player> included = util.getIncluded(w); ArrayList<Player> excluded = util.getExcluded(w);
int excluded = w.getPlayers().size() - included.size();
// Decrement the sleeping count if player isn't excluded // Decrement the sleeping count if player isn't excluded
if (included.contains(event.getPlayer())) { if (!excluded.contains(p)) {
util.remove(w, event.getPlayer()); util.remove(w, p);
} }
// Send a chat message when player gets out of bed (if it's not day) // Send a chat message when player gets out of bed (if it's not day)
if (config.getBoolean("messages.chat.chat") && (config.getString("messages.chat.left").length() != 0) && !(w.getTime() > 0 && w.getTime() < 12300) && included.contains(event.getPlayer())) { if (config.getBoolean("messages.chat.chat") && (config.getString("messages.chat.left").length() != 0) && !(w.getTime() > 0 && w.getTime() < 12300) && !excluded.contains(p)) {
Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.chat.left") Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.chat.left")
.replace("[sleeping]", String.valueOf(util.getSleeping(w)))) .replace("[sleeping]", String.valueOf(util.getSleeping(w))))
.replace("[online]", String.valueOf(included.size())) .replace("[online]", String.valueOf(util.getOnline(w) - excluded.size()))
.replace("[player]", event.getPlayer().getName()) .replace("[player]", event.getPlayer().getName())
.replace("[needed]", String.valueOf(util.getNeeded(w) - excluded))); .replace("[needed]", String.valueOf(util.getNeeded(w) - excluded.size())));
} }
} }
} }

View File

@ -3,33 +3,18 @@ package mykyta.Harbor.Events;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import mykyta.Harbor.EncodingUtils; import mykyta.Harbor.Config;
import mykyta.Harbor.GUI;
import mykyta.Harbor.Util;
import mykyta.Harbor.GUI.GUIType;
public class GUIClick implements Listener { public class GUIClick implements Listener {
@SuppressWarnings("deprecation")
@EventHandler @EventHandler
public void onGUIClick(InventoryClickEvent event) { public void onGUIClick(InventoryClickEvent event) {
Config config = new Config();
String title = event.getInventory().getName(); 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 (title.equals(config.getString("gui.sleeping"))) {
if (type.equals("SLEEPING")) {
event.setCancelled(true); event.setCancelled(true);
return;
} }
} }
else System.out.println("asdfasd");;
}
} }

View File

@ -1,6 +1,7 @@
package mykyta.Harbor.Events; package mykyta.Harbor.Events;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
@ -11,9 +12,18 @@ public class PlayerLeave implements Listener {
@EventHandler @EventHandler
public void onPlayerLeave(PlayerQuitEvent event) { public void onPlayerLeave(PlayerQuitEvent event) {
Util util = new Util(); Util util = new Util();
World w = event.getPlayer().getWorld(); Player p = event.getPlayer();
int excluded = (w.getPlayers().size() - 1) - (util.getIncluded(w).size() - 1); World w = p.getWorld();
util.skip(event.getPlayer().getWorld(), excluded, util.getNeededDecremented(w));
Util.activity.remove(event.getPlayer()); new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
if (w.getPlayers().size() > 0 && Math.max(0, util.getNeeded(w) - util.getExcluded(w).size()) == 0) util.skip(w);
Util.activity.remove(p);
}
},
1000
);
} }
} }

View File

@ -1,43 +0,0 @@
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

@ -1,5 +0,0 @@
package mykyta.Harbor;
enum GUIType {
MENU, SETTINGS;
}

View File

@ -21,9 +21,6 @@ import mykyta.Harbor.Events.PlayerLeave;
import mykyta.Harbor.Events.Spawn; import mykyta.Harbor.Events.Spawn;
public class Harbor extends JavaPlugin { public class Harbor extends JavaPlugin {
private Logger log = Bukkit.getLogger();
private Updater updater = new Updater();
public void onEnable() { public void onEnable() {
Config config = new Config(); Config config = new Config();
Util util = new Util(); Util util = new Util();
@ -40,26 +37,17 @@ public class Harbor extends JavaPlugin {
Bukkit.getPluginManager().registerEvents(new PlayerJoin(), this); Bukkit.getPluginManager().registerEvents(new PlayerJoin(), this);
Bukkit.getPluginManager().registerEvents(new PlayerLeave(), this); Bukkit.getPluginManager().registerEvents(new PlayerLeave(), this);
util.setupNMS(); 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.clock") * 20); Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Task(), 0L, config.getInteger("values.clock") * 20);
if (this.getConfig().getBoolean("debug")) Util.debug = true;
// Check for updates
if (this.getConfig().getBoolean("features.notifier")) { 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..."); if (Util.debug) Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.miscellaneous.prefix")) + "Checking for new updates...");
Updater updater = new Updater();
updater.check(); updater.check();
} }
// FIXME Initialize HashMap items for every world
for (World w : Bukkit.getServer().getWorlds()) { for (World w : Bukkit.getServer().getWorlds()) {
ArrayList<Player> sleeping = new ArrayList<Player>(); ArrayList<Player> sleeping = new ArrayList<Player>();
Util.sleeping.put(w, sleeping); Util.sleeping.put(w, sleeping);
} }
//FIXME temp add players to the count on realad
Bukkit.getServer().getWorlds().forEach(w -> { Bukkit.getServer().getWorlds().forEach(w -> {
w.getPlayers().forEach(p -> { w.getPlayers().forEach(p -> {
Util.activity.put(p, System.currentTimeMillis()); Util.activity.put(p, System.currentTimeMillis());

View File

@ -1,9 +1,9 @@
package mykyta.Harbor; package mykyta.Harbor;
import java.util.ArrayList; import java.util.concurrent.TimeUnit;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.ChatColor;
public class Task implements Runnable { public class Task implements Runnable {
@ -13,32 +13,19 @@ public class Task implements Runnable {
@Override @Override
public void run() { public void run() {
Bukkit.getServer().getWorlds().forEach(w -> { Bukkit.getServer().getWorlds().forEach(w -> {
// Display a title if it's time to sleep
if (w.getTime() >= 12516 && w.getTime() <= 12547) w.getPlayers().forEach(p -> { if (w.getTime() >= 12516 && w.getTime() <= 12547) w.getPlayers().forEach(p -> {
util.sendTitle(p, config.getString("messages.title.evening.top"), config.getString("messages.title.evening.bottom")); util.sendTitle(p, config.getString("messages.title.evening.top"), config.getString("messages.title.evening.bottom"));
}); });
if (util.getSleeping(w) > 0 && Math.max(0, util.getNeeded(w) - util.getExcluded(w).size()) == 0) {
// Fix time if players leave bed naturally util.skip(w);
/*if (w.getTime() >= 0 && w.getTime() <= 100) { }
ArrayList<Player> list = new ArrayList<Player>();
Util.sleeping.put(w, list);
}*/
// Send actionbar if someone's sleeping
if (util.getSleeping(w) > 0 && util.getSleeping(w) < w.getPlayers().size()) {w.getPlayers().forEach(p -> {util.sendActionbar(p, config.getString("messages.actionbar.sleeping"), w);});} if (util.getSleeping(w) > 0 && util.getSleeping(w) < w.getPlayers().size()) {w.getPlayers().forEach(p -> {util.sendActionbar(p, config.getString("messages.actionbar.sleeping"), w);});}
else if (util.getSleeping(w) == w.getPlayers().size()) {w.getPlayers().forEach(p -> {util.sendActionbar(p, config.getString("messages.actionbar.everyone"), w);});} else if (util.getSleeping(w) == w.getPlayers().size()) {w.getPlayers().forEach(p -> {util.sendActionbar(p, config.getString("messages.actionbar.everyone"), w);});}
}); /*if (TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - Util.activity.get(p)) > config.getInteger("values.timeout")) {
/*
// TODO if player hasnt moved for x minutes then put in afk
Bukkit.getServer().getWorlds().forEach(w -> {
w.getPlayers().forEach(p -> {
if (TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - Util.activity.get(p)) > config.getInteger("values.timeout")) {
///TODO custom afk prefix ///TODO custom afk prefix
p.setPlayerListName(ChatColor.GRAY + "[AFK] - " + ChatColor.RESET + p.getDisplayName()); p.setPlayerListName(ChatColor.GRAY + "[AFK] - " + ChatColor.RESET + p.getDisplayName());
System.out.println(p.getName() + " is AFK."); System.out.println(p.getName() + " is AFK.");
} }*/
}); });
});*/
} }
} }

View File

@ -12,6 +12,10 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.ConsoleCommandSender;
public class Updater { public class Updater {
private String latest = ""; private String latest = "";
@ -20,12 +24,15 @@ public class Updater {
* @see https://spiget.org/ * @see https://spiget.org/
*/ */
public boolean check() { public boolean check() {
ConsoleCommandSender c = Bukkit.getServer().getConsoleSender();
Util util = new Util();
Config config = new Config();
try { try {
URL url = new URL("https://api.spiget.org/v2/resources/60088/versions"); URL url = new URL("https://api.spiget.org/v2/resources/60088/versions");
URLConnection request = url.openConnection(); URLConnection request = url.openConnection();
request.connect(); request.connect();
Util util = new Util();
ArrayList<String> releases = new ArrayList<String>(); ArrayList<String> releases = new ArrayList<String>();
JsonParser parser = new JsonParser(); JsonParser parser = new JsonParser();
JsonElement element = parser.parse(new InputStreamReader((InputStream) request.getContent())); JsonElement element = parser.parse(new InputStreamReader((InputStream) request.getContent()));
@ -36,23 +43,22 @@ public class Updater {
releases.add(id.get("name").getAsString()); releases.add(id.get("name").getAsString());
} }
// TODO Beautify console messages
if (util.version.equals(releases.get(releases.size() - 1))) { if (util.version.equals(releases.get(releases.size() - 1))) {
System.out.println("Running latest version."); if (Util.debug) c.sendMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.miscellaneous.prefix")) + "Currently running the latest version of Harbor.");
return false; return false;
} }
else if (!releases.contains(util.version)) { else if (!releases.contains(util.version)) {
System.out.println("Hmm... looks like you're using some sort of time travel technology. Welp, at least you don't have updates to worry about any time soon."); if (config.getBoolean("features.notifier")) c.sendMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.miscellaneous.prefix")) + "You have a version of Harbor that is newer than the latest available version. Great work!");
return false; return false;
} }
else { else {
latest = releases.get(releases.size() - 1); latest = releases.get(releases.size() - 1);
System.out.println("Running an outdated version! Latest is " + latest); if (config.getBoolean("features.notifier")) c.sendMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.miscellaneous.prefix")) + "Currently running an outdated version of Harbor. The latest available release is version " + latest + ".");
return true; return true;
} }
} }
catch (IOException e) { catch (IOException e) {
System.out.println("Failed to check for updates."); if (Util.debug) c.sendMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.miscellaneous.prefix")) + "Failed to check for updated releases of Harbor.");
return false; return false;
} }
} }

View File

@ -18,7 +18,8 @@ public class Util {
public static HashMap<World, ArrayList<Player>> sleeping = new HashMap<World, ArrayList<Player>>(); public static HashMap<World, ArrayList<Player>> sleeping = new HashMap<World, ArrayList<Player>>();
public static HashMap<Player, Long> activity = new HashMap<Player, Long>(); public static HashMap<Player, Long> activity = new HashMap<Player, Long>();
public static ArrayList<Player> afk = new ArrayList<Player>(); public static ArrayList<Player> afk = new ArrayList<Player>();
public String version = "1.5";
public String version = "1.1";
public static boolean debug = false; public static boolean debug = false;
private Logger log = Bukkit.getLogger(); private Logger log = Bukkit.getLogger();
private static NMS nms; private static NMS nms;
@ -31,7 +32,7 @@ public class Util {
String version = ""; String version = "";
try {version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];} try {version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];}
catch (ArrayIndexOutOfBoundsException e) { catch (ArrayIndexOutOfBoundsException e) {
log.severe("Could not get server version. The plugin may not function correctly as a result."); Bukkit.getServer().getConsoleSender().sendMessage(config.getString("messages.miscellaneous.prefix") + "Could not get server version. The plugin may not function correctly as a result.");
if (Util.debug) System.err.println(e); if (Util.debug) System.err.println(e);
} }
Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.miscellaneous.prefix") + config.getString("messages.miscellaneous.running").replace("[version]", version))); Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.miscellaneous.prefix") + config.getString("messages.miscellaneous.running").replace("[version]", version)));
@ -58,58 +59,64 @@ public class Util {
public void remove(World world, Player player) { public void remove(World world, Player player) {
ArrayList<Player> list = Util.sleeping.get(world); ArrayList<Player> list = Util.sleeping.get(world);
list.remove(player); list.remove(player);
Util.sleeping.put(world, list);
} }
/** /**
* Fetch the sleeping count for a world * Fetch the sleeping count for a world
* @param world World to fetch count for * @param world World to fetch count for
*/ */
public int getSleeping(World world) { public int getSleeping(World w) {
return Util.sleeping.get(world).size(); return Util.sleeping.get(w).size();
} }
/** /**
* Fetch the amount of players needed to skip night * Fetch the amount of players needed to skip night
* @param world World to fetch count for * @param world World to fetch count for
*/ */
public int getNeeded(World world) { public int getNeeded(World w) {
return Math.max(0, (int) Math.ceil(world.getPlayers().size() * (config.getDouble("values.percent") / 100) - this.getSleeping(world))); //FIXME i think its broke
return Math.max(0, (int) Math.ceil(w.getPlayers().size() * (config.getDouble("values.percent") / 100) - this.getSleeping(w)));
} }
/** /**
* Fetch the amount of players needed to skip night (minus one) * Get players in a world (returns zero if negative)
* @param world World to fetch count for * @param world World to check player count for
*/ */
public int getNeededDecremented(World world) { public int getOnline(World w) {
return Math.max(0, (int) Math.ceil((world.getPlayers().size() - 1) * (config.getDouble("values.percent") / 100) - this.getSleeping(world))); return Math.max(0, w.getPlayers().size());
} }
/** /**
* Fetch the included players in a world * Fetch the excluded players in a world
* @param world World to fetch count for * @param world World to fetch count for
*/ */
public ArrayList<Player> getIncluded(World world) { public ArrayList<Player> getExcluded(World w) {
ArrayList<Player> players = new ArrayList<Player>(); ArrayList<Player> excluded = new ArrayList<Player>();
world.getPlayers().forEach(p -> { w.getPlayers().forEach(p -> {
if (this.isIncluded(p)) players.add(p); if (this.isExcluded(p)) excluded.add(p);
}); });
return players; return excluded;
} }
/** /**
* Returns true if player should be included in count * Returns whether or not a player should be excluded from the sleep count
* @param player Target player * @param player Target player
*/ */
public boolean isIncluded(Player p) { public boolean isExcluded(Player p) {
boolean state = true; boolean state = true;
if (config.getBoolean("features.ignore")) if (p.getGameMode() == GameMode.SURVIVAL) state = true; else state = false; if (config.getBoolean("features.ignore")) if (p.getGameMode() == GameMode.SURVIVAL) state = false; else state = true;
if (config.getBoolean("features.bypass")) if (p.hasPermission("harbor.bypass")) state = false; else state = true; if (config.getBoolean("features.bypass")) if (p.hasPermission("harbor.bypass")) state = true; else state = false;
if (TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - activity.get(p)) > config.getInteger("values.timeout")) state = false; if (TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - activity.get(p)) > config.getInteger("values.timeout")) state = true;
return state; return state;
} }
/**
* Returns if player is considered AFK
*/
public void isAFK(Player p) {
}
/** /**
* Sends an actionbar message to the given player * Sends an actionbar message to the given player
* @param player Player to show actionbar to * @param player Player to show actionbar to
@ -127,13 +134,12 @@ public class Util {
* @param world World to fetch information for * @param world World to fetch information for
*/ */
public void sendActionbar(Player p, String message, World w) { public void sendActionbar(Player p, String message, World w) {
ArrayList<Player> included = this.getIncluded(w); ArrayList<Player> excluded = this.getExcluded(w);
int excluded = w.getPlayers().size() - included.size();
nms.sendActionbar(p, message nms.sendActionbar(p, message
.replace("[sleeping]", String.valueOf(this.getSleeping(w))) .replace("[sleeping]", String.valueOf(this.getSleeping(w)))
.replace("[online]", String.valueOf(included.size())) .replace("[online]", String.valueOf(w.getPlayers().size() - excluded.size()))
.replace("[needed]", String.valueOf(this.getNeeded(w) - excluded))); .replace("[needed]", String.valueOf(this.getNeeded(w) - excluded.size())));
} }
/** /**
@ -158,9 +164,8 @@ public class Util {
* Skips the night in the specified world (if possible) * Skips the night in the specified world (if possible)
* @param World to return value for * @param World to return value for
*/ */
public void skip(World w, int excluded, int needed) { public void skip(World w) {
if (config.getBoolean("features.skip") && (needed - excluded) == 0) { if (config.getBoolean("features.skip") && this.getNeeded(w) - this.getExcluded(w).size() == 0) {
System.out.println("set time");
w.setTime(1000L); w.setTime(1000L);
// Set weather to clear // Set weather to clear
@ -172,7 +177,6 @@ public class Util {
// Display messages // 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("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")) { if (config.getBoolean("features.title")) {
System.out.println("sent message");
w.getPlayers().forEach(p -> { w.getPlayers().forEach(p -> {
this.sendTitle(p, config.getString("messages.title.morning.top"), config.getString("messages.title.morning.bottom")); this.sendTitle(p, config.getString("messages.title.morning.top"), config.getString("messages.title.morning.bottom"));
}); });