Refactoring and clean ups

This commit is contained in:
Minecon724 2024-12-31 13:34:17 +01:00
parent 916f44da47
commit d922221589
Signed by: Minecon724
GPG key ID: 3CCC4D267742C8E8
20 changed files with 199 additions and 133 deletions

View file

@ -0,0 +1,51 @@
/*
* Copyright (C) 2024 Minecon724
* Tweaks724 is licensed under the GNU General Public License. See the LICENSE.md file
* in the project root for the full license text.
*/
package eu.m724.tweaks;
import org.fusesource.jansi.Ansi;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DebugLogger {
static Logger logger;
public static void info(String message) {
log(Level.INFO, message);
}
public static void warning(String message) {
log(Level.WARNING, message);
}
public static void severe(String message) {
log(Level.SEVERE, message);
}
public static void fine(String message) {
log(Level.FINE, message);
}
private static void log(Level level, String message) {
if (logger.getLevel().intValue() > level.intValue()) return;
var caller = Thread.currentThread().getStackTrace()[3].getClassName();
if (caller.startsWith("eu.m724.tweaks."))
caller = caller.substring(15);
message = "[" + caller + "] " + message;
if (level.intValue() < Level.INFO.intValue()) { // levels below info are never logged even if set for some reason
level = Level.INFO;
// colors text gray (cyan is close to gray)
message = Ansi.ansi().fg(Ansi.Color.CYAN).a(message).reset().toString();
}
logger.log(level, message);
}
}

View file

@ -28,11 +28,15 @@ public class Language {
return INSTANCE.resourceBundle.getString(key);
}
public static String getString(String key, Object... format) {
return INSTANCE.resourceBundle.getString(key).formatted(format);
}
public static BaseComponent getComponent(String key, ChatColor color) {
return new ComponentBuilder(getString(key)).color(color).build();
}
public static BaseComponent getComponent(String key, ChatColor color, Object... format) {
return new ComponentBuilder(getString(key).formatted(format)).color(color).build();
return new ComponentBuilder(getString(key, format)).color(color).build();
}
}

View file

@ -11,6 +11,8 @@ import org.bukkit.plugin.Plugin;
public record TweaksConfig(
boolean metrics,
boolean debug,
String locale,
boolean worldborderExpand,
boolean worldborderHide,
@ -20,7 +22,6 @@ public record TweaksConfig(
boolean brandShowPing,
boolean brandShowMspt,
boolean doorEnabled,
boolean doorDoubleOpen,
boolean doorKnocking,
@ -76,6 +77,8 @@ public record TweaksConfig(
}
boolean metrics = config.getBoolean("metrics");
boolean debug = config.getBoolean("debug", false);
String locale = config.getString("locale", "US");
boolean worldborderExpand = config.getBoolean("worldborder.expand");
boolean worldborderHide = config.getBoolean("worldborder.hide");
@ -87,7 +90,6 @@ public record TweaksConfig(
boolean doorDoubleOpen = config.getBoolean("doors.doubleOpen");
boolean doorKnocking = config.getBoolean("doors.knocking");
boolean doorEnabled = doorDoubleOpen || doorKnocking;
String motdSet = config.getString("motd.set");
boolean motdEnabled = !(motdSet.equals("false") || motdSet.isBlank());
@ -120,10 +122,10 @@ public record TweaksConfig(
String redstoneListen = config.getString("retstone.listen");
TweaksConfig.config = new TweaksConfig(
metrics,
debug, metrics, locale,
worldborderExpand, worldborderHide,
brandEnabled, brandText, brandShowPing, brandShowMspt,
doorEnabled, doorDoubleOpen, doorKnocking,
doorDoubleOpen, doorKnocking,
motdEnabled, motdSet,
chatEnabled, chatLocalEvents, chatDefaultName, chatRadius,
compassEnabled, compassWidth, compassPrecision,

View file

@ -9,26 +9,23 @@ package eu.m724.tweaks;
import eu.m724.mstats.MStatsPlugin;
import eu.m724.tweaks.alert.AlertManager;
import eu.m724.tweaks.auth.AuthManager;
import eu.m724.tweaks.chat.ChatCommands;
import eu.m724.tweaks.chat.ChatManager;
import eu.m724.tweaks.door.DoorManager;
import eu.m724.tweaks.door.DoorKnockListener;
import eu.m724.tweaks.door.DoorOpenListener;
import eu.m724.tweaks.full.FullListener;
import eu.m724.tweaks.hardcore.HardcoreManager;
import eu.m724.tweaks.motd.MotdManager;
import eu.m724.tweaks.ping.F3NameListener;
import eu.m724.tweaks.ping.PingChecker;
import eu.m724.tweaks.ping.PingCommands;
import eu.m724.tweaks.pomodoro.PomodoroCommands;
import eu.m724.tweaks.pomodoro.PomodoroManager;
import eu.m724.tweaks.redstone.RedstoneManager;
import eu.m724.tweaks.sleep.SleepManager;
import eu.m724.tweaks.updater.UpdaterCommands;
import eu.m724.tweaks.updater.UpdaterManager;
import eu.m724.tweaks.worldborder.WorldBorderManager;
import eu.m724.tweaks.worldborder.WorldBorderExpander;
import eu.m724.tweaks.worldborder.WorldBorderHider;
import java.io.IOException;
import java.util.Locale;
import java.util.Objects;
import java.util.logging.Level;
public class TweaksPlugin extends MStatsPlugin {
@Override
@ -43,84 +40,99 @@ public class TweaksPlugin extends MStatsPlugin {
}
TweaksConfig config = TweaksConfig.load(this);
new Language(Locale.US); // TODO
// whether enabled is handled inside
new WorldBorderManager().init(this);
getLogger().setLevel(config.debug() ? Level.FINEST : Level.INFO);
DebugLogger.logger = getLogger();
DebugLogger.fine("Debug enabled. There may be performance issues.");
if (config.chatEnabled()) {
ChatManager chatManager = new ChatManager(this);
chatManager.init();
DebugLogger.fine("Enabling Language");
new Language(Locale.of(config.locale())); // TODO
DebugLogger.fine(Language.getString("languageNotice", Language.getString("language"), Language.getString("languageEnglish")));
ChatCommands chatCommands = new ChatCommands(chatManager);
Objects.requireNonNull(getCommand("chat")).setExecutor(chatCommands);
Objects.requireNonNull(getCommand("chatmanage")).setExecutor(chatCommands);
/* start modules */
if (config.worldborderHide()) {
DebugLogger.fine("Enabling Worldborder hide");
new WorldBorderHider().init(this);
}
if (config.doorEnabled()) {
new DoorManager().init(this);
if (config.worldborderExpand()) {
DebugLogger.fine("Enabling Worldborder expand");
new WorldBorderExpander().init(this);
}
if (config.chatEnabled()) {
DebugLogger.fine("Enabling Chat");
new ChatManager(this).init(getCommand("chat"), getCommand("chatmanage"));
}
if (config.doorKnocking()) {
DebugLogger.fine("Enabling Door knock");
getServer().getPluginManager().registerEvents(new DoorKnockListener(), this);
}
if (config.doorDoubleOpen()) {
DebugLogger.fine("Enabling Door double open");
getServer().getPluginManager().registerEvents(new DoorOpenListener(), this);
}
if (config.brandEnabled()) {
DebugLogger.fine("Enabling Brand");
new F3NameListener(this).init();
}
new PingChecker(this).init();
Objects.requireNonNull(getCommand("ping")).setExecutor(new PingCommands());
/*if (getServer().getPluginManager().getPlugin("voicechat") != null) {
new MusicPlayer(this).init();
} else {
getLogger().warning("To use voice extensions, install \"Simple Voice Chat\"");
}*/
DebugLogger.fine("Enabling Ping");
new PingChecker(this).init(getCommand("ping"));
if (config.motdEnabled()) {
try {
DebugLogger.fine("Enabling MOTD");
new MotdManager(this).init();
} catch (IOException e) {
getLogger().severe("Failed to initialize MOTD extension");
throw new RuntimeException(e);
}
}
if (config.pomodoroEnabled()) {
new PomodoroManager(this).init();
getCommand("pomodoro").setExecutor(new PomodoroCommands());
DebugLogger.fine("Enabling Pomodoro");
new PomodoroManager(this).init(getCommand("pomodoro"));
}
if (config.updaterEnabled()) {
try {
new UpdaterManager(this).init();
getCommand("updates").setExecutor(new UpdaterCommands());
} catch (IOException e) {
throw new RuntimeException(e);
}
DebugLogger.fine("Enabling Updater");
new UpdaterManager(this).init(getCommand("updates"));
}
if (config.hardcoreEnabled()) {
DebugLogger.fine("Enabling Hardcore");
new HardcoreManager().init(this);
}
if (config.sleepEnabled()) {
DebugLogger.fine("Enabling Sleep");
new SleepManager().init(this);
}
if (config.authEnabled()) {
DebugLogger.fine("Enabling Auth");
new AuthManager(this).init(getCommand("tauth"));
}
DebugLogger.fine("Enabling Alert");
new AlertManager(this).init(getCommand("emergencyalert"));
this.getServer().getPluginManager().registerEvents(new FullListener(), this);
DebugLogger.fine("Enabling Full");
getServer().getPluginManager().registerEvents(new FullListener(), this);
if (config.redstoneEnabled()) {
DebugLogger.fine("Enabling Redstone");
new RedstoneManager(this).init(getCommand("retstone"));
}
if (config.metrics())
mStats(1);
/* end modules */
getLogger().info("Took %.3f milliseconds".formatted((System.nanoTime() - start) / 1000000.0));
if (config.metrics()) {
DebugLogger.fine("Enabling Metrics");
mStats(1);
}
DebugLogger.fine("Took %.3f milliseconds".formatted((System.nanoTime() - start) / 1000000.0));
}
public boolean hasResource(String resource) {

View file

@ -11,6 +11,7 @@ import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.ComponentBuilder;
import org.bukkit.NamespacedKey;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Player;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.Plugin;
@ -18,6 +19,7 @@ import org.bukkit.plugin.Plugin;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class ChatManager {
private final Plugin plugin;
@ -33,13 +35,17 @@ public class ChatManager {
this.defaultRoom = TweaksConfig.getConfig().chatDefaultName();
}
public void init() {
public void init(PluginCommand chatCommand, PluginCommand chatManageCommand) {
if (plugin.getServer().isEnforcingSecureProfiles()) {
throw new RuntimeException("Please disable enforce-secure-profile in server.properties to use chatrooms");
}
getById(defaultRoom);
plugin.getServer().getPluginManager().registerEvents(new ChatListener(this), plugin);
var chatCommands = new ChatCommands(this);
chatCommand.setExecutor(chatCommands);
chatManageCommand.setExecutor(chatCommands);
}
/**

View file

@ -1,24 +0,0 @@
/*
* Copyright (C) 2024 Minecon724
* Tweaks724 is licensed under the GNU General Public License. See the LICENSE.md file
* in the project root for the full license text.
*/
package eu.m724.tweaks.door;
import eu.m724.tweaks.TweaksConfig;
import org.bukkit.plugin.Plugin;
public class DoorManager {
public void init(Plugin plugin) {
if (TweaksConfig.getConfig().doorKnocking()) {
plugin.getServer().getPluginManager().registerEvents(new DoorKnockListener(), plugin);
}
if (TweaksConfig.getConfig().doorDoubleOpen()) {
plugin.getServer().getPluginManager().registerEvents(new DoorOpenListener(), plugin);
}
}
}

View file

@ -37,7 +37,7 @@ public class MotdManager {
this.plugin = plugin;
}
public void init() throws IOException {
public void init() {
// TODO adding more MOTD features would require checking whether to enable set
String motdSetName = TweaksConfig.getConfig().motdSet();
@ -55,7 +55,13 @@ public class MotdManager {
throw new RuntimeException("MOTD set \"%s\" doesn't exist".formatted(motdSetName));
}
String fileContent = Files.readString(motdSetsFile.toPath());
String fileContent = null;
try {
fileContent = Files.readString(motdSetsFile.toPath());
} catch (IOException e) {
throw new RuntimeException("Reading motd set", e);
}
// MOTDs are split with an empty line
motds = Arrays.stream(fileContent.split("\n\n"))
.map(s -> {

View file

@ -6,8 +6,11 @@
package eu.m724.tweaks.ping;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.Plugin;
import java.util.Objects;
public class PingChecker {
private final Plugin plugin;
@ -15,8 +18,10 @@ public class PingChecker {
this.plugin = plugin;
}
public void init() {
public void init(PluginCommand pingCommand) {
new KeepAlivePingChecker(plugin).start();
new MsptChecker().init(plugin); // TODO should this be here
pingCommand.setExecutor(new PingCommands());
}
}

View file

@ -6,6 +6,7 @@
package eu.m724.tweaks.pomodoro;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.Plugin;
public class PomodoroManager {
@ -15,8 +16,10 @@ public class PomodoroManager {
this.plugin = plugin;
}
public void init() {
public void init(PluginCommand pomodoroCommand) {
plugin.getServer().getPluginManager().registerEvents(new PomodoroListener(), plugin);
new PomodoroRunnable(plugin).runTaskTimerAsynchronously(plugin, 0, 20L);
pomodoroCommand.setExecutor(new PomodoroCommands());
}
}

View file

@ -37,7 +37,8 @@ public class PomodoroRunnable extends BukkitRunnable {
player.playSound(player.getLocation(), Sound.BLOCK_ANVIL_FALL, 1.0f, 0.5f);
if (remaining < -60 && force) {
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> {
player.kickPlayer(Language.getString("pomodoroEndKick"));
pomodoro.next();
player.kickPlayer(Language.getString("pomodoroEndKick") + "\n" + Pomodoros.formatTimer(pomodoro, pomodoro.getRemainingSeconds(now)));
});
}
}

View file

@ -30,7 +30,7 @@ public class Pomodoros {
return timers.remove(player.getUniqueId()) != null;
}
static BaseComponent[] formatTimer(PlayerPomodoro pomodoro, long remaining) {
static BaseComponent formatTimer(PlayerPomodoro pomodoro, long remaining) {
ComponentBuilder builder = new ComponentBuilder();
if (pomodoro.isBreak()) {
@ -66,6 +66,6 @@ public class Pomodoros {
builder.append(" o").color(color);
}
return builder.create();
return builder.build();
}
}

View file

@ -6,6 +6,7 @@
package eu.m724.tweaks.redstone;
import eu.m724.tweaks.DebugLogger;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
@ -22,46 +23,46 @@ public class RedstoneListener implements Listener {
}
@EventHandler
public void onPlace(BlockPlaceEvent event) {
public void onBlockPlace(BlockPlaceEvent event) {
if (!redstoneRepeaters.isRepeater(event.getItemInHand())) return;
var block = event.getBlockPlaced();
var id = redstoneRepeaters.onPlace(block);
System.out.println("repeate place " + id);
DebugLogger.fine("Repeater placed: " + id);
}
@EventHandler
public void onBreak(BlockBreakEvent event) {
public void onBlockBreak(BlockBreakEvent event) {
var id = redstoneRepeaters.getId(event.getBlock());
if (id == Integer.MIN_VALUE) return;
redstoneRepeaters.onBreak(id);
System.out.println("repeate brek " + id);
DebugLogger.fine("Repeater broken: " + id);
}
@EventHandler
public void a(PlayerInteractEvent event) {
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return;
if (event.getClickedBlock() == null) return;
var id = redstoneRepeaters.getId(event.getClickedBlock());
if (id == Integer.MIN_VALUE) return;
// TODO find a less lame way of showing ID
event.getPlayer().sendMessage("Repeater ID: " + id);
}
@EventHandler
public void b(BlockRedstoneEvent event) {
public void onBlockRedstone(BlockRedstoneEvent event) {
var block = event.getBlock();
System.out.println(block);
var id = redstoneRepeaters.getId(block);
if (id == Integer.MIN_VALUE) return;
System.out.println("yes it isi");
event.setNewCurrent(redstoneRepeaters.getOutboundPower(id));
DebugLogger.fine("Repeater redstone event: " + id);
}
}

View file

@ -6,6 +6,7 @@
package eu.m724.tweaks.redstone;
import eu.m724.tweaks.DebugLogger;
import eu.m724.tweaks.TweaksConfig;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.Plugin;
@ -63,7 +64,7 @@ public class RedstoneManager {
try {
socket.receive(packet);
} catch (IOException e) {
System.err.println("Error reading packet: " + e.getMessage());
DebugLogger.severe("Error reading packet: " + e.getMessage());
continue;
}
@ -77,7 +78,7 @@ public class RedstoneManager {
var newPacket = new DatagramPacket(new byte[1], 1, packet.getSocketAddress());
enqueueRetrieve(repeaterId, value -> {
System.out.println("retieved state " + value);
DebugLogger.fine("Retrieved for " + repeaterId + " power " + value);
newPacket.setData(new byte[] { (byte) Math.max(value, 0) });
try {
@ -92,12 +93,12 @@ public class RedstoneManager {
}
private void enqueueUpdate(int repeaterId, byte power) {
System.out.println("Update enqueud " + repeaterId + " " + power);
DebugLogger.fine("Update enqueued " + repeaterId + " " + power);
runnable.enqueueUpdate(repeaterId, power);
}
private void enqueueRetrieve(int repeaterId, Consumer<Byte> consumer) {
System.out.println("retieve enqueud " + repeaterId);
DebugLogger.fine("Retrieve enqueued " + repeaterId);
runnable.enqueueRetrieve(repeaterId, consumer);
}
}

View file

@ -36,7 +36,6 @@ public class PluginScanner {
Set<SpigotResource> spigotResources = new HashSet<>();
for (Plugin plugin : plugins) {
// System.out.println("Found " + plugin.getName());
String pluginName = plugin.getName();
if (!configuration.isSet(pluginName)) {

View file

@ -70,7 +70,7 @@ public class UpdateChecker extends BukkitRunnable {
private void alert() {
int n = availableUpdates.size();
if (n == 0) return;
logger.info(Language.getString("updateAvailableNotice").formatted(n));
logger.info(Language.getString("updateAvailableNotice", n));
availableUpdates.stream()
.map(u -> "- %s (%s -> %s)".formatted(u.resource().name(), u.running().label(), u.latest().label()))

View file

@ -35,7 +35,7 @@ public class UpdaterCommands implements CommandExecutor {
if (n > 0) {
sender.spigot().sendMessage(
new ComponentBuilder(Language.getString("updateAvailableNotice").formatted(n)).color(ChatColor.GRAY).build()
Language.getComponent("updateAvailableNotice", ChatColor.GRAY, n)
);
int i = 0;
@ -45,7 +45,7 @@ public class UpdaterCommands implements CommandExecutor {
);
}
} else {
sender.sendMessage(Language.getString("updatesNoUpdates").formatted(lastChecked));
sender.spigot().sendMessage(Language.getComponent("updatesNoUpdates", ChatColor.GREEN, lastChecked));
}
return true;
@ -71,7 +71,7 @@ public class UpdaterCommands implements CommandExecutor {
.event(
new HoverEvent(
HoverEvent.Action.SHOW_TEXT,
new Text(Language.getString("updatesClickToOpen").formatted(v.latest().description().title()))
new Text(Language.getString("updatesClickToOpen", v.latest().description().title()))
)
)
.build();

View file

@ -6,9 +6,11 @@
package eu.m724.tweaks.updater;
import eu.m724.tweaks.DebugLogger;
import eu.m724.tweaks.updater.cache.ResourceVersion;
import eu.m724.tweaks.updater.cache.SpigotResource;
import eu.m724.tweaks.updater.cache.VersionedResource;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.Plugin;
import java.io.File;
@ -29,9 +31,14 @@ public class UpdaterManager {
cacheFile = new File(plugin.getDataFolder(), "cache/updater");
}
public void init() throws IOException {
public void init(PluginCommand updatesCommand){
// scan installed plugins
Set<SpigotResource> resources = new PluginScanner(plugin).load();
Set<SpigotResource> resources = null;
try {
resources = new PluginScanner(plugin).load();
} catch (IOException e) {
throw new RuntimeException("Loading plugins", e);
}
cacheFile.getParentFile().mkdirs(); // TODO move this somewhere else
@ -41,6 +48,9 @@ public class UpdaterManager {
installedVersions = VersionCheckCache.loadAll(inputStream);
} catch (FileNotFoundException e) {
installedVersions = new HashSet<>();
} catch (IOException e) {
DebugLogger.warning("Error loading installed version cache, starting fresh. " + e.getMessage());
installedVersions = new HashSet<>();
}
final Set<ResourceVersion> ivf = installedVersions;
@ -52,5 +62,7 @@ public class UpdaterManager {
new UpdateChecker(plugin, versionedResources)
.runTaskTimerAsynchronously(plugin, 600, 12 * 3600 * 20);
updatesCommand.setExecutor(new UpdaterCommands());
}
}

View file

@ -11,8 +11,18 @@ import org.bukkit.craftbukkit.v1_21_R1.CraftWorld;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.plugin.Plugin;
public class WorldBorderExpander implements Listener {
public void init(Plugin plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
// because the plugin loads "post world"
plugin.getServer().getWorlds().forEach(w -> {
onWorldLoad(new WorldLoadEvent(w));
});
}
public class WorldBorderExpanderListener implements Listener {
@EventHandler
public void onWorldLoad(WorldLoadEvent event) {
ServerLevel level = ((CraftWorld) event.getWorld()).getHandle();

View file

@ -1,29 +0,0 @@
/*
* Copyright (C) 2024 Minecon724
* Tweaks724 is licensed under the GNU General Public License. See the LICENSE.md file
* in the project root for the full license text.
*/
package eu.m724.tweaks.worldborder;
import eu.m724.tweaks.TweaksConfig;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.plugin.Plugin;
public class WorldBorderManager {
public void init(Plugin plugin) {
if (TweaksConfig.getConfig().worldborderExpand()) {
WorldBorderExpanderListener wbrl = new WorldBorderExpanderListener();
plugin.getServer().getPluginManager().registerEvents(wbrl, plugin);
// because the plugin loads "post world"
plugin.getServer().getWorlds().forEach(w -> {
wbrl.onWorldLoad(new WorldLoadEvent(w));
});
}
if (TweaksConfig.getConfig().worldborderHide()) {
new WorldBorderHider().init(plugin);
}
}
}

View file

@ -4,8 +4,14 @@
# in the project root for the full license text.
#
languageNotice = Language: %s (%s)
# Language name in your language
language = English
# Language name in English
languageEnglish = English
updateAvailableNotice = Available updates (%d):
pomodoroEndKick = Break time! Come back in 5 minutes.
pomodoroEndKick = Take a break!
# Used in /updates
updatesNotChecked = Not checked yet