applied code styling

This commit is contained in:
Elias Müller 2024-08-24 11:02:28 +02:00
parent 78ba105291
commit 3dc25d63fd
56 changed files with 554 additions and 490 deletions

View File

@ -1,28 +1,28 @@
package eu.mhsl.craftattack.spawn; package eu.mhsl.craftattack.spawn;
import eu.mhsl.craftattack.spawn.appliances.displayName.DisplayName;
import eu.mhsl.craftattack.spawn.api.HttpServer; import eu.mhsl.craftattack.spawn.api.HttpServer;
import eu.mhsl.craftattack.spawn.appliance.Appliance; import eu.mhsl.craftattack.spawn.appliance.Appliance;
import eu.mhsl.craftattack.spawn.appliances.adminMarker.AdminMarker; import eu.mhsl.craftattack.spawn.appliances.adminMarker.AdminMarker;
import eu.mhsl.craftattack.spawn.appliances.customAdvancements.CustomAdvancements;
import eu.mhsl.craftattack.spawn.appliances.fleischerchest.Fleischerchest;
import eu.mhsl.craftattack.spawn.appliances.kick.Kick;
import eu.mhsl.craftattack.spawn.appliances.chatMessages.ChatMessages; import eu.mhsl.craftattack.spawn.appliances.chatMessages.ChatMessages;
import eu.mhsl.craftattack.spawn.appliances.customAdvancements.CustomAdvancements;
import eu.mhsl.craftattack.spawn.appliances.debug.Debug;
import eu.mhsl.craftattack.spawn.appliances.displayName.DisplayName;
import eu.mhsl.craftattack.spawn.appliances.event.Event;
import eu.mhsl.craftattack.spawn.appliances.fleischerchest.Fleischerchest;
import eu.mhsl.craftattack.spawn.appliances.help.Help;
import eu.mhsl.craftattack.spawn.appliances.kick.Kick;
import eu.mhsl.craftattack.spawn.appliances.outlawed.Outlawed; import eu.mhsl.craftattack.spawn.appliances.outlawed.Outlawed;
import eu.mhsl.craftattack.spawn.appliances.panicBan.PanicBan; import eu.mhsl.craftattack.spawn.appliances.panicBan.PanicBan;
import eu.mhsl.craftattack.spawn.appliances.projectStart.ProjectStart;
import eu.mhsl.craftattack.spawn.appliances.debug.Debug;
import eu.mhsl.craftattack.spawn.appliances.event.Event;
import eu.mhsl.craftattack.spawn.appliances.help.Help;
import eu.mhsl.craftattack.spawn.appliances.playerlimit.PlayerLimit; import eu.mhsl.craftattack.spawn.appliances.playerlimit.PlayerLimit;
import eu.mhsl.craftattack.spawn.appliances.projectStart.ProjectStart;
import eu.mhsl.craftattack.spawn.appliances.report.Report; import eu.mhsl.craftattack.spawn.appliances.report.Report;
import eu.mhsl.craftattack.spawn.appliances.restart.Restart; import eu.mhsl.craftattack.spawn.appliances.restart.Restart;
import eu.mhsl.craftattack.spawn.appliances.settings.Settings; import eu.mhsl.craftattack.spawn.appliances.settings.Settings;
import eu.mhsl.craftattack.spawn.appliances.tablist.Tablist; import eu.mhsl.craftattack.spawn.appliances.tablist.Tablist;
import eu.mhsl.craftattack.spawn.appliances.titleClear.TitleClear; import eu.mhsl.craftattack.spawn.appliances.titleClear.TitleClear;
import eu.mhsl.craftattack.spawn.appliances.whitelist.Whitelist; import eu.mhsl.craftattack.spawn.appliances.whitelist.Whitelist;
import eu.mhsl.craftattack.spawn.config.Configuration;
import eu.mhsl.craftattack.spawn.appliances.worldmuseum.WorldMuseum; import eu.mhsl.craftattack.spawn.appliances.worldmuseum.WorldMuseum;
import eu.mhsl.craftattack.spawn.config.Configuration;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
@ -35,6 +35,7 @@ public final class Main extends JavaPlugin {
private List<Appliance> appliances; private List<Appliance> appliances;
private HttpServer httpApi; private HttpServer httpApi;
@Override @Override
public void onEnable() { public void onEnable() {
instance = this; instance = this;
@ -42,26 +43,26 @@ public final class Main extends JavaPlugin {
Configuration.readConfig(); Configuration.readConfig();
appliances = List.of( appliances = List.of(
new AdminMarker(), new AdminMarker(),
new WorldMuseum(), new WorldMuseum(),
new TitleClear(), new TitleClear(),
new ProjectStart(), new ProjectStart(),
new Tablist(), new Tablist(),
new ChatMessages(), new ChatMessages(),
new Report(), new Report(),
new Event(), new Event(),
new Help(), new Help(),
new PlayerLimit(), new PlayerLimit(),
new Whitelist(), new Whitelist(),
new Restart(), new Restart(),
new Kick(), new Kick(),
new PanicBan(), new PanicBan(),
new Outlawed(), new Outlawed(),
new DisplayName(), new DisplayName(),
new Debug(), new Debug(),
new Fleischerchest(), new Fleischerchest(),
new CustomAdvancements(), new CustomAdvancements(),
new Settings() new Settings()
); );
Bukkit.getLogger().info("Loading appliances..."); Bukkit.getLogger().info("Loading appliances...");
@ -94,10 +95,10 @@ public final class Main extends JavaPlugin {
public <T extends Appliance> T getAppliance(Class<T> clazz) { public <T extends Appliance> T getAppliance(Class<T> clazz) {
return this.appliances.stream() return this.appliances.stream()
.filter(clazz::isInstance) .filter(clazz::isInstance)
.map(clazz::cast) .map(clazz::cast)
.findFirst() .findFirst()
.orElseThrow(() -> new RuntimeException(String.format("Appliance %s not loaded or instantiated!", clazz))); .orElseThrow(() -> new RuntimeException(String.format("Appliance %s not loaded or instantiated!", clazz)));
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")

View File

@ -15,6 +15,7 @@ public class HttpServer {
protected final Gson gson = new Gson(); protected final Gson gson = new Gson();
public static Object nothing = null; public static Object nothing = null;
public HttpServer() { public HttpServer() {
Spark.port(8080); Spark.port(8080);
@ -41,6 +42,7 @@ public class HttpServer {
} }
private final String applianceName; private final String applianceName;
private ApiBuilder(Appliance appliance) { private ApiBuilder(Appliance appliance) {
this.applianceName = appliance.getClass().getSimpleName().toLowerCase(); this.applianceName = appliance.getClass().getSimpleName().toLowerCase();
} }
@ -69,7 +71,7 @@ public class HttpServer {
HttpServer.Response response; HttpServer.Response response;
try { try {
response = new Response(Response.Status.SUCCESS, null, exec.get()); response = new Response(Response.Status.SUCCESS, null, exec.get());
} catch (Exception e) { } catch(Exception e) {
response = new Response(Response.Status.FAILURE, e, null); response = new Response(Response.Status.FAILURE, e, null);
} }
return HttpServer.this.gson.toJson(response); return HttpServer.this.gson.toJson(response);

View File

@ -24,10 +24,12 @@ public abstract class Appliance {
private List<Listener> listeners; private List<Listener> listeners;
private List<ApplianceCommand<?>> commands; private List<ApplianceCommand<?>> commands;
public Appliance() {} public Appliance() {
}
/** /**
* Use this constructor to specify a config sub-path for use with the localConfig() method. * Use this constructor to specify a config sub-path for use with the localConfig() method.
*
* @param localConfigPath sub path, if not found, the whole config will be used * @param localConfigPath sub path, if not found, the whole config will be used
*/ */
public Appliance(String localConfigPath) { public Appliance(String localConfigPath) {
@ -36,6 +38,7 @@ public abstract class Appliance {
/** /**
* Provides a list of listeners for the appliance. All listeners will be automatically registered. * Provides a list of listeners for the appliance. All listeners will be automatically registered.
*
* @return List of listeners * @return List of listeners
*/ */
@NotNull @NotNull
@ -45,6 +48,7 @@ public abstract class Appliance {
/** /**
* Provides a list of commands for the appliance. All commands will be automatically registered. * Provides a list of commands for the appliance. All commands will be automatically registered.
*
* @return List of commands * @return List of commands
*/ */
@NotNull @NotNull
@ -55,12 +59,15 @@ public abstract class Appliance {
/** /**
* Called on initialization to add all needed API Routes. * Called on initialization to add all needed API Routes.
* The routeBuilder can be used to get the correct Path prefixes * The routeBuilder can be used to get the correct Path prefixes
*
* @param apiBuilder holds data for needed route prefixes. * @param apiBuilder holds data for needed route prefixes.
*/ */
public void httpApi(HttpServer.ApiBuilder apiBuilder) {} public void httpApi(HttpServer.ApiBuilder apiBuilder) {
}
/** /**
* Provides a localized config section. Path can be set in appliance constructor. * Provides a localized config section. Path can be set in appliance constructor.
*
* @return Section of configuration for your appliance * @return Section of configuration for your appliance
*/ */
@NotNull @NotNull
@ -68,8 +75,11 @@ public abstract class Appliance {
return Optional.ofNullable(Configuration.cfg.getConfigurationSection(localConfigPath)).orElse(Configuration.cfg); return Optional.ofNullable(Configuration.cfg.getConfigurationSection(localConfigPath)).orElse(Configuration.cfg);
} }
public void onEnable() {} public void onEnable() {
public void onDisable() {} }
public void onDisable() {
}
public void initialize(@NotNull JavaPlugin plugin) { public void initialize(@NotNull JavaPlugin plugin) {
this.listeners = eventHandlers(); this.listeners = eventHandlers();

View File

@ -20,6 +20,7 @@ import java.util.Optional;
public abstract class ApplianceCommand<T extends Appliance> extends ApplianceSupplier<T> implements TabCompleter, CommandExecutor { public abstract class ApplianceCommand<T extends Appliance> extends ApplianceSupplier<T> implements TabCompleter, CommandExecutor {
public String commandName; public String commandName;
protected Component errorMessage = Component.text("Fehler: ").color(NamedTextColor.RED); protected Component errorMessage = Component.text("Fehler: ").color(NamedTextColor.RED);
public ApplianceCommand(String command) { public ApplianceCommand(String command) {
this.commandName = command; this.commandName = command;
} }
@ -33,9 +34,9 @@ public abstract class ApplianceCommand<T extends Appliance> extends ApplianceSup
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
try { try {
execute(sender, command, label, args); execute(sender, command, label, args);
} catch (Error e) { } catch(Error e) {
sender.sendMessage(errorMessage.append(Component.text(e.getMessage()))); sender.sendMessage(errorMessage.append(Component.text(e.getMessage())));
} catch (Exception e) { } catch(Exception e) {
sender.sendMessage(errorMessage.append(Component.text("Interner Fehler"))); sender.sendMessage(errorMessage.append(Component.text("Interner Fehler")));
Bukkit.getLogger().warning("Error executing appliance command " + commandName + ": " + e.getMessage()); Bukkit.getLogger().warning("Error executing appliance command " + commandName + ": " + e.getMessage());
e.printStackTrace(System.err); e.printStackTrace(System.err);
@ -50,7 +51,7 @@ public abstract class ApplianceCommand<T extends Appliance> extends ApplianceSup
} }
protected List<String> tabCompleteReducer(List<String> response, String[] args) { protected List<String> tabCompleteReducer(List<String> response, String[] args) {
return response.stream().filter(s -> s.startsWith(args[args.length-1])).toList(); return response.stream().filter(s -> s.startsWith(args[args.length - 1])).toList();
} }
protected abstract void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) throws Exception; protected abstract void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) throws Exception;
@ -61,6 +62,7 @@ public abstract class ApplianceCommand<T extends Appliance> extends ApplianceSup
public static abstract class PlayerChecked<T extends Appliance> extends ApplianceCommand<T> { public static abstract class PlayerChecked<T extends Appliance> extends ApplianceCommand<T> {
private Player player; private Player player;
private Component notPlayerMessage = Component.text("Dieser Command kann nur von Spielern ausgeführt werden!").color(NamedTextColor.RED); private Component notPlayerMessage = Component.text("Dieser Command kann nur von Spielern ausgeführt werden!").color(NamedTextColor.RED);
public PlayerChecked(String command) { public PlayerChecked(String command) {
super(command); super(command);
} }

View File

@ -5,6 +5,7 @@ import org.bukkit.event.Listener;
/** /**
* Utility class which provides a specific, type save appliance. * Utility class which provides a specific, type save appliance.
* You can access the appliance with the protected 'appliance' field. * You can access the appliance with the protected 'appliance' field.
*
* @param <T> the type of your appliance * @param <T> the type of your appliance
*/ */
public abstract class ApplianceListener<T extends Appliance> extends ApplianceSupplier<T> implements Listener { public abstract class ApplianceListener<T extends Appliance> extends ApplianceSupplier<T> implements Listener {

View File

@ -11,7 +11,8 @@ import java.util.List;
public class AdminMarker extends Appliance { public class AdminMarker extends Appliance {
public TextColor getPlayerColor(Player player) { public TextColor getPlayerColor(Player player) {
if (player.hasPermission("chatcolor")) return TextColor.color(Color.AQUA.asRGB()); // TODO read permission from config if(player.hasPermission("chatcolor"))
return TextColor.color(Color.AQUA.asRGB()); // TODO read permission from config
return TextColor.color(Color.WHITE.asRGB()); return TextColor.color(Color.WHITE.asRGB());
} }

View File

@ -7,7 +7,8 @@ import org.bukkit.entity.Player;
public class AdminMarkerListener extends ApplianceListener<AdminMarker> { public class AdminMarkerListener extends ApplianceListener<AdminMarker> {
private TextColor getPlayerColor(Player player) { private TextColor getPlayerColor(Player player) {
if (player.hasPermission("chatcolor")) return TextColor.color(Color.AQUA.asRGB()); // TODO read permission from config if(player.hasPermission("chatcolor"))
return TextColor.color(Color.AQUA.asRGB()); // TODO read permission from config
return TextColor.color(Color.WHITE.asRGB()); return TextColor.color(Color.WHITE.asRGB());
} }
} }

View File

@ -22,11 +22,11 @@ public class ChatMessagesListener extends ApplianceListener<ChatMessages> {
@EventHandler @EventHandler
public void onPlayerChatEvent(AsyncChatEvent event) { public void onPlayerChatEvent(AsyncChatEvent event) {
event.renderer( event.renderer(
(source, sourceDisplayName, message, viewer) -> (source, sourceDisplayName, message, viewer) ->
Component.text("") Component.text("")
.append(getReportablePlayerName(source)) .append(getReportablePlayerName(source))
.append(Component.text(" > ").color(TextColor.color(Color.GRAY.asRGB()))) .append(Component.text(" > ").color(TextColor.color(Color.GRAY.asRGB())))
.append(message).color(TextColor.color(Color.SILVER.asRGB())) .append(message).color(TextColor.color(Color.SILVER.asRGB()))
); );
} }
@ -59,22 +59,22 @@ public class ChatMessagesListener extends ApplianceListener<ChatMessages> {
@EventHandler @EventHandler
public void onDeath(PlayerDeathEvent event) { public void onDeath(PlayerDeathEvent event) {
event.deathMessage( event.deathMessage(
Component Component
.text("") .text("")
.append( .append(
Optional Optional
.ofNullable(event.deathMessage()) .ofNullable(event.deathMessage())
.orElse(Component.text(event.getPlayer().getName())) .orElse(Component.text(event.getPlayer().getName()))
) )
.color(TextColor.color(Color.SILVER.asRGB())) .color(TextColor.color(Color.SILVER.asRGB()))
); );
} }
private Component getReportablePlayerName(Player player) { private Component getReportablePlayerName(Player player) {
return Component return Component
.text("") .text("")
.append(player.displayName()) .append(player.displayName())
.hoverEvent(HoverEvent.showText(Component.text("Klicke, um diesen Spieler zu reporten").color(NamedTextColor.GOLD))) .hoverEvent(HoverEvent.showText(Component.text("Klicke, um diesen Spieler zu reporten").color(NamedTextColor.GOLD)))
.clickEvent(ClickEvent.clickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/report " + player.getName() + " ")); .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/report " + player.getName() + " "));
} }
} }

View File

@ -7,13 +7,14 @@ import eu.mhsl.craftattack.spawn.appliances.debug.command.UserInfoCommand;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
public class Debug extends Appliance { public class Debug extends Appliance {
@Override @Override
@NotNull @NotNull
protected List<ApplianceCommand<?>> commands() { protected List<ApplianceCommand<?>> commands() {
return List.of( return List.of(
new UserInfoCommand(), new UserInfoCommand(),
new AppliancesCommand() new AppliancesCommand()
); );
} }
} }

View File

@ -24,38 +24,38 @@ public class AppliancesCommand extends ApplianceCommand<Debug> {
@Override @Override
protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
ComponentBuilder<TextComponent, TextComponent.Builder> componentBuilder = Component.text() ComponentBuilder<TextComponent, TextComponent.Builder> componentBuilder = Component.text()
.append(Component.text(Main.instance().getAppliances().size())) .append(Component.text(Main.instance().getAppliances().size()))
.append(Component.text(" appliances running:")) .append(Component.text(" appliances running:"))
.appendNewline(); .appendNewline();
Main.instance().getAppliances().forEach(appliance -> { Main.instance().getAppliances().forEach(appliance -> {
List<ApplianceCommand<?>> commands = appliance.getCommands(); List<ApplianceCommand<?>> commands = appliance.getCommands();
List<Listener> listener = appliance.getListeners(); List<Listener> listener = appliance.getListeners();
componentBuilder componentBuilder
.append(Component.text(appliance.getClass().getSimpleName(), NamedTextColor.GREEN) .append(Component.text(appliance.getClass().getSimpleName(), NamedTextColor.GREEN)
.hoverEvent(HoverEvent.showText(Component.text(appliance.getClass().getName())))) .hoverEvent(HoverEvent.showText(Component.text(appliance.getClass().getName()))))
.append(Component.text(": ", NamedTextColor.DARK_GRAY)) .append(Component.text(": ", NamedTextColor.DARK_GRAY))
.append(Component.text(commands.size() + " Commands", NamedTextColor.GRAY) .append(Component.text(commands.size() + " Commands", NamedTextColor.GRAY)
.hoverEvent(HoverEvent.showText(commands.stream() .hoverEvent(HoverEvent.showText(commands.stream()
.map(applianceCommand -> Component.text() .map(applianceCommand -> Component.text()
.append(Component.text(applianceCommand.commandName, NamedTextColor.DARK_GREEN)) .append(Component.text(applianceCommand.commandName, NamedTextColor.DARK_GREEN))
.append(Component.text(": ")) .append(Component.text(": "))
.append(Component.text(applianceCommand.getClass().getName())) .append(Component.text(applianceCommand.getClass().getName()))
.build()) .build())
.reduce(ComponentUtil::appendWithNewline) .reduce(ComponentUtil::appendWithNewline)
.orElse(Component.text("No commands available"))))) .orElse(Component.text("No commands available")))))
.append(Component.text(", ", NamedTextColor.GRAY)) .append(Component.text(", ", NamedTextColor.GRAY))
.append(Component.text(listener.size() + " Listener", NamedTextColor.GRAY) .append(Component.text(listener.size() + " Listener", NamedTextColor.GRAY)
.hoverEvent(HoverEvent.showText(listener.stream() .hoverEvent(HoverEvent.showText(listener.stream()
.map(eventHandler -> Component.text() .map(eventHandler -> Component.text()
.append(Component.text(eventHandler.getClass().getSimpleName(), NamedTextColor.DARK_GREEN)) .append(Component.text(eventHandler.getClass().getSimpleName(), NamedTextColor.DARK_GREEN))
.append(Component.text(": ")) .append(Component.text(": "))
.append(Component.text(eventHandler.getClass().getName())) .append(Component.text(eventHandler.getClass().getName()))
.build()) .build())
.reduce(ComponentUtil::appendWithNewline) .reduce(ComponentUtil::appendWithNewline)
.orElse(Component.text("No listeners available"))))) .orElse(Component.text("No listeners available")))))
.appendNewline(); .appendNewline();
}); });
componentBuilder.append(Component.text(Main.instance().getClass().getName(), NamedTextColor.GRAY)); componentBuilder.append(Component.text(Main.instance().getClass().getName(), NamedTextColor.GRAY));

View File

@ -26,40 +26,40 @@ public class UserInfoCommand extends ApplianceCommand<Debug> {
@Override @Override
protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if(args.length != 1) { if(args.length != 1) {
sender.sendMessage(Component.text("Bitte gib einen Nutzernamen an.", NamedTextColor.RED)); sender.sendMessage(Component.text("Bitte gib einen Nutzernamen an.", NamedTextColor.RED));
return; return;
} }
OfflinePlayer player = Bukkit.getOfflinePlayer(args[0]); OfflinePlayer player = Bukkit.getOfflinePlayer(args[0]);
sender.sendMessage( sender.sendMessage(
Component.text() Component.text()
.appendNewline() .appendNewline()
.append(Component.text("Informationen zu: ", NamedTextColor.GOLD)) .append(Component.text("Informationen zu: ", NamedTextColor.GOLD))
.append( .append(
Component Component
.text(Objects.requireNonNull(player.getName()), NamedTextColor.YELLOW) .text(Objects.requireNonNull(player.getName()), NamedTextColor.YELLOW)
.clickEvent(ClickEvent.copyToClipboard(Objects.requireNonNull(player.getName()))) .clickEvent(ClickEvent.copyToClipboard(Objects.requireNonNull(player.getName())))
) )
.appendNewline() .appendNewline()
.append( .append(
Component Component
.text("UUID: " + player.getUniqueId(), NamedTextColor.GRAY) .text("UUID: " + player.getUniqueId(), NamedTextColor.GRAY)
.clickEvent(ClickEvent.copyToClipboard(player.getUniqueId().toString())) .clickEvent(ClickEvent.copyToClipboard(player.getUniqueId().toString()))
) )
.appendNewline() .appendNewline()
.append( .append(
Component Component
.text("Erster Besuch: " + formatUnixTimestamp(player.getFirstPlayed()), NamedTextColor.GRAY) .text("Erster Besuch: " + formatUnixTimestamp(player.getFirstPlayed()), NamedTextColor.GRAY)
.clickEvent(ClickEvent.copyToClipboard(String.valueOf(player.getFirstPlayed()))) .clickEvent(ClickEvent.copyToClipboard(String.valueOf(player.getFirstPlayed())))
) )
.appendNewline() .appendNewline()
.append( .append(
Component Component
.text("Letzter Besuch: " + formatUnixTimestamp(player.getLastSeen()), NamedTextColor.GRAY) .text("Letzter Besuch: " + formatUnixTimestamp(player.getLastSeen()), NamedTextColor.GRAY)
.clickEvent(ClickEvent.copyToClipboard(String.valueOf(player.getLastSeen()))) .clickEvent(ClickEvent.copyToClipboard(String.valueOf(player.getLastSeen())))
) )
.appendNewline() .appendNewline()
); );
} }
@ -67,8 +67,8 @@ public class UserInfoCommand extends ApplianceCommand<Debug> {
public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if(args.length < 2) { if(args.length < 2) {
return Stream.concat( return Stream.concat(
Bukkit.getOnlinePlayers().stream().map(Player::getName), Bukkit.getOnlinePlayers().stream().map(Player::getName),
Arrays.stream(Bukkit.getOfflinePlayers()).map(OfflinePlayer::getName) Arrays.stream(Bukkit.getOfflinePlayers()).map(OfflinePlayer::getName)
).toList(); ).toList();
} }

View File

@ -19,7 +19,7 @@ public class DisplayName extends Appliance {
public void update(Player player) { public void update(Player player) {
TextColor playerColor = queryAppliance(AdminMarker.class).getPlayerColor(player); TextColor playerColor = queryAppliance(AdminMarker.class).getPlayerColor(player);
List<Supplier<Component>> prefixes = List.of( List<Supplier<Component>> prefixes = List.of(
() -> queryAppliance(Outlawed.class).getNamePrefix(player) () -> queryAppliance(Outlawed.class).getNamePrefix(player)
); );
ComponentBuilder<TextComponent, TextComponent.Builder> playerName = Component.text(); ComponentBuilder<TextComponent, TextComponent.Builder> playerName = Component.text();
@ -39,7 +39,7 @@ public class DisplayName extends Appliance {
player.customName(component); player.customName(component);
player.displayName(component); player.displayName(component);
player.playerListName(component); player.playerListName(component);
} catch (Exception e) { } catch(Exception e) {
//TODO this throws often exceptions, but still works, don't know why //TODO this throws often exceptions, but still works, don't know why
//Main.instance().getLogger().log(Level.SEVERE, e, e::getMessage); //Main.instance().getLogger().log(Level.SEVERE, e, e::getMessage);
} }

View File

@ -9,9 +9,9 @@ import eu.mhsl.craftattack.spawn.appliances.event.command.*;
import eu.mhsl.craftattack.spawn.appliances.event.listener.ApplyPendingRewardsListener; import eu.mhsl.craftattack.spawn.appliances.event.listener.ApplyPendingRewardsListener;
import eu.mhsl.craftattack.spawn.util.IteratorUtil; import eu.mhsl.craftattack.spawn.util.IteratorUtil;
import eu.mhsl.craftattack.spawn.util.entity.DisplayVillager; import eu.mhsl.craftattack.spawn.util.entity.DisplayVillager;
import eu.mhsl.craftattack.spawn.util.server.PluginMessage;
import eu.mhsl.craftattack.spawn.util.listener.DismissInventoryOpenFromHolder; import eu.mhsl.craftattack.spawn.util.listener.DismissInventoryOpenFromHolder;
import eu.mhsl.craftattack.spawn.util.listener.PlayerInteractAtEntityEventListener; import eu.mhsl.craftattack.spawn.util.listener.PlayerInteractAtEntityEventListener;
import eu.mhsl.craftattack.spawn.util.server.PluginMessage;
import eu.mhsl.craftattack.spawn.util.text.ComponentUtil; import eu.mhsl.craftattack.spawn.util.text.ComponentUtil;
import eu.mhsl.craftattack.spawn.util.text.Countdown; import eu.mhsl.craftattack.spawn.util.text.Countdown;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
@ -39,16 +39,17 @@ public class Event extends Appliance {
ADVERTISED, ADVERTISED,
DONE DONE
} }
Countdown advertiseCountdown = new Countdown( Countdown advertiseCountdown = new Countdown(
120, 120,
announcementData -> Component.text() announcementData -> Component.text()
.append(ComponentUtil.createRainbowText("Event", 30)) .append(ComponentUtil.createRainbowText("Event", 30))
.append(Component.text(" Start in ", NamedTextColor.GOLD)) .append(Component.text(" Start in ", NamedTextColor.GOLD))
.append(Component.text(announcementData.count(), NamedTextColor.AQUA)) .append(Component.text(announcementData.count(), NamedTextColor.AQUA))
.append(Component.text(" " + announcementData.unit() + "!", NamedTextColor.GOLD)) .append(Component.text(" " + announcementData.unit() + "!", NamedTextColor.GOLD))
.build(), .build(),
component -> IteratorUtil.onlinePlayers(player -> player.sendMessage(component)), component -> IteratorUtil.onlinePlayers(player -> player.sendMessage(component)),
() -> this.advertiseStatus = AdvertisementStatus.DONE () -> this.advertiseStatus = AdvertisementStatus.DONE
); );
public DisplayVillager.ConfigBound villager; public DisplayVillager.ConfigBound villager;
private boolean isOpen = false; private boolean isOpen = false;
@ -57,8 +58,12 @@ public class Event extends Appliance {
private final HttpClient eventServerClient = HttpClient.newHttpClient(); private final HttpClient eventServerClient = HttpClient.newHttpClient();
private final List<Reward> pendingRewards = new ArrayList<>(); private final List<Reward> pendingRewards = new ArrayList<>();
record RewardConfiguration(String memorialMaterial, String memorialTitle, String memorialLore, List<UUID> memorials, String material, Map<UUID, Integer> rewards) {} record RewardConfiguration(String memorialMaterial, String memorialTitle, String memorialLore, List<UUID> memorials,
record Reward(UUID playerUuid, ItemStack itemStack) {} String material, Map<UUID, Integer> rewards) {
}
record Reward(UUID playerUuid, ItemStack itemStack) {
}
public Event() { public Event() {
super("event"); super("event");
@ -67,12 +72,12 @@ public class Event extends Appliance {
@Override @Override
public void onEnable() { public void onEnable() {
this.villager = new DisplayVillager.ConfigBound( this.villager = new DisplayVillager.ConfigBound(
localConfig(), localConfig(),
villager -> { villager -> {
villager.customName(Component.text("Events", NamedTextColor.GOLD)); villager.customName(Component.text("Events", NamedTextColor.GOLD));
villager.setProfession(Villager.Profession.LIBRARIAN); villager.setProfession(Villager.Profession.LIBRARIAN);
villager.setVillagerType(Villager.Type.SNOW); villager.setVillagerType(Villager.Type.SNOW);
} }
); );
this.isOpen = localConfig().getBoolean("enabled", false); this.isOpen = localConfig().getBoolean("enabled", false);
if(this.isOpen) this.roomId = UUID.fromString(localConfig().getString("roomId", "")); if(this.isOpen) this.roomId = UUID.fromString(localConfig().getString("roomId", ""));
@ -81,14 +86,16 @@ public class Event extends Appliance {
public void openEvent() throws URISyntaxException, IOException, InterruptedException { public void openEvent() throws URISyntaxException, IOException, InterruptedException {
if(isOpen) throw new ApplianceCommand.Error("Es läuft derzeit bereits ein Event!"); if(isOpen) throw new ApplianceCommand.Error("Es läuft derzeit bereits ein Event!");
HttpRequest createRoomRequest = HttpRequest.newBuilder() HttpRequest createRoomRequest = HttpRequest.newBuilder()
.uri(new URI(localConfig().getString("api") + "/room")) .uri(new URI(localConfig().getString("api") + "/room"))
.POST(HttpRequest.BodyPublishers.noBody()) .POST(HttpRequest.BodyPublishers.noBody())
.build(); .build();
HttpResponse<String> rawResponse = eventServerClient.send(createRoomRequest, HttpResponse.BodyHandlers.ofString()); HttpResponse<String> rawResponse = eventServerClient.send(createRoomRequest, HttpResponse.BodyHandlers.ofString());
if(rawResponse.statusCode() != 200) throw new ApplianceCommand.Error("Event-Server meldet Fehler: " + rawResponse.statusCode()); if(rawResponse.statusCode() != 200)
throw new ApplianceCommand.Error("Event-Server meldet Fehler: " + rawResponse.statusCode());
record Response(UUID uuid) {} record Response(UUID uuid) {
}
Response response = new Gson().fromJson(rawResponse.body(), Response.class); Response response = new Gson().fromJson(rawResponse.body(), Response.class);
isOpen = true; isOpen = true;
@ -114,14 +121,16 @@ public class Event extends Appliance {
try { try {
Main.instance().getLogger().info("Verbinde mit eventserver: " + p.getName()); Main.instance().getLogger().info("Verbinde mit eventserver: " + p.getName());
p.sendMessage(Component.text("Authentifiziere...", NamedTextColor.GREEN)); p.sendMessage(Component.text("Authentifiziere...", NamedTextColor.GREEN));
record Request(UUID player, UUID room) {} record Request(UUID player, UUID room) {
}
Request request = new Request(p.getUniqueId(), this.roomId); Request request = new Request(p.getUniqueId(), this.roomId);
HttpRequest queueRoomRequest = HttpRequest.newBuilder() HttpRequest queueRoomRequest = HttpRequest.newBuilder()
.uri(new URI(localConfig().getString("api") + "/queueRoom")) .uri(new URI(localConfig().getString("api") + "/queueRoom"))
.POST(HttpRequest.BodyPublishers.ofString(new Gson().toJson(request))) .POST(HttpRequest.BodyPublishers.ofString(new Gson().toJson(request)))
.build(); .build();
record Response(String error) {} record Response(String error) {
}
HttpResponse<String> rawResponse = eventServerClient.send(queueRoomRequest, HttpResponse.BodyHandlers.ofString()); HttpResponse<String> rawResponse = eventServerClient.send(queueRoomRequest, HttpResponse.BodyHandlers.ofString());
Main.instance().getLogger().info("Response: " + rawResponse.body()); Main.instance().getLogger().info("Response: " + rawResponse.body());
Response response = new Gson().fromJson(rawResponse.body(), Response.class); Response response = new Gson().fromJson(rawResponse.body(), Response.class);
@ -134,7 +143,7 @@ public class Event extends Appliance {
p.sendMessage(Component.text("Betrete...", NamedTextColor.GREEN)); p.sendMessage(Component.text("Betrete...", NamedTextColor.GREEN));
PluginMessage.connect(p, localConfig().getString("connect-server-name")); PluginMessage.connect(p, localConfig().getString("connect-server-name"));
} catch (URISyntaxException | IOException | InterruptedException e) { } catch(URISyntaxException | IOException | InterruptedException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@ -163,7 +172,7 @@ public class Event extends Appliance {
memorialItem.setItemMeta(meta); memorialItem.setItemMeta(meta);
Reward memorial = new Reward(uuid, memorialItem); Reward memorial = new Reward(uuid, memorialItem);
if (Bukkit.getPlayer(uuid) == null) { if(Bukkit.getPlayer(uuid) == null) {
pendingRewards.add(memorial); pendingRewards.add(memorial);
return; return;
} }
@ -177,8 +186,8 @@ public class Event extends Appliance {
Map<Integer, ItemStack> remaining = player.getInventory().addItem(reward.itemStack); Map<Integer, ItemStack> remaining = player.getInventory().addItem(reward.itemStack);
Bukkit.getScheduler().runTask( Bukkit.getScheduler().runTask(
Main.instance(), Main.instance(),
() -> remaining.values().forEach(remainingStack -> player.getWorld().dropItem(player.getLocation(), remainingStack)) () -> remaining.values().forEach(remainingStack -> player.getWorld().dropItem(player.getLocation(), remainingStack))
); );
} }
@ -194,13 +203,13 @@ public class Event extends Appliance {
this.advertiseStatus = AdvertisementStatus.ADVERTISED; this.advertiseStatus = AdvertisementStatus.ADVERTISED;
IteratorUtil.onlinePlayers(player -> { IteratorUtil.onlinePlayers(player -> {
player.sendMessage( player.sendMessage(
Component.text() Component.text()
.append(Component.text("-".repeat(10), NamedTextColor.GRAY)).appendNewline() .append(Component.text("-".repeat(10), NamedTextColor.GRAY)).appendNewline()
.append(Component.text("Ein Event wurde gestartet!", NamedTextColor.GOLD)).appendNewline() .append(Component.text("Ein Event wurde gestartet!", NamedTextColor.GOLD)).appendNewline()
.append(Component.text("Nutze ")) .append(Component.text("Nutze "))
.append(Component.text("/event", NamedTextColor.AQUA)) .append(Component.text("/event", NamedTextColor.AQUA))
.append(Component.text(", um dem Event beizutreten!")).appendNewline() .append(Component.text(", um dem Event beizutreten!")).appendNewline()
.append(Component.text("-".repeat(10), NamedTextColor.GRAY)).appendNewline() .append(Component.text("-".repeat(10), NamedTextColor.GRAY)).appendNewline()
); );
}); });
advertiseCountdown.start(); advertiseCountdown.start();
@ -218,11 +227,11 @@ public class Event extends Appliance {
@NotNull @NotNull
protected List<ApplianceCommand<?>> commands() { protected List<ApplianceCommand<?>> commands() {
return List.of( return List.of(
new EventCommand(), new EventCommand(),
new MoveEventVillagerCommand(), new MoveEventVillagerCommand(),
new EventOpenSessionCommand(), new EventOpenSessionCommand(),
new EventEndSessionCommand(), new EventEndSessionCommand(),
new EventAdvertiseCommand() new EventAdvertiseCommand()
); );
} }
@ -230,9 +239,9 @@ public class Event extends Appliance {
@NotNull @NotNull
protected List<Listener> eventHandlers() { protected List<Listener> eventHandlers() {
return List.of( return List.of(
new ApplyPendingRewardsListener(), new ApplyPendingRewardsListener(),
new PlayerInteractAtEntityEventListener(this.villager.getUniqueId(), playerInteractAtEntityEvent -> joinEvent(playerInteractAtEntityEvent.getPlayer())), new PlayerInteractAtEntityEventListener(this.villager.getUniqueId(), playerInteractAtEntityEvent -> joinEvent(playerInteractAtEntityEvent.getPlayer())),
new DismissInventoryOpenFromHolder(this.villager.getUniqueId()) new DismissInventoryOpenFromHolder(this.villager.getUniqueId())
); );
} }
} }

View File

@ -19,10 +19,10 @@ public class Help extends Appliance {
@NotNull @NotNull
protected List<ApplianceCommand<?>> commands() { protected List<ApplianceCommand<?>> commands() {
return List.of( return List.of(
new HelpCommand(), new HelpCommand(),
new SpawnCommand(), new SpawnCommand(),
new TeamspeakCommand(), new TeamspeakCommand(),
new DiscordCommand() new DiscordCommand()
); );
} }
} }

View File

@ -16,8 +16,8 @@ public class DiscordCommand extends ApplianceCommand<Help> {
@Override @Override
protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) throws Exception { protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) throws Exception {
sender.sendMessage( sender.sendMessage(
Component.text("Einen offiziellen Discord Server gibt es nicht, aber Du kannst gerne unserem Teamspeak joinen: ", NamedTextColor.GOLD) Component.text("Einen offiziellen Discord Server gibt es nicht, aber Du kannst gerne unserem Teamspeak joinen: ", NamedTextColor.GOLD)
.append(Component.text("mhsl.eu", NamedTextColor.AQUA)) .append(Component.text("mhsl.eu", NamedTextColor.AQUA))
); );
} }
} }

View File

@ -16,9 +16,9 @@ public class HelpCommand extends ApplianceCommand<Help> {
@Override @Override
protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
sender.sendMessage( sender.sendMessage(
Component.text("Willkommen auf Craftattack!", NamedTextColor.GOLD) Component.text("Willkommen auf Craftattack!", NamedTextColor.GOLD)
.appendNewline() .appendNewline()
.append(Component.text("Hier ist ein Hilfetext!", NamedTextColor.GRAY)) .append(Component.text("Hier ist ein Hilfetext!", NamedTextColor.GRAY))
); );
} }
} }

View File

@ -12,13 +12,15 @@ import java.util.Objects;
public class SpawnCommand extends ApplianceCommand<Help> { public class SpawnCommand extends ApplianceCommand<Help> {
private static final String spawnKey = "spawn"; private static final String spawnKey = "spawn";
public SpawnCommand() { public SpawnCommand() {
super("spawn"); super("spawn");
} }
@Override @Override
protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if(!getAppliance().localConfig().isString(spawnKey)) throw new ApplianceCommand.Error("Es wurde kein Spawnbereich hinterlegt!"); if(!getAppliance().localConfig().isString(spawnKey))
throw new ApplianceCommand.Error("Es wurde kein Spawnbereich hinterlegt!");
sender.sendMessage(Component.text(Objects.requireNonNull(getAppliance().localConfig().getString(spawnKey)), NamedTextColor.GOLD)); sender.sendMessage(Component.text(Objects.requireNonNull(getAppliance().localConfig().getString(spawnKey)), NamedTextColor.GOLD));
} }
} }

View File

@ -10,23 +10,25 @@ import org.jetbrains.annotations.NotNull;
public class TeamspeakCommand extends ApplianceCommand<Help> { public class TeamspeakCommand extends ApplianceCommand<Help> {
private static final String teamspeakKey = "teamspeak"; private static final String teamspeakKey = "teamspeak";
public TeamspeakCommand() { public TeamspeakCommand() {
super("teamspeak"); super("teamspeak");
} }
@Override @Override
protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if(!getAppliance().localConfig().isString(teamspeakKey)) throw new ApplianceCommand.Error("Es wurde kein Teamspeak hinterlegt!"); if(!getAppliance().localConfig().isString(teamspeakKey))
throw new ApplianceCommand.Error("Es wurde kein Teamspeak hinterlegt!");
sender.sendMessage( sender.sendMessage(
Component.text() Component.text()
.append(Component.text("Joine unserem Teamspeak: ", NamedTextColor.GOLD)) .append(Component.text("Joine unserem Teamspeak: ", NamedTextColor.GOLD))
.append(getTeamspeakIp(getAppliance().localConfig().getString(teamspeakKey))) .append(getTeamspeakIp(getAppliance().localConfig().getString(teamspeakKey)))
); );
} }
private Component getTeamspeakIp(String ip) { private Component getTeamspeakIp(String ip) {
return Component.text() return Component.text()
.append(Component.text(ip, NamedTextColor.AQUA)) .append(Component.text(ip, NamedTextColor.AQUA))
.build(); .build();
} }
} }

View File

@ -18,10 +18,10 @@ public class Kick extends Appliance {
throw new ApplianceCommand.Error("Player not found"); throw new ApplianceCommand.Error("Player not found");
new DisconnectInfo( new DisconnectInfo(
"Administrator Eingriff", "Administrator Eingriff",
"Du wurdest von einem Admin vom Server geworfen.", "Du wurdest von einem Admin vom Server geworfen.",
message, message,
player.getUniqueId() player.getUniqueId()
).applyKick(player); ).applyKick(player);
} }

View File

@ -20,16 +20,16 @@ public class KickCommand extends ApplianceCommand<Kick> {
@Override @Override
protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) throws Exception { protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) throws Exception {
getAppliance().kick( getAppliance().kick(
args[0], args[0],
Arrays.stream(args).skip(1).collect(Collectors.joining(" ")) Arrays.stream(args).skip(1).collect(Collectors.joining(" "))
); );
} }
@Override @Override
public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
return super.tabCompleteReducer( return super.tabCompleteReducer(
Bukkit.getOnlinePlayers().stream().map(Player::getName).toList(), Bukkit.getOnlinePlayers().stream().map(Player::getName).toList(),
args args
); );
} }
} }

View File

@ -1,9 +1,9 @@
package eu.mhsl.craftattack.spawn.appliances.outlawed; package eu.mhsl.craftattack.spawn.appliances.outlawed;
import eu.mhsl.craftattack.spawn.Main; import eu.mhsl.craftattack.spawn.Main;
import eu.mhsl.craftattack.spawn.appliances.displayName.DisplayName;
import eu.mhsl.craftattack.spawn.appliance.Appliance; import eu.mhsl.craftattack.spawn.appliance.Appliance;
import eu.mhsl.craftattack.spawn.appliance.ApplianceCommand; import eu.mhsl.craftattack.spawn.appliance.ApplianceCommand;
import eu.mhsl.craftattack.spawn.appliances.displayName.DisplayName;
import eu.mhsl.craftattack.spawn.appliances.whitelist.Whitelist; import eu.mhsl.craftattack.spawn.appliances.whitelist.Whitelist;
import eu.mhsl.craftattack.spawn.config.Configuration; import eu.mhsl.craftattack.spawn.config.Configuration;
import eu.mhsl.craftattack.spawn.util.text.DisconnectInfo; import eu.mhsl.craftattack.spawn.util.text.DisconnectInfo;
@ -18,8 +18,9 @@ import org.jetbrains.annotations.NotNull;
import java.util.*; import java.util.*;
public class Outlawed extends Appliance { public class Outlawed extends Appliance {
public final int timeoutInMs = 1000*60*60*6; public final int timeoutInMs = 1000 * 60 * 60 * 6;
private final Map<UUID, Long> timeouts = new HashMap<>(); private final Map<UUID, Long> timeouts = new HashMap<>();
public enum Status { public enum Status {
DISABLED, DISABLED,
VOLUNTARILY, VOLUNTARILY,
@ -32,18 +33,18 @@ public class Outlawed extends Appliance {
public Outlawed() { public Outlawed() {
super("outlawed"); super("outlawed");
Bukkit.getScheduler().runTaskTimerAsynchronously( Bukkit.getScheduler().runTaskTimerAsynchronously(
Main.instance(), Main.instance(),
() -> playerStatusMap.forEach((player, status) -> { () -> playerStatusMap.forEach((player, status) -> {
if(!player.isOnline()) return; if(!player.isOnline()) return;
if(status != Status.FORCED) return; if(status != Status.FORCED) return;
try { try {
Main.instance().getAppliance(Whitelist.class).integrityCheck(player); Main.instance().getAppliance(Whitelist.class).integrityCheck(player);
} catch (DisconnectInfo.Throwable e) { } catch(DisconnectInfo.Throwable e) {
Bukkit.getScheduler().runTask(Main.instance(), () -> e.getDisconnectScreen().applyKick(player)); Bukkit.getScheduler().runTask(Main.instance(), () -> e.getDisconnectScreen().applyKick(player));
} }
}), }),
20*60, 20 * 60,
20*60*5 20 * 60 * 5
); );
} }
@ -66,7 +67,8 @@ public class Outlawed extends Appliance {
public Status getLawStatus(Player player) { public Status getLawStatus(Player player) {
return playerStatusMap.computeIfAbsent(player, p -> { return playerStatusMap.computeIfAbsent(player, p -> {
if(localConfig().getStringList(voluntarilyEntry).contains(p.getUniqueId().toString())) return Status.VOLUNTARILY; if(localConfig().getStringList(voluntarilyEntry).contains(p.getUniqueId().toString()))
return Status.VOLUNTARILY;
return Status.DISABLED; return Status.DISABLED;
}); });
} }
@ -99,19 +101,19 @@ public class Outlawed extends Appliance {
} }
public Component getStatusDescription(Status status) { public Component getStatusDescription(Status status) {
return switch (status) { return switch(status) {
case DISABLED -> Component.text("Vogelfreistatus inaktiv: ", NamedTextColor.GREEN) case DISABLED -> Component.text("Vogelfreistatus inaktiv: ", NamedTextColor.GREEN)
.append(Component.text("Es gelten die Standard Regeln!", NamedTextColor.GOLD)); .append(Component.text("Es gelten die Standard Regeln!", NamedTextColor.GOLD));
case VOLUNTARILY, FORCED -> Component.text("Vogelfreistatus aktiv: ", NamedTextColor.RED) case VOLUNTARILY, FORCED -> Component.text("Vogelfreistatus aktiv: ", NamedTextColor.RED)
.append(Component.text("Du darfst von jedem angegriffen und getötet werden!", NamedTextColor.GOLD)); .append(Component.text("Du darfst von jedem angegriffen und getötet werden!", NamedTextColor.GOLD));
}; };
} }
public Component getNamePrefix(Player player) { public Component getNamePrefix(Player player) {
if(isOutlawed(player)) { if(isOutlawed(player)) {
return Component.text("[☠]", NamedTextColor.RED) return Component.text("[☠]", NamedTextColor.RED)
.hoverEvent(HoverEvent.showText(Component.text("Vogelfreie Spieler dürfen ohne Grund angegriffen werden!"))); .hoverEvent(HoverEvent.showText(Component.text("Vogelfreie Spieler dürfen ohne Grund angegriffen werden!")));
} }
return null; return null;

View File

@ -17,10 +17,10 @@ public class OutlawedCommand extends ApplianceCommand.PlayerChecked<Outlawed> {
try { try {
getAppliance().switchLawStatus(getPlayer()); getAppliance().switchLawStatus(getPlayer());
sender.sendMessage( sender.sendMessage(
getAppliance() getAppliance()
.getStatusDescription(getAppliance().getLawStatus(getPlayer())) .getStatusDescription(getAppliance().getLawStatus(getPlayer()))
); );
} catch (OutlawChangeNotPermitted e) { } catch(OutlawChangeNotPermitted e) {
sender.sendMessage(Component.text(e.getMessage(), NamedTextColor.RED)); sender.sendMessage(Component.text(e.getMessage(), NamedTextColor.RED));
} }
} }

View File

@ -8,7 +8,10 @@ import org.bukkit.entity.Player;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.*; import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class PanicBan extends Appliance { public class PanicBan extends Appliance {
private final Map<UUID, Long> panicBans = new HashMap<>(); private final Map<UUID, Long> panicBans = new HashMap<>();
@ -32,10 +35,10 @@ public class PanicBan extends Appliance {
public DisconnectInfo getDisconnectInfo(UUID playerUuid) { public DisconnectInfo getDisconnectInfo(UUID playerUuid) {
return new DisconnectInfo( return new DisconnectInfo(
"Temporäre Sperre", "Temporäre Sperre",
"Du wurdest von einen Admin vom Server geworfen!", "Du wurdest von einen Admin vom Server geworfen!",
"Du bist bis zur endgültigen Klärung gesperrt.", "Du bist bis zur endgültigen Klärung gesperrt.",
playerUuid playerUuid
); );
} }

View File

@ -26,11 +26,11 @@ public class PanicBanCommand extends ApplianceCommand<PanicBan> {
@Override @Override
public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
return super.tabCompleteReducer( return super.tabCompleteReducer(
Stream.concat( Stream.concat(
Bukkit.getOnlinePlayers().stream().map(Player::getName), Bukkit.getOnlinePlayers().stream().map(Player::getName),
Arrays.stream(Bukkit.getOfflinePlayers()).map(OfflinePlayer::getName) Arrays.stream(Bukkit.getOfflinePlayers()).map(OfflinePlayer::getName)
).toList(), ).toList(),
args args
); );
} }
} }

View File

@ -12,6 +12,7 @@ import java.util.List;
public class PlayerLimit extends Appliance { public class PlayerLimit extends Appliance {
private static final String playerLimitKey = "maxPlayers"; private static final String playerLimitKey = "maxPlayers";
private int limit; private int limit;
public PlayerLimit() { public PlayerLimit() {
super("playerLimit"); super("playerLimit");
this.limit = localConfig().getInt(playerLimitKey); this.limit = localConfig().getInt(playerLimitKey);
@ -32,7 +33,7 @@ public class PlayerLimit extends Appliance {
@NotNull @NotNull
protected List<Listener> eventHandlers() { protected List<Listener> eventHandlers() {
return List.of( return List.of(
new PlayerLimiterListener() new PlayerLimiterListener()
); );
} }
@ -40,7 +41,7 @@ public class PlayerLimit extends Appliance {
@NotNull @NotNull
protected List<ApplianceCommand<?>> commands() { protected List<ApplianceCommand<?>> commands() {
return List.of( return List.of(
new SetPlayerLimitCommand() new SetPlayerLimitCommand()
); );
} }
} }

View File

@ -10,12 +10,12 @@ public class PlayerLimiterListener extends ApplianceListener<PlayerLimit> {
@EventHandler @EventHandler
public void onLogin(AsyncPlayerPreLoginEvent playerPreLoginEvent) { public void onLogin(AsyncPlayerPreLoginEvent playerPreLoginEvent) {
playerPreLoginEvent.kickMessage( playerPreLoginEvent.kickMessage(
new DisconnectInfo( new DisconnectInfo(
"Hohe Serverauslastung", "Hohe Serverauslastung",
"Der Server ist momentan an seiner Kapazitätsgrenze angelangt!", "Der Server ist momentan an seiner Kapazitätsgrenze angelangt!",
"Bitte versuche es zu einem späteren Zeitpunkt erneut.", "Bitte versuche es zu einem späteren Zeitpunkt erneut.",
playerPreLoginEvent.getUniqueId() playerPreLoginEvent.getUniqueId()
).getComponent() ).getComponent()
); );
if(Bukkit.getOnlinePlayers().size() >= getAppliance().getLimit()) if(Bukkit.getOnlinePlayers().size() >= getAppliance().getLimit())

View File

@ -16,9 +16,9 @@ public class SetPlayerLimitCommand extends ApplianceCommand<PlayerLimit> {
protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if(args.length == 0) { if(args.length == 0) {
sender.sendMessage( sender.sendMessage(
Component.text() Component.text()
.append(Component.text("Das aktuelle Spielerlimit beträgt: ", NamedTextColor.GRAY)) .append(Component.text("Das aktuelle Spielerlimit beträgt: ", NamedTextColor.GRAY))
.append(Component.text(getAppliance().getLimit(), NamedTextColor.GOLD)) .append(Component.text(getAppliance().getLimit(), NamedTextColor.GOLD))
); );
return; return;
} }

View File

@ -8,11 +8,11 @@ import eu.mhsl.craftattack.spawn.appliances.projectStart.command.ProjectStartRes
import eu.mhsl.craftattack.spawn.appliances.projectStart.listener.NoAdvancementsListener; import eu.mhsl.craftattack.spawn.appliances.projectStart.listener.NoAdvancementsListener;
import eu.mhsl.craftattack.spawn.appliances.projectStart.listener.PlayerInvincibleListener; import eu.mhsl.craftattack.spawn.appliances.projectStart.listener.PlayerInvincibleListener;
import eu.mhsl.craftattack.spawn.config.Configuration; import eu.mhsl.craftattack.spawn.config.Configuration;
import eu.mhsl.craftattack.spawn.util.IteratorUtil;
import eu.mhsl.craftattack.spawn.util.entity.PlayerUtils; import eu.mhsl.craftattack.spawn.util.entity.PlayerUtils;
import eu.mhsl.craftattack.spawn.util.world.BlockCycle;
import eu.mhsl.craftattack.spawn.util.text.ComponentUtil; import eu.mhsl.craftattack.spawn.util.text.ComponentUtil;
import eu.mhsl.craftattack.spawn.util.text.Countdown; import eu.mhsl.craftattack.spawn.util.text.Countdown;
import eu.mhsl.craftattack.spawn.util.IteratorUtil; import eu.mhsl.craftattack.spawn.util.world.BlockCycle;
import net.kyori.adventure.sound.Sound; import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.NamedTextColor;
@ -33,63 +33,63 @@ public class ProjectStart extends Appliance {
private final World startWorld = Bukkit.getWorld("world"); private final World startWorld = Bukkit.getWorld("world");
private final Location glassLocation = new Location(startWorld, -224, 67, -368); private final Location glassLocation = new Location(startWorld, -224, 67, -368);
private final List<Location> netherFireLocations = List.of( private final List<Location> netherFireLocations = List.of(
new Location(startWorld, -211, 68, -354), new Location(startWorld, -211, 68, -354),
new Location(startWorld, -209, 68, -356), new Location(startWorld, -209, 68, -356),
new Location(startWorld, -207, 68, -354), new Location(startWorld, -207, 68, -354),
new Location(startWorld, -209, 68, -352) new Location(startWorld, -209, 68, -352)
); );
private final Countdown countdown = new Countdown( private final Countdown countdown = new Countdown(
localConfig().getInt("countdown"), localConfig().getInt("countdown"),
this::format, this::format,
this::announce, this::announce,
this::startProject this::startProject
); );
private final BlockCycle blockCycle = new BlockCycle( private final BlockCycle blockCycle = new BlockCycle(
glassLocation, glassLocation,
Material.ORANGE_STAINED_GLASS, Material.ORANGE_STAINED_GLASS,
List.of( List.of(
Material.RED_STAINED_GLASS, Material.RED_STAINED_GLASS,
Material.YELLOW_STAINED_GLASS, Material.YELLOW_STAINED_GLASS,
Material.GREEN_STAINED_GLASS, Material.GREEN_STAINED_GLASS,
Material.BLUE_STAINED_GLASS Material.BLUE_STAINED_GLASS
) )
); );
private final Map<GameRule<Boolean>, Boolean> gameRulesAfterStart = Map.ofEntries( private final Map<GameRule<Boolean>, Boolean> gameRulesAfterStart = Map.ofEntries(
entry(GameRule.DO_DAYLIGHT_CYCLE, true), entry(GameRule.DO_DAYLIGHT_CYCLE, true),
entry(GameRule.DO_INSOMNIA, true), entry(GameRule.DO_INSOMNIA, true),
entry(GameRule.ANNOUNCE_ADVANCEMENTS, true), entry(GameRule.ANNOUNCE_ADVANCEMENTS, true),
entry(GameRule.DISABLE_RAIDS, false), entry(GameRule.DISABLE_RAIDS, false),
entry(GameRule.DO_FIRE_TICK, true), entry(GameRule.DO_FIRE_TICK, true),
entry(GameRule.DO_ENTITY_DROPS, true), entry(GameRule.DO_ENTITY_DROPS, true),
entry(GameRule.DO_PATROL_SPAWNING, true), entry(GameRule.DO_PATROL_SPAWNING, true),
entry(GameRule.DO_TRADER_SPAWNING, true), entry(GameRule.DO_TRADER_SPAWNING, true),
entry(GameRule.DO_WEATHER_CYCLE, true), entry(GameRule.DO_WEATHER_CYCLE, true),
entry(GameRule.FALL_DAMAGE, true), entry(GameRule.FALL_DAMAGE, true),
entry(GameRule.FIRE_DAMAGE, true) entry(GameRule.FIRE_DAMAGE, true)
); );
public ProjectStart() { public ProjectStart() {
super("countdown"); super("countdown");
this.countdown.addCustomAnnouncement( this.countdown.addCustomAnnouncement(
new Countdown.CustomAnnouncements( new Countdown.CustomAnnouncements(
counter -> counter == startMusicAt, counter -> counter == startMusicAt,
counter -> glassLocation counter -> glassLocation
.getWorld() .getWorld()
.playSound(glassLocation, MUSIC_DISC_PIGSTEP, SoundCategory.RECORDS, 500f, 1f) .playSound(glassLocation, MUSIC_DISC_PIGSTEP, SoundCategory.RECORDS, 500f, 1f)
) )
); );
} }
private Component format(Countdown.AnnouncementData data) { private Component format(Countdown.AnnouncementData data) {
return Component.text() return Component.text()
.append(ComponentUtil.createRainbowText("CraftAttack", 10)) .append(ComponentUtil.createRainbowText("CraftAttack", 10))
.append(Component.text(" startet in ", NamedTextColor.GOLD)) .append(Component.text(" startet in ", NamedTextColor.GOLD))
.append(Component.text(data.count(), NamedTextColor.AQUA)) .append(Component.text(data.count(), NamedTextColor.AQUA))
.append(Component.text(" " + data.unit() + "!", NamedTextColor.GOLD)) .append(Component.text(" " + data.unit() + "!", NamedTextColor.GOLD))
.build(); .build();
} }
private void announce(Component message) { private void announce(Component message) {
@ -133,11 +133,11 @@ public class ProjectStart extends Appliance {
}); });
Bukkit.getServer().advancementIterator().forEachRemaining( Bukkit.getServer().advancementIterator().forEachRemaining(
advancement -> Bukkit.getOnlinePlayers().forEach( advancement -> Bukkit.getOnlinePlayers().forEach(
player -> player.getAdvancementProgress(advancement).getAwardedCriteria().forEach( player -> player.getAdvancementProgress(advancement).getAwardedCriteria().forEach(
criteria -> player.getAdvancementProgress(advancement).revokeCriteria(criteria) criteria -> player.getAdvancementProgress(advancement).revokeCriteria(criteria)
)
) )
)
); );
blockCycle.reset(); blockCycle.reset();
@ -177,8 +177,8 @@ public class ProjectStart extends Appliance {
@NotNull @NotNull
protected List<Listener> eventHandlers() { protected List<Listener> eventHandlers() {
return List.of( return List.of(
new PlayerInvincibleListener(), new PlayerInvincibleListener(),
new NoAdvancementsListener() new NoAdvancementsListener()
); );
} }
@ -186,9 +186,9 @@ public class ProjectStart extends Appliance {
@NotNull @NotNull
protected List<ApplianceCommand<?>> commands() { protected List<ApplianceCommand<?>> commands() {
return List.of( return List.of(
new ProjectStartCommand(), new ProjectStartCommand(),
new ProjectStartCancelCommand(), new ProjectStartCancelCommand(),
new ProjectStartResetCommand() new ProjectStartResetCommand()
); );
} }
} }

View File

@ -26,22 +26,26 @@ import java.util.UUID;
public class Report extends Appliance { public class Report extends Appliance {
public static Component helpText() { public static Component helpText() {
return Component.text() return Component.text()
.appendNewline() .appendNewline()
.append(Component.text(" Um einen Spieler zu melden, verwende ", NamedTextColor.GRAY)).appendNewline() .append(Component.text(" Um einen Spieler zu melden, verwende ", NamedTextColor.GRAY)).appendNewline()
.append(Component.text("/report", NamedTextColor.GOLD)).appendNewline() .append(Component.text("/report", NamedTextColor.GOLD)).appendNewline()
.append(Component.text("oder", NamedTextColor.GRAY)).appendNewline() .append(Component.text("oder", NamedTextColor.GRAY)).appendNewline()
.append(Component.text("/report <spieler> [grund]", NamedTextColor.GOLD)).appendNewline() .append(Component.text("/report <spieler> [grund]", NamedTextColor.GOLD)).appendNewline()
.build(); .build();
} }
private final URI apiEndpoint; private final URI apiEndpoint;
public Report() { public Report() {
super("report"); super("report");
this.apiEndpoint = URI.create(Objects.requireNonNull(localConfig().getString("api"))); this.apiEndpoint = URI.create(Objects.requireNonNull(localConfig().getString("api")));
} }
private record Request(@NotNull UUID reporter, @Nullable UUID reported, String reason) {} private record Request(@NotNull UUID reporter, @Nullable UUID reported, String reason) {
private record Response(@NotNull String url) {} }
private record Response(@NotNull String url) {
}
public void reportToUnknown(@NotNull Player issuer) { public void reportToUnknown(@NotNull Player issuer) {
Request request = new Request(issuer.getUniqueId(), null, ""); Request request = new Request(issuer.getUniqueId(), null, "");
@ -52,7 +56,7 @@ public class Report extends Appliance {
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(targetUsername); OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(targetUsername);
if(issuer.getUniqueId().equals(offlinePlayer.getUniqueId())) { if(issuer.getUniqueId().equals(offlinePlayer.getUniqueId())) {
issuer.sendMessage( issuer.sendMessage(
Component.text("Du kannst dich nicht selbst reporten.").color(NamedTextColor.RED) Component.text("Du kannst dich nicht selbst reporten.").color(NamedTextColor.RED)
); );
return; return;
} }
@ -65,60 +69,60 @@ public class Report extends Appliance {
try { try {
HttpClient client = HttpClient.newHttpClient(); HttpClient client = HttpClient.newHttpClient();
HttpRequest httpRequest = HttpRequest.newBuilder() HttpRequest httpRequest = HttpRequest.newBuilder()
.uri(this.apiEndpoint) .uri(this.apiEndpoint)
.header("Content-Type", "application/json") .header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(new Gson().toJson(reportRequest))) .POST(HttpRequest.BodyPublishers.ofString(new Gson().toJson(reportRequest)))
.build(); .build();
HttpResponse<String> httpResponse = client.send(httpRequest, HttpResponse.BodyHandlers.ofString()); HttpResponse<String> httpResponse = client.send(httpRequest, HttpResponse.BodyHandlers.ofString());
this.printResultMessage(issuer, httpResponse); this.printResultMessage(issuer, httpResponse);
} catch (IOException | InterruptedException e) { } catch(IOException | InterruptedException e) {
issuer.sendMessage( issuer.sendMessage(
Component.text("Internal server description: " + e.getMessage()).color(NamedTextColor.RED) Component.text("Internal server description: " + e.getMessage()).color(NamedTextColor.RED)
); );
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
private void printResultMessage(Player issuer, HttpResponse<String> httpResponse) { private void printResultMessage(Player issuer, HttpResponse<String> httpResponse) {
switch (httpResponse.statusCode()) { switch(httpResponse.statusCode()) {
case 201: case 201:
Response response = new Gson().fromJson(httpResponse.body(), Response.class); Response response = new Gson().fromJson(httpResponse.body(), Response.class);
issuer.sendMessage( issuer.sendMessage(
Component.text() Component.text()
.append(Component.text("\\/".repeat(20), NamedTextColor.DARK_GRAY)) .append(Component.text("\\/".repeat(20), NamedTextColor.DARK_GRAY))
.appendNewline() .appendNewline()
.appendNewline() .appendNewline()
.append(Component.text("!!! Report hier fertigstellen !!!", NamedTextColor.GOLD)) .append(Component.text("!!! Report hier fertigstellen !!!", NamedTextColor.GOLD))
.appendNewline() .appendNewline()
.appendNewline() .appendNewline()
.append( .append(
Component Component
.text(" > Hier klicken < ", NamedTextColor.GREEN) .text(" > Hier klicken < ", NamedTextColor.GREEN)
.hoverEvent(HoverEvent.showText(Component.text(response.url).color(NamedTextColor.GREEN))) .hoverEvent(HoverEvent.showText(Component.text(response.url).color(NamedTextColor.GREEN)))
.clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, response.url)) .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, response.url))
) )
.appendNewline() .appendNewline()
.appendNewline() .appendNewline()
.append( .append(
Component Component
.text(response.url, NamedTextColor.GRAY) .text(response.url, NamedTextColor.GRAY)
.clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, response.url)) .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, response.url))
) )
.appendNewline() .appendNewline()
.appendNewline() .appendNewline()
.append(Component.text("/\\".repeat(20), NamedTextColor.DARK_GRAY)) .append(Component.text("/\\".repeat(20), NamedTextColor.DARK_GRAY))
); );
break; break;
case 400: case 400:
issuer.sendMessage( issuer.sendMessage(
Component.text() Component.text()
.append(Component.text("Der angegebene Nutzer ist in unserem System nicht bekannt.", NamedTextColor.RED)) .append(Component.text("Der angegebene Nutzer ist in unserem System nicht bekannt.", NamedTextColor.RED))
.appendNewline() .appendNewline()
.append(Component.text("Bist du sicher, dass du den Namen richtig geschrieben hast?", NamedTextColor.RED)) .append(Component.text("Bist du sicher, dass du den Namen richtig geschrieben hast?", NamedTextColor.RED))
.appendNewline() .appendNewline()
.append(Component.text("Du kannst dich alternativ jederzeit bei einem Admin melden.", NamedTextColor.GRAY)) .append(Component.text("Du kannst dich alternativ jederzeit bei einem Admin melden.", NamedTextColor.GRAY))
); );
break; break;
@ -126,10 +130,10 @@ public class Report extends Appliance {
default: default:
Bukkit.getLogger().warning("Failed to request Report: " + httpResponse.statusCode()); Bukkit.getLogger().warning("Failed to request Report: " + httpResponse.statusCode());
issuer.sendMessage( issuer.sendMessage(
Component.text() Component.text()
.append(Component.text("Interner Serverfehler beim anlegen des Reports.", NamedTextColor.RED)) .append(Component.text("Interner Serverfehler beim anlegen des Reports.", NamedTextColor.RED))
.appendNewline() .appendNewline()
.append(Component.text("Bitte melde dich bei einem Admin!", NamedTextColor.RED)) .append(Component.text("Bitte melde dich bei einem Admin!", NamedTextColor.RED))
); );
break; break;
} }

View File

@ -1,7 +1,6 @@
package eu.mhsl.craftattack.spawn.appliances.report; package eu.mhsl.craftattack.spawn.appliances.report;
import eu.mhsl.craftattack.spawn.appliance.ApplianceCommand; import eu.mhsl.craftattack.spawn.appliance.ApplianceCommand;
import eu.mhsl.craftattack.spawn.appliances.report.Report;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -26,11 +25,11 @@ public class ReportCommand extends ApplianceCommand.PlayerChecked<Report> {
@Override @Override
protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { protected void execute(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
sender.sendMessage( sender.sendMessage(
Component.newline() Component.newline()
.append(Component.text("Reportanfrage wird erstellt...", NamedTextColor.GREEN)) .append(Component.text("Reportanfrage wird erstellt...", NamedTextColor.GREEN))
.appendNewline() .appendNewline()
.append(Component.text("Bitte warte einen Augenblick", NamedTextColor.GRAY)) .append(Component.text("Bitte warte einen Augenblick", NamedTextColor.GRAY))
.appendNewline() .appendNewline()
); );
if(args.length == 0) { if(args.length == 0) {
@ -52,19 +51,19 @@ public class ReportCommand extends ApplianceCommand.PlayerChecked<Report> {
if(args.length == 1) { if(args.length == 1) {
response = Stream.concat( response = Stream.concat(
Bukkit.getOnlinePlayers().stream().map(Player::getName), Bukkit.getOnlinePlayers().stream().map(Player::getName),
Arrays.stream(Bukkit.getOfflinePlayers()).map(OfflinePlayer::getName) Arrays.stream(Bukkit.getOfflinePlayers()).map(OfflinePlayer::getName)
).toList(); ).toList();
} }
if(args.length == 2) { if(args.length == 2) {
response = List.of( response = List.of(
"Griefing", "Griefing",
"Diebstahl", "Diebstahl",
"Beleidigung", "Beleidigung",
"Hacking", "Hacking",
"Andere Regelverstöße", "Andere Regelverstöße",
" " " "
); );
} }

View File

@ -4,9 +4,9 @@ import eu.mhsl.craftattack.spawn.appliance.Appliance;
import eu.mhsl.craftattack.spawn.appliance.ApplianceCommand; import eu.mhsl.craftattack.spawn.appliance.ApplianceCommand;
import eu.mhsl.craftattack.spawn.appliances.restart.command.CancelRestartCommand; import eu.mhsl.craftattack.spawn.appliances.restart.command.CancelRestartCommand;
import eu.mhsl.craftattack.spawn.appliances.restart.command.ScheduleRestartCommand; import eu.mhsl.craftattack.spawn.appliances.restart.command.ScheduleRestartCommand;
import eu.mhsl.craftattack.spawn.util.IteratorUtil;
import eu.mhsl.craftattack.spawn.util.text.Countdown; import eu.mhsl.craftattack.spawn.util.text.Countdown;
import eu.mhsl.craftattack.spawn.util.text.DisconnectInfo; import eu.mhsl.craftattack.spawn.util.text.DisconnectInfo;
import eu.mhsl.craftattack.spawn.util.IteratorUtil;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -24,7 +24,7 @@ public class Restart extends Appliance {
public void scheduleRestart() { public void scheduleRestart() {
try { try {
this.countdown.start(); this.countdown.start();
} catch (IllegalStateException e) { } catch(IllegalStateException e) {
throw new ApplianceCommand.Error(e.getMessage()); throw new ApplianceCommand.Error(e.getMessage());
} }
} }
@ -33,17 +33,17 @@ public class Restart extends Appliance {
try { try {
this.countdown.cancel(); this.countdown.cancel();
this.announce(Component.text("Der geplante Serverneustart wurde abgebrochen!", NamedTextColor.RED)); this.announce(Component.text("Der geplante Serverneustart wurde abgebrochen!", NamedTextColor.RED));
} catch (IllegalStateException e) { } catch(IllegalStateException e) {
throw new ApplianceCommand.Error(e.getMessage()); throw new ApplianceCommand.Error(e.getMessage());
} }
} }
private Component format(Countdown.AnnouncementData data) { private Component format(Countdown.AnnouncementData data) {
return Component.text() return Component.text()
.append(Component.text("Serverneustart in ", NamedTextColor.DARK_RED)) .append(Component.text("Serverneustart in ", NamedTextColor.DARK_RED))
.append(Component.text(data.count(), NamedTextColor.RED)) .append(Component.text(data.count(), NamedTextColor.RED))
.append(Component.text(" " + data.unit() + "!", NamedTextColor.DARK_RED)) .append(Component.text(" " + data.unit() + "!", NamedTextColor.DARK_RED))
.build(); .build();
} }
private void announce(Component message) { private void announce(Component message) {

View File

@ -26,14 +26,16 @@ public class Settings extends Appliance {
return Main.instance().getAppliance(Settings.class); return Main.instance().getAppliance(Settings.class);
} }
public record OpenSettingsInventory(Inventory inventory, List<Setting<?>> settings) {} public record OpenSettingsInventory(Inventory inventory, List<Setting<?>> settings) {
}
private final WeakHashMap<Player, OpenSettingsInventory> openSettingsInventories = new WeakHashMap<>(); private final WeakHashMap<Player, OpenSettingsInventory> openSettingsInventories = new WeakHashMap<>();
private final WeakHashMap<Player, List<Setting<?>>> settingsCache = new WeakHashMap<>(); private final WeakHashMap<Player, List<Setting<?>>> settingsCache = new WeakHashMap<>();
private List<Setting<?>> getSettings(Player player) { private List<Setting<?>> getSettings(Player player) {
if(settingsCache.containsKey(player)) return settingsCache.get(player); if(settingsCache.containsKey(player)) return settingsCache.get(player);
List<Setting<?>> settings = List.of( List<Setting<?>> settings = List.of(
new TechnicalTablistSetting(), new TechnicalTablistSetting(),
new ShowJoinAndLeaveMessagesSetting() new ShowJoinAndLeaveMessagesSetting()
); );
@ -45,12 +47,14 @@ public class Settings extends Appliance {
public <T> T getSetting(Player player, Key key, Class<T> clazz) { public <T> T getSetting(Player player, Key key, Class<T> clazz) {
Setting<?> setting = getSettings(player).stream() Setting<?> setting = getSettings(player).stream()
.filter(s -> s.getKey().equals(key)) .filter(s -> s.getKey().equals(key))
.findFirst() .findFirst()
.orElseThrow(); .orElseThrow();
if(!clazz.equals(setting.dataType())) throw new IllegalStateException("Tried to retrieve Setting with Datatype " + clazz.getSimpleName() + " but expected " + setting.dataType().getSimpleName()); if(!clazz.equals(setting.dataType()))
if(!clazz.isInstance(setting.state())) throw new ClassCastException(clazz.getSimpleName() + " is not an instance of " + setting.dataType().getSimpleName()); throw new IllegalStateException("Tried to retrieve Setting with Datatype " + clazz.getSimpleName() + " but expected " + setting.dataType().getSimpleName());
if(!clazz.isInstance(setting.state()))
throw new ClassCastException(clazz.getSimpleName() + " is not an instance of " + setting.dataType().getSimpleName());
return clazz.cast(setting.state()); return clazz.cast(setting.state());
} }

View File

@ -47,8 +47,8 @@ public abstract class Setting<TDataType> {
protected List<TextComponent> buildDescription(String description) { protected List<TextComponent> buildDescription(String description) {
return ComponentUtil.lineBreak(description, 50) return ComponentUtil.lineBreak(description, 50)
.map(s -> Component.text(s, NamedTextColor.GRAY)) .map(s -> Component.text(s, NamedTextColor.GRAY))
.toList(); .toList();
} }
protected abstract Material icon(); protected abstract Material icon();

View File

@ -4,9 +4,9 @@ import eu.mhsl.craftattack.spawn.Main;
import eu.mhsl.craftattack.spawn.appliance.Appliance; import eu.mhsl.craftattack.spawn.appliance.Appliance;
import eu.mhsl.craftattack.spawn.appliances.report.Report; import eu.mhsl.craftattack.spawn.appliances.report.Report;
import eu.mhsl.craftattack.spawn.appliances.settings.Settings; import eu.mhsl.craftattack.spawn.appliances.settings.Settings;
import eu.mhsl.craftattack.spawn.util.IteratorUtil;
import eu.mhsl.craftattack.spawn.util.statistics.NetworkMonitor; import eu.mhsl.craftattack.spawn.util.statistics.NetworkMonitor;
import eu.mhsl.craftattack.spawn.util.text.ComponentUtil; import eu.mhsl.craftattack.spawn.util.text.ComponentUtil;
import eu.mhsl.craftattack.spawn.util.IteratorUtil;
import eu.mhsl.craftattack.spawn.util.text.RainbowComponent; import eu.mhsl.craftattack.spawn.util.text.RainbowComponent;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.NamedTextColor;
@ -53,17 +53,17 @@ public class Tablist extends Appliance {
private void updateHeader(Player player) { private void updateHeader(Player player) {
boolean detailedInfo = queryAppliance(Settings.class).getSetting(player, Settings.Key.TechnicalTab, Boolean.class); boolean detailedInfo = queryAppliance(Settings.class).getSetting(player, Settings.Key.TechnicalTab, Boolean.class);
Component header = Component.newline() Component header = Component.newline()
.append(serverName.getRainbowState()).appendNewline() .append(serverName.getRainbowState()).appendNewline()
.append(Component.text("mhsl.eu", NamedTextColor.GOLD)).appendNewline().appendNewline() .append(Component.text("mhsl.eu", NamedTextColor.GOLD)).appendNewline().appendNewline()
.append(ComponentUtil.getFormattedTickTimes(detailedInfo)).appendNewline(); .append(ComponentUtil.getFormattedTickTimes(detailedInfo)).appendNewline();
if(detailedInfo) { if(detailedInfo) {
header = header header = header
.appendNewline() .appendNewline()
.append(ComponentUtil.getFormattedPing(player)).appendNewline() .append(ComponentUtil.getFormattedPing(player)).appendNewline()
.append(ComponentUtil.getFormattedNetworkStats( .append(ComponentUtil.getFormattedNetworkStats(
this.networkMonitor.getTraffic(), this.networkMonitor.getTraffic(),
this.networkMonitor.getPackets()) this.networkMonitor.getPackets())
).appendNewline(); ).appendNewline();
} }

View File

@ -11,6 +11,7 @@ public class TitleClear extends Appliance {
public void clearTitle(Player player) { public void clearTitle(Player player) {
player.clearTitle(); player.clearTitle();
} }
@Override @Override
@NotNull @NotNull
protected List<Listener> eventHandlers() { protected List<Listener> eventHandlers() {

View File

@ -10,10 +10,10 @@ public class PlayerJoinListener extends ApplianceListener<Whitelist> {
public void preLoginEvent(PlayerLoginEvent preLoginEvent) { public void preLoginEvent(PlayerLoginEvent preLoginEvent) {
try { try {
getAppliance().integrityCheck(preLoginEvent.getPlayer()); getAppliance().integrityCheck(preLoginEvent.getPlayer());
} catch (DisconnectInfo.Throwable e) { } catch(DisconnectInfo.Throwable e) {
preLoginEvent.disallow( preLoginEvent.disallow(
PlayerLoginEvent.Result.KICK_WHITELIST, PlayerLoginEvent.Result.KICK_WHITELIST,
e.getDisconnectScreen().getComponent() e.getDisconnectScreen().getComponent()
); );
} }
} }

View File

@ -23,11 +23,16 @@ import java.time.Instant;
import java.time.ZoneOffset; import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit; import java.time.temporal.ChronoUnit;
import java.util.*; import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
public class Whitelist extends Appliance { public class Whitelist extends Appliance {
private record UserData(UUID uuid, String username, String firstname, String lastname, Long banned_until, Long outlawed_until) {} private record UserData(UUID uuid, String username, String firstname, String lastname, Long banned_until,
Long outlawed_until) {
}
private final URI apiEndpoint = URI.create(Objects.requireNonNull(localConfig().getString("api"))); private final URI apiEndpoint = URI.create(Objects.requireNonNull(localConfig().getString("api")));
@ -42,17 +47,17 @@ public class Whitelist extends Appliance {
if(timestampRelevant(user.banned_until)) { if(timestampRelevant(user.banned_until)) {
Instant bannedDate = new Date(user.banned_until * 1000L) Instant bannedDate = new Date(user.banned_until * 1000L)
.toInstant() .toInstant()
.plus(1, ChronoUnit.HOURS); .plus(1, ChronoUnit.HOURS);
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd.MM.yyyy").withZone(ZoneOffset.UTC); DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd.MM.yyyy").withZone(ZoneOffset.UTC);
DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("HH:mm").withZone(ZoneOffset.UTC); DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("HH:mm").withZone(ZoneOffset.UTC);
throw new DisconnectInfo.Throwable( throw new DisconnectInfo.Throwable(
"Du wurdest vom Server gebannt.", "Du wurdest vom Server gebannt.",
String.format("Dein Bann läuft am %s um %s ab!", dateFormat.format(bannedDate), timeFormat.format(bannedDate)), String.format("Dein Bann läuft am %s um %s ab!", dateFormat.format(bannedDate), timeFormat.format(bannedDate)),
"Wende dich an einen Admin für weitere Informationen.", "Wende dich an einen Admin für weitere Informationen.",
player.getUniqueId() player.getUniqueId()
); );
} }
@ -67,21 +72,21 @@ public class Whitelist extends Appliance {
if(!user.username.trim().equalsIgnoreCase(purePlayerName)) if(!user.username.trim().equalsIgnoreCase(purePlayerName))
throw new DisconnectInfo.Throwable( throw new DisconnectInfo.Throwable(
"Nutzername geändert", "Nutzername geändert",
String.format("Der Name '%s' stimmt nicht mit '%s' überein.", user.username, player.getName()), String.format("Der Name '%s' stimmt nicht mit '%s' überein.", user.username, player.getName()),
"Bitte kontaktiere einen Admin, um Deine Anmeldedaten zu aktualisieren!", "Bitte kontaktiere einen Admin, um Deine Anmeldedaten zu aktualisieren!",
player.getUniqueId() player.getUniqueId()
); );
} catch (DisconnectInfo.Throwable e) { } catch(DisconnectInfo.Throwable e) {
throw e; throw e;
} catch (Exception e) { } catch(Exception e) {
Main.instance().getLogger().log(Level.SEVERE, e, e::getMessage); Main.instance().getLogger().log(Level.SEVERE, e, e::getMessage);
throw new DisconnectInfo.Throwable( throw new DisconnectInfo.Throwable(
"Interner Serverfehler", "Interner Serverfehler",
"Deine Anmeldedaten konnten nicht abgerufen/ überprüft werden.", "Deine Anmeldedaten konnten nicht abgerufen/ überprüft werden.",
"Versuche es später erneut oder kontaktiere einen Admin!", "Versuche es später erneut oder kontaktiere einen Admin!",
player.getUniqueId() player.getUniqueId()
); );
} }
} }
@ -98,38 +103,39 @@ public class Whitelist extends Appliance {
try { try {
HttpClient client = HttpClient.newHttpClient(); HttpClient client = HttpClient.newHttpClient();
HttpRequest httpRequest = HttpRequest.newBuilder() HttpRequest httpRequest = HttpRequest.newBuilder()
.uri(uriBuilder.build()) .uri(uriBuilder.build())
.header("Content-Type", "application/json") .header("Content-Type", "application/json")
.GET() .GET()
.build(); .build();
HttpResponse<String> httpResponse = client.send(httpRequest, HttpResponse.BodyHandlers.ofString()); HttpResponse<String> httpResponse = client.send(httpRequest, HttpResponse.BodyHandlers.ofString());
if(httpResponse.statusCode() == 404) if(httpResponse.statusCode() == 404)
throw new DisconnectInfo.Throwable( throw new DisconnectInfo.Throwable(
"Nicht angemeldet", "Nicht angemeldet",
"Du bist derzeit nicht als Teilnehmer des CraftAttack-Projektes registriert!", "Du bist derzeit nicht als Teilnehmer des CraftAttack-Projektes registriert!",
"Melde Dich bei einem Admin für eine nachträgliche Anmeldung.", "Melde Dich bei einem Admin für eine nachträgliche Anmeldung.",
uuid uuid
); );
return new Gson().fromJson(httpResponse.body(), UserData.class); return new Gson().fromJson(httpResponse.body(), UserData.class);
} catch (IOException | InterruptedException | URISyntaxException e) { } catch(IOException | InterruptedException | URISyntaxException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@Override @Override
public void httpApi(HttpServer.ApiBuilder apiBuilder) { public void httpApi(HttpServer.ApiBuilder apiBuilder) {
record User(UUID user) {} record User(UUID user) {
}
apiBuilder.post("update", User.class, (user, request) -> { apiBuilder.post("update", User.class, (user, request) -> {
Main.instance().getLogger().info(String.format("API Triggered Profile update for %s", user.user)); Main.instance().getLogger().info(String.format("API Triggered Profile update for %s", user.user));
Player player = Bukkit.getPlayer(user.user); Player player = Bukkit.getPlayer(user.user);
if(player != null) { if(player != null) {
try { try {
this.integrityCheck(player); this.integrityCheck(player);
} catch (DisconnectInfo.Throwable e) { } catch(DisconnectInfo.Throwable e) {
e.getDisconnectScreen().applyKick(player); e.getDisconnectScreen().applyKick(player);
} }
} }
@ -141,7 +147,7 @@ public class Whitelist extends Appliance {
@NotNull @NotNull
protected List<Listener> eventHandlers() { protected List<Listener> eventHandlers() {
return List.of( return List.of(
new PlayerJoinListener() new PlayerJoinListener()
); );
} }
} }

View File

@ -1,7 +1,6 @@
package eu.mhsl.craftattack.spawn.appliances.worldmuseum; package eu.mhsl.craftattack.spawn.appliances.worldmuseum;
import eu.mhsl.craftattack.spawn.appliance.ApplianceCommand; import eu.mhsl.craftattack.spawn.appliance.ApplianceCommand;
import eu.mhsl.craftattack.spawn.appliances.worldmuseum.WorldMuseum;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;

View File

@ -3,15 +3,16 @@ package eu.mhsl.craftattack.spawn.appliances.worldmuseum;
import eu.mhsl.craftattack.spawn.appliance.Appliance; import eu.mhsl.craftattack.spawn.appliance.Appliance;
import eu.mhsl.craftattack.spawn.appliance.ApplianceCommand; import eu.mhsl.craftattack.spawn.appliance.ApplianceCommand;
import eu.mhsl.craftattack.spawn.util.entity.DisplayVillager; import eu.mhsl.craftattack.spawn.util.entity.DisplayVillager;
import eu.mhsl.craftattack.spawn.util.server.Floodgate;
import eu.mhsl.craftattack.spawn.util.server.PluginMessage;
import eu.mhsl.craftattack.spawn.util.listener.DismissInventoryOpenFromHolder; import eu.mhsl.craftattack.spawn.util.listener.DismissInventoryOpenFromHolder;
import eu.mhsl.craftattack.spawn.util.listener.PlayerInteractAtEntityEventListener; import eu.mhsl.craftattack.spawn.util.listener.PlayerInteractAtEntityEventListener;
import eu.mhsl.craftattack.spawn.util.server.Floodgate;
import eu.mhsl.craftattack.spawn.util.server.PluginMessage;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
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.Location; import org.bukkit.Location;
import org.bukkit.entity.*; import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.geysermc.cumulus.form.SimpleForm; import org.geysermc.cumulus.form.SimpleForm;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -28,14 +29,15 @@ public class WorldMuseum extends Appliance {
@Override @Override
public void onEnable() { public void onEnable() {
this.villager = new DisplayVillager.ConfigBound( this.villager = new DisplayVillager.ConfigBound(
localConfig(), localConfig(),
villager -> { villager -> {
villager.customName(Component.text("Museum der Welten").color(NamedTextColor.GOLD)); villager.customName(Component.text("Museum der Welten").color(NamedTextColor.GOLD));
villager.setProfession(Villager.Profession.CARTOGRAPHER); villager.setProfession(Villager.Profession.CARTOGRAPHER);
villager.setVillagerType(Villager.Type.SNOW); villager.setVillagerType(Villager.Type.SNOW);
} }
); );
} }
public void updateVillagerPosition(Location location) { public void updateVillagerPosition(Location location) {
this.villager.updateLocation(location); this.villager.updateLocation(location);
} }
@ -44,11 +46,11 @@ public class WorldMuseum extends Appliance {
if(Floodgate.isBedrock(player)) { if(Floodgate.isBedrock(player)) {
Floodgate.runBedrockOnly(player, floodgatePlayer -> { Floodgate.runBedrockOnly(player, floodgatePlayer -> {
floodgatePlayer.sendForm( floodgatePlayer.sendForm(
SimpleForm.builder() SimpleForm.builder()
.title("Nicht unterstützt") .title("Nicht unterstützt")
.content("Bedrock-Spieler werden derzeit für das Weltenmuseum aus Kompatiblitätsgründen nicht zugelassen! Tut uns Leid.") .content("Bedrock-Spieler werden derzeit für das Weltenmuseum aus Kompatiblitätsgründen nicht zugelassen! Tut uns Leid.")
.button("Ok") .button("Ok")
.build() .build()
); );
}); });
return; return;
@ -68,8 +70,8 @@ public class WorldMuseum extends Appliance {
@NotNull @NotNull
protected List<Listener> eventHandlers() { protected List<Listener> eventHandlers() {
return List.of( return List.of(
new PlayerInteractAtEntityEventListener(this.villager.getUniqueId(), playerInteractAtEntityEvent -> handleVillagerInteraction(playerInteractAtEntityEvent.getPlayer())), new PlayerInteractAtEntityEventListener(this.villager.getUniqueId(), playerInteractAtEntityEvent -> handleVillagerInteraction(playerInteractAtEntityEvent.getPlayer())),
new DismissInventoryOpenFromHolder(this.villager.getUniqueId()) new DismissInventoryOpenFromHolder(this.villager.getUniqueId())
); );
} }
} }

View File

@ -10,12 +10,12 @@ public class ConfigUtil {
public static class Position { public static class Position {
public static Location paseLocation(ConfigurationSection section) { public static Location paseLocation(ConfigurationSection section) {
return new Location( return new Location(
Bukkit.getWorld(Optional.ofNullable(section.getString("world")).orElse("world")), Bukkit.getWorld(Optional.ofNullable(section.getString("world")).orElse("world")),
section.getDouble("x"), section.getDouble("x"),
section.getDouble("y"), section.getDouble("y"),
section.getDouble("z"), section.getDouble("z"),
(float) section.getDouble("yaw"), (float) section.getDouble("yaw"),
(float) section.getDouble("pitch") (float) section.getDouble("pitch")
); );
} }

View File

@ -19,7 +19,7 @@ public class Configuration {
public static void saveChanges() { public static void saveChanges() {
try { try {
cfg.save(configFile); cfg.save(configFile);
} catch (Exception e) { } catch(Exception e) {
Bukkit.getLogger().warning("Could not save configuration: " + e.getMessage()); Bukkit.getLogger().warning("Could not save configuration: " + e.getMessage());
} }
} }

View File

@ -2,7 +2,7 @@ package eu.mhsl.craftattack.spawn.util;
public class NumberUtil { public class NumberUtil {
public static double map(double oldValue, double oldMin, double oldMax, double newMin, double newMax) { public static double map(double oldValue, double oldMin, double oldMax, double newMin, double newMax) {
double out = (((oldValue - oldMin) * (newMax - newMin)) / (oldMax - oldMin)) + newMin; double out = (((oldValue - oldMin) * (newMax - newMin)) / (oldMax - oldMin)) + newMin;
if(out > newMax) out = newMax; if(out > newMax) out = newMax;
if(out < newMin) out = newMin; if(out < newMin) out = newMin;

View File

@ -23,7 +23,7 @@ public class DisplayVillager {
ChunkUtils.loadChunkAtLocation(this.location); ChunkUtils.loadChunkAtLocation(this.location);
this.villager = (Villager) this.location.getWorld().getEntity(uuid); this.villager = (Villager) this.location.getWorld().getEntity(uuid);
Objects.requireNonNull(this.villager); Objects.requireNonNull(this.villager);
} catch (NullPointerException | IllegalArgumentException e) { } catch(NullPointerException | IllegalArgumentException e) {
this.villager = getBaseVillager(); this.villager = getBaseVillager();
villagerCreator.accept(this.villager); villagerCreator.accept(this.villager);
} }
@ -51,26 +51,27 @@ public class DisplayVillager {
public static class ConfigBound { public static class ConfigBound {
private final DisplayVillager villager; private final DisplayVillager villager;
private final ConfigurationSection config; private final ConfigurationSection config;
public ConfigBound(ConfigurationSection configurationSection, Consumer<Villager> villagerCreator) { public ConfigBound(ConfigurationSection configurationSection, Consumer<Villager> villagerCreator) {
this.config = configurationSection; this.config = configurationSection;
Location location = ConfigUtil.Position.paseLocation(Objects.requireNonNull(this.config.getConfigurationSection("villagerLocation"))); Location location = ConfigUtil.Position.paseLocation(Objects.requireNonNull(this.config.getConfigurationSection("villagerLocation")));
this.villager = new DisplayVillager( this.villager = new DisplayVillager(
UUID.fromString(this.config.getString("uuid", UUID.randomUUID().toString())), UUID.fromString(this.config.getString("uuid", UUID.randomUUID().toString())),
location, location,
villager -> { villager -> {
this.config.set("uuid", villager.getUniqueId().toString()); this.config.set("uuid", villager.getUniqueId().toString());
Configuration.saveChanges(); Configuration.saveChanges();
villagerCreator.accept(villager); villagerCreator.accept(villager);
} }
); );
} }
public void updateLocation(Location location) { public void updateLocation(Location location) {
ConfigUtil.Position.writeLocation( ConfigUtil.Position.writeLocation(
Objects.requireNonNull(this.config.getConfigurationSection("villagerLocation")), Objects.requireNonNull(this.config.getConfigurationSection("villagerLocation")),
location location
); );
Configuration.saveChanges(); Configuration.saveChanges();

View File

@ -11,7 +11,7 @@ public class PlayerUtils {
for(Material material : Material.values()) { for(Material material : Material.values()) {
try { try {
player.setStatistic(statistic, material, 0); player.setStatistic(statistic, material, 0);
} catch (IllegalArgumentException e) { } catch(IllegalArgumentException e) {
break; break;
} }
} }
@ -19,14 +19,15 @@ public class PlayerUtils {
for(EntityType entityType : EntityType.values()) { for(EntityType entityType : EntityType.values()) {
try { try {
player.setStatistic(statistic, entityType, 0); player.setStatistic(statistic, entityType, 0);
} catch (IllegalArgumentException e) { } catch(IllegalArgumentException e) {
break; break;
} }
} }
try{ try {
player.setStatistic(statistic, 0); player.setStatistic(statistic, 0);
} catch (IllegalArgumentException ignored){} } catch(IllegalArgumentException ignored) {
}
} }
} }
} }

View File

@ -18,7 +18,7 @@ public class PlayerInteractAtEntityEventListener implements Listener {
@EventHandler @EventHandler
public void onInteract(PlayerInteractAtEntityEvent event) { public void onInteract(PlayerInteractAtEntityEvent event) {
if (!event.getRightClicked().getUniqueId().equals(this.interactableEntityUUID)) return; if(!event.getRightClicked().getUniqueId().equals(this.interactableEntityUUID)) return;
this.callback.accept(event); this.callback.accept(event);
} }
} }

View File

@ -8,6 +8,7 @@ import java.util.function.Consumer;
public class Floodgate { public class Floodgate {
private static final FloodgateApi instance = FloodgateApi.getInstance(); private static final FloodgateApi instance = FloodgateApi.getInstance();
public static boolean isBedrock(Player p) { public static boolean isBedrock(Player p) {
return instance.isFloodgatePlayer(p.getUniqueId()); return instance.isFloodgatePlayer(p.getUniqueId());
} }

View File

@ -37,8 +37,11 @@ public class NetworkMonitor {
); );
} }
public record Traffic(long rxBytes, long txBytes) {} public record Traffic(long rxBytes, long txBytes) {
public record Packets(long rxCount, long txCount) {} }
public record Packets(long rxCount, long txCount) {
}
public Traffic getTraffic() { public Traffic getTraffic() {
return new Traffic(rxBytesLastDuration, txBytesLastDuration); return new Traffic(rxBytesLastDuration, txBytesLastDuration);
@ -74,7 +77,7 @@ public class NetworkMonitor {
String path = String.format("/sys/class/net/%s/statistics/%s", this.iFace, statistic); String path = String.format("/sys/class/net/%s/statistics/%s", this.iFace, statistic);
String content = new String(Files.readAllBytes(Paths.get(path))); String content = new String(Files.readAllBytes(Paths.get(path)));
return Long.parseLong(content.trim()); return Long.parseLong(content.trim());
} catch (IOException e) { } catch(IOException e) {
throw new RuntimeException("Failed recieving Network statistic", e); throw new RuntimeException("Failed recieving Network statistic", e);
} }
} }

View File

@ -13,6 +13,6 @@ public class ColorUtil {
hue = Math.abs(hue - 120); hue = Math.abs(hue - 120);
} }
return TextColor.color(Color.getHSBColor(hue/360, 1f, 1f).getRGB()); return TextColor.color(Color.getHSBColor(hue / 360, 1f, 1f).getRGB());
} }
} }

View File

@ -26,15 +26,15 @@ public class ComponentUtil {
String[] words = text.split(" "); String[] words = text.split(" ");
StringBuilder line = new StringBuilder(); StringBuilder line = new StringBuilder();
for (String word : words) { for(String word : words) {
if (line.length() + word.length() + 1 > charactersPerLine) { if(line.length() + word.length() + 1 > charactersPerLine) {
lines.add(line.toString().trim()); lines.add(line.toString().trim());
line = new StringBuilder(); line = new StringBuilder();
} }
line.append(word).append(" "); line.append(word).append(" ");
} }
if (!line.isEmpty()) { if(!line.isEmpty()) {
lines.add(line.toString().trim()); lines.add(line.toString().trim());
} }
@ -65,13 +65,13 @@ public class ComponentUtil {
TextColor tpsColor3 = TextColor.color(red3, green3, 0); TextColor tpsColor3 = TextColor.color(red3, green3, 0);
return Component.text() return Component.text()
.append(Component.text("TPS 1, 5, 15m: ", NamedTextColor.GRAY)) .append(Component.text("TPS 1, 5, 15m: ", NamedTextColor.GRAY))
.append(Component.text(String.format("%.2f", tpsValues[0]), tpsColor1)) .append(Component.text(String.format("%.2f", tpsValues[0]), tpsColor1))
.append(Component.text(", ")) .append(Component.text(", "))
.append(Component.text(String.format("%.2f", tpsValues[1]), tpsColor2)) .append(Component.text(String.format("%.2f", tpsValues[1]), tpsColor2))
.append(Component.text(", ")) .append(Component.text(", "))
.append(Component.text(String.format("%.2f", tpsValues[2]), tpsColor3)) .append(Component.text(String.format("%.2f", tpsValues[2]), tpsColor3))
.build(); .build();
} }
public static Component getFormattedTickTimes(boolean detailed) { public static Component getFormattedTickTimes(boolean detailed) {
@ -86,9 +86,9 @@ public class ComponentUtil {
TextColor tpsColor = ColorUtil.mapGreenToRed(roundedTPS, 15, 20, false); TextColor tpsColor = ColorUtil.mapGreenToRed(roundedTPS, 15, 20, false);
ComponentBuilder<TextComponent, TextComponent.Builder> tickTimes = Component.text() ComponentBuilder<TextComponent, TextComponent.Builder> tickTimes = Component.text()
.append(Component.text("Serverlast: ", NamedTextColor.GRAY)) .append(Component.text("Serverlast: ", NamedTextColor.GRAY))
.append(Component.text(loadPercentage + "% ", percentageColor)) .append(Component.text(loadPercentage + "% ", percentageColor))
.appendNewline(); .appendNewline();
if(detailed) { if(detailed) {
tickTimes tickTimes
@ -105,22 +105,22 @@ public class ComponentUtil {
public static Component getFormattedPing(Player player) { public static Component getFormattedPing(Player player) {
int playerPing = player.getPing(); int playerPing = player.getPing();
int averagePing = Bukkit.getOnlinePlayers().stream() int averagePing = Bukkit.getOnlinePlayers().stream()
.map(Player::getPing).reduce(Integer::sum) .map(Player::getPing).reduce(Integer::sum)
.orElse(0) / Bukkit.getOnlinePlayers().size(); .orElse(0) / Bukkit.getOnlinePlayers().size();
return Component.text() return Component.text()
.append(Component.text("Dein Ping: ", NamedTextColor.GRAY)) .append(Component.text("Dein Ping: ", NamedTextColor.GRAY))
.append(Component.text(playerPing + "ms", ColorUtil.mapGreenToRed(playerPing, 50, 200, true))) .append(Component.text(playerPing + "ms", ColorUtil.mapGreenToRed(playerPing, 50, 200, true)))
.append(Component.text(" | ", NamedTextColor.GRAY)) .append(Component.text(" | ", NamedTextColor.GRAY))
.append(Component.text("Durschnitt: ", NamedTextColor.GRAY)) .append(Component.text("Durschnitt: ", NamedTextColor.GRAY))
.append(Component.text(averagePing + "ms", ColorUtil.mapGreenToRed(averagePing, 50, 200, true))) .append(Component.text(averagePing + "ms", ColorUtil.mapGreenToRed(averagePing, 50, 200, true)))
.build(); .build();
} }
public static Component createRainbowText(String text, int step) { public static Component createRainbowText(String text, int step) {
Component builder = Component.empty(); Component builder = Component.empty();
int hue = 0; int hue = 0;
for (char c : text.toCharArray()) { for(char c : text.toCharArray()) {
TextColor color = TextColor.color(Color.getHSBColor((float) hue / 360, 1, 1).getRGB()); TextColor color = TextColor.color(Color.getHSBColor((float) hue / 360, 1, 1).getRGB());
builder = builder.append(Component.text(c).color(color)); builder = builder.append(Component.text(c).color(color));
hue += step; hue += step;
@ -132,13 +132,13 @@ public class ComponentUtil {
public static Component getFormattedNetworkStats(NetworkMonitor.Traffic traffic, NetworkMonitor.Packets packets) { public static Component getFormattedNetworkStats(NetworkMonitor.Traffic traffic, NetworkMonitor.Packets packets) {
return Component.text() return Component.text()
.append(Component.text( .append(Component.text(
DataSizeConverter.convertBytesToHumanReadable(traffic.rxBytes()) + "" + NumberAbbreviation.abbreviateNumber(packets.rxCount()) + "pps", DataSizeConverter.convertBytesToHumanReadable(traffic.rxBytes()) + "" + NumberAbbreviation.abbreviateNumber(packets.rxCount()) + "pps",
NamedTextColor.GREEN NamedTextColor.GREEN
)) ))
.append(Component.text(" | ", NamedTextColor.GRAY)) .append(Component.text(" | ", NamedTextColor.GRAY))
.append(Component.text( .append(Component.text(
DataSizeConverter.convertBytesToHumanReadable(traffic.txBytes()) + "" + NumberAbbreviation.abbreviateNumber(packets.rxCount()) + "pps", DataSizeConverter.convertBytesToHumanReadable(traffic.txBytes()) + "" + NumberAbbreviation.abbreviateNumber(packets.rxCount()) + "pps",
NamedTextColor.RED NamedTextColor.RED
)) ))
.build(); .build();
} }

View File

@ -21,8 +21,11 @@ public class Countdown {
private final Runnable onDone; private final Runnable onDone;
public record AnnouncementData(int count, String unit) {} public record AnnouncementData(int count, String unit) {
public record CustomAnnouncements(Function<Integer, Boolean> test, Consumer<Integer> task) {} }
public record CustomAnnouncements(Function<Integer, Boolean> test, Consumer<Integer> task) {
}
public Countdown(int countdownFrom, Function<AnnouncementData, Component> announcementBuilder, Consumer<Component> announcementConsumer, Runnable onDone) { public Countdown(int countdownFrom, Function<AnnouncementData, Component> announcementBuilder, Consumer<Component> announcementConsumer, Runnable onDone) {
this.countdownFrom = countdownFrom; this.countdownFrom = countdownFrom;
@ -77,9 +80,9 @@ public class Countdown {
} }
customAnnouncements customAnnouncements
.stream() .stream()
.filter(a -> a.test.apply(current)) .filter(a -> a.test.apply(current))
.forEach(a -> a.task.accept(current)); .forEach(a -> a.task.accept(current));
this.current--; this.current--;

View File

@ -5,7 +5,7 @@ public class DataSizeConverter {
double kbits = bytes * 8.0 / 1000.0; double kbits = bytes * 8.0 / 1000.0;
double mbits = kbits / 1000.0; double mbits = kbits / 1000.0;
if (mbits >= 1) { if(mbits >= 1) {
return String.format("%.2f Mbit", mbits); return String.format("%.2f Mbit", mbits);
} else { } else {
return String.format("%.2f Kbit", kbits); return String.format("%.2f Kbit", kbits);

View File

@ -12,14 +12,15 @@ public record DisconnectInfo(String error, String description, String help, UUID
public void applyKick(Player player) { public void applyKick(Player player) {
Bukkit.getScheduler().runTask(Main.instance(), () -> player.kick(this.getComponent())); Bukkit.getScheduler().runTask(Main.instance(), () -> player.kick(this.getComponent()));
} }
public Component getComponent() { public Component getComponent() {
return Component.text() return Component.text()
.appendNewline().appendNewline() .appendNewline().appendNewline()
.append(Component.text(this.error, NamedTextColor.DARK_RED)).appendNewline() .append(Component.text(this.error, NamedTextColor.DARK_RED)).appendNewline()
.append(Component.text(this.description, NamedTextColor.RED)).appendNewline().appendNewline() .append(Component.text(this.description, NamedTextColor.RED)).appendNewline().appendNewline()
.append(Component.text(this.help, NamedTextColor.GRAY)).appendNewline().appendNewline() .append(Component.text(this.help, NamedTextColor.GRAY)).appendNewline().appendNewline()
.append(Component.text(this.user.toString(), NamedTextColor.DARK_GRAY)).appendNewline() .append(Component.text(this.user.toString(), NamedTextColor.DARK_GRAY)).appendNewline()
.build(); .build();
} }
public static class Throwable extends Exception { public static class Throwable extends Exception {

View File

@ -3,9 +3,9 @@ package eu.mhsl.craftattack.spawn.util.text;
public class NumberAbbreviation { public class NumberAbbreviation {
public static <T extends Number & Comparable<T>> String abbreviateNumber(T number) { public static <T extends Number & Comparable<T>> String abbreviateNumber(T number) {
double value = number.doubleValue(); double value = number.doubleValue();
if (value >= 1_000_000) { if(value >= 1_000_000) {
return String.format("%.1fM", value / 1_000_000.0); return String.format("%.1fM", value / 1_000_000.0);
} else if (value >= 1_000) { } else if(value >= 1_000) {
return String.format("%.1fk", value / 1_000.0); return String.format("%.1fk", value / 1_000.0);
} else { } else {
return number.toString(); return number.toString();

View File

@ -20,7 +20,7 @@ public class RainbowComponent {
public Component getRainbowState() { public Component getRainbowState() {
Component builder = Component.empty(); Component builder = Component.empty();
int hue = this.hueOffset; int hue = this.hueOffset;
for (char c : text.toCharArray()) { for(char c : text.toCharArray()) {
TextColor color = TextColor.color(Color.getHSBColor((float) hue / 360, 1, 1).getRGB()); TextColor color = TextColor.color(Color.getHSBColor((float) hue / 360, 1, 1).getRGB());
builder = builder.append(Component.text(c).color(color)); builder = builder.append(Component.text(c).color(color));
hue += density; hue += density;

View File

@ -4,7 +4,8 @@ import org.bukkit.Chunk;
import org.bukkit.Location; import org.bukkit.Location;
public class ChunkUtils { public class ChunkUtils {
public record ChunkPos(int x, int z) {} public record ChunkPos(int x, int z) {
}
public static Chunk loadChunkAtLocation(Location location) { public static Chunk loadChunkAtLocation(Location location) {
ChunkPos chunkPos = locationToChunk(location); ChunkPos chunkPos = locationToChunk(location);

View File

@ -27,9 +27,9 @@ commands:
help: help:
spawn: spawn:
teamspeak: teamspeak:
aliases: ["ts"] aliases: [ "ts" ]
discord: discord:
aliases: ["dc"] aliases: [ "dc" ]
setPlayerLimit: setPlayerLimit:
scheduleRestart: scheduleRestart:
cancelRestart: cancelRestart: