reformatted code

This commit is contained in:
Elias Müller 2024-12-17 13:58:41 +01:00
parent 184617e9c3
commit 63d8335b3a
120 changed files with 525 additions and 471 deletions

View File

@ -26,10 +26,10 @@ public final class Main extends JavaPlugin {
public void onEnable() { public void onEnable() {
instance = this; instance = this;
logger = instance().getLogger(); logger = instance().getLogger();
saveDefaultConfig(); this.saveDefaultConfig();
try { try {
this.wrappedEnable(); this.wrappedEnable();
} catch (Exception e) { } catch(Exception e) {
Main.logger().log(Level.SEVERE, "Error while initializing Spawn plugin, shutting down!", e); Main.logger().log(Level.SEVERE, "Error while initializing Spawn plugin, shutting down!", e);
Bukkit.shutdown(); Bukkit.shutdown();
} }
@ -52,31 +52,31 @@ public final class Main extends JavaPlugin {
.map(applianceClass -> { .map(applianceClass -> {
try { try {
return (Appliance) applianceClass.getDeclaredConstructor().newInstance(); return (Appliance) applianceClass.getDeclaredConstructor().newInstance();
} catch (Exception e) { } catch(Exception e) {
throw new RuntimeException(String.format("Failed to create instance of '%s'", applianceClass.getName()), e); throw new RuntimeException(String.format("Failed to create instance of '%s'", applianceClass.getName()), e);
} }
}) })
.toList(); .toList();
Main.logger().info(String.format("Loaded %d appliances!", appliances.size())); Main.logger().info(String.format("Loaded %d appliances!", this.appliances.size()));
Main.logger().info("Initializing appliances..."); Main.logger().info("Initializing appliances...");
this.appliances.forEach(appliance -> { this.appliances.forEach(appliance -> {
appliance.onEnable(); appliance.onEnable();
appliance.initialize(this); appliance.initialize(this);
}); });
Main.logger().info(String.format("Initialized %d appliances!", appliances.size())); Main.logger().info(String.format("Initialized %d appliances!", this.appliances.size()));
Main.logger().info("Starting HTTP API..."); Main.logger().info("Starting HTTP API...");
new HttpServer(); new HttpServer();
getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
Main.logger().info("Startup complete!"); Main.logger().info("Startup complete!");
} }
@Override @Override
public void onDisable() { public void onDisable() {
Main.logger().info("Disabling appliances..."); Main.logger().info("Disabling appliances...");
appliances.forEach(appliance -> { this.appliances.forEach(appliance -> {
Main.logger().info("Disabling " + appliance.getClass().getSimpleName()); Main.logger().info("Disabling " + appliance.getClass().getSimpleName());
appliance.onDisable(); appliance.onDisable();
appliance.destruct(this); appliance.destruct(this);
@ -84,7 +84,7 @@ public final class Main extends JavaPlugin {
HandlerList.unregisterAll(this); HandlerList.unregisterAll(this);
Bukkit.getScheduler().cancelTasks(this); Bukkit.getScheduler().cancelTasks(this);
Main.logger().info("Disabled " + appliances.size() + " appliances!"); Main.logger().info("Disabled " + this.appliances.size() + " appliances!");
} }
public <T extends Appliance> T getAppliance(Class<T> clazz) { public <T extends Appliance> T getAppliance(Class<T> clazz) {
@ -101,7 +101,7 @@ public final class Main extends JavaPlugin {
} }
public List<Appliance> getAppliances() { public List<Appliance> getAppliances() {
return appliances; return this.appliances;
} }
public RepositoryLoader getRepositoryLoader() { public RepositoryLoader getRepositoryLoader() {

View File

@ -19,17 +19,21 @@ public abstract class HttpRepository extends Repository {
public HttpRepository(URI basePath) { public HttpRepository(URI basePath) {
this(basePath, null); this(basePath, null);
} }
public HttpRepository(URI basePath, @Nullable Consumer<URIBuilder> baseUriBuilder) { public HttpRepository(URI basePath, @Nullable Consumer<URIBuilder> baseUriBuilder) {
super(basePath); super(basePath);
this.baseUriBuilder = baseUriBuilder == null this.baseUriBuilder = baseUriBuilder == null
? uriBuilder -> {} ? uriBuilder -> {
}
: baseUriBuilder; : baseUriBuilder;
} }
protected <TInput, TOutput> ReqResp<TOutput> post(String command, TInput data, Class<TOutput> outputType) { protected <TInput, TOutput> ReqResp<TOutput> post(String command, TInput data, Class<TOutput> outputType) {
return this.post(command, parameters -> {}, data, outputType); return this.post(command, parameters -> {
}, data, outputType);
} }
protected <TInput, TOutput> ReqResp<TOutput> post(String command, Consumer<URIBuilder> parameters, TInput data, Class<TOutput> outputType) { protected <TInput, TOutput> ReqResp<TOutput> post(String command, Consumer<URIBuilder> parameters, TInput data, Class<TOutput> outputType) {
HttpRequest request = this.getRequestBuilder(this.getUri(command, parameters)) HttpRequest request = this.getRequestBuilder(this.getUri(command, parameters))
.POST(HttpRequest.BodyPublishers.ofString(this.gson.toJson(data))) .POST(HttpRequest.BodyPublishers.ofString(this.gson.toJson(data)))
@ -39,8 +43,10 @@ public abstract class HttpRepository extends Repository {
} }
protected <TOutput> ReqResp<TOutput> get(String command, Class<TOutput> outputType) { protected <TOutput> ReqResp<TOutput> get(String command, Class<TOutput> outputType) {
return this.get(command, parameters -> {}, outputType); return this.get(command, parameters -> {
}, outputType);
} }
protected <TOutput> ReqResp<TOutput> get(String command, Consumer<URIBuilder> parameters, Class<TOutput> outputType) { protected <TOutput> ReqResp<TOutput> get(String command, Consumer<URIBuilder> parameters, Class<TOutput> outputType) {
HttpRequest request = this.getRequestBuilder(this.getUri(command, parameters)) HttpRequest request = this.getRequestBuilder(this.getUri(command, parameters))
.GET() .GET()
@ -55,7 +61,7 @@ public abstract class HttpRepository extends Repository {
this.baseUriBuilder.accept(builder); this.baseUriBuilder.accept(builder);
parameters.accept(builder); parameters.accept(builder);
return builder.build(); return builder.build();
} catch (URISyntaxException e) { } catch(URISyntaxException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }

View File

@ -25,7 +25,8 @@ public class RepositoryLoader {
.map(repository -> { .map(repository -> {
try { try {
return (Repository) repository.getDeclaredConstructor().newInstance(); return (Repository) repository.getDeclaredConstructor().newInstance();
} catch(InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { } catch(InstantiationException | IllegalAccessException | InvocationTargetException |
NoSuchMethodException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
}) })
@ -42,6 +43,6 @@ public class RepositoryLoader {
} }
public List<Repository> getRepositories() { public List<Repository> getRepositories() {
return repositories; return this.repositories;
} }
} }

View File

@ -15,10 +15,12 @@ public class FeedbackRepository extends HttpRepository {
super(WebsiteApiUtil.getBaseUri(), WebsiteApiUtil::withAuthorizationSecret); super(WebsiteApiUtil.getBaseUri(), WebsiteApiUtil::withAuthorizationSecret);
} }
public record Request(String event, List<UUID> users) {} public record Request(String event, List<UUID> users) {
}
public ReqResp<Map<UUID, String>> createFeedbackUrls(Request data) { public ReqResp<Map<UUID, String>> createFeedbackUrls(Request data) {
final Type responseType = new TypeToken<Map<UUID, String>>(){}.getType(); final Type responseType = new TypeToken<Map<UUID, String>>() {
}.getType();
ReqResp<Object> rawData = this.post("feedback", data, Object.class); ReqResp<Object> rawData = this.post("feedback", data, Object.class);
return new ReqResp<>(rawData.status(), this.gson.fromJson(this.gson.toJson(rawData.data()), responseType)); return new ReqResp<>(rawData.status(), this.gson.fromJson(this.gson.toJson(rawData.data()), responseType));
} }

View File

@ -73,8 +73,8 @@ public abstract class Appliance {
*/ */
@NotNull @NotNull
public ConfigurationSection localConfig() { public ConfigurationSection localConfig() {
return Optional.ofNullable(Configuration.cfg.getConfigurationSection(localConfigPath)) return Optional.ofNullable(Configuration.cfg.getConfigurationSection(this.localConfigPath))
.orElseGet(() -> Configuration.cfg.createSection(localConfigPath)); .orElseGet(() -> Configuration.cfg.createSection(this.localConfigPath));
} }
public void onEnable() { public void onEnable() {
@ -84,15 +84,15 @@ public abstract class Appliance {
} }
public void initialize(@NotNull JavaPlugin plugin) { public void initialize(@NotNull JavaPlugin plugin) {
this.listeners = listeners(); this.listeners = this.listeners();
this.commands = commands(); this.commands = this.commands();
listeners.forEach(listener -> Bukkit.getPluginManager().registerEvents(listener, plugin)); this.listeners.forEach(listener -> Bukkit.getPluginManager().registerEvents(listener, plugin));
commands.forEach(command -> setCommandExecutor(plugin, command.commandName, command)); this.commands.forEach(command -> this.setCommandExecutor(plugin, command.commandName, command));
} }
public void destruct(@NotNull JavaPlugin plugin) { public void destruct(@NotNull JavaPlugin plugin) {
listeners.forEach(HandlerList::unregisterAll); this.listeners.forEach(HandlerList::unregisterAll);
} }
protected <T extends Appliance> T queryAppliance(Class<T> clazz) { protected <T extends Appliance> T queryAppliance(Class<T> clazz) {
@ -115,10 +115,10 @@ public abstract class Appliance {
} }
public List<Listener> getListeners() { public List<Listener> getListeners() {
return listeners; return this.listeners;
} }
public List<ApplianceCommand<?>> getCommands() { public List<ApplianceCommand<?>> getCommands() {
return commands; return this.commands;
} }
} }

View File

@ -33,12 +33,12 @@ public abstract class ApplianceCommand<T extends Appliance> extends CachedApplia
@Override @Override
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); this.execute(sender, command, label, args);
} catch(Error e) { } catch(Error e) {
sender.sendMessage(errorMessage.append(Component.text(e.getMessage()))); sender.sendMessage(this.errorMessage.append(Component.text(e.getMessage())));
} catch(Exception e) { } catch(Exception e) {
sender.sendMessage(errorMessage.append(Component.text("Interner Fehler"))); sender.sendMessage(this.errorMessage.append(Component.text("Interner Fehler")));
Main.logger().warning("Error executing appliance command " + commandName + ": " + e.getMessage()); Main.logger().warning("Error executing appliance command " + this.commandName + ": " + e.getMessage());
e.printStackTrace(System.err); e.printStackTrace(System.err);
return false; return false;
} }
@ -80,7 +80,7 @@ public abstract class ApplianceCommand<T extends Appliance> extends CachedApplia
@Override @Override
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) {
if(!(sender instanceof Player)) { if(!(sender instanceof Player)) {
sender.sendMessage(notPlayerMessage); sender.sendMessage(this.notPlayerMessage);
return false; return false;
} }
this.player = (Player) sender; this.player = (Player) sender;

View File

@ -6,7 +6,7 @@ public class CachedApplianceSupplier<T extends Appliance> implements IApplianceS
private final T appliance; private final T appliance;
public CachedApplianceSupplier() { public CachedApplianceSupplier() {
this.appliance = Main.instance().getAppliance(Main.getApplianceType(getClass())); this.appliance = Main.instance().getAppliance(Main.getApplianceType(this.getClass()));
} }
@Override @Override

View File

@ -11,7 +11,7 @@ import org.bukkit.Bukkit;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.*; import java.util.List;
public class AcInform extends Appliance { public class AcInform extends Appliance {
public void processCommand(@NotNull String[] args) { public void processCommand(@NotNull String[] args) {
@ -22,8 +22,8 @@ public class AcInform extends Appliance {
for(int i = 0; i < args.length; i++) { for(int i = 0; i < args.length; i++) {
if(!args[i].startsWith("--")) continue; if(!args[i].startsWith("--")) continue;
if(i == args.length-1) continue; if(i == args.length - 1) continue;
String nextArgument = args[i+1]; String nextArgument = args[i + 1];
if(nextArgument.startsWith("--")) continue; if(nextArgument.startsWith("--")) continue;
switch(args[i]) { switch(args[i]) {
@ -42,7 +42,8 @@ public class AcInform extends Appliance {
Component prefix = Component.text("# ", NamedTextColor.DARK_RED); Component prefix = Component.text("# ", NamedTextColor.DARK_RED);
NamedTextColor textColor = NamedTextColor.GRAY; NamedTextColor textColor = NamedTextColor.GRAY;
if(playerName == null || playerName.isBlank()) throw new ApplianceCommand.Error("acinform command needs a player (--playerName)"); if(playerName == null || playerName.isBlank())
throw new ApplianceCommand.Error("acinform command needs a player (--playerName)");
if(anticheatName != null && !anticheatName.isBlank()) { if(anticheatName != null && !anticheatName.isBlank()) {
component.append( component.append(
@ -66,7 +67,7 @@ public class AcInform extends Appliance {
if(checkName == null || checkName.isBlank()) { if(checkName == null || checkName.isBlank()) {
component.append(Component.text("got detected by Anticheat", textColor)); component.append(Component.text("got detected by Anticheat", textColor));
} else if(violationCount != null){ } else if(violationCount != null) {
component.append( component.append(
Component.text("failed ", textColor) Component.text("failed ", textColor)
.append(Component.text(String.format("%sx ", violationCount), NamedTextColor.WHITE)) .append(Component.text(String.format("%sx ", violationCount), NamedTextColor.WHITE))

View File

@ -14,6 +14,6 @@ public class AcInformCommand extends ApplianceCommand<AcInform> {
@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 {
if(sender instanceof Player) throw new ApplianceCommand.Error("Dieser Command ist nicht für Spieler!"); if(sender instanceof Player) throw new ApplianceCommand.Error("Dieser Command ist nicht für Spieler!");
getAppliance().processCommand(args); this.getAppliance().processCommand(args);
} }
} }

View File

@ -17,6 +17,6 @@ public class AdminChatCommand extends ApplianceCommand.PlayerChecked<AdminChat>
if(!sender.hasPermission("admin")) return; if(!sender.hasPermission("admin")) return;
String message = String.join(" ", args); String message = String.join(" ", args);
getAppliance().sendMessage(getPlayer(), message); this.getAppliance().sendMessage(this.getPlayer(), message);
} }
} }

View File

@ -10,21 +10,21 @@ import org.bukkit.event.player.PlayerMoveEvent;
public class AfkResetListener extends ApplianceListener<AfkTag> { public class AfkResetListener extends ApplianceListener<AfkTag> {
@EventHandler @EventHandler
public void onMove(PlayerMoveEvent event) { public void onMove(PlayerMoveEvent event) {
getAppliance().resetTiming(event.getPlayer()); this.getAppliance().resetTiming(event.getPlayer());
} }
@EventHandler @EventHandler
public void onInteract(PlayerInteractEvent event) { public void onInteract(PlayerInteractEvent event) {
getAppliance().resetTiming(event.getPlayer()); this.getAppliance().resetTiming(event.getPlayer());
} }
@EventHandler @EventHandler
public void onChat(AsyncChatEvent event) { public void onChat(AsyncChatEvent event) {
getAppliance().resetTiming(event.getPlayer()); this.getAppliance().resetTiming(event.getPlayer());
} }
@EventHandler @EventHandler
public void onJoin(PlayerJoinEvent event) { public void onJoin(PlayerJoinEvent event) {
getAppliance().resetTiming(event.getPlayer()); this.getAppliance().resetTiming(event.getPlayer());
} }
} }

View File

@ -13,7 +13,10 @@ import org.bukkit.event.Listener;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.*; import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
public class AfkTag extends Appliance implements DisplayName.Prefixed { public class AfkTag extends Appliance implements DisplayName.Prefixed {
private final HashMap<UUID, Long> afkTimings = new HashMap<>(); private final HashMap<UUID, Long> afkTimings = new HashMap<>();
@ -31,9 +34,9 @@ public class AfkTag extends Appliance implements DisplayName.Prefixed {
} }
public void resetTiming(Player player) { public void resetTiming(Player player) {
boolean wasAfk = isAfk(player); boolean wasAfk = this.isAfk(player);
this.afkTimings.put(player.getUniqueId(), System.currentTimeMillis()); this.afkTimings.put(player.getUniqueId(), System.currentTimeMillis());
if (wasAfk) this.updateAfkPrefix(player); if(wasAfk) this.updateAfkPrefix(player);
} }
private void checkAfkPlayers() { private void checkAfkPlayers() {
@ -58,7 +61,7 @@ public class AfkTag extends Appliance implements DisplayName.Prefixed {
@Override @Override
public @Nullable Component getNamePrefix(Player player) { public @Nullable Component getNamePrefix(Player player) {
if(isAfk(player)) return Component.text("[ᵃᶠᵏ]", NamedTextColor.GRAY) if(this.isAfk(player)) return Component.text("[ᵃᶠᵏ]", NamedTextColor.GRAY)
.hoverEvent(HoverEvent.showText(Component.text("Der Spieler ist AFK"))); .hoverEvent(HoverEvent.showText(Component.text("Der Spieler ist AFK")));
return null; return null;

View File

@ -10,6 +10,6 @@ public class OnSignEditListener extends ApplianceListener<AntiSignEdit> {
public void onEdit(PlayerOpenSignEvent event) { public void onEdit(PlayerOpenSignEvent event) {
if(event.getCause().equals(PlayerOpenSignEvent.Cause.PLACE)) return; if(event.getCause().equals(PlayerOpenSignEvent.Cause.PLACE)) return;
SignSide signSide = event.getSign().getSide(event.getSide()); SignSide signSide = event.getSign().getSide(event.getSide());
event.setCancelled(getAppliance().preventSignEdit(event.getPlayer(), signSide)); event.setCancelled(this.getAppliance().preventSignEdit(event.getPlayer(), signSide));
} }
} }

View File

@ -31,7 +31,8 @@ public class AutoShulker extends Appliance {
ShulkerBox shulkerBox = (ShulkerBox) blockStateMeta.getBlockState(); ShulkerBox shulkerBox = (ShulkerBox) blockStateMeta.getBlockState();
HashMap<Integer, ItemStack> leftOver = shulkerBox.getInventory().addItem(itemStack); HashMap<Integer, ItemStack> leftOver = shulkerBox.getInventory().addItem(itemStack);
if(leftOver.size() > 1) throw new IllegalStateException("Multiple ItemStacks cannot be processed by AutoShulker!"); if(leftOver.size() > 1)
throw new IllegalStateException("Multiple ItemStacks cannot be processed by AutoShulker!");
if(itemStack.equals(leftOver.get(0))) { if(itemStack.equals(leftOver.get(0))) {
p.sendActionBar(Component.text("Die Shulkerbox ist voll!", NamedTextColor.RED)); p.sendActionBar(Component.text("Die Shulkerbox ist voll!", NamedTextColor.RED));
return false; return false;

View File

@ -14,7 +14,7 @@ public class ItemPickupListener extends ApplianceListener<AutoShulker> {
SelectSetting.Options.Option setting = Settings.instance().getSetting(p, Settings.Key.AutoShulker, SelectSetting.Options.Option.class); SelectSetting.Options.Option setting = Settings.instance().getSetting(p, Settings.Key.AutoShulker, SelectSetting.Options.Option.class);
if(setting.is(AutoShulkerSetting.disabled)) return; if(setting.is(AutoShulkerSetting.disabled)) return;
if(setting.is(AutoShulkerSetting.notFromPlayers) && event.getItem().getThrower() != null) return; if(setting.is(AutoShulkerSetting.notFromPlayers) && event.getItem().getThrower() != null) return;
event.setCancelled(getAppliance().tryAutoShulker(p, event.getItem())); event.setCancelled(this.getAppliance().tryAutoShulker(p, event.getItem()));
} }
} }
} }

View File

@ -56,7 +56,7 @@ public class ChatMention extends Appliance {
@Override @Override
public void onEnable() { public void onEnable() {
Settings.instance().declareSetting(ChatMentionSetting.class); Settings.instance().declareSetting(ChatMentionSetting.class);
refreshPlayers(); this.refreshPlayers();
} }
@Override @Override

View File

@ -30,11 +30,11 @@ public class ChatMentionListener extends ApplianceListener<ChatMention> {
Component result = words.stream() Component result = words.stream()
.map(word -> { .map(word -> {
String wordWithoutAnnotation = word.replace("@", ""); String wordWithoutAnnotation = word.replace("@", "");
boolean isPlayer = getAppliance().getPlayerNames().contains(wordWithoutAnnotation); boolean isPlayer = this.getAppliance().getPlayerNames().contains(wordWithoutAnnotation);
if(isPlayer && config.applyMentions()) { if(isPlayer && config.applyMentions()) {
mentioned.add(wordWithoutAnnotation); mentioned.add(wordWithoutAnnotation);
Component mention = Component.text( Component mention = Component.text(
getAppliance().formatPlayer(wordWithoutAnnotation), this.getAppliance().formatPlayer(wordWithoutAnnotation),
NamedTextColor.GOLD NamedTextColor.GOLD
); );
return chatMessages.addReportActions(mention, wordWithoutAnnotation); return chatMessages.addReportActions(mention, wordWithoutAnnotation);
@ -45,12 +45,12 @@ public class ChatMentionListener extends ApplianceListener<ChatMention> {
.reduce(ComponentUtil::appendWithSpace) .reduce(ComponentUtil::appendWithSpace)
.orElseThrow(); .orElseThrow();
getAppliance().notifyPlayers(mentioned); this.getAppliance().notifyPlayers(mentioned);
event.result(result); event.result(result);
} }
@EventHandler @EventHandler
public void onJoin(PlayerJoinEvent event) { public void onJoin(PlayerJoinEvent event) {
getAppliance().refreshPlayers(); this.getAppliance().refreshPlayers();
} }
} }

View File

@ -15,7 +15,8 @@ public class ChatMentionSetting extends MultiBoolSetting<ChatMentionSetting.Chat
public record ChatMentionConfig( public record ChatMentionConfig(
@DisplayName("Spielernamen hervorheben") boolean applyMentions, @DisplayName("Spielernamen hervorheben") boolean applyMentions,
@DisplayName("Benachrichtigungston") boolean notifyOnMention @DisplayName("Benachrichtigungston") boolean notifyOnMention
) {} ) {
}
public ChatMentionSetting() { public ChatMentionSetting() {
super(Settings.Key.ChatMentions); super(Settings.Key.ChatMentions);

View File

@ -19,7 +19,7 @@ public class ChatMessages extends Appliance {
} }
public Component getReportablePlayerName(Player player) { public Component getReportablePlayerName(Player player) {
return addReportActions(player.displayName(), player.getName()); return this.addReportActions(player.displayName(), player.getName());
} }
public Component addReportActions(Component message, String username) { public Component addReportActions(Component message, String username) {

View File

@ -21,7 +21,7 @@ public class ChatMessagesListener extends ApplianceListener<ChatMessages> {
event.renderer( event.renderer(
(source, sourceDisplayName, message, viewer) -> (source, sourceDisplayName, message, viewer) ->
Component.text("") Component.text("")
.append(getAppliance().getReportablePlayerName(source)) .append(this.getAppliance().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()))
); );
@ -35,7 +35,7 @@ public class ChatMessagesListener extends ApplianceListener<ChatMessages> {
player.sendMessage( player.sendMessage(
Component Component
.text(">>> ").color(NamedTextColor.GREEN) .text(">>> ").color(NamedTextColor.GREEN)
.append(getAppliance().getReportablePlayerName(event.getPlayer())) .append(this.getAppliance().getReportablePlayerName(event.getPlayer()))
); );
}); });
} }
@ -48,7 +48,7 @@ public class ChatMessagesListener extends ApplianceListener<ChatMessages> {
player.sendMessage( player.sendMessage(
Component Component
.text("<<< ").color(NamedTextColor.RED) .text("<<< ").color(NamedTextColor.RED)
.append(getAppliance().getReportablePlayerName(event.getPlayer())) .append(this.getAppliance().getReportablePlayerName(event.getPlayer()))
); );
}); });
} }

View File

@ -25,7 +25,7 @@ public class CustomAdvancements extends Appliance {
public void grantAdvancement(String advancementName, UUID playerUUID) { public void grantAdvancement(String advancementName, UUID playerUUID) {
Player player = Bukkit.getPlayer(playerUUID); Player player = Bukkit.getPlayer(playerUUID);
if(player == null) { if(player == null) {
addPendingAdvancement(playerUUID, advancementName); this.addPendingAdvancement(playerUUID, advancementName);
return; return;
} }
@ -33,7 +33,7 @@ public class CustomAdvancements extends Appliance {
NamespacedKey namespacedKey = Objects.requireNonNull(NamespacedKey.fromString("custom_advancements:craftattack/" + advancementName), "NamespacedKey is invalid!"); NamespacedKey namespacedKey = Objects.requireNonNull(NamespacedKey.fromString("custom_advancements:craftattack/" + advancementName), "NamespacedKey is invalid!");
Advancement advancement = Objects.requireNonNull(Bukkit.getAdvancement(namespacedKey), "The advancement does not exist!"); Advancement advancement = Objects.requireNonNull(Bukkit.getAdvancement(namespacedKey), "The advancement does not exist!");
player.getAdvancementProgress(advancement).awardCriteria("criteria"); player.getAdvancementProgress(advancement).awardCriteria("criteria");
} catch (Exception e) { } catch(Exception e) {
Main.logger().info("Advancement " + advancementName + " not found! (is Custom Advancements data pack loaded?)"); Main.logger().info("Advancement " + advancementName + " not found! (is Custom Advancements data pack loaded?)");
throw e; throw e;
} }
@ -41,14 +41,14 @@ public class CustomAdvancements extends Appliance {
public void applyPendingAdvancements(Player player) { public void applyPendingAdvancements(Player player) {
if(this.pendingAdvancements.isEmpty()) return; if(this.pendingAdvancements.isEmpty()) return;
List<PendingAdvancement> grantedAdvancements = pendingAdvancements.stream() List<PendingAdvancement> grantedAdvancements = this.pendingAdvancements.stream()
.filter(pendingAdvancement -> pendingAdvancement.receiver.equals(player.getUniqueId())).toList(); .filter(pendingAdvancement -> pendingAdvancement.receiver.equals(player.getUniqueId())).toList();
this.pendingAdvancements.removeAll(grantedAdvancements); this.pendingAdvancements.removeAll(grantedAdvancements);
grantedAdvancements.forEach(pendingAdvancement -> grantAdvancement(pendingAdvancement.advancement(), player.getUniqueId())); grantedAdvancements.forEach(pendingAdvancement -> this.grantAdvancement(pendingAdvancement.advancement(), player.getUniqueId()));
} }
private void addPendingAdvancement(UUID receiver, String advancement) { private void addPendingAdvancement(UUID receiver, String advancement) {
pendingAdvancements.add(new PendingAdvancement(receiver, advancement)); this.pendingAdvancements.add(new PendingAdvancement(receiver, advancement));
} }
@Override @Override

View File

@ -8,6 +8,6 @@ import org.bukkit.event.player.PlayerJoinEvent;
public class ApplyPendingAdvancementsListener extends ApplianceListener<CustomAdvancements> { public class ApplyPendingAdvancementsListener extends ApplianceListener<CustomAdvancements> {
@EventHandler @EventHandler
public void onJoin(PlayerJoinEvent event) { public void onJoin(PlayerJoinEvent event) {
getAppliance().applyPendingAdvancements(event.getPlayer()); this.getAppliance().applyPendingAdvancements(event.getPlayer());
} }
} }

View File

@ -20,7 +20,7 @@ public class CustomAdvancementsListener extends ApplianceListener<CustomAdvancem
if(!damager.getInventory().getItemInMainHand().getType().equals(Material.AIR)) return; if(!damager.getInventory().getItemInMainHand().getType().equals(Material.AIR)) return;
if(!damaged.hasPermission("admin")) return; if(!damaged.hasPermission("admin")) return;
getAppliance().grantAdvancement(Advancements.searchTrouble, damager.getUniqueId()); this.getAppliance().grantAdvancement(Advancements.searchTrouble, damager.getUniqueId());
} }
@EventHandler @EventHandler
@ -30,12 +30,12 @@ public class CustomAdvancementsListener extends ApplianceListener<CustomAdvancem
if(!(event.getView().getPlayer() instanceof Player player)) return; if(!(event.getView().getPlayer() instanceof Player player)) return;
if(result.getType() == Material.RED_SHULKER_BOX) { if(result.getType() == Material.RED_SHULKER_BOX) {
getAppliance().grantAdvancement(Advancements.fleischerchest, player.getUniqueId()); this.getAppliance().grantAdvancement(Advancements.fleischerchest, player.getUniqueId());
return; return;
} }
if(result.getItemMeta().itemName().equals(Component.text("98fdf0ae-c3ab-4ef7-ae25-efd518d600de"))) { if(result.getItemMeta().itemName().equals(Component.text("98fdf0ae-c3ab-4ef7-ae25-efd518d600de"))) {
getAppliance().grantAdvancement(Advancements.craftPixelblock, player.getUniqueId()); this.getAppliance().grantAdvancement(Advancements.craftPixelblock, player.getUniqueId());
} }
} }
@ -43,6 +43,6 @@ public class CustomAdvancementsListener extends ApplianceListener<CustomAdvancem
public void onChangeWorld(PlayerChangedWorldEvent event) { public void onChangeWorld(PlayerChangedWorldEvent event) {
if(!event.getPlayer().getWorld().getName().startsWith("plugins/PixelBlocks/worlds")) return; if(!event.getPlayer().getWorld().getName().startsWith("plugins/PixelBlocks/worlds")) return;
getAppliance().grantAdvancement(Advancements.usePixelblock, event.getPlayer().getUniqueId()); this.getAppliance().grantAdvancement(Advancements.usePixelblock, event.getPlayer().getUniqueId());
} }
} }

View File

@ -50,13 +50,13 @@ public class UserInfoCommand extends ApplianceCommand<Debug> {
.appendNewline() .appendNewline()
.append( .append(
Component Component
.text("Erster Besuch: " + formatUnixTimestamp(player.getFirstPlayed()), NamedTextColor.GRAY) .text("Erster Besuch: " + this.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: " + this.formatUnixTimestamp(player.getLastSeen()), NamedTextColor.GRAY)
.clickEvent(ClickEvent.copyToClipboard(String.valueOf(player.getLastSeen()))) .clickEvent(ClickEvent.copyToClipboard(String.valueOf(player.getLastSeen())))
) )
.appendNewline() .appendNewline()

View File

@ -27,16 +27,17 @@ import java.util.logging.Level;
public class DisplayName extends Appliance { public class DisplayName extends Appliance {
public interface Prefixed { public interface Prefixed {
@Nullable Component getNamePrefix(Player player); @Nullable
Component getNamePrefix(Player player);
} }
public void update(Player player) { public void update(Player player) {
TextColor playerColor = queryAppliance(AdminMarker.class).getPlayerColor(player); TextColor playerColor = this.queryAppliance(AdminMarker.class).getPlayerColor(player);
List<Supplier<Component>> prefixes = List.of( List<Supplier<Component>> prefixes = List.of(
() -> queryAppliance(Outlawed.class).getNamePrefix(player), () -> this.queryAppliance(Outlawed.class).getNamePrefix(player),
() -> queryAppliance(YearRank.class).getNamePrefix(player), () -> this.queryAppliance(YearRank.class).getNamePrefix(player),
() -> queryAppliance(AfkTag.class).getNamePrefix(player), () -> this.queryAppliance(AfkTag.class).getNamePrefix(player),
() -> queryAppliance(SleepTag.class).getNamePrefix(player) () -> this.queryAppliance(SleepTag.class).getNamePrefix(player)
); );
ComponentBuilder<TextComponent, TextComponent.Builder> playerName = Component.text(); ComponentBuilder<TextComponent, TextComponent.Builder> playerName = Component.text();
@ -61,7 +62,7 @@ public class DisplayName extends Appliance {
playerName.append(Component.text(player.getName(), playerColor)); playerName.append(Component.text(player.getName(), playerColor));
setGlobal(player, playerName.build()); this.setGlobal(player, playerName.build());
} }
private void setGlobal(Player player, Component component) { private void setGlobal(Player player, Component component) {

View File

@ -8,6 +8,6 @@ import org.bukkit.event.player.PlayerJoinEvent;
public class DisplayNameUpdateListener extends ApplianceListener<DisplayName> { public class DisplayNameUpdateListener extends ApplianceListener<DisplayName> {
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onJoin(PlayerJoinEvent event) { public void onJoin(PlayerJoinEvent event) {
getAppliance().update(event.getPlayer()); this.getAppliance().update(event.getPlayer());
} }
} }

View File

@ -19,9 +19,9 @@ public class DoubleDoor extends Appliance {
public void openNextDoor(Block block) { public void openNextDoor(Block block) {
BlockData clickedData = block.getBlockData(); BlockData clickedData = block.getBlockData();
if (!(clickedData instanceof Door clickedDoor)) return; if(!(clickedData instanceof Door clickedDoor)) return;
BlockFace neighborFace = getNeighborFace(clickedDoor.getFacing(), clickedDoor.getHinge()); BlockFace neighborFace = this.getNeighborFace(clickedDoor.getFacing(), clickedDoor.getHinge());
Block neighbourBlock = block.getRelative(neighborFace); Block neighbourBlock = block.getRelative(neighborFace);
BlockData neighbourData = neighbourBlock.getBlockData(); BlockData neighbourData = neighbourBlock.getBlockData();
@ -39,7 +39,8 @@ public class DoubleDoor extends Appliance {
case WEST -> (hinge == Door.Hinge.RIGHT) ? BlockFace.SOUTH : BlockFace.NORTH; case WEST -> (hinge == Door.Hinge.RIGHT) ? BlockFace.SOUTH : BlockFace.NORTH;
case SOUTH -> (hinge == Door.Hinge.RIGHT) ? BlockFace.EAST : BlockFace.WEST; case SOUTH -> (hinge == Door.Hinge.RIGHT) ? BlockFace.EAST : BlockFace.WEST;
case NORTH -> (hinge == Door.Hinge.RIGHT) ? BlockFace.WEST : BlockFace.EAST; case NORTH -> (hinge == Door.Hinge.RIGHT) ? BlockFace.WEST : BlockFace.EAST;
default -> throw new IllegalStateException(String.format("BlockFace '%s' of clicked door is not valid!", face)); default ->
throw new IllegalStateException(String.format("BlockFace '%s' of clicked door is not valid!", face));
}; };
} }

View File

@ -22,6 +22,6 @@ public class OnDoorInteractListener extends ApplianceListener<DoubleDoor> {
if(clickedBlock == null) return; if(clickedBlock == null) return;
if(clickedBlock.getType().equals(Material.IRON_DOOR)) return; if(clickedBlock.getType().equals(Material.IRON_DOOR)) return;
if(!Settings.instance().getSetting(event.getPlayer(), Settings.Key.DoubleDoors, Boolean.class)) return; if(!Settings.instance().getSetting(event.getPlayer(), Settings.Key.DoubleDoors, Boolean.class)) return;
getAppliance().openNextDoor(clickedBlock); this.getAppliance().openNextDoor(clickedBlock);
} }
} }

View File

@ -14,17 +14,17 @@ public class EndPrevent extends Appliance {
public EndPrevent() { public EndPrevent() {
super("endPrevent"); super("endPrevent");
this.endDisabled = localConfig().getBoolean(endDisabledKey); this.endDisabled = this.localConfig().getBoolean(this.endDisabledKey);
} }
public void setEndDisabled(boolean disabled) { public void setEndDisabled(boolean disabled) {
localConfig().set(endDisabledKey, disabled); this.localConfig().set(this.endDisabledKey, disabled);
Configuration.saveChanges(); Configuration.saveChanges();
this.endDisabled = disabled; this.endDisabled = disabled;
} }
public boolean isEndDisabled() { public boolean isEndDisabled() {
return endDisabled; return this.endDisabled;
} }
@Override @Override

View File

@ -20,18 +20,18 @@ public class EndPreventCommand extends ApplianceCommand<EndPrevent> {
@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 {
if(args.length == 1 && arguments.containsKey(args[0])) { if(args.length == 1 && this.arguments.containsKey(args[0])) {
getAppliance().setEndDisabled(arguments.get(args[0])); this.getAppliance().setEndDisabled(this.arguments.get(args[0]));
sender.sendMessage(Component.text("Setting updated!", NamedTextColor.GREEN)); sender.sendMessage(Component.text("Setting updated!", NamedTextColor.GREEN));
} }
sender.sendMessage(Component.text( sender.sendMessage(Component.text(
String.format("The End is %s!", getAppliance().isEndDisabled() ? "open" : "closed"), String.format("The End is %s!", this.getAppliance().isEndDisabled() ? "open" : "closed"),
NamedTextColor.GOLD NamedTextColor.GOLD
)); ));
} }
@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 arguments.keySet().stream().toList(); return this.arguments.keySet().stream().toList();
} }
} }

View File

@ -15,7 +15,7 @@ public class PreventEnderEyeUseListener extends ApplianceListener<EndPrevent> {
if(event.getItem() == null) return; if(event.getItem() == null) return;
if(!event.getItem().getType().equals(Material.ENDER_EYE)) return; if(!event.getItem().getType().equals(Material.ENDER_EYE)) return;
if(!getAppliance().isEndDisabled()) return; if(!this.getAppliance().isEndDisabled()) return;
event.setCancelled(true); event.setCancelled(true);
event.getPlayer().sendActionBar(Component.text("Das End ist noch nicht freigeschaltet!", NamedTextColor.RED)); event.getPlayer().sendActionBar(Component.text("Das End ist noch nicht freigeschaltet!", NamedTextColor.RED));

View File

@ -13,6 +13,6 @@ public class EventAdvertiseCommand extends ApplianceCommand<Event> {
@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().advertise(); this.getAppliance().advertise();
} }
} }

View File

@ -13,6 +13,6 @@ public class EventCommand extends ApplianceCommand.PlayerChecked<Event> {
@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().joinEvent(getPlayer()); this.getAppliance().joinEvent(this.getPlayer());
} }
} }

View File

@ -13,6 +13,6 @@ public class EventEndSessionCommand extends ApplianceCommand<Event> {
@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) {
getAppliance().endEvent(); this.getAppliance().endEvent();
} }
} }

View File

@ -15,7 +15,7 @@ public class EventOpenSessionCommand extends ApplianceCommand<Event> {
@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().openEvent(); this.getAppliance().openEvent();
sender.sendMessage(Component.text("Event-Server erfolgreich gestartet!", NamedTextColor.GREEN)); sender.sendMessage(Component.text("Event-Server erfolgreich gestartet!", NamedTextColor.GREEN));
} }
} }

View File

@ -13,6 +13,6 @@ public class MoveEventVillagerCommand extends ApplianceCommand.PlayerChecked<Eve
@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) {
getAppliance().villager.updateLocation(getPlayer().getLocation()); this.getAppliance().villager.updateLocation(this.getPlayer().getLocation());
} }
} }

View File

@ -8,6 +8,6 @@ import org.bukkit.event.player.PlayerJoinEvent;
public class ApplyPendingRewardsListener extends ApplianceListener<Event> { public class ApplyPendingRewardsListener extends ApplianceListener<Event> {
@EventHandler @EventHandler
public void onJoin(PlayerJoinEvent event) { public void onJoin(PlayerJoinEvent event) {
getAppliance().applyPendingRewards(event.getPlayer()); this.getAppliance().applyPendingRewards(event.getPlayer());
} }
} }

View File

@ -19,7 +19,9 @@ import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.*; import java.util.List;
import java.util.Map;
import java.util.UUID;
public class Feedback extends Appliance { public class Feedback extends Appliance {
public Feedback() { public Feedback() {

View File

@ -17,6 +17,6 @@ public class FeedbackCommand extends ApplianceCommand.PlayerChecked<Feedback> {
@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(ComponentUtil.pleaseWait()); sender.sendMessage(ComponentUtil.pleaseWait());
getAppliance().requestFeedback("self-issued-ingame", List.of(getPlayer()), null); this.getAppliance().requestFeedback("self-issued-ingame", List.of(this.getPlayer()), null);
} }
} }

View File

@ -16,6 +16,6 @@ public class RequestFeedbackCommand extends ApplianceCommand<Feedback> {
@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().requestFeedback("admin-issued-ingame", new ArrayList<>(Bukkit.getOnlinePlayers()), String.join(" ", args)); this.getAppliance().requestFeedback("admin-issued-ingame", new ArrayList<>(Bukkit.getOnlinePlayers()), String.join(" ", args));
} }
} }

View File

@ -13,6 +13,6 @@ public class FleischerchestCraftItemListener extends ApplianceListener<Fleischer
if(result == null) return; if(result == null) return;
if(result.getType() != Material.RED_SHULKER_BOX) return; if(result.getType() != Material.RED_SHULKER_BOX) return;
getAppliance().renameItem(event.getInventory().getResult()); this.getAppliance().renameItem(event.getInventory().getResult());
} }
} }

View File

@ -8,6 +8,6 @@ import org.bukkit.event.player.PlayerItemConsumeEvent;
public class OnBerryEaten extends ApplianceListener<GlowingBerries> { public class OnBerryEaten extends ApplianceListener<GlowingBerries> {
@EventHandler @EventHandler
public void onEat(PlayerItemConsumeEvent event) { public void onEat(PlayerItemConsumeEvent event) {
if(event.getItem().getType().equals(Material.GLOW_BERRIES)) getAppliance().letPlayerGlow(event.getPlayer()); if(event.getItem().getType().equals(Material.GLOW_BERRIES)) this.getAppliance().letPlayerGlow(event.getPlayer());
} }
} }

View File

@ -19,8 +19,8 @@ public class SpawnCommand 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) {
if(!getAppliance().localConfig().isString(spawnKey)) if(!this.getAppliance().localConfig().isString(spawnKey))
throw new ApplianceCommand.Error("Es wurde kein Spawnbereich hinterlegt!"); 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(this.getAppliance().localConfig().getString(spawnKey)), NamedTextColor.GOLD));
} }
} }

View File

@ -17,12 +17,12 @@ public class TeamspeakCommand 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) {
if(!getAppliance().localConfig().isString(teamspeakKey)) if(!this.getAppliance().localConfig().isString(teamspeakKey))
throw new ApplianceCommand.Error("Es wurde kein Teamspeak hinterlegt!"); 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(this.getTeamspeakIp(this.getAppliance().localConfig().getString(teamspeakKey)))
); );
} }

View File

@ -24,21 +24,21 @@ public class HotbarRefillListener extends ApplianceListener<HotbarRefill> {
if(stackInHand.getAmount() != 1) return; if(stackInHand.getAmount() != 1) return;
if(stackInHand.getType().getMaxDurability() > 0) return; if(stackInHand.getType().getMaxDurability() > 0) return;
if(!getPlayerSetting(event.getPlayer()).onBlocks()) return; if(!this.getPlayerSetting(event.getPlayer()).onBlocks()) return;
getAppliance().handleHotbarChange(event.getPlayer(), stackInHand); this.getAppliance().handleHotbarChange(event.getPlayer(), stackInHand);
} }
@EventHandler @EventHandler
public void onPlayerItemBreak(PlayerItemBreakEvent event) { public void onPlayerItemBreak(PlayerItemBreakEvent event) {
if(!getPlayerSetting(event.getPlayer()).onTools()) return; if(!this.getPlayerSetting(event.getPlayer()).onTools()) return;
getAppliance().handleHotbarChange(event.getPlayer(), event.getBrokenItem()); this.getAppliance().handleHotbarChange(event.getPlayer(), event.getBrokenItem());
} }
@EventHandler @EventHandler
public void onPlayerItemConsume(PlayerItemConsumeEvent event) { public void onPlayerItemConsume(PlayerItemConsumeEvent event) {
if(!getPlayerSetting(event.getPlayer()).onConsumable()) return; if(!this.getPlayerSetting(event.getPlayer()).onConsumable()) return;
getAppliance().handleHotbarChange(event.getPlayer(), event.getItem()); this.getAppliance().handleHotbarChange(event.getPlayer(), event.getItem());
} }
} }

