1
0
mirror of https://github.com/nkomarn/harbor.git synced 2024-11-16 07:05:22 +01:00

I've been working for ages now so here's the updated stuff...

This commit is contained in:
Mykyta Komarn 2019-04-01 14:09:56 -07:00
parent f3e7a3b853
commit 4cc227f9fe
14 changed files with 269 additions and 68 deletions

View File

@ -14,10 +14,13 @@
# GitHub URL: https://github.com/nkomarn/Harbor/issues
values:
# How often (in seconds) to check if a player is in a bed (increase for slower servers)
# 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
# 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)
timeout: 1
features:
# Toggle night skipping feature. Configure amount of players needed to skip above (percent)
@ -27,9 +30,11 @@ features:
# Toggle exclusion of operators/players with permission "harbor.bypass" from sleep count
bypass: false
# Toggle exclusion of players in creative and spectator mode
ignoreCreative: true
ignore: true
# Prevent all players from entering a bed
block: false
# Display a title in the morning and when going to bed
title: true
# Display debug information in console
debug: false
# Displays a notification when a new update is released
@ -60,9 +65,19 @@ messages:
everyone: "&eEveryone is sleeping. Sweet dreams!"
# Shown when a player tries to sleep and sleeping is blocked
blocked: "&cSleeping is disabled."
title:
morning:
top: "&6Good morning!"
bottom: "&7Ah, such wonderful weather."
evening:
top: "&cIt's getting a bit late."
bottom: "&7Might want to hit the hay..."
sleeping:
top: "&8ZZZZZZ..."
bottom: "&7Sweet dreams."
miscellaneous:
# Prefix for Harbor command/miscellaneous messages
prefix: "&8&l(&6&lHarbor&8&l) "
prefix: "&8&l(&6&lHarbor&8&l)&r "
# Display server version in console
running: "&7Running on version [version]."
# Sent in console when the plugin isn't compatible with the server

View File

@ -9,4 +9,7 @@ commands:
harbor:
description: List information and control Harbor.
usage: /<command>
sleeping:
description: Show a list of the sleeping players in your world.
usage: /<command>

View File

@ -0,0 +1,51 @@
package mykyta.Harbor.Commands;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import mykyta.Harbor.Util;
public class Sleeping implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String args, String[] label) {
if (sender instanceof Player) {
Player player = (Player) sender;
World world = player.getWorld();
Inventory gui = Bukkit.createInventory(player, 9, "Sleeping players");
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);
SkullMeta skull = (SkullMeta) item.getItemMeta();
skull.setDisplayName(p.getName());
/*ArrayList<String> lore = new ArrayList<String>();
lore.add("Custom head");
skull.setLore(lore);
*/
skull.setOwner(p.getName());
item.setItemMeta(skull);
gui.setItem(sleeping.indexOf(p), item);
});
player.openInventory(gui);
}
else {
//TODO console stuff
}
return true;
}
}

View File

@ -4,7 +4,6 @@ import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
@ -31,35 +30,26 @@ public class BedEnter implements Listener {
if (event.getBedEnterResult() == BedEnterResult.OK) {
World world = event.getPlayer().getWorld();
// Create list of players included in sleep count
ArrayList<Player> players = new ArrayList<Player>();
world.getPlayers().stream().filter(p -> util.isSurvival(event.getPlayer())).forEach(p -> {
if (true) {
players.add(p);
}
});
System.out.println(players);
System.out.println("Included players: " + players.size());
ArrayList<Player> included = util.getIncluded(world);
int excluded = world.getPlayers().size() - included.size();
// Increment the sleeping count TODO bypass stuff
if (players.contains(event.getPlayer())) {
util.increment(world);
if (included.contains(event.getPlayer())) {
util.add(world, 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.fetch(world))))
.replace("[online]", String.valueOf(world.getPlayers().size()))
.replace("[sleeping]", String.valueOf(util.getSleeping(world))))
.replace("[online]", String.valueOf(included.size()))
.replace("[player]", event.getPlayer().getName())
.replace("[needed]", String.valueOf(Math.max(0, (int) Math.ceil(world.getPlayers().size() * (config.getDouble("values.percent") / 100) - util.fetch(world))))));
.replace("[needed]", String.valueOf(util.getNeeded(world) - 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.fetch(world) >= (int) Math.ceil(world.getPlayers().size() * (config.getDouble("values.percent") / 100) - util.fetch(world)))) {
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
@ -69,8 +59,13 @@ public class BedEnter implements Listener {
}
// 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")));
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"));
}
}
}
}

View File

@ -20,28 +20,22 @@ public class BedLeave implements Listener {
Util util = new Util();
Config config = new Config();
World world = event.getPlayer().getWorld();
// Create list of players included in sleep count
ArrayList<Player> players = new ArrayList<Player>();
world.getPlayers().stream().filter(p -> util.isSurvival(event.getPlayer())).forEach(p -> {
if (true) {
players.add(p);
}
});
// Decrement the sleeping count TODO bypass stuff
if (players.contains(event.getPlayer())) {
util.decrement(world);
ArrayList<Player> included = util.getIncluded(world);
int excluded = world.getPlayers().size() - included.size();
// Decrement the sleeping count if player isn't excluded
if (included.contains(event.getPlayer())) {
util.remove(world, event.getPlayer());
}
else if (config.getString("messages.chat.bypass").length() != 0) event.getPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.chat.bypass")));
// 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.sleeping").length() != 0) && Bukkit.getServer().getWorld(world.getName()).getTime() < 1000L) {
Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.chat.left")
.replace("[sleeping]", String.valueOf(util.fetch(world))))
.replace("[online]", String.valueOf(world.getPlayers().size()))
Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', config.getString("messages.chat.sleeping")
.replace("[sleeping]", String.valueOf(util.getSleeping(world))))
.replace("[online]", String.valueOf(included.size()))
.replace("[player]", event.getPlayer().getName())
.replace("[needed]", String.valueOf(Math.max(0, Math.round(world.getPlayers().size() * Float.parseFloat(config.getString("values.percent")) - util.fetch(world))))));
.replace("[needed]", String.valueOf(util.getNeeded(world) - excluded)));
}
}
}

View File

@ -0,0 +1,16 @@
package mykyta.Harbor.Events;
import java.time.Instant;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import mykyta.Harbor.Util;
public class Move implements Listener {
@EventHandler
public void onPlayerMovement(PlayerMoveEvent event) {
Util.activity.put(event.getPlayer(), System.currentTimeMillis());
}
}

View File

@ -1,7 +1,5 @@
package mykyta.Harbor.Events;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
@ -19,5 +17,8 @@ public class PlayerJoin implements Listener {
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("&", "§"));
// Add activity entry
Util.activity.put(event.getPlayer(), System.currentTimeMillis());
}
}

View File

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

View File

@ -1,12 +1,18 @@
package mykyta.Harbor;
import java.util.ArrayList;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import mykyta.Harbor.Commands.Sleeping;
import mykyta.Harbor.Events.BedEnter;
import mykyta.Harbor.Events.BedLeave;
import mykyta.Harbor.Events.Move;
import mykyta.Harbor.Events.PlayerJoin;
public class Harbor extends JavaPlugin {
@ -19,19 +25,41 @@ public class Harbor extends JavaPlugin {
config.setInstance(this);
saveDefaultConfig();
this.getCommand("harbor").setExecutor(new Command());
this.getCommand("sleeping").setExecutor(new Sleeping());
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);
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);
// Check for updates
if (this.getConfig().getBoolean("features.notifier")) {
log.info("Checking for updates.");
if (Util.debug) Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("messages.miscellaneous.prefix")) + "Checking for new updates...");
updater.check();
}
// Enable debugging if set in configuration
if (this.getConfig().getBoolean("debug")) Util.debug = true;
// 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()) {
ArrayList<Player> sleeping = new ArrayList<Player>();
Util.sleeping.put(w, sleeping);
}
//FIXME temp add players to the count on realad
Bukkit.getServer().getWorlds().forEach(w -> {
w.getPlayers().forEach(p -> {
Util.activity.put(p, System.currentTimeMillis());
});
});
}
public void onDisable() {

View File

@ -5,4 +5,5 @@ import org.bukkit.entity.Player;
public interface NMS {
public void sendActionbar(Player player, String message);
public void sendJSONMessage(Player player, String json);
public void sendTitle(Player player, String top, String bottom);
}

View File

@ -8,6 +8,7 @@ import net.minecraft.server.v1_13_R2.IChatBaseComponent;
import net.minecraft.server.v1_13_R2.PacketPlayOutChat;
import net.minecraft.server.v1_13_R2.PacketPlayOutTitle;
import net.minecraft.server.v1_13_R2.IChatBaseComponent.ChatSerializer;
import net.minecraft.server.v1_13_R2.PacketPlayOutTitle.EnumTitleAction;
public class NMS_1_13_R2 implements NMS {
@Override
@ -23,4 +24,14 @@ public class NMS_1_13_R2 implements NMS {
PacketPlayOutChat packet = new PacketPlayOutChat(component);
((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet);
}
@Override
public void sendTitle(Player player, String top, String bottom) {
IChatBaseComponent titleComponentTop = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + ChatColor.translateAlternateColorCodes('&', top) + "\"}");
IChatBaseComponent titleComponentBottom = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + ChatColor.translateAlternateColorCodes('&', bottom) + "\"}");
PacketPlayOutTitle title = new PacketPlayOutTitle(EnumTitleAction.TITLE, titleComponentTop);
PacketPlayOutTitle subtitle = new PacketPlayOutTitle(EnumTitleAction.SUBTITLE, titleComponentBottom);
((CraftPlayer) player).getHandle().playerConnection.sendPacket(title);
((CraftPlayer) player).getHandle().playerConnection.sendPacket(subtitle);
}
}

View File

@ -1,11 +1,42 @@
package mykyta.Harbor;
import java.util.concurrent.TimeUnit;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.entity.Player;
public class Task implements Runnable {
Util util = new Util();
Config config = new Config();
@Override
public void run() {
// Display a title if it's time to sleep
for (World world : Bukkit.getWorlds()) {
if (world.getTime() >= 12516l && world.getTime() <= 12547l) {
System.out.println("sleepy time");
Bukkit.getWorld(world.getUID()).getPlayers().stream().forEach(p -> {
util.sendTitle(p, config.getString("messages.title.evening.top"), config.getString("messages.title.evening.bottom"));
});
}
}
// 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
p.setPlayerListName(ChatColor.GRAY + "[AFK] - " + ChatColor.RESET + p.getDisplayName());
System.out.println(p.getName() + " is AFK.");
}
});
});
}
/* @Override
public void run() {
try {

View File

@ -36,7 +36,7 @@ public class Updater {
releases.add(id.get("name").getAsString());
}
// TODO add super secret message for when the version is newer than the latest published one
// TODO Beautify console messages
if (util.version.equals(releases.get(releases.size() - 1))) {
System.out.println("Running latest version.");
return false;

View File

@ -1,6 +1,11 @@
package mykyta.Harbor;
import java.time.Instant;
import java.time.temporal.Temporal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
@ -13,8 +18,10 @@ import mykyta.Harbor.NMS.NMS_1_13_R2;
import net.md_5.bungee.api.ChatColor;
public class Util {
public static HashMap<World, Integer> sleeping = new HashMap<World, Integer>();
public String version = "1.4.2";
public static HashMap<World, ArrayList<Player>> sleeping = new HashMap<World, ArrayList<Player>>();
public static HashMap<Player, Long> activity = new HashMap<Player, Long>();
public static ArrayList<Player> afk = new ArrayList<Player>();
public String version = "1.5";
public static boolean debug = false;
private Logger log = Bukkit.getLogger();
private static NMS nms;
@ -41,33 +48,76 @@ public class Util {
* Increment the sleeping count for a world
* @param world World to increment count in
*/
public void increment(World world) {
int count;
try {count = Util.sleeping.get(world);}
catch (Exception e){count = 0;}
Util.sleeping.put(world, count + 1);
public void add(World world, Player player) {
ArrayList<Player> list = Util.sleeping.get(world);
list.add(player);
Util.sleeping.put(world, list);
}
/**
* Decrement the sleeping count for a world
* @param world World to increment count in
*/
public void decrement(World world) {
int count;
try {count = Util.sleeping.get(world);}
catch (Exception e){count = 0;}
Util.sleeping.put(world, count - 1);
public void remove(World world, Player player) {
ArrayList<Player> list = Util.sleeping.get(world);
list.remove(player);
Util.sleeping.put(world, list);
}
/**
* Fetch the sleeping count for a world
* @param world World to fetch count for
*/
public int fetch(World world) {
int count;
try {count = Util.sleeping.get(world);}
catch (Exception e){count = 0;}
return count;
public int getSleeping(World world) {
return Util.sleeping.get(world).size();
}
/**
* Fetch the amount of players needed to skip night
* @param world World to fetch count for
*/
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 included players in a world
* @param world World to fetch count for
*/
public ArrayList<Player> getIncluded(World world) {
//TODO convert to a foreach
ArrayList<Player> players = new ArrayList<Player>();
for (Player player : world.getPlayers()) {
if (this.isIncluded(player)) players.add(player);
}
return players;
// FIXME 2 fancy 4 me to understand
/*world.getPlayers().stream().filter(p -> this.isIncluded(world.getPlayers)).forEach(p -> {
if (true) {
players.add(p);
}
});*/
}
/**
* Returns true if player should be included in count
* @param player Target player
*/
public boolean isIncluded(Player player) {
if (config.getBoolean("features.ignore")) {
if (player.getGameMode() == GameMode.SURVIVAL) return true;
else return false;
}
else if (config.getBoolean("features.bypass")) {
if (player.hasPermission("harbor.bypass")) return false;
else return true;
}
else if (TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - activity.get(player)) > config.getInteger("values.timeout")) {
return false;
}
else return true;
}
/**
@ -93,7 +143,7 @@ public class Util {
//TODO add bypassers functionaliyt .replace("[online]", String.valueOf(world.getPlayers().size() - bypassers.size()))
// .replace("[needed]", String.valueOf(Math.max(0, Math.round(world.getPlayers().size() * Float.parseFloat(plugin.getConfig().getString("values.percent")) - bypassers.size() - ((Integer)worlds.get(world)).intValue())))));
.replace("[online]", String.valueOf(world.getPlayers().size()))
.replace("[needed]", String.valueOf(Math.max(0, Math.round(world.getPlayers().size() * Float.parseFloat(config.getString("values.percent")) - (sleeping.get(world)).intValue())))));
.replace("[needed]", String.valueOf(Math.max(0, Math.round(world.getPlayers().size() * Float.parseFloat(config.getString("values.percent")) - sleeping.get(world).size())))));
}
/**
@ -106,11 +156,11 @@ public class Util {
}
/**
* Returns true if player is in survival mode
* @param player Target player
* Sends a title to selected player
* @param player Player to send message to
* @param JSON Message in JSON format
*/
public boolean isSurvival(Player player) {
if (player.getGameMode() == GameMode.SURVIVAL) return true;
else return false;
public void sendTitle(Player player, String top, String bottom) {
nms.sendTitle(player, top, bottom);
}
}