1
0

use a better event system

This commit is contained in:
Lee
2024-04-01 12:34:28 +01:00
parent 7c5557abd2
commit ba8423aedd
12 changed files with 232 additions and 95 deletions

View File

@ -3,6 +3,7 @@ package cc.fascinated;
import cc.fascinated.account.AccountManager; import cc.fascinated.account.AccountManager;
import cc.fascinated.chat.ChatManager; import cc.fascinated.chat.ChatManager;
import cc.fascinated.command.CommandManager; import cc.fascinated.command.CommandManager;
import cc.fascinated.event.EventManager;
import cc.fascinated.metrics.MetricManager; import cc.fascinated.metrics.MetricManager;
import cc.fascinated.misc.PlayerVersionWarning; import cc.fascinated.misc.PlayerVersionWarning;
import cc.fascinated.motd.MotdManager; import cc.fascinated.motd.MotdManager;
@ -38,6 +39,7 @@ public class Aetheria extends JavaPlugin {
new AccountManager(); new AccountManager();
new EventManager();
new CommandManager(); new CommandManager();
new WorldSizeManager(); new WorldSizeManager();
new PlaceholderManager(); new PlaceholderManager();

View File

@ -23,6 +23,11 @@ import java.util.UUID;
@Getter @Log4j2 @Getter @Log4j2
public class Account { public class Account {
/**
* Profile keys.
*/
private static final String playerColorProfileId = "playerColorProfile";
/** /**
* The UUID of the player. * The UUID of the player.
*/ */
@ -78,26 +83,6 @@ public class Account {
this.lastLogin = System.currentTimeMillis(); this.lastLogin = System.currentTimeMillis();
this.save(false); // Save default values this.save(false); // Save default values
log.info("Created new account for " + this.uuid); log.info("Created new account for " + this.uuid);
Bukkit.broadcast(Style.getMiniMessage().deserialize(Lang.FIRST_JOIN_MESSAGE.getAsString()
.replace("%player%", player.getName())
));
Aetheria.EXECUTOR.execute(() -> {
// todo: re-code this it's so ugly
DiscordWebhook discordWebhook = new DiscordWebhook(Config.DISCORD_LOG_WEBHOOK.getAsString());
DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject();
embed.setTitle("New Player Joined");
embed.addField("Name", player.getName(), true);
embed.addField("UUID", uuid.toString(), true);
discordWebhook.addEmbed(embed);
try {
discordWebhook.execute();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
} }
this.firstJoin = config.getLong("firstJoin"); this.firstJoin = config.getLong("firstJoin");
@ -106,7 +91,7 @@ public class Account {
this.lastLogin = System.currentTimeMillis(); // Update last login this.lastLogin = System.currentTimeMillis(); // Update last login
// Load profiles // Load profiles
this.playerColorProfile = new PlayerColor(this, this.getProfileSection("playerColor")); this.playerColorProfile = new PlayerColor(this, this.getProfileSection(playerColorProfileId));
//log.info("Loaded account for " + this.uuid); //log.info("Loaded account for " + this.uuid);
} }
@ -163,16 +148,11 @@ public class Account {
* @param key the key to save the profile under * @param key the key to save the profile under
*/ */
private void saveProfile(Profile profile, String key) { private void saveProfile(Profile profile, String key) {
key = this.getProfileId(key); // append "Profile" to the key to signify it's a profile
profile.save(config.getConfigurationSection(key) == null ? config.createSection(key) : config.getConfigurationSection(key)); profile.save(config.getConfigurationSection(key) == null ? config.createSection(key) : config.getConfigurationSection(key));
} }
private ConfigurationSection getProfileSection(String key) { private ConfigurationSection getProfileSection(String key) {
return this.config.getConfigurationSection(this.getProfileId(key)); return this.config.getConfigurationSection(key);
}
private String getProfileId(String key) {
return key + "Profile"; // append "Profile" to the key to signify it's a profile
} }
@SneakyThrows @SneakyThrows
@ -181,7 +161,7 @@ public class Account {
this.config.set("lastLogin", this.lastLogin); this.config.set("lastLogin", this.lastLogin);
if (saveProfiles) { if (saveProfiles) {
this.saveProfile(this.playerColorProfile, "playerColor"); this.saveProfile(this.playerColorProfile, playerColorProfileId);
} }
this.config.save(this.file); this.config.save(this.file);

View File

@ -1,15 +1,19 @@
package cc.fascinated.account; package cc.fascinated.account;
import cc.fascinated.Aetheria; import cc.fascinated.Aetheria;
import cc.fascinated.config.Config;
import cc.fascinated.config.Lang;
import cc.fascinated.utils.DiscordWebhook;
import cc.fascinated.utils.Manager; import cc.fascinated.utils.Manager;
import cc.fascinated.utils.Style;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.server.PluginDisableEvent;
import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
@ -23,7 +27,7 @@ public class AccountManager extends Manager {
public AccountManager() { public AccountManager() {
for (Player player : Bukkit.getOnlinePlayers()) { for (Player player : Bukkit.getOnlinePlayers()) {
registerAccount(player); loadAccount(player);
} }
Bukkit.getAsyncScheduler().runAtFixedRate(Aetheria.INSTANCE, (task) -> { Bukkit.getAsyncScheduler().runAtFixedRate(Aetheria.INSTANCE, (task) -> {
@ -40,7 +44,7 @@ public class AccountManager extends Manager {
public static Account getAccount(Player player) { public static Account getAccount(Player player) {
UUID uuid = player.getUniqueId(); UUID uuid = player.getUniqueId();
if (!ACCOUNTS.containsKey(uuid)) { if (!ACCOUNTS.containsKey(uuid)) {
return registerAccount(player); return loadAccount(player);
} }
return ACCOUNTS.get(uuid); return ACCOUNTS.get(uuid);
} }
@ -51,7 +55,7 @@ public class AccountManager extends Manager {
* @param player the player * @param player the player
* @return true if the account is already registered, false otherwise * @return true if the account is already registered, false otherwise
*/ */
private boolean accountRegistered(Player player) { private boolean isAccountLoaded(Player player) {
return ACCOUNTS.containsKey(player.getUniqueId()); return ACCOUNTS.containsKey(player.getUniqueId());
} }
@ -60,7 +64,7 @@ public class AccountManager extends Manager {
* *
* @param player the player * @param player the player
*/ */
private static Account registerAccount(Player player) { private static Account loadAccount(Player player) {
UUID uuid = player.getUniqueId(); UUID uuid = player.getUniqueId();
Account account = new Account(player); Account account = new Account(player);
ACCOUNTS.put(uuid, account); ACCOUNTS.put(uuid, account);
@ -79,30 +83,53 @@ public class AccountManager extends Manager {
log.info("Saved {} accounts. ({}ms)", ACCOUNTS.size(), System.currentTimeMillis() - before); log.info("Saved {} accounts. ({}ms)", ACCOUNTS.size(), System.currentTimeMillis() - before);
} }
@EventHandler @Override
public void onJoin(PlayerJoinEvent event) { public void onPlayerJoin(Account account, PlayerJoinEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
if (accountRegistered(player)) { // Account already registered if (player.hasPlayedBefore()) {
return; return;
} }
registerAccount(player);
event.joinMessage(null); // Remove the join message so we can send our own
Bukkit.broadcast(Style.getMiniMessage().deserialize(Lang.FIRST_JOIN_MESSAGE.getAsString()
.replace("%player%", player.getName())
));
Aetheria.EXECUTOR.execute(() -> {
// todo: re-code this it's so ugly
DiscordWebhook discordWebhook = new DiscordWebhook(Config.DISCORD_LOG_WEBHOOK.getAsString());
DiscordWebhook.EmbedObject embed = new DiscordWebhook.EmbedObject();
embed.setTitle("New Player Joined");
embed.addField("Name", player.getName(), true);
embed.addField("UUID", player.getUniqueId().toString(), true);
discordWebhook.addEmbed(embed);
try {
discordWebhook.execute();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
} }
@EventHandler @Override
public void onQuit(PlayerQuitEvent event) { public void onPlayerLogin(Account account, PlayerLoginEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
Account account = getAccount(player); if (isAccountLoaded(player)) { // Account already loaded
return;
}
loadAccount(player);
}
@Override
public void onPlayerQuit(Account account, PlayerQuitEvent event) {
account.save(true); account.save(true);
ACCOUNTS.remove(player.getUniqueId()); ACCOUNTS.remove(account.getUuid());
}
@EventHandler
public void onPluginDisable(PluginDisableEvent event) {
if (event.getPlugin() != Aetheria.INSTANCE) {
return;
} }
@Override
public void onAetheriaDisable() {
this.saveAccounts(); // Save the accounts to disk this.saveAccounts(); // Save the accounts to disk
ACCOUNTS.clear(); // Remove the accounts from the cache ACCOUNTS.clear(); // Remove the accounts from the cache
} }

View File

@ -1,7 +1,6 @@
package cc.fascinated.chat; package cc.fascinated.chat;
import cc.fascinated.account.Account; import cc.fascinated.account.Account;
import cc.fascinated.account.AccountManager;
import cc.fascinated.config.Lang; import cc.fascinated.config.Lang;
import cc.fascinated.utils.Manager; import cc.fascinated.utils.Manager;
import cc.fascinated.utils.MessageUtils; import cc.fascinated.utils.MessageUtils;
@ -12,8 +11,6 @@ import lombok.RequiredArgsConstructor;
import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import java.util.HashMap; import java.util.HashMap;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -33,10 +30,8 @@ public class ChatManager extends Manager {
private final Pattern domainPattern = Pattern.compile("^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,8}$"); private final Pattern domainPattern = Pattern.compile("^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,8}$");
private final Pattern ipPattern = Pattern.compile("\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b"); private final Pattern ipPattern = Pattern.compile("\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b");
@EventHandler @Override
public void onChat(AsyncChatEvent event) { public void onAsyncChat(Account account, AsyncChatEvent event) {
Player player = event.getPlayer();
Account account = AccountManager.getAccount(player);
NamedTextColor color = account.getPlayerColorProfile().getColor(); NamedTextColor color = account.getPlayerColorProfile().getColor();
BlockReason blockReason = null; BlockReason blockReason = null;

View File

@ -0,0 +1,23 @@
package cc.fascinated.event;
import cc.fascinated.account.Account;
import cc.fascinated.utils.Priority;
import io.papermc.paper.event.player.AsyncChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.server.ServerListPingEvent;
public interface EventListener {
default Priority getPriority() {
return Priority.NORMAL;
}
default void onAetheriaDisable() {}
default void onPlayerJoin(Account account, PlayerJoinEvent event) {}
default void onPlayerLogin(Account account, PlayerLoginEvent event) {}
default void onPlayerQuit(Account account, PlayerQuitEvent event) {}
default void onAsyncChat(Account account, AsyncChatEvent event) {}
default void onServerListPing(ServerListPingEvent event) {}
}

View File

@ -0,0 +1,96 @@
package cc.fascinated.event;
import cc.fascinated.Aetheria;
import cc.fascinated.account.Account;
import cc.fascinated.account.AccountManager;
import io.papermc.paper.event.player.AsyncChatEvent;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.ServerListPingEvent;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class EventManager implements Listener {
/**
* All registered listeners.
*/
private static final List<EventListener> LISTENERS = Collections.synchronizedList(new LinkedList<>());
public EventManager() {
Aetheria.INSTANCE.getServer().getPluginManager().registerEvents(this, Aetheria.INSTANCE);
}
/**
* Registers a new listener.
*
* @param listener the listener to register
*/
public static void registerListener(EventListener listener) {
LISTENERS.add(listener);
}
@EventHandler
public void onPluginDisable(PluginDisableEvent event) {
if (event.getPlugin() != Aetheria.INSTANCE) {
return;
}
for (EventListener listener : LISTENERS) {
listener.onAetheriaDisable();
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
Account account = AccountManager.getAccount(player);
for (EventListener listener : LISTENERS) {
listener.onPlayerJoin(account, event);
}
}
@EventHandler
public void onPlayerLogin(PlayerLoginEvent event) {
Player player = event.getPlayer();
Account account = AccountManager.getAccount(player);
for (EventListener listener : LISTENERS) {
listener.onPlayerLogin(account, event);
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
Account account = AccountManager.getAccount(player);
for (EventListener listener : LISTENERS) {
listener.onPlayerQuit(account, event);
}
}
@EventHandler
public void onAsyncChat(AsyncChatEvent event) {
Player player = event.getPlayer();
Account account = AccountManager.getAccount(player);
for (EventListener listener : LISTENERS) {
listener.onAsyncChat(account, event);
}
}
@EventHandler
public void onServerListPing(ServerListPingEvent event) {
for (EventListener listener : LISTENERS) {
listener.onServerListPing(event);
}
}
}

View File

@ -5,6 +5,7 @@ import cc.fascinated.config.Config;
import cc.fascinated.metrics.impl.server.*; import cc.fascinated.metrics.impl.server.*;
import cc.fascinated.metrics.impl.system.CpuUsageMetric; import cc.fascinated.metrics.impl.system.CpuUsageMetric;
import cc.fascinated.metrics.impl.world.WorldSizeMetric; import cc.fascinated.metrics.impl.world.WorldSizeMetric;
import cc.fascinated.utils.Manager;
import com.influxdb.client.InfluxDBClient; import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory; import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.InfluxDBClientOptions; import com.influxdb.client.InfluxDBClientOptions;
@ -15,16 +16,13 @@ import com.influxdb.client.write.Point;
import com.influxdb.client.write.WriteParameters; import com.influxdb.client.write.WriteParameters;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@Log4j2 @Log4j2
public class MetricManager implements Listener { public class MetricManager extends Manager {
private InfluxDBClient influxDB; private InfluxDBClient influxDB;
private WriteApiBlocking writeApi; private WriteApiBlocking writeApi;
@ -112,11 +110,8 @@ public class MetricManager implements Listener {
metrics.add(metric); metrics.add(metric);
} }
@EventHandler @Override
public void onPluginDisable(PluginDisableEvent event) { public void onAetheriaDisable() {
if (event.getPlugin() != Aetheria.INSTANCE) {
return;
}
influxDB.close(); // close the connection influxDB.close(); // close the connection
} }
} }

View File

@ -1,21 +1,19 @@
package cc.fascinated.misc; package cc.fascinated.misc;
import cc.fascinated.account.Account;
import cc.fascinated.config.Config; import cc.fascinated.config.Config;
import cc.fascinated.utils.Manager; import cc.fascinated.utils.Manager;
import cc.fascinated.utils.Style; import cc.fascinated.utils.Style;
import com.viaversion.viaversion.api.Via; import com.viaversion.viaversion.api.Via;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
public class PlayerVersionWarning extends Manager { public class PlayerVersionWarning extends Manager {
@EventHandler @Override
public void onPlayerJoin(PlayerJoinEvent event) { public void onPlayerJoin(Account account, PlayerJoinEvent event) {
Player player = event.getPlayer(); int version = Via.getAPI().getPlayerVersion(account.getUuid());
int version = Via.getAPI().getPlayerVersion(player.getUniqueId());
if (version < Config.VERSION_WARNING_VERSION.getAsInt()) { if (version < Config.VERSION_WARNING_VERSION.getAsInt()) {
player.sendMessage(Style.getMiniMessage().deserialize(Config.VERSION_WARNING_MESSAGE.getAsString())); account.sendMessage(Style.getMiniMessage().deserialize(Config.VERSION_WARNING_MESSAGE.getAsString()));
} }
} }
} }

View File

@ -3,7 +3,6 @@ package cc.fascinated.motd;
import cc.fascinated.config.Config; import cc.fascinated.config.Config;
import cc.fascinated.utils.Manager; import cc.fascinated.utils.Manager;
import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.event.EventHandler;
import org.bukkit.event.server.ServerListPingEvent; import org.bukkit.event.server.ServerListPingEvent;
import java.util.List; import java.util.List;
@ -18,8 +17,8 @@ public class MotdManager extends Manager {
motds = Config.MOTD_LIST.getAsStringList(); motds = Config.MOTD_LIST.getAsStringList();
} }
@EventHandler @Override
public void onServerPing(ServerListPingEvent event) { public void onServerListPing(ServerListPingEvent event) {
MiniMessage miniMessage = MiniMessage.miniMessage(); MiniMessage miniMessage = MiniMessage.miniMessage();
String motd = motds.get((int) (Math.random() * motds.size())); String motd = motds.get((int) (Math.random() * motds.size()));

View File

@ -1,15 +1,12 @@
package cc.fascinated.playercolor; package cc.fascinated.playercolor;
import cc.fascinated.account.Account; import cc.fascinated.account.Account;
import cc.fascinated.account.AccountManager;
import cc.fascinated.playercolor.command.PlayerColorCommand; import cc.fascinated.playercolor.command.PlayerColorCommand;
import cc.fascinated.utils.Manager; import cc.fascinated.utils.Manager;
import lombok.Getter; import lombok.Getter;
import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team; import org.bukkit.scoreboard.Team;
@ -80,23 +77,19 @@ public class PlayerColorManager extends Manager {
return team; return team;
} }
@EventHandler @Override
public void onLogin(PlayerLoginEvent event) { public void onPlayerJoin(Account account, PlayerJoinEvent event) {
Player player = event.getPlayer();
Account account = AccountManager.getAccount(player);
PlayerColor playerColor = account.getPlayerColorProfile(); PlayerColor playerColor = account.getPlayerColorProfile();
Team team = PlayerColorManager.getScoreboardTeam(playerColor.getColor()); Team team = PlayerColorManager.getScoreboardTeam(playerColor.getColor());
team.addEntry(player.getName()); team.addEntry(account.getName());
} }
@EventHandler @Override
public void onQuit(PlayerQuitEvent event) { public void onPlayerQuit(Account account, PlayerQuitEvent event) {
Player player = event.getPlayer();
Account account = AccountManager.getAccount(player);
PlayerColor playerColor = account.getPlayerColorProfile(); PlayerColor playerColor = account.getPlayerColorProfile();
Team team = PlayerColorManager.getScoreboardTeam(playerColor.getColor()); Team team = PlayerColorManager.getScoreboardTeam(playerColor.getColor());
team.removeEntry(player.getName()); team.removeEntry(account.getName());
} }
} }

View File

@ -1,14 +1,14 @@
package cc.fascinated.utils; package cc.fascinated.utils;
import cc.fascinated.Aetheria;
import cc.fascinated.command.Command; import cc.fascinated.command.Command;
import cc.fascinated.command.CommandManager; import cc.fascinated.command.CommandManager;
import org.bukkit.event.Listener; import cc.fascinated.event.EventListener;
import cc.fascinated.event.EventManager;
public class Manager implements Listener { public class Manager implements EventListener {
public Manager() { public Manager() {
Aetheria.INSTANCE.getServer().getPluginManager().registerEvents(this, Aetheria.INSTANCE); EventManager.registerListener(this);
} }
/** /**

View File

@ -0,0 +1,29 @@
package cc.fascinated.utils;
public enum Priority {
/**
* The lowest priority, this will be called first.
*/
LOWEST,
/**
* The low priority, this will be called second.
*/
LOW,
/**
* The normal priority, this has no effect.
*/
NORMAL,
/**
* The high priority, this will be called second to last.
*/
HIGH,
/**
* The highest priority, this will be called last.
*/
HIGHEST
}