View File

@ -16,7 +16,8 @@ public class HotbarRefillSetting extends MultiBoolSetting<HotbarRefillSetting.Ho
@DisplayName("Blöcke") boolean onBlocks, @DisplayName("Blöcke") boolean onBlocks,
@DisplayName("Werkzeuge") boolean onTools, @DisplayName("Werkzeuge") boolean onTools,
@DisplayName("Essen") boolean onConsumable @DisplayName("Essen") boolean onConsumable
) {} ) {
}
public HotbarRefillSetting() { public HotbarRefillSetting() {
super(Settings.Key.HotbarReplacer); super(Settings.Key.HotbarReplacer);

View File

@ -56,7 +56,9 @@ public abstract class Bar {
return Math.clamp(this.progress(), 0, 1); return Math.clamp(this.progress(), 0, 1);
} }
protected void beforeRefresh() {} protected void beforeRefresh() {
}
protected abstract Duration refresh(); protected abstract Duration refresh();
protected abstract String name(); protected abstract String name();

View File

@ -17,9 +17,9 @@ public class InfoBarCommand extends ApplianceCommand.PlayerChecked<InfoBars> {
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 {
if(args.length == 0) throw new Error("<show|hide|hideall> [bar name]"); if(args.length == 0) throw new Error("<show|hide|hideall> [bar name]");
switch(args[0]) { switch(args[0]) {
case "hideAll" -> getAppliance().hideAll(getPlayer()); case "hideAll" -> this.getAppliance().hideAll(this.getPlayer());
case "show" -> getAppliance().show(getPlayer(), args[1]); case "show" -> this.getAppliance().show(this.getPlayer(), args[1]);
case "hide" -> getAppliance().hide(getPlayer(), args[1]); case "hide" -> this.getAppliance().hide(this.getPlayer(), args[1]);
default -> throw new Error("Erlaubte Optionen sind 'show', 'hide', 'hideAll'!"); default -> throw new Error("Erlaubte Optionen sind 'show', 'hide', 'hideAll'!");
} }
} }
@ -27,6 +27,6 @@ public class InfoBarCommand extends ApplianceCommand.PlayerChecked<InfoBars> {
@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) {
if(args.length == 1) return List.of("show", "hide", "hideAll"); if(args.length == 1) return List.of("show", "hide", "hideAll");
return getAppliance().getInfoBars().stream().map(Bar::name).toList(); return this.getAppliance().getInfoBars().stream().map(Bar::name).toList();
} }
} }

View File

@ -51,32 +51,33 @@ public class InfoBars extends Appliance {
private List<String> getStoredBars(Player player) { private List<String> getStoredBars(Player player) {
PersistentDataContainer container = player.getPersistentDataContainer(); PersistentDataContainer container = player.getPersistentDataContainer();
if(!container.has(infoBarKey)) return List.of(); if(!container.has(this.infoBarKey)) return List.of();
return container.get(infoBarKey, PersistentDataType.LIST.strings()); return container.get(this.infoBarKey, PersistentDataType.LIST.strings());
} }
private void setStoredBars(Player player, List<String> bars) { private void setStoredBars(Player player, List<String> bars) {
player.getPersistentDataContainer().set(infoBarKey, PersistentDataType.LIST.strings(), bars); player.getPersistentDataContainer().set(this.infoBarKey, PersistentDataType.LIST.strings(), bars);
} }
private Bar getBarByName(String name) { private Bar getBarByName(String name) {
return infoBars.stream() return this.infoBars.stream()
.filter(bar -> bar.name().equalsIgnoreCase(name)) .filter(bar -> bar.name().equalsIgnoreCase(name))
.findFirst() .findFirst()
.orElse(null); .orElse(null);
} }
private void validateBarName(String name) { private void validateBarName(String name) {
if(getBarByName(name) == null) throw new ApplianceCommand.Error(String.format("Ungültiger infobar name '%s'", name)); if(this.getBarByName(name) == null)
throw new ApplianceCommand.Error(String.format("Ungültiger infobar name '%s'", name));
} }
public List<Bar> getInfoBars() { public List<Bar> getInfoBars() {
return infoBars; return this.infoBars;
} }
@Override @Override
public void onDisable() { public void onDisable() {
infoBars.forEach(Bar::stopUpdate); this.infoBars.forEach(Bar::stopUpdate);
} }
@Override @Override

View File

@ -7,6 +7,6 @@ import org.bukkit.event.player.PlayerJoinEvent;
public class ShowPreviousBarsListener extends ApplianceListener<InfoBars> { public class ShowPreviousBarsListener extends ApplianceListener<InfoBars> {
@EventHandler @EventHandler
public void onJoin(PlayerJoinEvent event) { public void onJoin(PlayerJoinEvent event) {
getAppliance().showAll(event.getPlayer()); this.getAppliance().showAll(event.getPlayer());
} }
} }

View File

@ -19,7 +19,7 @@ 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( this.getAppliance().kick(
args[0], args[0],
Arrays.stream(args).skip(1).collect(Collectors.joining(" ")) Arrays.stream(args).skip(1).collect(Collectors.joining(" "))
); );

View File

@ -25,7 +25,7 @@ public class KnockDoor extends Appliance {
if(setting.is(KnockDoorSetting.disabled)) return; if(setting.is(KnockDoorSetting.disabled)) return;
if(setting.is(KnockDoorSetting.knockSingleTime)) { if(setting.is(KnockDoorSetting.knockSingleTime)) {
playSound(knockedBlock); this.playSound(knockedBlock);
} }
if(setting.is(KnockDoorSetting.knockThreeTimes)) { if(setting.is(KnockDoorSetting.knockThreeTimes)) {
@ -39,10 +39,10 @@ public class KnockDoor extends Appliance {
int timesKnocked = knockingPlayer.getMetadata(metadataKey).getFirst().asInt(); int timesKnocked = knockingPlayer.getMetadata(metadataKey).getFirst().asInt();
if(timesKnocked >= 3) { if(timesKnocked >= 3) {
knockingPlayer.removeMetadata(metadataKey, Main.instance()); knockingPlayer.removeMetadata(metadataKey, Main.instance());
cancel(); this.cancel();
return; return;
} }
playSound(knockedBlock); KnockDoor.this.playSound(knockedBlock);
knockingPlayer.setMetadata(metadataKey, new FixedMetadataValue(Main.instance(), timesKnocked + 1)); knockingPlayer.setMetadata(metadataKey, new FixedMetadataValue(Main.instance(), timesKnocked + 1));
} }
}.runTaskTimer(Main.instance(), 0, 8); }.runTaskTimer(Main.instance(), 0, 8);

View File

@ -13,6 +13,6 @@ public class KnockDoorListener extends ApplianceListener<KnockDoor> {
if(event.getPlayer().getGameMode() != GameMode.SURVIVAL) return; if(event.getPlayer().getGameMode() != GameMode.SURVIVAL) return;
Block block = event.getBlock(); Block block = event.getBlock();
if(!(block.getBlockData() instanceof Door)) return; if(!(block.getBlockData() instanceof Door)) return;
getAppliance().knockAtDoor(event.getPlayer(), block); this.getAppliance().knockAtDoor(event.getPlayer(), block);
} }
} }

View File

@ -18,17 +18,17 @@ public class Maintenance extends Appliance {
@Override @Override
public void onEnable() { public void onEnable() {
this.isInMaintenance = localConfig().getBoolean(configKey, false); this.isInMaintenance = this.localConfig().getBoolean(this.configKey, false);
} }
public void setState(boolean enabled) { public void setState(boolean enabled) {
this.isInMaintenance = enabled; this.isInMaintenance = enabled;
localConfig().set(configKey, enabled); this.localConfig().set(this.configKey, enabled);
Configuration.saveChanges(); Configuration.saveChanges();
} }
public boolean isInMaintenance() { public boolean isInMaintenance() {
return isInMaintenance; return this.isInMaintenance;
} }
@Override @Override

View File

@ -20,18 +20,18 @@ public class MaintenanceCommand extends ApplianceCommand<Maintenance> {
@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 {
if(args.length == 1 && arguments.containsKey(args[0])) { if(args.length == 1 && this.arguments.containsKey(args[0])) {
getAppliance().setState(arguments.get(args[0])); this.getAppliance().setState(this.arguments.get(args[0]));
sender.sendMessage(Component.text("Maintanance mode updated!", NamedTextColor.GREEN)); sender.sendMessage(Component.text("Maintanance mode updated!", NamedTextColor.GREEN));
} }
sender.sendMessage(Component.text( sender.sendMessage(Component.text(
String.format("Maintanance mode is %b", getAppliance().isInMaintenance()), String.format("Maintanance mode is %b", this.getAppliance().isInMaintenance()),
NamedTextColor.GOLD NamedTextColor.GOLD
)); ));
} }
@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 arguments.keySet().stream().toList(); return this.arguments.keySet().stream().toList();
} }
} }

View File

@ -8,7 +8,7 @@ import org.bukkit.event.player.PlayerLoginEvent;
public class PreventMaintenanceJoinListener extends ApplianceListener<Maintenance> { public class PreventMaintenanceJoinListener extends ApplianceListener<Maintenance> {
@EventHandler @EventHandler
public void onJoin(PlayerLoginEvent event) { public void onJoin(PlayerLoginEvent event) {
if(!getAppliance().isInMaintenance()) return; if(!this.getAppliance().isInMaintenance()) return;
if(event.getPlayer().hasPermission("bypassMaintainance")) return; if(event.getPlayer().hasPermission("bypassMaintainance")) return;
DisconnectInfo disconnectInfo = new DisconnectInfo( DisconnectInfo disconnectInfo = new DisconnectInfo(

View File

@ -17,10 +17,17 @@ import java.util.logging.Level;
@SuppressWarnings("UnstableApiUsage") @SuppressWarnings("UnstableApiUsage")
public class OptionLinks extends Appliance { public class OptionLinks extends Appliance {
record ComponentSupplier() {} record ComponentSupplier() {
record UriSupplier(Player player) {} }
record UriConsumer(String uri) {}
record SuppliedLink(Function<ComponentSupplier, Component> component, Function<UriSupplier, UriConsumer> uri) {} record UriSupplier(Player player) {
}
record UriConsumer(String uri) {
}
record SuppliedLink(Function<ComponentSupplier, Component> component, Function<UriSupplier, UriConsumer> uri) {
}
List<SuppliedLink> links = List.of( List<SuppliedLink> links = List.of(
new SuppliedLink( new SuppliedLink(
@ -41,19 +48,19 @@ public class OptionLinks extends Appliance {
public void setServerLinks(Player player) { public void setServerLinks(Player player) {
ServerLinks playerLinks = Bukkit.getServerLinks().copy(); ServerLinks playerLinks = Bukkit.getServerLinks().copy();
Bukkit.getScheduler().runTaskAsynchronously(Main.instance(), () -> { Bukkit.getScheduler().runTaskAsynchronously(Main.instance(), () -> {
this.links.forEach(suppliedLink -> { this.links.forEach(suppliedLink -> {
Component component = suppliedLink.component.apply(new ComponentSupplier()); Component component = suppliedLink.component.apply(new ComponentSupplier());
String uri = suppliedLink.uri.apply(new UriSupplier(player)).uri; String uri = suppliedLink.uri.apply(new UriSupplier(player)).uri;
try { try {
playerLinks.addLink(component, URI.create(uri)); playerLinks.addLink(component, URI.create(uri));
} catch(IllegalArgumentException e) { } catch(IllegalArgumentException e) {
Main.logger().log(Level.INFO, String.format("Failed to create OptionLink '%s' for player '%s'", uri, player.getName()), e); Main.logger().log(Level.INFO, String.format("Failed to create OptionLink '%s' for player '%s'", uri, player.getName()), e);
} }
}); });
player.sendLinks(playerLinks); player.sendLinks(playerLinks);
}); });
} }
@Override @Override

View File

@ -7,6 +7,6 @@ import org.bukkit.event.player.PlayerJoinEvent;
public class UpdateLinksListener extends ApplianceListener<OptionLinks> { public class UpdateLinksListener extends ApplianceListener<OptionLinks> {
@EventHandler @EventHandler
public void onJoin(PlayerJoinEvent event) { public void onJoin(PlayerJoinEvent event) {
getAppliance().setServerLinks(event.getPlayer()); this.getAppliance().setServerLinks(event.getPlayer());
} }
} }

View File

@ -34,11 +34,11 @@ public class Outlawed extends Appliance implements DisplayName.Prefixed {
super("outlawed"); super("outlawed");
Bukkit.getScheduler().runTaskTimerAsynchronously( Bukkit.getScheduler().runTaskTimerAsynchronously(
Main.instance(), Main.instance(),
() -> playerStatusMap.forEach((player, status) -> { () -> this.playerStatusMap.forEach((player, status) -> {
if(!player.isOnline()) return; if(!player.isOnline()) return;
if(status != Status.FORCED) return; if(status != Status.FORCED) return;
try { try {
queryAppliance(Whitelist.class).integrityCheck(player); this.queryAppliance(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));
} }
@ -49,55 +49,55 @@ public class Outlawed extends Appliance implements DisplayName.Prefixed {
} }
public void switchLawStatus(Player player) throws OutlawChangeNotPermitted { public void switchLawStatus(Player player) throws OutlawChangeNotPermitted {
if(getLawStatus(player).equals(Status.FORCED)) { if(this.getLawStatus(player).equals(Status.FORCED)) {
throw new OutlawChangeNotPermitted("Dein Vogelfreistatus wurde als Strafe auferlegt und kann daher nicht verändert werden."); throw new OutlawChangeNotPermitted("Dein Vogelfreistatus wurde als Strafe auferlegt und kann daher nicht verändert werden.");
} }
if(isTimeout(player)) { if(this.isTimeout(player)) {
throw new OutlawChangeNotPermitted("Du kannst deinen Vogelfreistatus nicht so schnell wechseln. Bitte warte einige Stunden bevor du umschaltest!"); throw new OutlawChangeNotPermitted("Du kannst deinen Vogelfreistatus nicht so schnell wechseln. Bitte warte einige Stunden bevor du umschaltest!");
} }
setLawStatus(player, isOutlawed(player) ? Status.DISABLED : Status.VOLUNTARILY); this.setLawStatus(player, this.isOutlawed(player) ? Status.DISABLED : Status.VOLUNTARILY);
setTimeout(player); this.setTimeout(player);
} }
public void updateForcedStatus(Player player, boolean forced) { public void updateForcedStatus(Player player, boolean forced) {
setLawStatus(player, forced ? Status.FORCED : getLawStatus(player) == Status.FORCED ? Status.DISABLED : getLawStatus(player)); this.setLawStatus(player, forced ? Status.FORCED : this.getLawStatus(player) == Status.FORCED ? Status.DISABLED : this.getLawStatus(player));
} }
public Status getLawStatus(Player player) { public Status getLawStatus(Player player) {
return playerStatusMap.computeIfAbsent(player, p -> { return this.playerStatusMap.computeIfAbsent(player, p -> {
if(localConfig().getStringList(voluntarilyEntry).contains(p.getUniqueId().toString())) if(this.localConfig().getStringList(this.voluntarilyEntry).contains(p.getUniqueId().toString()))
return Status.VOLUNTARILY; return Status.VOLUNTARILY;
return Status.DISABLED; return Status.DISABLED;
}); });
} }
private void setLawStatus(Player player, Status status) { private void setLawStatus(Player player, Status status) {
playerStatusMap.put(player, status); this.playerStatusMap.put(player, status);
queryAppliance(DisplayName.class).update(player); this.queryAppliance(DisplayName.class).update(player);
List<String> newList = localConfig().getStringList(voluntarilyEntry); List<String> newList = this.localConfig().getStringList(this.voluntarilyEntry);
if(status.equals(Status.VOLUNTARILY)) { if(status.equals(Status.VOLUNTARILY)) {
newList.add(player.getUniqueId().toString()); newList.add(player.getUniqueId().toString());
} else { } else {
newList.remove(player.getUniqueId().toString()); newList.remove(player.getUniqueId().toString());
} }
localConfig().set(voluntarilyEntry, newList.stream().distinct().toList()); this.localConfig().set(this.voluntarilyEntry, newList.stream().distinct().toList());
Configuration.saveChanges(); Configuration.saveChanges();
} }
public boolean isOutlawed(Player player) { public boolean isOutlawed(Player player) {
return getLawStatus(player) != Status.DISABLED; return this.getLawStatus(player) != Status.DISABLED;
} }
private boolean isTimeout(Player player) { private boolean isTimeout(Player player) {
return timeouts.getOrDefault(player.getUniqueId(), 0L) > System.currentTimeMillis() - timeoutInMs; return this.timeouts.getOrDefault(player.getUniqueId(), 0L) > System.currentTimeMillis() - this.timeoutInMs;
} }
private void setTimeout(Player player) { private void setTimeout(Player player) {
timeouts.put(player.getUniqueId(), System.currentTimeMillis()); this.timeouts.put(player.getUniqueId(), System.currentTimeMillis());
} }
public Component getStatusDescription(Status status) { public Component getStatusDescription(Status status) {
@ -112,7 +112,7 @@ public class Outlawed extends Appliance implements DisplayName.Prefixed {
@Override @Override
public Component getNamePrefix(Player player) { public Component getNamePrefix(Player player) {
if(isOutlawed(player)) { if(this.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!")));
} }

View File

@ -15,10 +15,10 @@ public class OutlawedCommand extends ApplianceCommand.PlayerChecked<Outlawed> {
@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 {
try { try {
getAppliance().switchLawStatus(getPlayer()); this.getAppliance().switchLawStatus(this.getPlayer());
sender.sendMessage( sender.sendMessage(
getAppliance() this.getAppliance()
.getStatusDescription(getAppliance().getLawStatus(getPlayer())) .getStatusDescription(this.getAppliance().getLawStatus(this.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

@ -7,8 +7,8 @@ import org.bukkit.event.player.PlayerJoinEvent;
public class OutlawedReminderListener extends ApplianceListener<Outlawed> { public class OutlawedReminderListener extends ApplianceListener<Outlawed> {
@EventHandler @EventHandler
public void onJoin(PlayerJoinEvent e) { public void onJoin(PlayerJoinEvent e) {
if(getAppliance().isOutlawed(e.getPlayer())) { if(this.getAppliance().isOutlawed(e.getPlayer())) {
e.getPlayer().sendMessage(getAppliance().getStatusDescription(getAppliance().getLawStatus(e.getPlayer()))); e.getPlayer().sendMessage(this.getAppliance().getStatusDescription(this.getAppliance().getLawStatus(e.getPlayer())));
} }
} }
} }

View File

@ -7,12 +7,13 @@ import org.jetbrains.annotations.NotNull;
public class ChangePackCommand extends ApplianceCommand.PlayerChecked<PackSelect> { public class ChangePackCommand extends ApplianceCommand.PlayerChecked<PackSelect> {
public static final String commandName = "texturepack"; public static final String commandName = "texturepack";
public ChangePackCommand() { public ChangePackCommand() {
super(commandName); super(commandName);
} }
@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().openPackInventory(getPlayer()); this.getAppliance().openPackInventory(this.getPlayer());
} }
} }

View File

@ -1,6 +1,7 @@
package eu.mhsl.craftattack.spawn.appliances.packSelect; package eu.mhsl.craftattack.spawn.appliances.packSelect;
import com.google.gson.*; import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import eu.mhsl.craftattack.spawn.appliance.CachedApplianceSupplier; import eu.mhsl.craftattack.spawn.appliance.CachedApplianceSupplier;
import eu.mhsl.craftattack.spawn.util.inventory.HeadBuilder; import eu.mhsl.craftattack.spawn.util.inventory.HeadBuilder;
import eu.mhsl.craftattack.spawn.util.text.ComponentUtil; import eu.mhsl.craftattack.spawn.util.text.ComponentUtil;
@ -17,15 +18,15 @@ import java.util.stream.Collectors;
public class PackConfiguration extends CachedApplianceSupplier<PackSelect> { public class PackConfiguration extends CachedApplianceSupplier<PackSelect> {
public record Pack(UUID id, String name, String description, String author, ResourcePackInfo info, String icon) { public record Pack(UUID id, String name, String description, String author, ResourcePackInfo info, String icon) {
public ItemStack buildItem() { public ItemStack buildItem() {
ItemStack stack = HeadBuilder.getCustomTextureHead(icon); ItemStack stack = HeadBuilder.getCustomTextureHead(this.icon);
ItemMeta meta = stack.getItemMeta(); ItemMeta meta = stack.getItemMeta();
meta.itemName(Component.text(id.toString())); meta.itemName(Component.text(this.id.toString()));
meta.displayName(Component.text(name(), NamedTextColor.GOLD)); meta.displayName(Component.text(this.name(), NamedTextColor.GOLD));
List<Component> lore = new ArrayList<>(); List<Component> lore = new ArrayList<>();
lore.add(Component.text("Autor: ", NamedTextColor.DARK_GRAY).append(Component.text(author))); lore.add(Component.text("Autor: ", NamedTextColor.DARK_GRAY).append(Component.text(this.author)));
lore.add(Component.text(" ")); lore.add(Component.text(" "));
lore.addAll( lore.addAll(
ComponentUtil.lineBreak(description()) ComponentUtil.lineBreak(this.description())
.map(s -> Component.text(s, NamedTextColor.GRAY)) .map(s -> Component.text(s, NamedTextColor.GRAY))
.toList() .toList()
); );
@ -38,20 +39,23 @@ public class PackConfiguration extends CachedApplianceSupplier<PackSelect> {
public boolean equalsItem(ItemStack other) { public boolean equalsItem(ItemStack other) {
String itemName = PlainTextComponentSerializer.plainText().serialize(other.getItemMeta().itemName()); String itemName = PlainTextComponentSerializer.plainText().serialize(other.getItemMeta().itemName());
try { try {
return UUID.fromString(itemName).equals(id); return UUID.fromString(itemName).equals(this.id);
} catch(IllegalArgumentException ignored) { } catch(IllegalArgumentException ignored) {
return false; return false;
} }
} }
} }
public record PackList(List<Pack> packs) { public record PackList(List<Pack> packs) {
public Optional<Pack> findFromItem(ItemStack itemStack) { public Optional<Pack> findFromItem(ItemStack itemStack) {
return packs.stream() return this.packs.stream()
.filter(pack -> pack.equalsItem(itemStack)) .filter(pack -> pack.equalsItem(itemStack))
.findFirst(); .findFirst();
} }
} }
public record SerializedPackList(List<UUID> packs) {}
public record SerializedPackList(List<UUID> packs) {
}
private final PackList packList; private final PackList packList;
private final Gson gson = new GsonBuilder().create(); private final Gson gson = new GsonBuilder().create();
@ -61,9 +65,9 @@ public class PackConfiguration extends CachedApplianceSupplier<PackSelect> {
} }
private PackConfiguration(String data) { private PackConfiguration(String data) {
SerializedPackList serializedData = gson.fromJson(data, SerializedPackList.class); SerializedPackList serializedData = this.gson.fromJson(data, SerializedPackList.class);
var availablePackMap = getAppliance().availablePacks.packs().stream() var availablePackMap = this.getAppliance().availablePacks.packs().stream()
.collect(Collectors.toMap(PackConfiguration.Pack::id, pack -> pack)); .collect(Collectors.toMap(PackConfiguration.Pack::id, pack -> pack));
this.packList = new PackList( this.packList = new PackList(
@ -73,7 +77,8 @@ public class PackConfiguration extends CachedApplianceSupplier<PackSelect> {
.collect(Collectors.toList()) .collect(Collectors.toList())
); );
if (this.packList.packs().isEmpty()) throw new IllegalArgumentException("Serialized data does not contain any valid data!"); if(this.packList.packs().isEmpty())
throw new IllegalArgumentException("Serialized data does not contain any valid data!");
} }
public static PackConfiguration deserialize(String data) { public static PackConfiguration deserialize(String data) {
@ -85,10 +90,10 @@ public class PackConfiguration extends CachedApplianceSupplier<PackSelect> {
} }
public String serialize() { public String serialize() {
return gson.toJson(new SerializedPackList(this.packList.packs().stream().map(Pack::id).toList())); return this.gson.toJson(new SerializedPackList(this.packList.packs().stream().map(Pack::id).toList()));
} }
public List<Pack> getPackList() { public List<Pack> getPackList() {
return packList.packs(); return this.packList.packs();
} }
} }

View File

@ -34,8 +34,8 @@ public class PackConfigurationInventory extends CachedApplianceSupplier<PackSele
.displayName(Component.text("Texturepacks", NamedTextColor.GOLD)) .displayName(Component.text("Texturepacks", NamedTextColor.GOLD))
.lore( .lore(
"Wähle aus der oberen Liste eine oder mehrere Texturepacks aus. " + "Wähle aus der oberen Liste eine oder mehrere Texturepacks aus. " +
"Ändere die anzuwendende Reihenfolge durch Links/Rechtsklick in der unteren Liste. " + "Ändere die anzuwendende Reihenfolge durch Links/Rechtsklick in der unteren Liste. " +
"Klicke auf Speichern um die Änderungen anzuwenden!" "Klicke auf Speichern um die Änderungen anzuwenden!"
) )
.build(); .build();
@ -58,99 +58,99 @@ public class PackConfigurationInventory extends CachedApplianceSupplier<PackSele
} }
public Inventory getInventory() { public Inventory getInventory() {
return inventory; return this.inventory;
} }
public void handleClick(@Nullable ItemStack clickedItem, int slot, ClickType clickType) { public void handleClick(@Nullable ItemStack clickedItem, int slot, ClickType clickType) {
if(clickedItem == null) return; if(clickedItem == null) return;
if(clickedItem.equals(reset)) reset(); if(clickedItem.equals(this.reset)) this.reset();
if(clickedItem.equals(save)) apply(); if(clickedItem.equals(this.save)) this.apply();
if(slot >= 9 && slot < 9 * 4) { if(slot >= 9 && slot < 9 * 4) {
getAppliance().availablePacks.findFromItem(clickedItem) this.getAppliance().availablePacks.findFromItem(clickedItem)
.ifPresent(this::toggle); .ifPresent(this::toggle);
} }
if(slot >= 9 * 5) { if(slot >= 9 * 5) {
getAppliance().availablePacks.findFromItem(clickedItem) this.getAppliance().availablePacks.findFromItem(clickedItem)
.ifPresent(pack -> { .ifPresent(pack -> {
switch(clickType) { switch(clickType) {
case RIGHT -> move(pack, true); case RIGHT -> this.move(pack, true);
case LEFT -> move(pack, false); case LEFT -> this.move(pack, false);
case MIDDLE -> toggle(pack); case MIDDLE -> this.toggle(pack);
} }
}); });
} }
} }
private void move(PackConfiguration.Pack pack, boolean moveToRight) { private void move(PackConfiguration.Pack pack, boolean moveToRight) {
List<PackConfiguration.Pack> packs = packConfiguration.getPackList(); List<PackConfiguration.Pack> packs = this.packConfiguration.getPackList();
int index = packs.indexOf(pack); int index = packs.indexOf(pack);
if (index != -1) { if(index != -1) {
int newIndex = moveToRight ? index + 1 : index - 1; int newIndex = moveToRight ? index + 1 : index - 1;
if (newIndex >= 0 && newIndex < packs.size()) Collections.swap(packs, index, newIndex); if(newIndex >= 0 && newIndex < packs.size()) Collections.swap(packs, index, newIndex);
} }
InteractSounds.of(inventoryOwner).click(); InteractSounds.of(this.inventoryOwner).click();
draw(); this.draw();
} }
private void toggle(PackConfiguration.Pack pack) { private void toggle(PackConfiguration.Pack pack) {
if(packConfiguration.getPackList().contains(pack)) { if(this.packConfiguration.getPackList().contains(pack)) {
packConfiguration.getPackList().remove(pack); this.packConfiguration.getPackList().remove(pack);
} else { } else {
packConfiguration.getPackList().add(pack); this.packConfiguration.getPackList().add(pack);
} }
InteractSounds.of(inventoryOwner).click(); InteractSounds.of(this.inventoryOwner).click();
draw(); this.draw();
} }
private void reset() { private void reset() {
packConfiguration.getPackList().clear(); this.packConfiguration.getPackList().clear();
InteractSounds.of(inventoryOwner).delete(); InteractSounds.of(this.inventoryOwner).delete();
draw(); this.draw();
} }
private void apply() { private void apply() {
inventoryOwner.closeInventory(); this.inventoryOwner.closeInventory();
InteractSounds.of(inventoryOwner).success(); InteractSounds.of(this.inventoryOwner).success();
Bukkit.getScheduler().runTask(Main.instance(), () -> getAppliance().setPack(inventoryOwner, packConfiguration)); Bukkit.getScheduler().runTask(Main.instance(), () -> this.getAppliance().setPack(this.inventoryOwner, this.packConfiguration));
} }
private void draw() { private void draw() {
inventory.clear(); this.inventory.clear();
inventory.setItem(0, packConfiguration.getPackList().isEmpty() ? PlaceholderItems.grayStainedGlassPane : reset); this.inventory.setItem(0, this.packConfiguration.getPackList().isEmpty() ? PlaceholderItems.grayStainedGlassPane : this.reset);
IteratorUtil.times(3, () -> inventory.addItem(PlaceholderItems.grayStainedGlassPane)); IteratorUtil.times(3, () -> this.inventory.addItem(PlaceholderItems.grayStainedGlassPane));
inventory.setItem(4, info); this.inventory.setItem(4, this.info);
IteratorUtil.times(3, () -> inventory.addItem(PlaceholderItems.grayStainedGlassPane)); IteratorUtil.times(3, () -> this.inventory.addItem(PlaceholderItems.grayStainedGlassPane));
inventory.setItem(8, save); this.inventory.setItem(8, this.save);
IteratorUtil.iterateListInGlobal( IteratorUtil.iterateListInGlobal(
9, 9,
getAppliance().availablePacks.packs().stream() this.getAppliance().availablePacks.packs().stream()
.filter(pack -> !packConfiguration.getPackList().contains(pack)) .filter(pack -> !this.packConfiguration.getPackList().contains(pack))
.limit(9 * 3) .limit(9 * 3)
.map(pack -> { .map(pack -> {
ItemBuilder stack = ItemBuilder.of(pack.buildItem()); ItemBuilder stack = ItemBuilder.of(pack.buildItem());
if(packConfiguration.getPackList().contains(pack)) stack.glint(); if(this.packConfiguration.getPackList().contains(pack)) stack.glint();
return stack.build(); return stack.build();
}) })
.toList(), .toList(),
inventory::setItem this.inventory::setItem
); );
IntStream.range(9 * 4, 9 * 5) IntStream.range(9 * 4, 9 * 5)
.forEach(slot -> inventory.setItem(slot, PlaceholderItems.grayStainedGlassPane)); .forEach(slot -> this.inventory.setItem(slot, PlaceholderItems.grayStainedGlassPane));
IteratorUtil.iterateListInGlobal( IteratorUtil.iterateListInGlobal(
9 * 5, 9 * 5,
IteratorUtil.expandList( IteratorUtil.expandList(
IntStream.range(0, Math.min(packConfiguration.getPackList().size(), 9)) IntStream.range(0, Math.min(this.packConfiguration.getPackList().size(), 9))
.mapToObj(i -> { .mapToObj(i -> {
PackConfiguration.Pack pack = packConfiguration.getPackList().get(i); PackConfiguration.Pack pack = this.packConfiguration.getPackList().get(i);
ItemBuilder builder = ItemBuilder.of(pack.buildItem()); ItemBuilder builder = ItemBuilder.of(pack.buildItem());
builder builder
@ -162,9 +162,9 @@ public class PackConfigurationInventory extends CachedApplianceSupplier<PackSele
}) })
.toList(), .toList(),
9, 9,
unusedSlot this.unusedSlot
), ),
inventory::setItem this.inventory::setItem
); );
} }

View File

@ -3,8 +3,8 @@ package eu.mhsl.craftattack.spawn.appliances.packSelect;
import eu.mhsl.craftattack.spawn.Main; 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.appliance.ApplianceCommand; import eu.mhsl.craftattack.spawn.appliance.ApplianceCommand;
import eu.mhsl.craftattack.spawn.appliances.packSelect.listeners.ClosePackInventoryListener;
import eu.mhsl.craftattack.spawn.appliances.packSelect.listeners.ClickPackInventoryListener; import eu.mhsl.craftattack.spawn.appliances.packSelect.listeners.ClickPackInventoryListener;
import eu.mhsl.craftattack.spawn.appliances.packSelect.listeners.ClosePackInventoryListener;
import eu.mhsl.craftattack.spawn.appliances.packSelect.listeners.SetPacksOnJoinListener; import eu.mhsl.craftattack.spawn.appliances.packSelect.listeners.SetPacksOnJoinListener;
import eu.mhsl.craftattack.spawn.appliances.settings.Settings; import eu.mhsl.craftattack.spawn.appliances.settings.Settings;
import net.kyori.adventure.resource.ResourcePackInfo; import net.kyori.adventure.resource.ResourcePackInfo;
@ -37,7 +37,7 @@ public class PackSelect extends Appliance {
public void onEnable() { public void onEnable() {
Settings.instance().declareSetting(PackSelectSetting.class); Settings.instance().declareSetting(PackSelectSetting.class);
List<Map<?, ?>> packs = localConfig().getMapList("packs"); List<Map<?, ?>> packs = this.localConfig().getMapList("packs");
Bukkit.getScheduler().runTaskAsynchronously( Bukkit.getScheduler().runTaskAsynchronously(
Main.instance(), Main.instance(),
() -> packs.stream() () -> packs.stream()
@ -58,8 +58,8 @@ public class PackSelect extends Appliance {
resourcePackInfo, resourcePackInfo,
packData.get("icon") packData.get("icon")
); );
availablePacks.packs().add(packToAdd); this.availablePacks.packs().add(packToAdd);
} catch (Exception e) { } catch(Exception e) {
Main.logger().warning(String.format("Failed to add pack %s: %s", packData.get("name"), e.getMessage())); Main.logger().warning(String.format("Failed to add pack %s: %s", packData.get("name"), e.getMessage()));
} }
}) })
@ -78,9 +78,9 @@ public class PackSelect extends Appliance {
} }
public void openPackInventory(Player player) { public void openPackInventory(Player player) {
PackConfigurationInventory packInventory = new PackConfigurationInventory(getPackConfigurationForPlayer(player), player); PackConfigurationInventory packInventory = new PackConfigurationInventory(this.getPackConfigurationForPlayer(player), player);
player.openInventory(packInventory.getInventory()); player.openInventory(packInventory.getInventory());
openInventories.put(player, packInventory); this.openInventories.put(player, packInventory);
} }
public void setPack(Player player, PackConfiguration packConfiguration) { public void setPack(Player player, PackConfiguration packConfiguration) {

View File

@ -19,7 +19,7 @@ public class ResourcePackInfoFactory {
} }
public static @NotNull CompletableFuture<ResourcePackInfo> createResourcePackInfo(@NotNull URI resourcePackUrl, @Nullable String hash) { public static @NotNull CompletableFuture<ResourcePackInfo> createResourcePackInfo(@NotNull URI resourcePackUrl, @Nullable String hash) {
if (isValidHash(hash)) { if(isValidHash(hash)) {
return CompletableFuture.completedFuture( return CompletableFuture.completedFuture(
ResourcePackInfo.resourcePackInfo(UUID.nameUUIDFromBytes(hash.getBytes()), resourcePackUrl, hash) ResourcePackInfo.resourcePackInfo(UUID.nameUUIDFromBytes(hash.getBytes()), resourcePackUrl, hash)
); );
@ -32,11 +32,11 @@ public class ResourcePackInfoFactory {
connection.setRequestMethod("GET"); connection.setRequestMethod("GET");
connection.connect(); connection.connect();
try (InputStream inputStream = connection.getInputStream()) { try(InputStream inputStream = connection.getInputStream()) {
MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1"); MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1");
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
int bytesRead; int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) { while((bytesRead = inputStream.read(buffer)) != -1) {
sha1Digest.update(buffer, 0, bytesRead); sha1Digest.update(buffer, 0, bytesRead);
} }
String sha1Hex = bytesToHex(sha1Digest.digest()); String sha1Hex = bytesToHex(sha1Digest.digest());
@ -44,7 +44,7 @@ public class ResourcePackInfoFactory {
Main.logger().info(String.format("Calculating SHA1 Hash of %s completed: %s", resourcePackUrl, sha1Hex)); Main.logger().info(String.format("Calculating SHA1 Hash of %s completed: %s", resourcePackUrl, sha1Hex));
return ResourcePackInfo.resourcePackInfo(UUID.nameUUIDFromBytes(sha1Hex.getBytes()), resourcePackUrl, sha1Hex); return ResourcePackInfo.resourcePackInfo(UUID.nameUUIDFromBytes(sha1Hex.getBytes()), resourcePackUrl, sha1Hex);
} }
} catch (Exception e) { } catch(Exception e) {
String error = String.format("Error whilst SHA1 calculation of %s: %s", resourcePackUrl, e.getMessage()); String error = String.format("Error whilst SHA1 calculation of %s: %s", resourcePackUrl, e.getMessage());
Main.logger().warning(error); Main.logger().warning(error);
throw new RuntimeException(error); throw new RuntimeException(error);
@ -54,7 +54,7 @@ public class ResourcePackInfoFactory {
private static String bytesToHex(byte[] bytes) { private static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder(bytes.length * 2); StringBuilder hexString = new StringBuilder(bytes.length * 2);
for (byte b : bytes) { for(byte b : bytes) {
hexString.append(String.format("%02x", b)); hexString.append(String.format("%02x", b));
} }
return hexString.toString(); return hexString.toString();

View File

@ -10,10 +10,10 @@ public class ClickPackInventoryListener extends ApplianceListener<PackSelect> {
@EventHandler @EventHandler
public void interact(InventoryClickEvent event) { public void interact(InventoryClickEvent event) {
if(!(event.getWhoClicked() instanceof Player player)) return; if(!(event.getWhoClicked() instanceof Player player)) return;
if(getAppliance().isNotPackInventory(player, event.getInventory())) return; if(this.getAppliance().isNotPackInventory(player, event.getInventory())) return;
event.setCancelled(true); event.setCancelled(true);
getAppliance().openInventories.get(player).handleClick( this.getAppliance().openInventories.get(player).handleClick(
event.getCurrentItem(), event.getCurrentItem(),
event.getSlot(), event.getSlot(),
event.getClick() event.getClick()

View File

@ -10,7 +10,7 @@ public class ClosePackInventoryListener extends ApplianceListener<PackSelect> {
@EventHandler @EventHandler
public void onClose(InventoryCloseEvent event) { public void onClose(InventoryCloseEvent event) {
if(!(event.getPlayer() instanceof Player player)) return; if(!(event.getPlayer() instanceof Player player)) return;
if(getAppliance().isNotPackInventory(player, event.getInventory())) return; if(this.getAppliance().isNotPackInventory(player, event.getInventory())) return;
getAppliance().openInventories.remove(player); this.getAppliance().openInventories.remove(player);
} }
} }

View File

@ -12,7 +12,7 @@ public class SetPacksOnJoinListener extends ApplianceListener<PackSelect> {
public void onJoin(PlayerJoinEvent event) { public void onJoin(PlayerJoinEvent event) {
Bukkit.getScheduler().runTask( Bukkit.getScheduler().runTask(
Main.instance(), Main.instance(),
() -> getAppliance().setPack(event.getPlayer(), getAppliance().getPackConfigurationForPlayer(event.getPlayer())) () -> this.getAppliance().setPack(event.getPlayer(), this.getAppliance().getPackConfigurationForPlayer(event.getPlayer()))
); );
} }
} }

View File

@ -22,15 +22,15 @@ public class PanicBan extends Appliance {
if(player == null) if(player == null)
throw new ApplianceCommand.Error("Player not found"); throw new ApplianceCommand.Error("Player not found");
panicBans.put(player.getUniqueId(), System.currentTimeMillis()); this.panicBans.put(player.getUniqueId(), System.currentTimeMillis());
this.getDisconnectInfo(player.getUniqueId()).applyKick(player); this.getDisconnectInfo(player.getUniqueId()).applyKick(player);
} }
public boolean isBanned(UUID player) { public boolean isBanned(UUID player) {
if(panicBans.containsKey(player) && panicBans.get(player) < System.currentTimeMillis() - 15 * 60 * 1000) if(this.panicBans.containsKey(player) && this.panicBans.get(player) < System.currentTimeMillis() - 15 * 60 * 1000)
panicBans.remove(player); this.panicBans.remove(player);
return panicBans.containsKey(player); return this.panicBans.containsKey(player);
} }
public DisconnectInfo getDisconnectInfo(UUID playerUuid) { public DisconnectInfo getDisconnectInfo(UUID playerUuid) {

View File

@ -20,7 +20,7 @@ public class PanicBanCommand extends ApplianceCommand<PanicBan> {
@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().panicBan(args[0]); this.getAppliance().panicBan(args[0]);
} }
@Override @Override

View File

@ -7,8 +7,8 @@ import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
public class PanicBanJoinListener extends ApplianceListener<PanicBan> { public class PanicBanJoinListener extends ApplianceListener<PanicBan> {
@EventHandler @EventHandler
public void onLogin(AsyncPlayerPreLoginEvent event) { public void onLogin(AsyncPlayerPreLoginEvent event) {
if(getAppliance().isBanned(event.getUniqueId())) { if(this.getAppliance().isBanned(event.getUniqueId())) {
event.kickMessage(getAppliance().getDisconnectInfo(event.getUniqueId()).getComponent()); event.kickMessage(this.getAppliance().getDisconnectInfo(event.getUniqueId()).getComponent());
event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_BANNED); event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_BANNED);
} }
} }

View File

@ -15,18 +15,18 @@ public class PlayerLimit extends Appliance {
public PlayerLimit() { public PlayerLimit() {
super("playerLimit"); super("playerLimit");
this.limit = localConfig().getInt(playerLimitKey); this.limit = this.localConfig().getInt(playerLimitKey);
Bukkit.setMaxPlayers(Integer.MAX_VALUE); Bukkit.setMaxPlayers(Integer.MAX_VALUE);
} }
public void setPlayerLimit(int limit) { public void setPlayerLimit(int limit) {
this.limit = limit; this.limit = limit;
localConfig().set(playerLimitKey, limit); this.localConfig().set(playerLimitKey, limit);
Configuration.saveChanges(); Configuration.saveChanges();
} }
public int getLimit() { public int getLimit() {
return limit; return this.limit;
} }
@Override @Override

View File

@ -18,7 +18,7 @@ public class PlayerLimiterListener extends ApplianceListener<PlayerLimit> {
).getComponent() ).getComponent()
); );
if(Bukkit.getOnlinePlayers().size() >= getAppliance().getLimit()) if(Bukkit.getOnlinePlayers().size() >= this.getAppliance().getLimit())
playerPreLoginEvent.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_FULL); playerPreLoginEvent.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_FULL);
} }
} }

View File

@ -18,11 +18,11 @@ public class SetPlayerLimitCommand extends ApplianceCommand<PlayerLimit> {
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(this.getAppliance().getLimit(), NamedTextColor.GOLD))
); );
return; return;
} }
getAppliance().setPlayerLimit(Integer.parseInt(args[0])); this.getAppliance().setPlayerLimit(Integer.parseInt(args[0]));
} }
} }

View File

@ -17,15 +17,15 @@ public class PlaytimeCommand extends ApplianceCommand.PlayerChecked<Playtime> {
@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 {
String playerName = args.length == 1 ? args[0] : getPlayer().getName(); String playerName = args.length == 1 ? args[0] : this.getPlayer().getName();
Bukkit.getScheduler().runTaskAsynchronously(Main.instance(), () -> { Bukkit.getScheduler().runTaskAsynchronously(Main.instance(), () -> {
OfflinePlayer player = Bukkit.getOfflinePlayer(playerName); OfflinePlayer player = Bukkit.getOfflinePlayer(playerName);
if (!player.hasPlayedBefore()) { if(!player.hasPlayedBefore()) {
sender.sendMessage(Component.text("Der Spieler existiert nicht!", NamedTextColor.RED)); sender.sendMessage(Component.text("Der Spieler existiert nicht!", NamedTextColor.RED));
return; return;
} }
sender.sendMessage(getAppliance().getFormattedPlaytime(player)); sender.sendMessage(this.getAppliance().getFormattedPlaytime(player));
}); });
} }
} }

View File

@ -11,6 +11,6 @@ public class OnCraftingTableUseListener extends ApplianceListener<PortableCrafti
public void inInteract(PlayerInteractEvent event) { public void inInteract(PlayerInteractEvent event) {
if(!event.getAction().equals(Action.RIGHT_CLICK_AIR)) return; if(!event.getAction().equals(Action.RIGHT_CLICK_AIR)) return;
if(!event.getMaterial().equals(Material.CRAFTING_TABLE)) return; if(!event.getMaterial().equals(Material.CRAFTING_TABLE)) return;
getAppliance().openFor(event.getPlayer()); this.getAppliance().openFor(event.getPlayer());
} }
} }

View File

@ -23,7 +23,9 @@ public class PrivateMessage extends Appliance {
public final int targetChangeTimeoutSeconds = 30; public final int targetChangeTimeoutSeconds = 30;
public final int conversationTimeoutMinutes = 30; public final int conversationTimeoutMinutes = 30;
private record Conversation(UUID target, Long lastSet) {} private record Conversation(UUID target, Long lastSet) {
}
private final Map<Player, List<Conversation>> replyMapping = new WeakHashMap<>(); private final Map<Player, List<Conversation>> replyMapping = new WeakHashMap<>();
public void reply(Player sender, String message) { public void reply(Player sender, String message) {
@ -32,7 +34,7 @@ public class PrivateMessage extends Appliance {
List<Conversation> replyList = this.replyMapping.get(sender); List<Conversation> replyList = this.replyMapping.get(sender);
List<Conversation> tooOldConversations = replyList.stream() List<Conversation> tooOldConversations = replyList.stream()
.filter(conversation -> conversation.lastSet < System.currentTimeMillis() - (conversationTimeoutMinutes*60*1000)) .filter(conversation -> conversation.lastSet < System.currentTimeMillis() - (this.conversationTimeoutMinutes * 60 * 1000))
.toList(); .toList();
replyList.removeAll(tooOldConversations); replyList.removeAll(tooOldConversations);
@ -60,12 +62,13 @@ public class PrivateMessage extends Appliance {
} }
List<Conversation> oldConversations = replyList.stream() List<Conversation> oldConversations = replyList.stream()
.filter(conversation -> conversation.lastSet < System.currentTimeMillis() - (targetChangeTimeoutSeconds*1000)) .filter(conversation -> conversation.lastSet < System.currentTimeMillis() - (this.targetChangeTimeoutSeconds * 1000))
.toList(); .toList();
if(oldConversations.contains(youngestEntry) || replyList.size() == 1) { if(oldConversations.contains(youngestEntry) || replyList.size() == 1) {
Player target = Bukkit.getPlayer(youngestEntry.target()); Player target = Bukkit.getPlayer(youngestEntry.target());
if(target == null) throw new ApplianceCommand.Error("Der Spieler " + Bukkit.getOfflinePlayer(youngestEntry.target()).getName() + " ist nicht mehr verfügbar."); if(target == null)
throw new ApplianceCommand.Error("Der Spieler " + Bukkit.getOfflinePlayer(youngestEntry.target()).getName() + " ist nicht mehr verfügbar.");
replyList.clear(); replyList.clear();
this.sendWhisper(sender, new ResolvedPmUserArguments(target, message)); this.sendWhisper(sender, new ResolvedPmUserArguments(target, message));
@ -98,11 +101,11 @@ public class PrivateMessage extends Appliance {
.toList(); .toList();
playerNames.forEach(playerName -> component.append( playerNames.forEach(playerName -> component.append(
Component.text("[") Component.text("[")
.append(Component.text(playerName, NamedTextColor.GOLD)) .append(Component.text(playerName, NamedTextColor.GOLD))
.append(Component.text("]")) .append(Component.text("]"))
.clickEvent(ClickEvent.runCommand(String.format("/msg %s %s", playerName, message))) .clickEvent(ClickEvent.runCommand(String.format("/msg %s %s", playerName, message)))
.hoverEvent(HoverEvent.showText(Component.text("Klicke, um diesem Spieler zu schreiben.").color(NamedTextColor.GOLD)))) .hoverEvent(HoverEvent.showText(Component.text("Klicke, um diesem Spieler zu schreiben.").color(NamedTextColor.GOLD))))
.append(Component.text(" ")) .append(Component.text(" "))
); );
component.appendNewline(); component.appendNewline();
@ -167,12 +170,16 @@ public class PrivateMessage extends Appliance {
); );
} }
public record ResolvedPmUserArguments(Player receiver, String message) {} public record ResolvedPmUserArguments(Player receiver, String message) {
}
public ResolvedPmUserArguments resolveImplicit(String[] args) { public ResolvedPmUserArguments resolveImplicit(String[] args) {
if(args.length < 2) throw new ApplianceCommand.Error("Es muss ein Spieler sowie eine Nachricht angegeben werden."); if(args.length < 2)
throw new ApplianceCommand.Error("Es muss ein Spieler sowie eine Nachricht angegeben werden.");
List<String> arguments = List.of(args); List<String> arguments = List.of(args);
Player targetPlayer = Bukkit.getPlayer(arguments.getFirst()); Player targetPlayer = Bukkit.getPlayer(arguments.getFirst());
if(targetPlayer == null) throw new ApplianceCommand.Error(String.format("Der Spieler %s konnte nicht gefunden werden.", arguments.getFirst())); if(targetPlayer == null)
throw new ApplianceCommand.Error(String.format("Der Spieler %s konnte nicht gefunden werden.", arguments.getFirst()));
String message = arguments.stream().skip(1).collect(Collectors.joining(" ")); String message = arguments.stream().skip(1).collect(Collectors.joining(" "));
return new ResolvedPmUserArguments(targetPlayer, message); return new ResolvedPmUserArguments(targetPlayer, message);
} }

View File

@ -13,6 +13,6 @@ public class PrivateMessageCommand extends ApplianceCommand.PlayerChecked<Privat
@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().sendWhisper(getPlayer(), getAppliance().resolveImplicit(args)); this.getAppliance().sendWhisper(this.getPlayer(), this.getAppliance().resolveImplicit(args));
} }
} }

View File

@ -13,6 +13,6 @@ public class PrivateReplyCommand extends ApplianceCommand.PlayerChecked<PrivateM
@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().reply(getPlayer(), String.join(" ", args)); this.getAppliance().reply(this.getPlayer(), String.join(" ", args));
} }
} }

View File

@ -34,22 +34,22 @@ import static org.bukkit.Sound.MUSIC_DISC_PIGSTEP;
public class ProjectStart extends Appliance { public class ProjectStart extends Appliance {
private final int startMusicAt = 137; private final int startMusicAt = 137;
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(this.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(this.startWorld, -211, 68, -354),
new Location(startWorld, -209, 68, -356), new Location(this.startWorld, -209, 68, -356),
new Location(startWorld, -207, 68, -354), new Location(this.startWorld, -207, 68, -354),
new Location(startWorld, -209, 68, -352) new Location(this.startWorld, -209, 68, -352)
); );
private final Countdown countdown = new Countdown( private final Countdown countdown = new Countdown(
localConfig().getInt("countdown"), this.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, this.glassLocation,
Material.ORANGE_STAINED_GLASS, Material.ORANGE_STAINED_GLASS,
List.of( List.of(
Material.RED_STAINED_GLASS, Material.RED_STAINED_GLASS,
@ -78,10 +78,10 @@ public class ProjectStart extends Appliance {
this.countdown.addCustomAnnouncement( this.countdown.addCustomAnnouncement(
new Countdown.CustomAnnouncements( new Countdown.CustomAnnouncements(
counter -> counter == startMusicAt, counter -> counter == this.startMusicAt,
counter -> glassLocation counter -> this.glassLocation
.getWorld() .getWorld()
.playSound(glassLocation, MUSIC_DISC_PIGSTEP, SoundCategory.RECORDS, 500f, 1f) .playSound(this.glassLocation, MUSIC_DISC_PIGSTEP, SoundCategory.RECORDS, 500f, 1f)
) )
); );
} }
@ -96,12 +96,12 @@ public class ProjectStart extends Appliance {
} }
private void announce(Component message) { private void announce(Component message) {
blockCycle.next(); this.blockCycle.next();
IteratorUtil.onlinePlayers(player -> player.sendMessage(message)); IteratorUtil.onlinePlayers(player -> player.sendMessage(message));
} }
public void startCountdown() { public void startCountdown() {
if(!isEnabled()) return; if(!this.isEnabled()) return;
this.countdown.start(); this.countdown.start();
} }
@ -111,13 +111,13 @@ public class ProjectStart extends Appliance {
} }
public void startProject() { public void startProject() {
setEnabled(false); this.setEnabled(false);
IteratorUtil.worlds(World::getWorldBorder, worldBorder -> worldBorder.setSize(worldBorder.getMaxSize())); IteratorUtil.worlds(World::getWorldBorder, worldBorder -> worldBorder.setSize(worldBorder.getMaxSize()));
IteratorUtil.worlds(world -> IteratorUtil.setGameRules(gameRulesAfterStart, false)); IteratorUtil.worlds(world -> IteratorUtil.setGameRules(this.gameRulesAfterStart, false));
IteratorUtil.worlds(world -> world.setFullTime(0)); IteratorUtil.worlds(world -> world.setFullTime(0));
netherFireLocations.forEach(location -> Objects.requireNonNull(startWorld).getBlockAt(location).setType(Material.FIRE)); this.netherFireLocations.forEach(location -> Objects.requireNonNull(this.startWorld).getBlockAt(location).setType(Material.FIRE));
Bukkit.getOnlinePlayers().forEach(player -> { Bukkit.getOnlinePlayers().forEach(player -> {
player.setFoodLevel(20); player.setFoodLevel(20);
@ -144,40 +144,40 @@ public class ProjectStart extends Appliance {
); );
Bukkit.getOnlinePlayers().forEach( Bukkit.getOnlinePlayers().forEach(
player -> Main.instance().getAppliance(CustomAdvancements.class).grantAdvancement(Advancements.start, player.getUniqueId()) player -> Main.instance().getAppliance(CustomAdvancements.class).grantAdvancement(Advancements.start, player.getUniqueId())
); );
blockCycle.reset(); this.blockCycle.reset();
} }
public void restoreBeforeStart() { public void restoreBeforeStart() {
setEnabled(true); this.setEnabled(true);
IteratorUtil.onlinePlayers(Player::stopAllSounds); IteratorUtil.onlinePlayers(Player::stopAllSounds);
IteratorUtil.worlds(World::getWorldBorder, worldBorder -> { IteratorUtil.worlds(World::getWorldBorder, worldBorder -> {
worldBorder.setSize(localConfig().getLong("worldborder-before")); worldBorder.setSize(this.localConfig().getLong("worldborder-before"));
worldBorder.setWarningDistance(0); worldBorder.setWarningDistance(0);
worldBorder.setDamageAmount(0); worldBorder.setDamageAmount(0);
}); });
IteratorUtil.worlds(world -> world, world -> IteratorUtil.setGameRules(gameRulesAfterStart, true)); IteratorUtil.worlds(world -> world, world -> IteratorUtil.setGameRules(this.gameRulesAfterStart, true));
blockCycle.reset(); this.blockCycle.reset();
} }
public boolean isEnabled() { public boolean isEnabled() {
return localConfig().getBoolean("enabled"); return this.localConfig().getBoolean("enabled");
} }
public void setEnabled(boolean enabled) { public void setEnabled(boolean enabled) {
localConfig().set("enabled", enabled); this.localConfig().set("enabled", enabled);
Configuration.saveChanges(); Configuration.saveChanges();
} }
public Countdown getCountdown() { public Countdown getCountdown() {
return countdown; return this.countdown;
} }
@Override @Override

View File

@ -15,8 +15,8 @@ public class ProjectStartCancelCommand extends ApplianceCommand<ProjectStart> {
@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().getCountdown().isRunning()) { if(this.getAppliance().getCountdown().isRunning()) {
getAppliance().cancelCountdown(); this.getAppliance().cancelCountdown();
sender.sendMessage(Component.text("Countdown cancelled successfully!").color(NamedTextColor.GREEN)); sender.sendMessage(Component.text("Countdown cancelled successfully!").color(NamedTextColor.GREEN));
} else { } else {
sender.sendMessage(Component.text("Countdown is not running!").color(NamedTextColor.RED)); sender.sendMessage(Component.text("Countdown is not running!").color(NamedTextColor.RED));

View File

@ -15,16 +15,16 @@ public class ProjectStartCommand extends ApplianceCommand<ProjectStart> {
@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().isEnabled()) { if(!this.getAppliance().isEnabled()) {
sender.sendMessage(Component.text("Countdown not enabled or executed once before!").color(NamedTextColor.RED)); sender.sendMessage(Component.text("Countdown not enabled or executed once before!").color(NamedTextColor.RED));
return; return;
} }
if(getAppliance().getCountdown().isRunning()) { if(this.getAppliance().getCountdown().isRunning()) {
sender.sendMessage(Component.text("Countdown already running!").color(NamedTextColor.RED)); sender.sendMessage(Component.text("Countdown already running!").color(NamedTextColor.RED));
return; return;
} }
getAppliance().startCountdown(); this.getAppliance().startCountdown();
} }
} }

View File

@ -13,6 +13,6 @@ public class ProjectStartResetCommand extends ApplianceCommand<ProjectStart> {
@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) {
getAppliance().restoreBeforeStart(); this.getAppliance().restoreBeforeStart();
} }
} }

View File

@ -10,7 +10,7 @@ import org.bukkit.event.player.PlayerAdvancementDoneEvent;
public class NoAdvancementsListener extends ApplianceListener<ProjectStart> { public class NoAdvancementsListener extends ApplianceListener<ProjectStart> {
@EventHandler @EventHandler
public void onAdvancement(PlayerAdvancementDoneEvent event) { public void onAdvancement(PlayerAdvancementDoneEvent event) {
if(!getAppliance().isEnabled()) return; if(!this.getAppliance().isEnabled()) return;
event.message(null); event.message(null);
Advancement advancement = event.getAdvancement(); Advancement advancement = event.getAdvancement();

View File

@ -12,16 +12,16 @@ public class PlayerInvincibleListener extends ApplianceListener<ProjectStart> {
@EventHandler @EventHandler
public void onDamage(EntityDamageEvent event) { public void onDamage(EntityDamageEvent event) {
if(!(event.getEntity() instanceof Player)) return; if(!(event.getEntity() instanceof Player)) return;
if(getAppliance().isEnabled()) event.setCancelled(true); if(this.getAppliance().isEnabled()) event.setCancelled(true);
} }
@EventHandler @EventHandler
public void onHunger(FoodLevelChangeEvent event) { public void onHunger(FoodLevelChangeEvent event) {
if(getAppliance().isEnabled()) event.setCancelled(true); if(this.getAppliance().isEnabled()) event.setCancelled(true);
} }
@EventHandler @EventHandler
public void onHit(PrePlayerAttackEntityEvent event) { public void onHit(PrePlayerAttackEntityEvent event) {
if(getAppliance().isEnabled()) event.setCancelled(true); if(this.getAppliance().isEnabled()) event.setCancelled(true);
} }
} }

View File

@ -26,15 +26,15 @@ public class ReportCommand extends ApplianceCommand.PlayerChecked<Report> {
sender.sendMessage(ComponentUtil.pleaseWait()); sender.sendMessage(ComponentUtil.pleaseWait());
if(args.length == 0) { if(args.length == 0) {
getAppliance().reportToUnknown(getPlayer()); this.getAppliance().reportToUnknown(this.getPlayer());
} }
if(args.length == 1) { if(args.length == 1) {
getAppliance().reportToKnown(getPlayer(), args[0], null); this.getAppliance().reportToKnown(this.getPlayer(), args[0], null);
} }
if(args.length > 1) { if(args.length > 1) {
getAppliance().reportToKnown(getPlayer(), args[0], Arrays.stream(args).skip(1).collect(Collectors.joining(" "))); this.getAppliance().reportToKnown(this.getPlayer(), args[0], Arrays.stream(args).skip(1).collect(Collectors.joining(" ")));
} }
} }

View File

@ -14,6 +14,6 @@ public class ReportsCommand 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(ComponentUtil.pleaseWait()); sender.sendMessage(ComponentUtil.pleaseWait());
getAppliance().queryReports(getPlayer()); this.getAppliance().queryReports(this.getPlayer());
} }
} }

View File

@ -13,6 +13,6 @@ public class CancelRestartCommand extends ApplianceCommand<Restart> {
@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().cancelRestart(); this.getAppliance().cancelRestart();
} }
} }

View File

@ -13,6 +13,6 @@ public class ScheduleRestartCommand extends ApplianceCommand<Restart> {
@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().scheduleRestart(); this.getAppliance().scheduleRestart();
} }
} }

View File

@ -58,20 +58,20 @@ public class Settings extends Appliance {
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(this.settingsCache.containsKey(player)) return this.settingsCache.get(player);
List<Setting<?>> settings = this.declaredSettings.stream() List<Setting<?>> settings = this.declaredSettings.stream()
.map(clazz -> { .map(clazz -> {
try { try {
return clazz.getDeclaredConstructor(); return clazz.getDeclaredConstructor();
} catch (NoSuchMethodException e) { } catch(NoSuchMethodException e) {
throw new RuntimeException(String.format("Setting '%s' does not have an accessible constructor", clazz.getName()), e); throw new RuntimeException(String.format("Setting '%s' does not have an accessible constructor", clazz.getName()), e);
} }
}) })
.map(constructor -> { .map(constructor -> {
try { try {
return constructor.newInstance(); return constructor.newInstance();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { } catch(InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(String.format("Failed to create instance of setting '%s'", constructor.getDeclaringClass().getName()), e); throw new RuntimeException(String.format("Failed to create instance of setting '%s'", constructor.getDeclaringClass().getName()), e);
} }
}) })
@ -83,7 +83,7 @@ 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 = this.getSettings(player).stream()
.filter(s -> Objects.equals(s.getKey(), key)) .filter(s -> Objects.equals(s.getKey(), key))
.findFirst() .findFirst()
.orElseThrow(); .orElseThrow();
@ -96,8 +96,8 @@ public class Settings extends Appliance {
} }
public void openSettings(Player player) { public void openSettings(Player player) {
List<Setting<?>> settings = getSettings(player); List<Setting<?>> settings = this.getSettings(player);
Inventory inventory = Bukkit.createInventory(null, calculateInvSize(settings), Component.text("Einstellungen")); Inventory inventory = Bukkit.createInventory(null, this.calculateInvSize(settings), Component.text("Einstellungen"));
AtomicInteger row = new AtomicInteger(0); AtomicInteger row = new AtomicInteger(0);
Arrays.stream(SettingCategory.values()) Arrays.stream(SettingCategory.values())
@ -107,11 +107,11 @@ public class Settings extends Appliance {
.filter(setting -> ((CategorizedSetting) setting).category().equals(category)) .filter(setting -> ((CategorizedSetting) setting).category().equals(category))
.toList(); .toList();
for (int i = 0; i < categorizedSettings.size(); i++) { for(int i = 0; i < categorizedSettings.size(); i++) {
int slot = row.get() * 9 + i % 9; int slot = row.get() * 9 + i % 9;
inventory.setItem(slot, categorizedSettings.get(i).buildItem()); inventory.setItem(slot, categorizedSettings.get(i).buildItem());
if (i % 9 == 8) { if(i % 9 == 8) {
row.incrementAndGet(); row.incrementAndGet();
} }
} }
@ -122,11 +122,11 @@ public class Settings extends Appliance {
.filter(setting -> !(setting instanceof CategorizedSetting)) .filter(setting -> !(setting instanceof CategorizedSetting))
.toList(); .toList();
for (int i = 0; i < uncategorizedSettings.size(); i++) { for(int i = 0; i < uncategorizedSettings.size(); i++) {
int slot = row.get() * 9 + i % 9; int slot = row.get() * 9 + i % 9;
inventory.setItem(slot, uncategorizedSettings.get(i).buildItem()); inventory.setItem(slot, uncategorizedSettings.get(i).buildItem());
if (i % 9 == 8) { if(i % 9 == 8) {
row.incrementAndGet(); row.incrementAndGet();
} }
} }
@ -153,8 +153,8 @@ public class Settings extends Appliance {
} }
public void onSettingsClose(Player player) { public void onSettingsClose(Player player) {
if(!openSettingsInventories.containsKey(player)) return; if(!this.openSettingsInventories.containsKey(player)) return;
openSettingsInventories.remove(player); this.openSettingsInventories.remove(player);
player.updateInventory(); player.updateInventory();
} }
@ -163,7 +163,8 @@ public class Settings extends Appliance {
} }
public OpenSettingsInventory getOpenInventory(Player player) { public OpenSettingsInventory getOpenInventory(Player player) {
if(hasSettingsNotOpen(player)) throw new RuntimeException("Cannot retrieve data from closed Settings inventory!"); if(this.hasSettingsNotOpen(player))
throw new RuntimeException("Cannot retrieve data from closed Settings inventory!");
return this.openSettingsInventories.get(player); return this.openSettingsInventories.get(player);
} }

View File

@ -12,6 +12,6 @@ public class SettingsCommand extends ApplianceCommand.PlayerChecked<Settings> {
@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().openSettings(getPlayer()); this.getAppliance().openSettings(this.getPlayer());
} }
} }

View File

@ -17,14 +17,14 @@ public abstract class ActionSetting extends Setting<Void> {
@Override @Override
public ItemMeta buildMeta(ItemMeta meta) { public ItemMeta buildMeta(ItemMeta meta) {
meta.displayName(Component.text(title(), NamedTextColor.WHITE)); meta.displayName(Component.text(this.title(), NamedTextColor.WHITE));
meta.lore(buildDescription(description())); meta.lore(this.buildDescription(this.description()));
return meta; return meta;
} }
@Override @Override
protected void change(Player player, ClickType clickType) { protected void change(Player player, ClickType clickType) {
onAction(player, clickType); this.onAction(player, clickType);
} }
@Override @Override
@ -33,10 +33,12 @@ public abstract class ActionSetting extends Setting<Void> {
} }
@Override @Override
protected void fromStorage(PersistentDataContainer container) {} protected void fromStorage(PersistentDataContainer container) {
}
@Override @Override
protected void toStorage(PersistentDataContainer container, Void value) {} protected void toStorage(PersistentDataContainer container, Void value) {
}
@Override @Override
public Class<?> dataType() { public Class<?> dataType() {

View File

@ -20,19 +20,19 @@ public abstract class BoolSetting extends Setting<Boolean> {
@Override @Override
public void fromStorage(PersistentDataContainer container) { public void fromStorage(PersistentDataContainer container) {
this.state = container.has(getNamespacedKey()) this.state = container.has(this.getNamespacedKey())
? Objects.requireNonNull(container.get(getNamespacedKey(), PersistentDataType.BOOLEAN)) ? Objects.requireNonNull(container.get(this.getNamespacedKey(), PersistentDataType.BOOLEAN))
: defaultValue(); : this.defaultValue();
} }
@Override @Override
protected void toStorage(PersistentDataContainer container, Boolean value) { protected void toStorage(PersistentDataContainer container, Boolean value) {
container.set(getNamespacedKey(), PersistentDataType.BOOLEAN, value); container.set(this.getNamespacedKey(), PersistentDataType.BOOLEAN, value);
} }
@Override @Override
public ItemMeta buildMeta(ItemMeta meta) { public ItemMeta buildMeta(ItemMeta meta) {
meta.displayName(Component.text(title(), NamedTextColor.WHITE)); meta.displayName(Component.text(this.title(), NamedTextColor.WHITE));
List<Component> lore = new ArrayList<>(List.of( List<Component> lore = new ArrayList<>(List.of(
Component.empty() Component.empty()
.append(Component.text("Status: ", NamedTextColor.DARK_GRAY)) .append(Component.text("Status: ", NamedTextColor.DARK_GRAY))
@ -42,7 +42,7 @@ public abstract class BoolSetting extends Setting<Boolean> {
), ),
Component.empty() Component.empty()
)); ));
lore.addAll(buildDescription(description())); lore.addAll(this.buildDescription(this.description()));
meta.lore(lore); meta.lore(lore);
return meta; return meta;
} }
@ -59,6 +59,6 @@ public abstract class BoolSetting extends Setting<Boolean> {
@Override @Override
public Boolean state() { public Boolean state() {
return state; return this.state;
} }
} }

View File

@ -35,9 +35,10 @@ public abstract class MultiBoolSetting<T> extends Setting<T> {
@Override @Override
public ItemMeta buildMeta(ItemMeta meta) { public ItemMeta buildMeta(ItemMeta meta) {
record SettingField(String name, String displayName, Boolean value) {} record SettingField(String name, String displayName, Boolean value) {
}
meta.displayName(Component.text(title(), NamedTextColor.WHITE)); meta.displayName(Component.text(this.title(), NamedTextColor.WHITE));
List<Component> lore = new ArrayList<>(); List<Component> lore = new ArrayList<>();
lore.add(Component.text("Status: ", NamedTextColor.DARK_GRAY)); lore.add(Component.text("Status: ", NamedTextColor.DARK_GRAY));
@ -54,12 +55,12 @@ public abstract class MultiBoolSetting<T> extends Setting<T> {
: component.getName(); : component.getName();
return new SettingField(component.getName(), displayName, value); return new SettingField(component.getName(), displayName, value);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { } catch(NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
}) })
.map(field -> { .map(field -> {
if (cursorPosition == null) cursorPosition = field.name; if(this.cursorPosition == null) this.cursorPosition = field.name;
boolean isSelected = field.name.equals(this.cursorPosition); boolean isSelected = field.name.equals(this.cursorPosition);
return Component.text() return Component.text()
.append(Component.text( .append(Component.text(
@ -79,7 +80,7 @@ public abstract class MultiBoolSetting<T> extends Setting<T> {
.toList() .toList()
); );
lore.add(Component.empty()); lore.add(Component.empty());
lore.addAll(buildDescription(description())); lore.addAll(this.buildDescription(this.description()));
lore.add(Component.empty()); lore.add(Component.empty());
lore.add(Component.text("Linksklick", NamedTextColor.AQUA).append(Component.text(" zum Wählen der Option", NamedTextColor.GRAY))); lore.add(Component.text("Linksklick", NamedTextColor.AQUA).append(Component.text(" zum Wählen der Option", NamedTextColor.GRAY)));
lore.add(Component.text("Rechtsklick", NamedTextColor.AQUA).append(Component.text(" zum Ändern des Wertes", NamedTextColor.GRAY))); lore.add(Component.text("Rechtsklick", NamedTextColor.AQUA).append(Component.text(" zum Ändern des Wertes", NamedTextColor.GRAY)));
@ -96,16 +97,16 @@ public abstract class MultiBoolSetting<T> extends Setting<T> {
.findFirst() .findFirst()
.orElse(-1); .orElse(-1);
if (clickType.equals(ClickType.LEFT)) { if(clickType.equals(ClickType.LEFT)) {
currentIndex = (currentIndex + 1) % recordComponents.length; currentIndex = (currentIndex + 1) % recordComponents.length;
this.cursorPosition = recordComponents[currentIndex].getName(); this.cursorPosition = recordComponents[currentIndex].getName();
} else if (clickType.equals(ClickType.RIGHT)) { } else if(clickType.equals(ClickType.RIGHT)) {
try { try {
Object[] values = Arrays.stream(recordComponents) Object[] values = Arrays.stream(recordComponents)
.map(rc -> { .map(rc -> {
try { try {
return this.state.getClass().getDeclaredMethod(rc.getName()).invoke(this.state); return this.state.getClass().getDeclaredMethod(rc.getName()).invoke(this.state);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { } catch(NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
}) })
@ -119,7 +120,8 @@ public abstract class MultiBoolSetting<T> extends Setting<T> {
this.state = (T) this.state.getClass().getConstructor( this.state = (T) this.state.getClass().getConstructor(
Arrays.stream(recordComponents).map(RecordComponent::getType).toArray(Class[]::new) Arrays.stream(recordComponents).map(RecordComponent::getType).toArray(Class[]::new)
).newInstance(values); ).newInstance(values);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) { } catch(NoSuchMethodException | InvocationTargetException | IllegalAccessException |
InstantiationException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@ -127,21 +129,21 @@ public abstract class MultiBoolSetting<T> extends Setting<T> {
@Override @Override
protected void fromStorage(PersistentDataContainer container) { protected void fromStorage(PersistentDataContainer container) {
String data = container.has(getNamespacedKey()) String data = container.has(this.getNamespacedKey())
? Objects.requireNonNull(container.get(getNamespacedKey(), PersistentDataType.STRING)) ? Objects.requireNonNull(container.get(this.getNamespacedKey(), PersistentDataType.STRING))
: new Gson().toJson(defaultValue()); : new Gson().toJson(this.defaultValue());
try { try {
//noinspection unchecked //noinspection unchecked
this.state = (T) new Gson().fromJson(data, dataType()); this.state = (T) new Gson().fromJson(data, this.dataType());
} catch(Exception e) { } catch(Exception e) {
this.state = defaultValue(); this.state = this.defaultValue();
} }
} }
@Override @Override
protected void toStorage(PersistentDataContainer container, T value) { protected void toStorage(PersistentDataContainer container, T value) {
container.set(getNamespacedKey(), PersistentDataType.STRING, new Gson().toJson(value)); container.set(this.getNamespacedKey(), PersistentDataType.STRING, new Gson().toJson(value));
} }
@Override @Override

View File

@ -37,7 +37,7 @@ public abstract class SelectSetting extends Setting<SelectSetting.Options.Option
@Override @Override
public ItemMeta buildMeta(ItemMeta meta) { public ItemMeta buildMeta(ItemMeta meta) {
meta.displayName(Component.text(title(), NamedTextColor.WHITE)); meta.displayName(Component.text(this.title(), NamedTextColor.WHITE));
List<Component> lore = new ArrayList<>(); List<Component> lore = new ArrayList<>();
lore.add(Component.text("Status: ", NamedTextColor.DARK_GRAY)); lore.add(Component.text("Status: ", NamedTextColor.DARK_GRAY));
lore.addAll( lore.addAll(
@ -52,7 +52,7 @@ public abstract class SelectSetting extends Setting<SelectSetting.Options.Option
.toList() .toList()
); );
lore.add(Component.empty()); lore.add(Component.empty());
lore.addAll(buildDescription(description())); lore.addAll(this.buildDescription(this.description()));
meta.lore(lore); meta.lore(lore);
return meta; return meta;
} }
@ -65,9 +65,9 @@ public abstract class SelectSetting extends Setting<SelectSetting.Options.Option
.filter(i -> options.get(i).equals(this.state)) .filter(i -> options.get(i).equals(this.state))
.mapToObj(i -> { .mapToObj(i -> {
int nextIndex = i + optionModifier; int nextIndex = i + optionModifier;
if (nextIndex >= options.size()) { if(nextIndex >= options.size()) {
return options.getFirst(); return options.getFirst();
} else if (nextIndex < 0) { } else if(nextIndex < 0) {
return options.getLast(); return options.getLast();
} else { } else {
return options.get(nextIndex); return options.get(nextIndex);
@ -79,19 +79,19 @@ public abstract class SelectSetting extends Setting<SelectSetting.Options.Option
@Override @Override
protected void fromStorage(PersistentDataContainer container) { protected void fromStorage(PersistentDataContainer container) {
String data = container.has(getNamespacedKey()) String data = container.has(this.getNamespacedKey())
? Objects.requireNonNull(container.get(getNamespacedKey(), PersistentDataType.STRING)) ? Objects.requireNonNull(container.get(this.getNamespacedKey(), PersistentDataType.STRING))
: defaultValue().key.asString(); : this.defaultValue().key.asString();
this.state = this.options.options.stream() this.state = this.options.options.stream()
.filter(option -> option.key.asString().equals(data)) .filter(option -> option.key.asString().equals(data))
.findFirst() .findFirst()
.orElse(defaultValue()); .orElse(this.defaultValue());
} }
@Override @Override
protected void toStorage(PersistentDataContainer container, Options.Option value) { protected void toStorage(PersistentDataContainer container, Options.Option value) {
container.set(getNamespacedKey(), PersistentDataType.STRING, value.key.asString()); container.set(this.getNamespacedKey(), PersistentDataType.STRING, value.key.asString());
} }
@Override @Override

View File

@ -25,25 +25,25 @@ public abstract class Setting<TDataType> {
} }
public NamespacedKey getNamespacedKey() { public NamespacedKey getNamespacedKey() {
return new NamespacedKey(Main.instance(), key.name()); return new NamespacedKey(Main.instance(), this.key.name());
} }
public Settings.Key getKey() { public Settings.Key getKey() {
return key; return this.key;
} }
public void initializeFromPlayer(Player p) { public void initializeFromPlayer(Player p) {
fromStorage(p.getPersistentDataContainer()); this.fromStorage(p.getPersistentDataContainer());
} }
public void triggerChange(Player p, ClickType clickType) { public void triggerChange(Player p, ClickType clickType) {
this.change(p, clickType); this.change(p, clickType);
toStorage(p.getPersistentDataContainer(), this.state()); this.toStorage(p.getPersistentDataContainer(), this.state());
} }
public ItemStack buildItem() { public ItemStack buildItem() {
ItemStack stack = new ItemStack(icon(), 1); ItemStack stack = new ItemStack(this.icon(), 1);
stack.setItemMeta(buildMeta(stack.getItemMeta())); stack.setItemMeta(this.buildMeta(stack.getItemMeta()));
return stack; return stack;
} }

View File

@ -9,8 +9,9 @@ public class OpenSettingsShortcutListener extends ApplianceListener<Settings> {
@EventHandler @EventHandler
public void onItemSwitch(PlayerSwapHandItemsEvent event) { public void onItemSwitch(PlayerSwapHandItemsEvent event) {
if(!event.getPlayer().isSneaking()) return; if(!event.getPlayer().isSneaking()) return;
if(!Settings.instance().getSetting(event.getPlayer(), Settings.Key.EnableSettingsShortcut, Boolean.class)) return; if(!Settings.instance().getSetting(event.getPlayer(), Settings.Key.EnableSettingsShortcut, Boolean.class))
return;
event.setCancelled(true); event.setCancelled(true);
getAppliance().openSettings(event.getPlayer()); this.getAppliance().openSettings(event.getPlayer());
} }
} }

View File

@ -11,10 +11,10 @@ public class SettingsInventoryListener extends ApplianceListener<Settings> {
@EventHandler @EventHandler
public void onInventoryClick(InventoryClickEvent event) { public void onInventoryClick(InventoryClickEvent event) {
Player player = (Player) event.getWhoClicked(); Player player = (Player) event.getWhoClicked();
if(getAppliance().hasSettingsNotOpen(player)) return; if(this.getAppliance().hasSettingsNotOpen(player)) return;
event.setCancelled(true); event.setCancelled(true);
Settings.OpenSettingsInventory openInventory = getAppliance().getOpenInventory(player); Settings.OpenSettingsInventory openInventory = this.getAppliance().getOpenInventory(player);
openInventory.settings().stream() openInventory.settings().stream()
.filter(setting -> setting.buildItem().equals(event.getCurrentItem())) .filter(setting -> setting.buildItem().equals(event.getCurrentItem()))
.findFirst() .findFirst()
@ -26,6 +26,6 @@ public class SettingsInventoryListener extends ApplianceListener<Settings> {
@EventHandler @EventHandler
public void onInventoryClose(InventoryCloseEvent event) { public void onInventoryClose(InventoryCloseEvent event) {
getAppliance().onSettingsClose((Player) event.getPlayer()); this.getAppliance().onSettingsClose((Player) event.getPlayer());
} }
} }

View File

@ -9,11 +9,11 @@ public class SleepStateChangeListener extends ApplianceListener<SleepTag> {
@EventHandler @EventHandler
public void onBedEnter(PlayerBedEnterEvent event) { public void onBedEnter(PlayerBedEnterEvent event) {
if(!event.getBedEnterResult().equals(PlayerBedEnterEvent.BedEnterResult.OK)) return; if(!event.getBedEnterResult().equals(PlayerBedEnterEvent.BedEnterResult.OK)) return;
getAppliance().updateSleeping(event.getPlayer(), true); this.getAppliance().updateSleeping(event.getPlayer(), true);
} }
@EventHandler @EventHandler
public void onBedLeave(PlayerBedLeaveEvent event) { public void onBedLeave(PlayerBedLeaveEvent event) {
getAppliance().updateSleeping(event.getPlayer(), false); this.getAppliance().updateSleeping(event.getPlayer(), false);
} }
} }

Some files were not shown because too many files have changed in this diff Show More