diff --git a/astralbooks-core/pom.xml b/astralbooks-core/pom.xml index 6f5cd8e..d241b70 100644 --- a/astralbooks-core/pom.xml +++ b/astralbooks-core/pom.xml @@ -38,6 +38,12 @@ + + org.spigotmc + spigot + 1.20.4-R0.1-SNAPSHOT + provided + ro.niconeko astralbooks-api @@ -53,13 +59,6 @@ provided - - me.lucko - commodore - 2.2 - compile - jar - org.bstats bstats-bukkit diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/AstralBooksCommand.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/AstralBooksCommand.java deleted file mode 100644 index 53b0eca..0000000 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/AstralBooksCommand.java +++ /dev/null @@ -1,1298 +0,0 @@ -/* - * CitizensBooks - * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ro.niconeko.astralbooks; - -import net.citizensnpcs.api.CitizensAPI; -import net.citizensnpcs.api.npc.NPC; -import org.bukkit.*; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.command.TabExecutor; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.BookMeta; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.persistence.PersistentDataType; -import org.bukkit.util.StringUtil; -import org.jetbrains.annotations.NotNull; -import ro.niconeko.astralbooks.settings.MessageSettings; -import ro.niconeko.astralbooks.storage.StorageType; -import ro.niconeko.astralbooks.utils.Message; -import ro.niconeko.astralbooks.utils.PersistentKey; -import ro.niconeko.astralbooks.utils.Side; -import ro.niconeko.astralbooks.utils.tuples.PairTuple; -import ro.niconeko.astralbooks.utils.tuples.TripletTuple; - -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.stream.Collectors; - -public class AstralBooksCommand implements TabExecutor { - private final AstralBooksPlugin plugin; - private final AstralBooksCore api; - - public AstralBooksCommand(AstralBooksPlugin plugin) { - this.api = (this.plugin = plugin).getAPI(); - } - - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, String[] args) { - Optional player = this.isPlayer(sender) ? Optional.of((Player) sender) : Optional.empty(); - MessageSettings messageSettings = this.plugin.getSettings().getMessageSettings(); - Side side; - NamespacedKey action; - if (args.length > 0) { - switch (args[0]) { - case "help" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.help")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (args.length > 1) { - try { - int page = Integer.parseInt(args[1]); - this.sendHelp(sender, page); - } catch (NumberFormatException ex) { - sender.sendMessage(messageSettings.getMessage(Message.USAGE_HELP)); - } - } else - this.sendHelp(sender, 0); - } - case "security" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.security")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (!this.plugin.getSettings().isBookSignSecurityEnabled()) { - sender.sendMessage(messageSettings.getMessage(Message.BOOK_SECURITY_NOT_ENABLED)); - break; - } - if (args.length > 1) { - switch (args[1]) { - case "list" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.security.list")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - int page = 1; - if (args.length > 2) { - if (args.length > 3) - try { - page = Integer.parseInt(args[3]); - } catch (NumberFormatException ex) { - sender.sendMessage(messageSettings.getMessage(Message.USAGE_SECURITY_LIST)); - break; - } - if (page < 1) { - sender.sendMessage(messageSettings.getMessage(Message.USAGE_SECURITY_LIST)); - break; - } - if (args[2].equalsIgnoreCase("*")) - this.sendSecurityPage(sender, page); - else { - @SuppressWarnings("deprecation") - OfflinePlayer offlineSelected = Bukkit.getOfflinePlayer(args[2]); - if (offlineSelected.hasPlayedBefore()) - this.sendSecurityPage(sender, offlineSelected, page); - else - sender.sendMessage(messageSettings.getMessage(Message.PLAYER_NOT_FOUND)); - } - } else - this.sendSecurityPage(sender, page); - } - case "getbook" -> { - if (player.isEmpty()) { - sender.sendMessage(messageSettings.getMessage(Message.CONSOLE_CANNOT_USE_COMMAND)); - break; - } - if (!this.api.hasPermission(sender, "astralbooks.command.security.getbook")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (args.length > 2) { - @SuppressWarnings("deprecation") - OfflinePlayer offlineSelected = Bukkit.getOfflinePlayer(args[2]); - if (offlineSelected.hasPlayedBefore()) { - if (args.length > 3) - try { - long timestamp = Long.parseLong(args[3]); - Date date = new Date(timestamp); - ItemStack book = this.plugin.getPluginStorage().getBookSecurity(offlineSelected.getUniqueId(), date); - if (book == null) { - sender.sendMessage(messageSettings.getMessage(Message.BOOK_SECURITY_NOT_FOUND)); - break; - } - player.get().getInventory().addItem(book); - } catch (NumberFormatException ex) { - sender.sendMessage(messageSettings.getMessage(Message.BOOK_SECURITY_NOT_FOUND)); - } - else - sender.sendMessage(messageSettings.getMessage(Message.USAGE_SECURITY_GETBOOK)); - } else - sender.sendMessage(messageSettings.getMessage(Message.PLAYER_NOT_FOUND)); - } else - sender.sendMessage(messageSettings.getMessage(Message.USAGE_SECURITY_GETBOOK)); - } - default -> this.sendSecurityHelp(sender); - } - } else - this.sendSecurityHelp(sender); - } - case "import" -> { - if (player.isPresent()) { - sender.sendMessage(messageSettings.getMessage(Message.PLAYER_CANNOT_USE_COMMAND)); - break; - } - if (args.length > 1 && args[1].equals("citizensbooks")) - this.api.importFromCitizensBooks(); - else - plugin.getLogger().info("Argument: citizensbooks"); - } - case "convert" -> { - if (player.isPresent()) { - sender.sendMessage(messageSettings.getMessage(Message.PLAYER_CANNOT_USE_COMMAND)); - break; - } - if (args.length > 1) { - StorageType type = switch (args[1]) { - case "mysql" -> StorageType.MYSQL; - case "sqlite" -> StorageType.SQLITE; - case "json" -> StorageType.JSON; - case "h2" -> StorageType.H2; - case "mariadb" -> StorageType.MARIADB; - default -> null; - }; - if (type == null) { - plugin.getLogger().info("Argument: mysql, sqlite, json, h2, mariadb"); - break; - } - this.plugin.getPluginStorage().convertFrom(type); - } else plugin.getLogger().info("Argument: mysql, sqlite, json, h2, mariadb"); - } - case "interaction" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.interaction")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (player.isEmpty()) { - sender.sendMessage(messageSettings.getMessage(Message.CONSOLE_CANNOT_USE_COMMAND)); - break; - } - if (args.length > 1) { - switch (args[1]) { - case "set" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.interaction.set")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - ItemStack book = player.get().getInventory().getItemInMainHand().clone(); - if (args.length > 2) { - switch (args[2]) { - case "block" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.interaction.set.block")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (args.length > 3) { - if ("right".equalsIgnoreCase(args[3])) - side = Side.RIGHT; - else if ("left".equalsIgnoreCase(args[3])) - side = Side.LEFT; - else { - sender.sendMessage(messageSettings.getMessage(Message.USAGE_INTERACTION_SET_BLOCK)); - break; - } - } else side = Side.RIGHT; - if (book.getType() != Material.WRITTEN_BOOK) { - sender.sendMessage(messageSettings.getMessage(Message.NO_WRITTEN_BOOK_IN_HAND)); - break; - } - this.plugin.getPlayerActionsListener().setBookBlockOperator(player.get(), book, side); - sender.sendMessage(messageSettings.getMessage(Message.BOOK_APPLY_TO_BLOCK_TIMEOUT)); - } - case "entity" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.interaction.set.entity")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (args.length > 3) { - if ("right".equalsIgnoreCase(args[3])) - side = Side.RIGHT; - else if ("left".equalsIgnoreCase(args[3])) - side = Side.LEFT; - else { - sender.sendMessage(messageSettings.getMessage(Message.USAGE_INTERACTION_SET_ENTITY)); - break; - } - } else side = Side.RIGHT; - if (book.getType() != Material.WRITTEN_BOOK) { - sender.sendMessage(messageSettings.getMessage(Message.NO_WRITTEN_BOOK_IN_HAND)); - break; - } - this.plugin.getPlayerActionsListener().setBookEntityOperator(player.get(), book, side); - sender.sendMessage(messageSettings.getMessage(Message.BOOK_APPLY_TO_ENTITY_TIMEOUT)); - } - default -> this.sendInteractionSetHelp(sender); - } - } else - this.sendInteractionSetHelp(sender); - } - case "remove" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.interaction.remove")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (args.length > 2) { - switch (args[2]) { - case "block" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.interaction.remove.block")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (args.length > 3) { - if ("right".equalsIgnoreCase(args[3])) - side = Side.RIGHT; - else if ("left".equalsIgnoreCase(args[3])) - side = Side.LEFT; - else { - sender.sendMessage(messageSettings.getMessage(Message.USAGE_INTERACTION_REMOVE_BLOCK)); - break; - } - } else side = Side.RIGHT; - this.plugin.getPlayerActionsListener().setBookBlockOperator(player.get(), null, side); - sender.sendMessage(messageSettings.getMessage(Message.BOOK_REMOVE_FROM_BLOCK_TIMEOUT)); - } - case "entity" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.interaction.remove.entity")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (args.length > 3) { - if ("right".equalsIgnoreCase(args[3])) - side = Side.RIGHT; - else if ("left".equalsIgnoreCase(args[3])) - side = Side.LEFT; - else { - sender.sendMessage(messageSettings.getMessage(Message.USAGE_INTERACTION_REMOVE_ENTITY)); - break; - } - } else side = Side.RIGHT; - this.plugin.getPlayerActionsListener().setBookEntityOperator(player.get(), null, side); - sender.sendMessage(messageSettings.getMessage(Message.BOOK_REMOVE_FROM_ENTITY_TIMEOUT)); - } - default -> this.sendInteractionRemoveHelp(sender); - } - } else - this.sendInteractionRemoveHelp(sender); - } - default -> this.sendInteractionHelp(sender); - } - } else - this.sendInteractionHelp(sender); - - } - case "npc" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.npc")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (!this.plugin.isCitizensEnabled()) { - sender.sendMessage(messageSettings.getMessage(Message.CITIZENS_NOT_ENABLED)); - break; - } - if (player.isEmpty()) { - sender.sendMessage(messageSettings.getMessage(Message.CONSOLE_CANNOT_USE_COMMAND)); - break; - } - Optional npc; - if (args.length > 1) { - switch (args[1]) { - case "set" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.npc.set")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - ItemStack book = player.get().getInventory().getItemInMainHand().clone(); - if (book.getType() != Material.WRITTEN_BOOK) { - sender.sendMessage(messageSettings.getMessage(Message.NO_WRITTEN_BOOK_IN_HAND)); - break; - } - npc = Optional.ofNullable(CitizensAPI.getDefaultNPCSelector().getSelected(player.get())); - if (npc.isEmpty()) { - sender.sendMessage(messageSettings.getMessage(Message.NO_NPC_SELECTED)); - break; - } - if (args.length > 2) { - if ("right".equalsIgnoreCase(args[2])) - side = Side.RIGHT; - else if ("left".equalsIgnoreCase(args[2])) - side = Side.LEFT; - else { - sender.sendMessage(messageSettings.getMessage(Message.USAGE_NPC_SET).replace("%npc%", npc.get().getFullName())); - break; - } - } else side = Side.RIGHT; - if (!this.plugin.getPluginStorage().putNPCBook(npc.get().getId(), side, book)) { - sender.sendMessage(messageSettings.getMessage(Message.OPERATION_FAILED)); - break; - } - sender.sendMessage(messageSettings.getMessage(Message.SET_BOOK_SUCCESSFULLY).replace("%npc%", npc.get().getFullName())); - } - case "remove" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.npc.remove")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - npc = Optional.ofNullable(CitizensAPI.getDefaultNPCSelector().getSelected(player.get())); - if (npc.isEmpty()) { - sender.sendMessage(messageSettings.getMessage(Message.NO_NPC_SELECTED)); - break; - } - if (args.length > 2) { - if ("right".equalsIgnoreCase(args[2])) - side = Side.RIGHT; - else if ("left".equalsIgnoreCase(args[2])) - side = Side.LEFT; - else { - sender.sendMessage(messageSettings.getMessage(Message.USAGE_NPC_REMOVE).replace("%npc%", npc.get().getFullName())); - break; - } - } else side = Side.RIGHT; - if (!this.plugin.getPluginStorage().removeNPCBook(npc.get().getId(), side)) { - sender.sendMessage(messageSettings.getMessage(Message.OPERATION_FAILED)); - break; - } - sender.sendMessage(messageSettings.getMessage(Message.REMOVED_BOOK_SUCCESSFULLY).replace("%npc%", npc.get().getFullName())); - } - case "getbook" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.npc.getbook")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - npc = Optional.ofNullable(CitizensAPI.getDefaultNPCSelector().getSelected(player.get())); - if (npc.isEmpty()) { - sender.sendMessage(messageSettings.getMessage(Message.NO_NPC_SELECTED)); - break; - } - if (args.length > 2) { - if ("right".equalsIgnoreCase(args[2])) - side = Side.RIGHT; - else if ("left".equalsIgnoreCase(args[2])) - side = Side.LEFT; - else { - sender.sendMessage(messageSettings.getMessage(Message.USAGE_NPC_GETBOOK).replace("%npc%", npc.get().getFullName())); - break; - } - } else - side = Side.RIGHT; - if (!this.plugin.getPluginStorage().hasNPCBook(npc.get().getId(), side)) { - sender.sendMessage(messageSettings.getMessage(Message.NO_BOOK_FOR_NPC).replace("%npc%", npc.get().getFullName())); - break; - } - ItemStack book = this.plugin.getPluginStorage().getNPCBook(npc.get().getId(), side, new ItemStack(Material.WRITTEN_BOOK)); - player.get().getInventory().addItem(book); - sender.sendMessage(messageSettings.getMessage(Message.BOOK_RECEIVED)); - } - default -> this.sendNpcHelp(sender); - } - } else - this.sendNpcHelp(sender); - } - case "actionitem", "ai" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.actionitem")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (player.isEmpty()) { - sender.sendMessage(messageSettings.getMessage(Message.CONSOLE_CANNOT_USE_COMMAND)); - break; - } - ItemStack item = player.get().getInventory().getItemInMainHand().clone(); - if (args.length > 1) { - switch (args[1]) { - case "set" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.actionitem.set")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (args.length > 2) { - String filter_name = args[2]; - if (!this.api.isValidName(filter_name)) { - sender.sendMessage(messageSettings.getMessage(Message.FILTER_NAME_INVALID).replace("%invalid_filter_name%", filter_name)); - break; - } - if (!this.plugin.getPluginStorage().hasFilterBook(filter_name)) { - sender.sendMessage(messageSettings.getMessage(Message.FILTER_NOT_FOUND)); - break; - } - ItemMeta data = item.getItemMeta(); - if (item.getType() == Material.AIR || data == null) { - sender.sendMessage(messageSettings.getMessage(Message.NO_ITEM_IN_HAND)); - break; - } - if (args.length > 3) { - if ("right".equalsIgnoreCase(args[3])) - action = PersistentKey.ITEM_RIGHT_KEY; - else if ("left".equalsIgnoreCase(args[3])) - action = PersistentKey.ITEM_LEFT_KEY; - else { - sender.sendMessage(messageSettings.getMessage(Message.USAGE_ACTIONITEM_SET).replace("%filter_name%", filter_name)); - break; - } - } else action = PersistentKey.ITEM_RIGHT_KEY; - - data.getPersistentDataContainer().set(action, PersistentDataType.STRING, filter_name); - item.setItemMeta(data); - player.get().getInventory().setItemInMainHand(item); - sender.sendMessage(messageSettings.getMessage(Message.FILTER_APPLIED_TO_ITEM).replace("%filter_name%", filter_name)); - - } else - sender.sendMessage(messageSettings.getMessage(Message.USAGE_ACTIONITEM_SET)); - } - case "remove" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.actionitem.remove")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - ItemMeta data = item.getItemMeta(); - if (item.getType() == Material.AIR || data == null) { - sender.sendMessage(messageSettings.getMessage(Message.NO_ITEM_IN_HAND)); - break; - } - if (args.length > 2) { - if ("right".equalsIgnoreCase(args[2])) - action = PersistentKey.ITEM_RIGHT_KEY; - else if ("left".equalsIgnoreCase(args[2])) - action = PersistentKey.ITEM_LEFT_KEY; - else { - sender.sendMessage(messageSettings.getMessage(Message.USAGE_ACTIONITEM_SET)); - break; - } - } else action = PersistentKey.ITEM_RIGHT_KEY; - if (data.getPersistentDataContainer().has(action, PersistentDataType.STRING)) - data.getPersistentDataContainer().remove(action); - item.setItemMeta(data); - player.get().getInventory().setItemInMainHand(item); - sender.sendMessage(messageSettings.getMessage(Message.FILTER_REMOVED_FROM_ITEM)); - } - default -> this.sendActionItemHelp(sender); - } - } else - this.sendActionItemHelp(sender); - } - case "forceopen" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.forceopen")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (args.length > 1) { - String filter_name = args[1]; - if (!this.api.isValidName(filter_name)) { - sender.sendMessage(messageSettings.getMessage(Message.FILTER_NAME_INVALID).replace("%invalid_filter_name%", filter_name)); - break; - } - if (!this.plugin.getPluginStorage().hasFilterBook(filter_name)) { - sender.sendMessage(messageSettings.getMessage(Message.FILTER_NOT_FOUND)); - break; - } - if (args.length == 2) { - if (player.isEmpty()) { - sender.sendMessage(messageSettings.getMessage(Message.CONSOLE_CANNOT_USE_COMMAND)); - sender.sendMessage(messageSettings.getMessage(Message.USAGE_FORCEOPEN)); - break; - } - if (!this.api.openBook(player.get(), this.api.placeholderHook(player.get(), this.plugin.getPluginStorage().getFilterBook(filter_name), null))) - sender.sendMessage(messageSettings.getMessage(Message.OPERATION_FAILED)); - else - sender.sendMessage(messageSettings.getMessage(Message.OPENED_BOOK_FOR_PLAYER) - .replace("%player%", sender.getName())); - } else { - if ("*".equals(args[2])) { - int failedReceiver = 0; - int successfulReceiver = 0; - for (Player receiver : Bukkit.getOnlinePlayers()) - if (!this.api.openBook(receiver, this.api.placeholderHook(receiver, this.plugin.getPluginStorage().getFilterBook(filter_name), null))) - failedReceiver++; - else - successfulReceiver++; - sender.sendMessage(messageSettings.getMessage(Message.OPENED_BOOK_FOR_PLAYERS) - .replace("%success%", String.valueOf(successfulReceiver)) - .replace("%failed%", String.valueOf(failedReceiver))); - } else { - Optional optionalPlayer = Bukkit.getOnlinePlayers().stream().filter(p -> p.getName().equals(args[2])).findFirst(); - if (optionalPlayer.isPresent()) - if (!this.api.openBook(optionalPlayer.get(), this.api.placeholderHook(optionalPlayer.get(), this.plugin.getPluginStorage().getFilterBook(filter_name), null))) - sender.sendMessage(messageSettings.getMessage(Message.OPERATION_FAILED)); - else - sender.sendMessage(messageSettings.getMessage(Message.OPENED_BOOK_FOR_PLAYER) - .replace("%player%", optionalPlayer.get().getName())); - else - sender.sendMessage(messageSettings.getMessage(Message.PLAYER_NOT_FOUND)); - } - } - } else - sender.sendMessage(messageSettings.getMessage(Message.USAGE_FORCEOPEN)); - } - case "about" -> this.sendAbout(sender); - case "reload" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.reload")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - /* - * this.plugin.saveSettings(); - * - * No need to be saved anymore! - * If config file is edited, the config is - * overwritten, so the edit is lost - */ - if (!this.plugin.reloadPlugin()) { - sender.sendMessage(messageSettings.getMessage(Message.OPERATION_FAILED)); - break; - } - sender.sendMessage(messageSettings.getMessage(Message.CONFIG_RELOADED)); - } - case "setjoin" -> { - if (player.isEmpty()) { - sender.sendMessage(messageSettings.getMessage(Message.CONSOLE_CANNOT_USE_COMMAND)); - break; - } - if (!this.api.hasPermission(sender, "astralbooks.command.setjoin")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - ItemStack item = player.get().getInventory().getItemInMainHand().clone(); - if (item.getType() != Material.WRITTEN_BOOK) { - sender.sendMessage(messageSettings.getMessage(Message.NO_WRITTEN_BOOK_IN_HAND)); - break; - } - if (!this.plugin.getPluginStorage().setJoinBook(item)) { - sender.sendMessage(messageSettings.getMessage(Message.OPERATION_FAILED)); - break; - } - this.plugin.getSettings().setJoinBookEnabled(true); - if (!this.plugin.saveSettings()) { - sender.sendMessage(messageSettings.getMessage(Message.OPERATION_FAILED)); - break; - } - sender.sendMessage(messageSettings.getMessage(Message.SET_JOIN_BOOK_SUCCESSFULLY)); - } - case "remjoin" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.remjoin")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (!this.plugin.getPluginStorage().removeJoinBook()) { - sender.sendMessage(messageSettings.getMessage(Message.OPERATION_FAILED)); - break; - } - this.plugin.getSettings().setJoinBookEnabled(false); - if (!this.plugin.saveSettings()) { - sender.sendMessage(messageSettings.getMessage(Message.OPERATION_FAILED)); - break; - } - sender.sendMessage(messageSettings.getMessage(Message.REMOVED_JOIN_BOOK_SUCCESSFULLY)); - } - case "openbook" -> { - if (player.isEmpty()) { - sender.sendMessage(messageSettings.getMessage(Message.CONSOLE_CANNOT_USE_COMMAND)); - break; - } - if (!this.api.hasPermission(sender, "astralbooks.command.getbook")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - ItemStack item = player.get().getInventory().getItemInMainHand().clone(); - if (item.getType() != Material.WRITTEN_BOOK) { - sender.sendMessage(messageSettings.getMessage(Message.NO_WRITTEN_BOOK_IN_HAND)); - break; - } - this.openBook(player.get(), item); - } - case "closebook" -> { - if (player.isEmpty()) { - sender.sendMessage(messageSettings.getMessage(Message.CONSOLE_CANNOT_USE_COMMAND)); - break; - } - if (!this.api.hasPermission(sender, "astralbooks.command.closebook")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (args.length > 2) { - ItemStack item = player.get().getInventory().getItemInMainHand(); - if (item.getType() != Material.WRITABLE_BOOK) { - sender.sendMessage(messageSettings.getMessage(Message.NO_WRITABLE_BOOK_IN_HAND)); - break; - } - String author = args[1]; - String title = args.length > 3 ? String.join(" ", Arrays.copyOfRange(args, 2, args.length)) : args[2]; // copy if at least 2 title-args - this.closeBook(player.get(), item, author, title); - } else - sender.sendMessage(messageSettings.getMessage(Message.USAGE_CLOSEBOOK)); - } - case "setcmd" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.setcmd")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (args.length > 2) { - String command_name = args[1]; - if (!this.api.isValidName(command_name)) { - sender.sendMessage(messageSettings.getMessage(Message.COMMAND_NAME_INVALID).replace("%invalid_command%", command_name)); - break; - } - String filter_name = args[2]; - if (!this.api.isValidName(filter_name)) { - sender.sendMessage(messageSettings.getMessage(Message.FILTER_NAME_INVALID).replace("%invalid_filter%", filter_name)); - break; - } - String permission = args.length > 3 ? args[3] : "none"; - if (!this.api.isValidPermission(permission)) { - sender.sendMessage(messageSettings.getMessage(Message.PERMISSION_INVALID).replace("%invalid_permission%", permission)); - break; - } - if (!this.plugin.getPluginStorage().putCommandFilter(command_name, filter_name, permission)) { - sender.sendMessage(messageSettings.getMessage(Message.OPERATION_FAILED)); - break; - } - sender.sendMessage(messageSettings.getMessage(Message.SET_CUSTOM_COMMAND_SUCCESSFULLY).replace("%command%", args[1]).replace("%filter%", filter_name)); - } else - sender.sendMessage(messageSettings.getMessage(Message.USAGE_SETCMD)); - } - case "remcmd" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.remcmd")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (args.length > 1) { - String command_name = args[1]; - if (!this.api.isValidName(command_name)) { - sender.sendMessage(messageSettings.getMessage(Message.COMMAND_NAME_INVALID).replace("%invalid_command%", command_name)); - break; - } - if (!this.plugin.getPluginStorage().removeCommandFilter(command_name)) { - sender.sendMessage(messageSettings.getMessage(Message.OPERATION_FAILED)); - break; - } - sender.sendMessage(messageSettings.getMessage(Message.REMOVED_CUSTOM_COMMAND_SUCCESSFULLY).replace("%command%", command_name)); - } else - sender.sendMessage(messageSettings.getMessage(Message.USAGE_REMCMD)); - } - case "filter" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.filter")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (args.length > 1) { - switch (args[1]) { - case "set" -> { - if (player.isEmpty()) { - sender.sendMessage(messageSettings.getMessage(Message.CONSOLE_CANNOT_USE_COMMAND)); - break; - } - if (!this.api.hasPermission(sender, "astralbooks.command.filter.set")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (args.length > 2) { - String filter_name = args[2]; - if (!this.api.isValidName(filter_name)) { - sender.sendMessage(messageSettings.getMessage(Message.FILTER_NAME_INVALID).replace("%invalid_filter%", filter_name)); - break; - } - if (player.get().getInventory().getItemInMainHand().getType() != Material.WRITTEN_BOOK) { - sender.sendMessage(messageSettings.getMessage(Message.NO_WRITTEN_BOOK_IN_HAND)); - break; - } - if (!this.plugin.getPluginStorage().putFilterBook(filter_name, ((Player) sender).getInventory().getItemInMainHand())) { - sender.sendMessage(messageSettings.getMessage(Message.OPERATION_FAILED)); - break; - } - sender.sendMessage(messageSettings.getMessage(Message.FILTER_SAVED).replace("%filter_name%", filter_name)); - } else - sender.sendMessage(messageSettings.getMessage(Message.USAGE_FILTER_SET)); - } - case "remove" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.filter.remove")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (args.length > 2) { - String filter_name = args[2]; - if (!this.api.isValidName(filter_name)) { - sender.sendMessage(messageSettings.getMessage(Message.FILTER_NAME_INVALID).replace("%invalid_filter%", filter_name)); - break; - } - if (!this.plugin.getPluginStorage().removeFilterBook(filter_name)) { - sender.sendMessage(messageSettings.getMessage(Message.OPERATION_FAILED)); - break; - } - sender.sendMessage(messageSettings.getMessage(Message.FILTER_REMOVED).replace("%filter%", filter_name)); - } else - sender.sendMessage(messageSettings.getMessage(Message.USAGE_FILTER_REMOVE)); - } - case "getbook" -> { - if (player.isEmpty()) { - sender.sendMessage(messageSettings.getMessage(Message.CONSOLE_CANNOT_USE_COMMAND)); - break; - } - if (!this.api.hasPermission(sender, "astralbooks.command.filter.getbook")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - if (args.length > 2) { - String filter_name = args[2]; - if (!this.api.isValidName(filter_name)) { - sender.sendMessage(messageSettings.getMessage(Message.FILTER_NAME_INVALID).replace("%invalid_filter%", filter_name)); - break; - } - if (!this.plugin.getPluginStorage().hasFilterBook(filter_name)) { - sender.sendMessage(messageSettings.getMessage(Message.NO_BOOK_FOR_FILTER)); - break; - } - ItemStack book = this.plugin.getPluginStorage().getFilterBook(filter_name); - player.get().getInventory().addItem(book); - sender.sendMessage(messageSettings.getMessage(Message.BOOK_RECEIVED)); - } else - sender.sendMessage(messageSettings.getMessage(Message.USAGE_FILTER_GETBOOK)); - } - case "list" -> { - if (!this.api.hasPermission(sender, "astralbooks.command.filter.list")) { - sender.sendMessage(messageSettings.getMessage(Message.NO_PERMISSION)); - break; - } - int pageNum = 1; - if (args.length > 2) { - try { - pageNum = Integer.parseInt(args[2]); - } catch (NumberFormatException ex) { - sender.sendMessage(messageSettings.getMessage(Message.USAGE_FILTER_LIST)); - break; - } - } - this.sendFiltersList(sender, pageNum); - } - default -> this.sendFilterHelp(sender); - } - } else - this.sendFilterHelp(sender); - } - default -> { - if (this.api.hasPermission(sender, "astralbooks.command.help")) - this.sendHelp(sender, 0); - else - this.sendAbout(sender); - } - } - } else { - if (this.api.hasPermission(sender, "astralbooks.command.help")) - this.sendHelp(sender, 0); - else - this.sendAbout(sender); - } - return true; - } - - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, String[] args) { - List completions = new ArrayList<>(); - Set commands = new HashSet<>(); - - if (args.length == 1) { - if (this.api.hasPermission(sender, "astralbooks.command")) - commands.add("help"); - if (this.api.hasPermission(sender, "astralbooks.command.npc")) - commands.add("npc"); - if (this.api.hasPermission(sender, "astralbooks.command.setjoin")) - commands.add("setjoin"); - if (this.api.hasPermission(sender, "astralbooks.command.remjoin")) - commands.add("remjoin"); - if (this.api.hasPermission(sender, "astralbooks.command.openbook")) - commands.add("openbook"); - if (this.api.hasPermission(sender, "astralbooks.command.filter")) - commands.add("filter"); - if (this.api.hasPermission(sender, "astralbooks.command.setcmd")) - commands.add("setcmd"); - if (this.api.hasPermission(sender, "astralbooks.command.remcmd")) - commands.add("remcmd"); - if (this.api.hasPermission(sender, "astralbooks.command.forceopen")) - commands.add("forceopen"); - if (this.api.hasPermission(sender, "astralbooks.command.actionitem")) - commands.add("actionitem"); - if (this.api.hasPermission(sender, "astralbooks.command.reload")) - commands.add("reload"); - if (this.api.hasPermission(sender, "astralbooks.command.interaction")) - commands.add("interaction"); - if (this.api.hasPermission(sender, "astralbooks.command.security")) - commands.add("security"); - StringUtil.copyPartialMatches(args[0], commands, completions); - } else if (args.length == 2) { - switch (args[0]) { - case "security" -> { - if (this.api.hasPermission(sender, "astralbooks.command.security.list")) - commands.add("list"); - if (this.api.hasPermission(sender, "astralbooks.command.security.getbook")) - commands.add("getbook"); - } - case "interaction" -> { - if (this.api.hasPermission(sender, "astralbooks.command.interaction.set")) - commands.add("set"); - if (this.api.hasPermission(sender, "astralbooks.command.interaction.remove")) - commands.add("remove"); - } - case "actionitem", "ai" -> { - if (this.api.hasPermission(sender, "astralbooks.command.actionitem.set")) - commands.add("set"); - if (this.api.hasPermission(sender, "astralbooks.command.actionitem.remove")) - commands.add("remove"); - } - case "filter" -> { - if (this.api.hasPermission(sender, "astralbooks.command.filter.set")) - commands.add("set"); - if (this.api.hasPermission(sender, "astralbooks.command.filter.remove")) - commands.add("remove"); - if (this.api.hasPermission(sender, "astralbooks.command.filter.getbook")) - commands.add("getbook"); - if (this.api.hasPermission(sender, "astralbooks.command.filter.list")) - commands.add("list"); - } - case "forceopen" -> { - if (this.api.hasPermission(sender, "astralbooks.command.forceopen")) - commands.addAll(this.plugin.getPluginStorage().getFilterNames()); - } - case "remcmd" -> { - if (this.api.hasPermission(sender, "astralbooks.command.remcmd")) - commands.addAll(this.plugin.getPluginStorage().getCommandFilterNames()); - } - case "npc" -> { - if (this.api.hasPermission(sender, "astralbooks.command.npc.set")) - commands.add("set"); - if (this.api.hasPermission(sender, "astralbooks.command.npc.remove")) - commands.add("remove"); - if (this.api.hasPermission(sender, "astralbooks.command.npc.getbook")) - commands.add("getbook"); - } - case "help" -> { - if (this.api.hasPermission(sender, "astralbooks.command")) - commands.addAll(List.of("1", "2", "3")); - } - } - StringUtil.copyPartialMatches(args[1], commands, completions); - } else if (args.length == 3) { - switch (args[0]) { - case "security" -> { - switch (args[1]) { - case "list" -> { - if (this.api.hasPermission(sender, "astralbooks.command.security.list")) { - commands.addAll(this.getPlayers()); - commands.addAll(this.getOfflinePlayers()); - commands.add("*"); - } - } - case "getbook" -> { - if (this.api.hasPermission(sender, "astralbooks.command.security.getbook")) { - commands.addAll(this.getPlayers()); - commands.addAll(this.getOfflinePlayers()); - commands.add("*"); - } - } - } - } - case "interaction" -> { - switch (args[1]) { - case "set" -> { - if (this.api.hasPermission(sender, "astralbooks.command.interaction.set.block")) - commands.add("block"); - if (this.api.hasPermission(sender, "astralbooks.command.interaction.set.entity")) - commands.add("entity"); - } - case "remove" -> { - if (this.api.hasPermission(sender, "astralbooks.command.interaction.remove.block")) - commands.add("block"); - if (this.api.hasPermission(sender, "astralbooks.command.interaction.remove.entity")) - commands.add("entity"); - } - } - } - case "filter" -> { - if (args[1].equals("remove") || args[1].equals("getbook")) { - if (this.api.hasPermission(sender, "astralbooks.command.filter.remove") - || this.api.hasPermission(sender, "astralbooks.command.filter.getbook")) { - commands.addAll(this.plugin.getPluginStorage().getFilterNames()); - } - } - } - case "forceopen" -> { - if (this.api.hasPermission(sender, "astralbooks.command.forceopen")) { - commands.addAll(this.getPlayers()); - commands.add("*"); - } - } - case "setcmd" -> { - if (this.api.hasPermission(sender, "astralbooks.command.setcmd")) - commands.addAll(this.plugin.getPluginStorage().getFilterNames()); - } - case "actionitem", "ai" -> { - switch (args[1]) { - case "set" -> { - if (this.api.hasPermission(sender, "astralbooks.command.actionitem.set")) - commands.addAll(this.plugin.getPluginStorage().getFilterNames()); - } - case "remove" -> { - if (this.api.hasPermission(sender, "astralbooks.command.actionitem.remove")) - commands.addAll(List.of("right", "left")); - } - } - } - case "npc" -> { - switch (args[1]) { - case "set" -> { - if (this.api.hasPermission(sender, "astralbooks.command.npc.set")) - commands.addAll(List.of("right", "left")); - } - case "remove" -> { - if (this.api.hasPermission(sender, "astralbooks.command.npc.remove")) - commands.addAll(List.of("right", "left")); - } - case "getbook" -> { - if (this.api.hasPermission(sender, "astralbooks.command.npc.getbook")) - commands.addAll(List.of("right", "left")); - } - } - } - } - StringUtil.copyPartialMatches(args[2], commands, completions); - } else if (args.length == 4) { - switch (args[0]) { - case "security" -> { - if (this.api.hasPermission(sender, "astralbooks.command.security.getbook") && "getbook".equalsIgnoreCase(args[1])) { - // this is stupid! - @SuppressWarnings("deprecation") - OfflinePlayer player = Bukkit.getOfflinePlayer(args[2]); - if (player.hasPlayedBefore()) - for (Date date : this.plugin.getPluginStorage().getCache().playerTimestamps.getUnchecked(player.getUniqueId())) - commands.add(String.valueOf(date.getTime())); - } - } - case "actionitem", "ai" -> { - if (this.api.hasPermission(sender, "astralbooks.command.actionitem.set") && "set".equalsIgnoreCase(args[1])) - commands.addAll(List.of("right", "left")); - } - case "interaction" -> { - switch (args[1]) { - case "set" -> { - switch (args[2]) { - case "block" -> { - if (this.api.hasPermission(sender, "astralbooks.command.interaction.set.block")) - commands.addAll(List.of("right", "left")); - } - case "entity" -> { - if (this.api.hasPermission(sender, "astralbooks.command.interaction.set.entity")) - commands.addAll(List.of("right", "left")); - } - } - } - case "remove" -> { - switch (args[2]) { - case "block" -> { - if (this.api.hasPermission(sender, "astralbooks.command.interaction.remove.block")) - commands.addAll(List.of("right", "left")); - } - case "entity" -> { - if (this.api.hasPermission(sender, "astralbooks.command.interaction.remove.entity")) - commands.addAll(List.of("right", "left")); - } - } - } - } - } - } - StringUtil.copyPartialMatches(args[3], commands, completions); - } - Collections.sort(completions); - return completions; - } - - private Set getPlayers() { - return Bukkit.getOnlinePlayers() - .stream() - .map(Player::getName) - .collect(Collectors.toSet()); - } - - private Set getOfflinePlayers() { - return Arrays.stream(Bukkit.getOfflinePlayers()) - .map(OfflinePlayer::getName) - .collect(Collectors.toSet()); - } - - private boolean isPlayer(CommandSender sender) { - return (sender instanceof Player); - } - - private void openBook(Player player, ItemStack book) { - BookMeta meta = (BookMeta) book.getItemMeta(); - ItemStack item = new ItemStack(Material.WRITABLE_BOOK, book.getAmount()); - item.setItemMeta(meta); - player.getInventory().setItemInMainHand(item); - } - - private void closeBook(Player player, ItemStack book, String author, String title) { - BookMeta meta = (BookMeta) book.getItemMeta(); - ItemStack item = new ItemStack(Material.WRITTEN_BOOK, book.getAmount()); - if (meta != null) { - meta.setAuthor(ChatColor.translateAlternateColorCodes('&', author)); - meta.setTitle(ChatColor.translateAlternateColorCodes('&', title)); - item.setItemMeta(meta); - } - player.getInventory().setItemInMainHand(item); - } - - private void sendAbout(CommandSender sender) { - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - sender.sendMessage(""); - sender.sendMessage(ChatColor.RED + "<+ AstralBooks +>"); - sender.sendMessage(ChatColor.GOLD + "Version: " + ChatColor.RED + this.plugin.getDescription().getVersion()); - sender.sendMessage(ChatColor.GOLD + "Auhtor: " + ChatColor.RED + "NicoNekoDev"); - sender.sendMessage(""); - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - } - - private void sendHelp(CommandSender sender, int page) { - MessageSettings messageSettings = this.plugin.getSettings().getMessageSettings(); - if (page < 1 || page > 4) page = 1; - sender.sendMessage(""); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_INFO).replace("%page%", String.valueOf(page))); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_ARGUMENTS)); - sender.sendMessage(""); - if (page == 2) { - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_FILTER_SET).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_FILTER_REMOVE).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_FILTER_GETBOOK).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_FILTER_LIST).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_ACTIONITEM_SET).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_ACTIONITEM_REMOVE).split("\\$")); - } else if (page == 3) { - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_OPENBOOK).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_CLOSEBOOK).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_SETJOIN).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_REMJOIN).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_SETCMD).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_REMCMD).split("\\$")); - } else if (page == 4) { - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_FORCEOPEN).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_HELP).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_RELOAD).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_NPC_SET).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_NPC_REMOVE).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_NPC_GETBOOK).split("\\$")); - } else { - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_INTERACTION_SET_BLOCK).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_INTERACTION_SET_ENTITY).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_INTERACTION_REMOVE_BLOCK).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_INTERACTION_REMOVE_ENTITY).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_ABOUT).split("\\$")); - } - sender.sendMessage(""); - } - - private void sendFilterHelp(CommandSender sender) { - MessageSettings messageSettings = this.plugin.getSettings().getMessageSettings(); - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_ARGUMENTS)); - sender.sendMessage(""); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_FILTER_SET).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_FILTER_REMOVE).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_FILTER_GETBOOK).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_FILTER_LIST).split("\\$")); - sender.sendMessage(""); - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - } - - private void sendActionItemHelp(CommandSender sender) { - MessageSettings messageSettings = this.plugin.getSettings().getMessageSettings(); - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_ARGUMENTS)); - sender.sendMessage(""); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_ACTIONITEM_SET).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_ACTIONITEM_REMOVE).split("\\$")); - sender.sendMessage(""); - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - } - - private void sendNpcHelp(CommandSender sender) { - MessageSettings messageSettings = this.plugin.getSettings().getMessageSettings(); - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_ARGUMENTS)); - sender.sendMessage(""); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_NPC_SET).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_NPC_REMOVE).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_NPC_GETBOOK).split("\\$")); - sender.sendMessage(""); - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - } - - private void sendInteractionSetHelp(CommandSender sender) { - MessageSettings messageSettings = this.plugin.getSettings().getMessageSettings(); - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_ARGUMENTS)); - sender.sendMessage(""); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_INTERACTION_SET_BLOCK).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_INTERACTION_SET_ENTITY).split("\\$")); - sender.sendMessage(""); - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - } - - private void sendInteractionRemoveHelp(CommandSender sender) { - MessageSettings messageSettings = this.plugin.getSettings().getMessageSettings(); - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_ARGUMENTS)); - sender.sendMessage(""); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_INTERACTION_REMOVE_BLOCK).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_INTERACTION_REMOVE_ENTITY).split("\\$")); - sender.sendMessage(""); - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - } - - private void sendInteractionHelp(CommandSender sender) { - MessageSettings messageSettings = this.plugin.getSettings().getMessageSettings(); - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_ARGUMENTS)); - sender.sendMessage(""); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_INTERACTION_SET_BLOCK).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_INTERACTION_SET_ENTITY).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_INTERACTION_REMOVE_BLOCK).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_INTERACTION_REMOVE_ENTITY).split("\\$")); - sender.sendMessage(""); - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - } - - - private void sendSecurityHelp(CommandSender sender) { - MessageSettings messageSettings = this.plugin.getSettings().getMessageSettings(); - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_ARGUMENTS)); - sender.sendMessage(""); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_SECURITY_LIST).split("\\$")); - sender.sendMessage(messageSettings.getMessageNoHeader(Message.HELP_SECURITY_GETBOOK).split("\\$")); - sender.sendMessage(""); - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - } - - private void sendSecurityPage(CommandSender sender, OfflinePlayer player, int page) { - MessageSettings messageSettings = this.plugin.getSettings().getMessageSettings(); - SimpleDateFormat dateFormat; - try { - dateFormat = new SimpleDateFormat(messageSettings.getMessageNoHeader(Message.BOOK_SECURITY_DATE_FORMAT)); - } catch (Exception ex) { - this.plugin.getLogger().warning("The date format for \"book_security_date_format\" is not correctly set. Please check the settings!"); - dateFormat = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss"); - } - LinkedList> securityBooks = this.plugin.getPluginStorage().getAllBookSecurity(player.getUniqueId(), page - 1, 10); - if (securityBooks.isEmpty()) { - sender.sendMessage(messageSettings.getMessage(Message.BOOK_SECURITY_NOT_FOUND)); - return; - } - sender.sendMessage(messageSettings.getMessage(Message.BOOK_SECURITY_LIST_PRESENT).replace("%page%", String.valueOf(page))); - int count = 0; - for (PairTuple securityBook : securityBooks) { - ItemStack book = securityBook.secondValue(); - String title = ""; - if (book.hasItemMeta() && book.getItemMeta() instanceof BookMeta bookMeta && bookMeta.hasTitle()) - title = bookMeta.getTitle(); - sender.sendMessage(messageSettings.parseMessage( - "&c&l " + (((page - 1) * 10) + count + 1) + - ") &f" + player.getName() + - " &e- &f" + dateFormat.format(securityBook.firstValue()) + - " &c(&b" + securityBook.firstValue().getTime() + "&c) &e- &f" + - title - )); - count++; - } - } - - private void sendSecurityPage(CommandSender sender, int page) { - MessageSettings messageSettings = this.plugin.getSettings().getMessageSettings(); - SimpleDateFormat dateFormat; - try { - dateFormat = new SimpleDateFormat(messageSettings.getMessageNoHeader(Message.BOOK_SECURITY_DATE_FORMAT)); - } catch (Exception ex) { - this.plugin.getLogger().warning("The date format for \"book_security_date_format\" is not correctly set. Please check the settings!"); - dateFormat = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss"); - } - LinkedList> securityBooks = this.plugin.getPluginStorage().getAllBookSecurity(page - 1, 10); - if (securityBooks.isEmpty()) { - sender.sendMessage(messageSettings.getMessage(Message.BOOK_SECURITY_NOT_FOUND).replace("%page%", String.valueOf(page))); - return; - } - sender.sendMessage(messageSettings.getMessage(Message.BOOK_SECURITY_LIST_PRESENT)); - int count = 0; - for (TripletTuple securityBook : securityBooks) { - OfflinePlayer player = Bukkit.getOfflinePlayer(securityBook.firstValue()); - ItemStack book = securityBook.thirdValue(); - String title = ""; - if (book.hasItemMeta() && book.getItemMeta() instanceof BookMeta bookMeta && bookMeta.hasTitle()) - title = bookMeta.getTitle(); - sender.sendMessage(messageSettings.parseMessage( - "&c&l " + (((page - 1) * 10) + count + 1) + - ") &f" + player.getName() + - " &e- &f" + dateFormat.format(securityBook.secondValue()) + - " &c(&b" + securityBook.secondValue().getTime() + "&c) &e- &f" + - title - )); - count++; - } - } - - private void sendFiltersList(CommandSender sender, int pageNum) { - MessageSettings messageSettings = this.plugin.getSettings().getMessageSettings(); - LinkedList pages = this.getSplitList(this.plugin.getPluginStorage().getFilterNames()); - if (pages.isEmpty()) { - sender.sendMessage(messageSettings.getMessage(Message.FILTERS_LIST_NO_FILTER_PRESENT)); - return; - } - if (pages.size() < pageNum || pageNum < 1) { - sender.sendMessage(messageSettings.getMessage(Message.FILTERS_LIST_PAGE_NOT_FOUND).replace("%page%", String.valueOf(pageNum))); - return; - } - String[] page = pages.get(pageNum - 1); - sender.sendMessage(messageSettings.getMessage(Message.FILTERS_LIST_PRESENT)); - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - for (int i = 0; i < 10; i++) { - String row = page[i]; - if (row == null) continue; - sender.sendMessage(messageSettings.parseMessage("&c&l " + (((pageNum - 1) * 10) + i + 1) + ") &a" + row)); - } - sender.sendMessage(ChatColor.GRAY + String.valueOf(ChatColor.STRIKETHROUGH) + "+----------------------------------+"); - } - - private LinkedList getSplitList(Collection list) { - LinkedList resultedFilters = new LinkedList<>(); - LinkedList sortedFilters = new LinkedList<>(list); - String pooledResult; - while ((pooledResult = sortedFilters.poll()) != null) { - String[] page = new String[10]; - page[0] = pooledResult; - for (int n = 1; n < 10; n++) { - page[n] = sortedFilters.poll(); - } - resultedFilters.add(page); - } - return resultedFilters; - } -} \ No newline at end of file diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/AstralBooksCore.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/AstralBooksCore.java index 03971c6..2b97655 100644 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/AstralBooksCore.java +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/AstralBooksCore.java @@ -24,16 +24,10 @@ import lombok.Getter; import net.citizensnpcs.api.CitizensAPI; import net.citizensnpcs.api.npc.NPC; -import net.luckperms.api.LuckPerms; -import net.luckperms.api.context.ContextManager; -import net.luckperms.api.model.user.User; -import net.luckperms.api.query.QueryOptions; -import net.milkbowl.vault.permission.Permission; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Material; import org.bukkit.block.Block; -import org.bukkit.command.CommandSender; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -345,28 +339,6 @@ public boolean openBook(Player player, ItemStack book) { return true; } - public boolean hasPermission(CommandSender sender, String permission) { - try { - if (sender.isOp()) return true; - Optional luckPerms = this.plugin.isLuckPermsEnabled() ? Optional.of(this.plugin.getLuckPerms()) : Optional.empty(); //If LuckPerms not enabled, this will return empty - Optional vaultPerms = this.plugin.isVaultEnabled() ? Optional.of(this.plugin.getVaultPerms()) : Optional.empty(); //If vault not enabled or luckperms is used, this will return empty - - return (luckPerms.isPresent() && this.hasLuckPermission(luckPerms.get().getUserManager().getUser(sender.getName()), permission)) || - (vaultPerms.isPresent() && vaultPerms.get().has(sender, permission)) || sender.hasPermission(permission); - } catch (NullPointerException ex) { - return false; - } - } - - protected boolean hasLuckPermission(User user, String permission) { - if (user == null) - throw new NullPointerException(); - ContextManager contextManager = this.plugin.getLuckPerms().getContextManager(); - return user.getCachedData().getPermissionData( - QueryOptions.contextual(contextManager.getContext(user).orElseGet(contextManager::getStaticContext)) - ).checkPermission(permission).asBoolean(); - } - public String encodeItemStack(ItemStack item) { if (item != null && item.getType() != Material.AIR) try { diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/AstralBooksPlugin.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/AstralBooksPlugin.java index 0e7d796..c6416b2 100644 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/AstralBooksPlugin.java +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/AstralBooksPlugin.java @@ -18,42 +18,31 @@ package ro.niconeko.astralbooks; import lombok.Getter; -import me.lucko.commodore.Commodore; -import me.lucko.commodore.CommodoreProvider; -import me.lucko.commodore.file.CommodoreFileReader; -import net.luckperms.api.LuckPerms; import net.milkbowl.vault.permission.Permission; import org.bstats.bukkit.Metrics; import org.bstats.charts.SimplePie; -import org.bukkit.command.PluginCommand; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import ro.niconeko.astralbooks.api.AstralBooks; -import ro.niconeko.astralbooks.listeners.AuthmeActions; -import ro.niconeko.astralbooks.listeners.CitizensActions; +import ro.niconeko.astralbooks.commands.AstralBooksCommand; import ro.niconeko.astralbooks.listeners.PlayerActions; import ro.niconeko.astralbooks.listeners.ServerActions; -import ro.niconeko.astralbooks.settings.PluginSettings; +import ro.niconeko.astralbooks.managers.BossBarManager; +import ro.niconeko.astralbooks.managers.HooksManager; +import ro.niconeko.astralbooks.managers.SettingsManager; import ro.niconeko.astralbooks.storage.PluginStorage; +import ro.niconeko.astralbooks.utils.MessageUtils; import ro.niconeko.astralbooks.utils.PersistentKey; import ro.niconeko.astralbooks.utils.UpdateChecker; +import ro.niconeko.astralbooks.values.Settings; import java.io.File; -import java.io.FileNotFoundException; -import java.io.InputStream; import java.sql.SQLException; -import java.util.List; -import java.util.logging.Level; public class AstralBooksPlugin extends JavaPlugin implements AstralBooks { private final File settingsFile = new File(getDataFolder(), "settings.yml"); @Getter private Permission vaultPerms; - @Getter private LuckPerms luckPerms; @Getter private final AstralBooksCore API = new AstralBooksCore(this); - @Getter private final PluginSettings settings = new PluginSettings(this); @Getter private PluginStorage pluginStorage; @Getter private boolean PlaceholderAPIEnabled, AuthMeEnabled, CitizensEnabled, LuckPermsEnabled, VaultEnabled; @Getter private PlayerActions playerActionsListener; @@ -61,130 +50,55 @@ public class AstralBooksPlugin extends JavaPlugin implements AstralBooks { @Override public void onEnable() { - try { - this.getLogger().info("============== BEGIN LOAD =============="); + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&a============== &fAstralBooks &a============="); - if (!this.API.loadDistribution()) { - this.getLogger().info("Failed to load distribution... disabling the plugin!"); - this.setEnabled(false); - this.getLogger().info("============== END LOAD =============="); - return; - } - if (!PersistentKey.init(this)) { - this.getLogger().info("Failed to load PersistentKey!"); - this.setEnabled(false); - this.getLogger().info("============== END LOAD =============="); - return; - } + if (!this.API.loadDistribution()) { + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "Failed to load distribution... disabling the plugin!"); + this.setEnabled(false); + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&a========================================"); + return; + } + if (!PersistentKey.init(this)) { + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&cFailed to load PersistentKey!"); + this.setEnabled(false); + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&a========================================"); + return; + } - PluginManager manager = this.getServer().getPluginManager(); - if (!manager.isPluginEnabled("LuckPerms")) { - this.getLogger().info("LuckPerms not found!"); - if (!manager.isPluginEnabled("Vault")) - this.getLogger().info("Vault not found!"); - else { - this.getLogger().info("Vault found, try hooking..."); - RegisteredServiceProvider provider = this.getServer().getServicesManager().getRegistration(Permission.class); - if (provider != null) { - this.VaultEnabled = true; - this.vaultPerms = provider.getProvider(); - this.getLogger().info("Successfully hooked into Vault!"); - } else - this.getLogger().info("Failed to hook into Vault!"); - } - } else { - this.getLogger().info("LuckPerms found, try hooking..."); - Plugin plugin = manager.getPlugin("LuckPerms"); - if (plugin != null) { - if (plugin.getDescription().getVersion().startsWith("5")) { - RegisteredServiceProvider provider = this.getServer().getServicesManager().getRegistration(LuckPerms.class); - if (provider != null) { - this.LuckPermsEnabled = true; - this.luckPerms = provider.getProvider(); - if (manager.isPluginEnabled("Vault")) - this.getLogger().info("Vault plugin found, but we'll use LuckPerms!"); - this.getLogger().info("Successfully hooked into LuckPerms!"); - } else - this.getLogger().info("Failed to hook into LuckPerms!"); - } else { - this.getLogger().info("Your LuckPerms version is outdated! :("); - if (manager.isPluginEnabled("Vault")) { - RegisteredServiceProvider provider = this.getServer().getServicesManager().getRegistration(Permission.class); - if (provider != null) { - this.getLogger().info("Vault found instead! Try hooking..."); - this.VaultEnabled = true; - this.vaultPerms = provider.getProvider(); - this.getLogger().info("Successfully hooked into Vault!"); - } else // do we need it? - this.getLogger().info("Failed to hook into Vault!"); - } - } - } else - this.getLogger().info("Failed to hook into LuckPerms!"); - } - if (!manager.isPluginEnabled("PlaceholderAPI")) - this.getLogger().info("PlaceholderAPI not found!"); - else { - this.getLogger().info("PlaceholderAPI found, try hooking..."); - this.PlaceholderAPIEnabled = true; - this.getLogger().info("Successfully hooked into PlaceholderAPI!"); - } - if (!manager.isPluginEnabled("Citizens")) - this.getLogger().info("Citizens not found!"); - else { - this.getLogger().info("Citizens found, try hooking..."); - manager.registerEvents(new CitizensActions(this), this); - this.CitizensEnabled = true; - this.getLogger().info("Successfully hooked into Citizens!"); - } - if (!manager.isPluginEnabled("Authme")) - this.getLogger().info("Authme not found!"); - else { - this.getLogger().info("AuthMe found, try hooking..."); - manager.registerEvents(new AuthmeActions(this), this); - this.AuthMeEnabled = true; - this.getLogger().info("Successfully hooked into AuthMe!"); - } + HooksManager.load(this); + BossBarManager.load(this); - this.playerActionsListener = new PlayerActions(this); - this.serverActionsListener = new ServerActions(this); + this.playerActionsListener = new PlayerActions(this); + this.serverActionsListener = new ServerActions(this); - if (!this.reloadPlugin()) - throw new IllegalStateException("Failed to load settings!"); + if (!this.reloadPlugin()) { + this.setEnabled(false); + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&a========================================"); + return; + } - if (this.settings.isMetricsEnabled()) { - Metrics metrics = new Metrics(this, 18026); - metrics.addCustomChart(new SimplePie("database_type", () -> - switch (this.settings.getStorageSettings().getDatabaseType()) { - case JSON -> "JSON"; - case MYSQL -> "MySQL"; - case SQLITE -> "SQLite"; - case H2 -> "H2"; - case MARIADB -> "MariaDB"; - })); - } + if (Settings.METRICS_ENABLED.get()) { + Metrics metrics = new Metrics(this, 18026); + metrics.addCustomChart(new SimplePie("database_type", () -> + switch (Settings.STORAGE.get().TYPE.get()) { + case JSON -> "JSON"; + case MYSQL -> "MySQL"; + case SQLITE -> "SQLite"; + case H2 -> "H2"; + case MARIADB -> "MariaDB"; + })); + } - manager.registerEvents(this.playerActionsListener, this); - manager.registerEvents(this.serverActionsListener, this); + Bukkit.getPluginManager().registerEvents(this.playerActionsListener, this); + Bukkit.getPluginManager().registerEvents(this.serverActionsListener, this); - PluginCommand astralBooksCommand = this.getCommand("abook"); - if (astralBooksCommand != null) - astralBooksCommand.setExecutor(new AstralBooksCommand(this)); - if (CommodoreProvider.isSupported()) { - this.getLogger().info("Loading Brigardier support..."); - Commodore commodore = CommodoreProvider.getCommodore(this); - this.getLogger().info(" Command /abook: " + (this.registerCompletions(commodore, astralBooksCommand) ? "supported" : "unsupported")); - } else - this.getLogger().info("Brigardier is not supported on this version!"); - //Update checker, by default enabled - if (this.settings.isUpdateCheck()) - manager.registerEvents(new UpdateChecker(this), this); - this.getLogger().info("============== END LOAD =============="); - } catch (Exception ex) { - this.getLogger().log(Level.WARNING, "Error detected, disabling the plugin!", ex); - this.getLogger().info("============== END LOAD =============="); - this.setEnabled(false); - } + // I hate reflections + API.getDistribution().register(new AstralBooksCommand(this)); + + //Update checker, by default enabled + if (Settings.UPDATE_CHECK.get()) + Bukkit.getPluginManager().registerEvents(new UpdateChecker(this), this); + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&a========================================"); } @Override @@ -197,76 +111,16 @@ public void onDisable() { this.pluginStorage.unload(); } - private boolean registerCompletions(Commodore commodore, PluginCommand command) { - if (command == null) - return false; - try (InputStream is = this.getResource("command.commodore")) { - if (is == null) - throw new FileNotFoundException(); - commodore.register(command, CommodoreFileReader.INSTANCE.parse(is), player -> this.API.hasPermission(player, "astralbooks.tab.completer")); - return true; - } catch (Exception ex) { - return false; - } - } - - public boolean loadSettings() { - try { - YamlConfiguration config = YamlConfiguration.loadConfiguration(this.settingsFile); - config.options().setHeader( - List.of(""" - _ _ ____ _ \s - /\\ | | | | _ \\ | | \s - / \\ ___| |_ _ __ __ _| | |_) | ___ ___ | | _____\s - / /\\ \\ / __| __| '__/ _` | | _ < / _ \\ / _ \\| |/ / __| - / ____ \\\\__ \\ |_| | | (_| | | |_) | (_) | (_) | <\\__ \\ - /_/ \\_\\___/\\__|_| \\__,_|_|____/ \\___/ \\___/|_|\\_\\___/ - \s - \s - """.split("\n")) - ); - this.settings.load(config); - return true; - } catch (Exception ex) { - this.getLogger().log(Level.WARNING, "Failed to load settings", ex); - return false; - } - } - - public boolean saveSettings() { - try { - YamlConfiguration config = new YamlConfiguration(); - this.settings.load(config); - config.options().setHeader( - List.of(""" - _ _ ____ _ \s - /\\ | | | | _ \\ | | \s - / \\ ___| |_ _ __ __ _| | |_) | ___ ___ | | _____\s - / /\\ \\ / __| __| '__/ _` | | _ < / _ \\ / _ \\| |/ / __| - / ____ \\\\__ \\ |_| | | (_| | | |_) | (_) | (_) | <\\__ \\ - /_/ \\_\\___/\\__|_| \\__,_|_|____/ \\___/ \\___/|_|\\_\\___/ - \s - \s - """.split("\n")) - ); - config.save(this.settingsFile); - return true; - } catch (Exception ex) { - this.getLogger().log(Level.WARNING, "Failed to save settings", ex); - return false; - } - } - public boolean reloadPlugin() { - if (this.loadSettings()) { - this.saveSettings(); + if (SettingsManager.loadAndSave(this)) { try { if (this.pluginStorage != null) this.pluginStorage.unload(); this.pluginStorage = new PluginStorage(this); - this.pluginStorage.load(this.settings.getStorageSettings()); + this.pluginStorage.load(Settings.STORAGE.get()); } catch (SQLException ex) { - this.getLogger().log(Level.SEVERE, "Could not load storage!", ex); + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&cFailed to load storage!"); + ex.printStackTrace(); return false; } if (this.playerActionsListener != null) diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/commands/AstralBooksCommand.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/commands/AstralBooksCommand.java new file mode 100644 index 0000000..bacbd94 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/commands/AstralBooksCommand.java @@ -0,0 +1,18 @@ +package ro.niconeko.astralbooks.commands; + +import ro.niconeko.astralbooks.AstralBooksPlugin; +import ro.niconeko.astralbooks.commands.subs.HelpCommand; +import ro.niconeko.astralbooks.commands.subs.ReloadCommand; +import ro.niconeko.astralbooks.values.Messages; +import ro.niconeko.astralbooks.values.Permissions; + +public class AstralBooksCommand extends AstralCommand { + public AstralBooksCommand(AstralBooksPlugin plugin) { + super(plugin, "abooks", Permissions.COMMAND); + super.then(new ReloadCommand(plugin)) + .then(new HelpCommand(plugin)) + // etc... + .then(super.greedyArgument("unknown").executes(context -> Messages.COMMAND_MAIN_UNKNOWN.send(getSender(context), replaceable(context, "%command%", "unknown")))); + super.executes(context -> Messages.COMMAND_MAIN_HELP.send(getSender(context))); + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/commands/AstralCommand.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/commands/AstralCommand.java new file mode 100644 index 0000000..a06ff3d --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/commands/AstralCommand.java @@ -0,0 +1,68 @@ +package ro.niconeko.astralbooks.commands; + +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.suggestion.SuggestionProvider; +import net.minecraft.commands.CommandListenerWrapper; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; +import ro.niconeko.astralbooks.AstralBooksPlugin; +import ro.niconeko.astralbooks.utils.Permission; +import ro.niconeko.astralbooks.utils.Replaceable; + +import java.util.ArrayList; +import java.util.List; + +import static com.mojang.brigadier.arguments.IntegerArgumentType.integer; +import static com.mojang.brigadier.arguments.StringArgumentType.greedyString; +import static com.mojang.brigadier.arguments.StringArgumentType.string; + +public abstract class AstralCommand extends LiteralArgumentBuilder { + protected final AstralBooksPlugin plugin; + + protected AstralCommand(AstralBooksPlugin plugin, String literal, Permission permission) { + super(literal); + super.requires(sender -> permission.has(sender.getBukkitSender())); + this.plugin = plugin; + } + + protected RequiredArgumentBuilder integerArgument(String name) { + return RequiredArgumentBuilder.argument(name, integer()); + } + + protected RequiredArgumentBuilder greedyArgument(String name) { + return RequiredArgumentBuilder.argument(name, greedyString()); + } + + protected RequiredArgumentBuilder stringArgument(String name) { + return RequiredArgumentBuilder.argument(name, string()); + } + + protected CommandSender getSender(CommandContext context) { + return context.getSource().getBukkitSender(); + } + + protected SuggestionProvider integerRange(int min, int max) { + return (context, builder) -> { + List rangeList = new ArrayList<>(); + for (int i = min; i <= max; i++) + rangeList.add(i + ""); + for (String str : StringUtil.copyPartialMatches(builder.getInput(), rangeList, new ArrayList<>())) + builder.suggest(str); + return builder.buildFuture(); + }; + } + + protected SuggestionProvider stringRange(List list) { + return (context, builder) -> { + for (String str : StringUtil.copyPartialMatches(builder.getInput(), list, new ArrayList<>())) + builder.suggest(str); + return builder.buildFuture(); + }; + } + + protected Replaceable replaceable(CommandContext context, String str, String value) { + return new Replaceable(context, str, value); + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/commands/subs/HelpCommand.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/commands/subs/HelpCommand.java new file mode 100644 index 0000000..89176e1 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/commands/subs/HelpCommand.java @@ -0,0 +1,39 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.commands.subs; + +import ro.niconeko.astralbooks.AstralBooksPlugin; +import ro.niconeko.astralbooks.commands.AstralCommand; +import ro.niconeko.astralbooks.values.Messages; +import ro.niconeko.astralbooks.values.Permissions; + +import static com.mojang.brigadier.arguments.IntegerArgumentType.getInteger; + +public class HelpCommand extends AstralCommand { + public HelpCommand(AstralBooksPlugin plugin) { + super(plugin, "help", Permissions.COMMAND_HELP); + super.then(super.integerArgument("page").suggests(super.integerRange(1, Messages.COMMAND_HELP_LIST.get().size())).executes(context -> { + int page = getInteger(context, "page"); + if (page < 1 || page > Messages.COMMAND_HELP_LIST.get().size()) + return Messages.COMMAND_HELP_INVALID_PAGE.send(getSender(context), replaceable(context, "%page%", page + "")); + return Messages.COMMAND_HELP_LIST.send(getSender(context), page - 1, replaceable(context, "%page%", page + "")); + })) + .then(super.greedyArgument("unknown").executes(context -> Messages.COMMAND_MAIN_UNKNOWN.send(getSender(context), replaceable(context, "%command%", "unknown")))); + super.executes(context -> Messages.COMMAND_HELP_USAGE.send(getSender(context))); + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/commands/subs/ReloadCommand.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/commands/subs/ReloadCommand.java new file mode 100644 index 0000000..3e3ee51 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/commands/subs/ReloadCommand.java @@ -0,0 +1,33 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.commands.subs; + +import ro.niconeko.astralbooks.AstralBooksPlugin; +import ro.niconeko.astralbooks.commands.AstralCommand; +import ro.niconeko.astralbooks.values.Messages; +import ro.niconeko.astralbooks.values.Permissions; + +public class ReloadCommand extends AstralCommand { + public ReloadCommand(AstralBooksPlugin plugin) { + super(plugin, "reload", Permissions.COMMAND_RELOAD); + super.executes(context -> { + plugin.reloadPlugin(); + return Messages.CONFIG_RELOADED.send(getSender(context)); + }); + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/dist/Distribution.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/dist/Distribution.java index b96089e..b7e0cd6 100644 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/dist/Distribution.java +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/dist/Distribution.java @@ -19,6 +19,7 @@ import com.google.gson.Gson; import com.google.gson.JsonObject; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; import me.clip.placeholderapi.PlaceholderAPI; import net.citizensnpcs.api.npc.NPC; import org.bukkit.configuration.ConfigurationSection; @@ -75,6 +76,8 @@ protected final List placeholders(Player player, List strList, O } } + public abstract void register(LiteralArgumentBuilder builder); + public abstract String getVersion(); @SuppressWarnings("OptionalUsedAsFieldOrParameterType") diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/hooks/AuthMeHook.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/hooks/AuthMeHook.java new file mode 100644 index 0000000..de6695f --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/hooks/AuthMeHook.java @@ -0,0 +1,36 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.hooks; + +import org.bukkit.Bukkit; +import ro.niconeko.astralbooks.AstralBooksPlugin; +import ro.niconeko.astralbooks.listeners.AuthmeActions; +import ro.niconeko.astralbooks.utils.MessageUtils; + +public class AuthMeHook extends Hook { + @Override + public void load(AstralBooksPlugin plugin) { + if (Bukkit.getPluginManager().isPluginEnabled("Authme")) { + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&aAuthme found! &eTrying to hook into it..."); + Bukkit.getPluginManager().registerEvents(new AuthmeActions(plugin), plugin); + super.enabled = true; + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&aSuccessfully hooked into Authme!"); + } else + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&cAuthme not found!"); + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/hooks/CitizensHook.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/hooks/CitizensHook.java new file mode 100644 index 0000000..0ead137 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/hooks/CitizensHook.java @@ -0,0 +1,38 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.hooks; + +import org.bukkit.Bukkit; +import ro.niconeko.astralbooks.AstralBooksPlugin; +import ro.niconeko.astralbooks.listeners.CitizensActions; +import ro.niconeko.astralbooks.utils.MessageUtils; + +public class CitizensHook extends Hook { + + @Override + public void load(AstralBooksPlugin plugin) { + // Load Vault + if (Bukkit.getPluginManager().isPluginEnabled("Citizens")) { + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&aCitizens found! &eTrying to hook into it..."); + Bukkit.getPluginManager().registerEvents(new CitizensActions(plugin), plugin); + super.enabled = true; + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&aSuccessfully hooked into Citizens!"); + } else + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&cCitizens not found!"); + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/hooks/Hook.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/hooks/Hook.java new file mode 100644 index 0000000..34dda73 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/hooks/Hook.java @@ -0,0 +1,29 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.hooks; + +import ro.niconeko.astralbooks.AstralBooksPlugin; + +public abstract class Hook { + protected boolean enabled = false; + public abstract void load(AstralBooksPlugin plugin); + + public final boolean isEnabled() { + return this.enabled; + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/hooks/PermissionsHook.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/hooks/PermissionsHook.java new file mode 100644 index 0000000..2568bd0 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/hooks/PermissionsHook.java @@ -0,0 +1,49 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.hooks; + +import net.milkbowl.vault.permission.Permission; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.RegisteredServiceProvider; +import ro.niconeko.astralbooks.AstralBooksPlugin; +import ro.niconeko.astralbooks.utils.MessageUtils; + +public class PermissionsHook extends Hook { + private Permission permissions; + + @Override + public void load(AstralBooksPlugin plugin) { + // Load Vault + if (Bukkit.getPluginManager().isPluginEnabled("Vault")) { + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&aVault found! &eTrying to hook into it..."); + RegisteredServiceProvider provider = plugin.getServer().getServicesManager().getRegistration(Permission.class); + if (provider != null) { + super.enabled = true; + this.permissions = provider.getProvider(); + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&aSuccessfully hooked into Vault!"); + } else + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&cFailed to hook into Vault!"); + } else + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&cVault not found!"); + } + + public boolean hasPermission(CommandSender sender, String permission) { + return this.permissions.has(sender, permission); + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/hooks/PlaceholderAPIHook.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/hooks/PlaceholderAPIHook.java new file mode 100644 index 0000000..8316270 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/hooks/PlaceholderAPIHook.java @@ -0,0 +1,57 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.hooks; + +import me.clip.placeholderapi.PlaceholderAPI; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import ro.niconeko.astralbooks.AstralBooksPlugin; +import ro.niconeko.astralbooks.utils.MessageUtils; + +import java.util.List; +import java.util.function.Function; +import java.util.function.Supplier; + +public class PlaceholderAPIHook extends Hook { + + @Override + public void load(AstralBooksPlugin plugin) { + if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&aPlaceholderAPI found! &eTrying to hook into it..."); + super.enabled = true; + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&aPlaceholderAPI hooked into PlaceholderAPI!"); + } else + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&cPlaceholderAPI not found!"); + } + + public Function> parseList(List list) { + return player -> PlaceholderAPI.setPlaceholders(player, list); + } + + public Function parse(String string) { + return player -> PlaceholderAPI.setPlaceholders(player, string); + } + + public Supplier> parseListSup(List list) { + return () -> PlaceholderAPI.setPlaceholders(null, list); + } + + public Supplier parseSup(String string) { + return () -> PlaceholderAPI.setPlaceholders(null, string); + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/listeners/AuthmeActions.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/listeners/AuthmeActions.java index 5494968..4877780 100644 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/listeners/AuthmeActions.java +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/listeners/AuthmeActions.java @@ -23,6 +23,8 @@ import org.bukkit.event.Listener; import ro.niconeko.astralbooks.AstralBooksCore; import ro.niconeko.astralbooks.AstralBooksPlugin; +import ro.niconeko.astralbooks.values.Permissions; +import ro.niconeko.astralbooks.values.Settings; @SuppressWarnings("unused") public class AuthmeActions implements Listener { @@ -36,14 +38,14 @@ public AuthmeActions(AstralBooksPlugin plugin) { @EventHandler public void onLogin(LoginEvent event) { - if (!this.plugin.getSettings().isJoinBookEnabled()) + if (!Settings.JOIN_BOOK_ENABLED.get()) return; if (!this.plugin.getPluginStorage().hasJoinBook()) return; Player player = event.getPlayer(); - if (this.api.hasPermission(player, "astralbooks.nojoinbook")) + if (Permissions.NO_JOIN_BOOK.has(player)) return; - if (!this.plugin.getSettings().isJoinBookAlwaysShow()) { + if (!Settings.JOIN_BOOK_ALWAYS_SHOW.get()) { if (this.plugin.getPluginStorage().hasJoinBookLastSeen(player)) if (this.plugin.getPluginStorage().getJoinBookLastSeen(player) >= this.plugin.getPluginStorage().getJoinBookLastChange()) return; diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/listeners/PlayerActions.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/listeners/PlayerActions.java index 5310654..1f30dbc 100644 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/listeners/PlayerActions.java +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/listeners/PlayerActions.java @@ -38,10 +38,12 @@ import org.jetbrains.annotations.NotNull; import ro.niconeko.astralbooks.AstralBooksCore; import ro.niconeko.astralbooks.AstralBooksPlugin; -import ro.niconeko.astralbooks.utils.Message; import ro.niconeko.astralbooks.utils.PersistentKey; import ro.niconeko.astralbooks.utils.Side; import ro.niconeko.astralbooks.utils.tuples.PairTuple; +import ro.niconeko.astralbooks.values.Messages; +import ro.niconeko.astralbooks.values.Permissions; +import ro.niconeko.astralbooks.values.Settings; import java.util.Date; import java.util.HashMap; @@ -96,11 +98,11 @@ public void onReload() { DelayedPlayer delayedInteractionBookEntityOperator; while ((delayedInteractionBookEntityOperator = this.delayedInteractionBookEntityOperators.poll()) != null) this.interactionBookEntityOperatorsMap.remove(delayedInteractionBookEntityOperator.getPlayer()); - if (this.plugin.getSettings().isJoinBookEnabled()) { + if (Settings.JOIN_BOOK_ENABLED.get()) { DelayedPlayer delayedJoinPlayer; while ((delayedJoinPlayer = this.delayedJoinBookPlayers.poll()) != null) { Player player = delayedJoinPlayer.getPlayer(); - if (!this.plugin.getSettings().isJoinBookAlwaysShow()) { + if (!Settings.JOIN_BOOK_ALWAYS_SHOW.get()) { if (this.plugin.getPluginStorage().hasJoinBookLastSeen(player)) if (this.plugin.getPluginStorage().getJoinBookLastSeen(player) >= this.plugin.getPluginStorage().getJoinBookLastChange()) continue; @@ -127,22 +129,22 @@ public void onInteract(PlayerInteractEvent event) { event.setCancelled(true); if (pair.firstValue() == null) { this.api.removeBookOfBlock(block, pair.secondValue()); - event.getPlayer().sendMessage(this.plugin.getSettings().getMessageSettings().getMessage(Message.BOOK_REMOVED_SUCCESSFULLY_FROM_BLOCK) - .replace("%player%", event.getPlayer().getName()) - .replace("%block_x%", String.valueOf(block.getX())) - .replace("%block_y%", String.valueOf(block.getY())) - .replace("%block_z%", String.valueOf(block.getZ())) - .replace("%world%", block.getWorld().getName()) - .replace("%type%", block.getType().name())); + Messages.BOOK_REMOVED_SUCCESSFULLY_FROM_BLOCK.send(event.getPlayer(), str -> + str.replace("%player%", event.getPlayer().getName()) + .replace("%block_x%", String.valueOf(block.getX())) + .replace("%block_y%", String.valueOf(block.getY())) + .replace("%block_z%", String.valueOf(block.getZ())) + .replace("%world%", block.getWorld().getName()) + .replace("%type%", block.getType().name())); } else { this.api.putBookOnBlock(block, pair.firstValue(), pair.secondValue()); - event.getPlayer().sendMessage(this.plugin.getSettings().getMessageSettings().getMessage(Message.BOOK_APPLIED_SUCCESSFULLY_TO_BLOCK) - .replace("%player%", event.getPlayer().getName()) - .replace("%block_x%", String.valueOf(block.getX())) - .replace("%block_y%", String.valueOf(block.getY())) - .replace("%block_z%", String.valueOf(block.getZ())) - .replace("%world%", block.getWorld().getName()) - .replace("%type%", block.getType().name())); + Messages.BOOK_APPLIED_SUCCESSFULLY_TO_BLOCK.send(event.getPlayer(), str -> + str.replace("%player%", event.getPlayer().getName()) + .replace("%block_x%", String.valueOf(block.getX())) + .replace("%block_y%", String.valueOf(block.getY())) + .replace("%block_z%", String.valueOf(block.getZ())) + .replace("%world%", block.getWorld().getName()) + .replace("%type%", block.getType().name())); } } else if (event.hasItem()) { ItemStack item = event.getItem(); @@ -188,7 +190,7 @@ public void onInteract(PlayerInteractAtEntityEvent event) { if (this.interactionBookEntityOperatorsMap.containsKey(event.getPlayer()) && !event.getPlayer().isSneaking()) { if (this.plugin.isCitizensEnabled()) { if (CitizensAPI.getNPCRegistry().isNPC(entity)) { - event.getPlayer().sendMessage(this.plugin.getSettings().getMessageSettings().getMessage(Message.ENTITY_IS_NPC)); + Messages.ENTITY_IS_NPC.send(event.getPlayer()); event.setCancelled(true); return; } @@ -196,18 +198,14 @@ public void onInteract(PlayerInteractAtEntityEvent event) { PairTuple pair = this.interactionBookEntityOperatorsMap.remove(event.getPlayer()); if (pair.firstValue() == null) { this.api.removeBookOfEntity(entity, pair.secondValue()); - event.getPlayer().sendMessage(this.plugin.getSettings().getMessageSettings().getMessage(Message.BOOK_REMOVED_SUCCESSFULLY_FROM_ENTITY) - .replace("%player%", event.getPlayer().getName()) - .replace("%type%", entity.getType().name()) - ); + Messages.BOOK_REMOVED_SUCCESSFULLY_FROM_ENTITY.send(event.getPlayer(), + str -> str.replace("%player%", event.getPlayer().getName()).replace("%type%", entity.getType().name())); event.setCancelled(true); return; } this.api.putBookOnEntity(entity, pair.firstValue(), pair.secondValue()); - event.getPlayer().sendMessage(this.plugin.getSettings().getMessageSettings().getMessage(Message.BOOK_APPLIED_SUCCESSFULLY_TO_ENTITY) - .replace("%player%", event.getPlayer().getName()) - .replace("%type%", entity.getType().name()) - ); + Messages.BOOK_APPLIED_SUCCESSFULLY_TO_ENTITY.send(event.getPlayer(), + str -> str.replace("%player%", event.getPlayer().getName()).replace("%type%", entity.getType().name())); event.setCancelled(true); return; } @@ -278,10 +276,10 @@ public void onCommand(PlayerCommandPreprocessEvent event) { PairTuple filter = this.plugin.getPluginStorage().getCommandFilter(command); String filterName = filter.firstValue(); String permission = filter.secondValue() != null && !filter.secondValue().isEmpty() ? filter.secondValue() : "none"; - if (!("none".equalsIgnoreCase(permission) || this.api.hasPermission(player, permission))) + if (!("none".equalsIgnoreCase(permission) || Permissions.has(player, permission))) return; if (!this.plugin.getPluginStorage().hasFilterBook(filterName)) { - player.sendMessage(this.plugin.getSettings().getMessageSettings().getMessage(Message.NO_BOOK_FOR_FILTER)); + Messages.NO_BOOK_FOR_FILTER.send(player); return; } ItemStack book = this.plugin.getPluginStorage().getFilterBook(filterName); @@ -292,15 +290,15 @@ public void onCommand(PlayerCommandPreprocessEvent event) { public void onJoin(PlayerJoinEvent event) { if (this.plugin.isAuthMeEnabled()) return; - if (!this.plugin.getSettings().isJoinBookEnabled()) + if (!Settings.JOIN_BOOK_ENABLED.get()) return; if (!this.plugin.getPluginStorage().hasJoinBook()) return; Player player = event.getPlayer(); - if (this.api.hasPermission(player, "astralbooks.nojoinbook")) + if (Permissions.NO_JOIN_BOOK.has(player)) return; - if (this.plugin.getSettings().isJoinBookEnableDelay()) { - int delay = this.plugin.getSettings().getJoinBookDelay(); + if (Settings.JOIN_BOOK_DELAY_ENABLED.get()) { + int delay = Settings.JOIN_BOOK_DELAY.get(); if (delay <= 0) delay = 0; this.delayedJoinBookPlayers.offer(new DelayedPlayer(player, delay * 50L)); // delay (ticks) * 50 (milliseconds) @@ -310,16 +308,16 @@ public void onJoin(PlayerJoinEvent event) { @EventHandler public void onQuit(PlayerQuitEvent event) { - if (!this.plugin.getSettings().isJoinBookEnabled()) + if (!Settings.JOIN_BOOK_ENABLED.get()) return; - if (this.plugin.getSettings().isJoinBookEnableDelay()) + if (Settings.JOIN_BOOK_DELAY_ENABLED.get()) //noinspection ResultOfMethodCallIgnored this.delayedJoinBookPlayers.remove(new DelayedPlayer(event.getPlayer(), 0)); } @EventHandler public void onBookSign(PlayerEditBookEvent event) { - if (!this.plugin.getSettings().isBookSignSecurityEnabled()) + if (!Settings.SIGN_BOOK_SECURITY_ENABLED.get()) return; if (!event.isSigning()) return; diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/managers/BossBarManager.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/managers/BossBarManager.java new file mode 100644 index 0000000..486f84f --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/managers/BossBarManager.java @@ -0,0 +1,94 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.managers; + +import org.bukkit.Bukkit; +import org.bukkit.boss.BossBar; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitTask; +import ro.niconeko.astralbooks.AstralBooksPlugin; +import ro.niconeko.astralbooks.utils.BossBarConfig; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.function.Function; + +public class BossBarManager { + private static final List players = new ArrayList<>(); + private static BukkitTask task; + + public static void load(AstralBooksPlugin plugin) { + if (task != null) + task.cancel(); + task = Bukkit.getScheduler().runTaskTimer(plugin, () -> { + Iterator iter = players.iterator(); + while (iter.hasNext()) { + if (!iter.next().tick()) + continue; + iter.remove(); + } + }, 1, 1); + } + + public static void sendBossBar(Player player, BossBarConfig config, Function message) { + players.add(new BossBarPlayer(player, config, message)); + } + + public static class BossBarPlayer { + private final Player player; + private final BossBar bar; + private final Function message; + private int fadeIn, stay, fadeOut; + private final int fadeInTotal, fadeOutTotal; + private final double maxProgress; + + public BossBarPlayer(Player player, BossBarConfig config, Function message) { + this.player = player; + this.message = message; + this.fadeInTotal = this.fadeIn = config.getIn(); + this.stay = config.getStay(); + this.fadeOutTotal = this.fadeOut = config.getOut(); + this.maxProgress = config.getProgress(); + this.bar = Bukkit.createBossBar(this.message.apply(this.player), config.getBarColor(), config.getBarStyle()); + } + + public boolean tick() { // return 'true' if ended + this.bar.setTitle(this.message.apply(player)); + if (this.fadeIn > 0) { + this.fadeIn--; + this.bar.setProgress((((this.fadeInTotal - (double) this.fadeIn) / this.fadeInTotal) * maxProgress) / 100); + this.bar.addPlayer(this.player); + return false; + } else if (this.stay > 0) { + this.stay--; + this.bar.setProgress(maxProgress / 100); + this.bar.addPlayer(this.player); + return false; + } else if (this.fadeOut > 0) { + this.fadeOut--; + this.bar.setProgress(((this.fadeOut / (double) this.fadeOutTotal) * maxProgress) / 100); + this.bar.addPlayer(this.player); + return false; + } else { + this.bar.removeAll(); + return true; + } + } + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/managers/HooksManager.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/managers/HooksManager.java new file mode 100644 index 0000000..2f63e0d --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/managers/HooksManager.java @@ -0,0 +1,38 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.managers; + +import ro.niconeko.astralbooks.AstralBooksPlugin; +import ro.niconeko.astralbooks.hooks.AuthMeHook; +import ro.niconeko.astralbooks.hooks.CitizensHook; +import ro.niconeko.astralbooks.hooks.PermissionsHook; +import ro.niconeko.astralbooks.hooks.PlaceholderAPIHook; + +public class HooksManager { + public final static PlaceholderAPIHook PAPI = new PlaceholderAPIHook(); + public final static PermissionsHook PERMISSIONS = new PermissionsHook(); + public final static AuthMeHook AUTHME = new AuthMeHook(); + public final static CitizensHook CITIZENS = new CitizensHook(); + + public static void load(AstralBooksPlugin plugin) { + PAPI.load(plugin); + PERMISSIONS.load(plugin); + AUTHME.load(plugin); + CITIZENS.load(plugin); + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/managers/SettingsManager.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/managers/SettingsManager.java new file mode 100644 index 0000000..9eec0a0 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/managers/SettingsManager.java @@ -0,0 +1,69 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.managers; + +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import ro.niconeko.astralbooks.AstralBooksPlugin; +import ro.niconeko.astralbooks.utils.settings.Setting; +import ro.niconeko.astralbooks.values.Messages; +import ro.niconeko.astralbooks.values.Settings; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.List; + +public class SettingsManager { + + public static boolean loadAndSave(AstralBooksPlugin plugin) { + try { + final File settingsFile = new File(plugin.getDataFolder(), "settings.yml"); + final YamlConfiguration settings = YamlConfiguration.loadConfiguration(settingsFile); + loadValues(settings, Settings.class); + settings.options().setHeader(List.of(""" + _ _ ____ _ \s + /\\ | | | | _ \\ | | \s + / \\ ___| |_ _ __ __ _| | |_) | ___ ___ | | _____\s + / /\\ \\ / __| __| '__/ _` | | _ < / _ \\ / _ \\| |/ / __| + / ____ \\\\__ \\ |_| | | (_| | | |_) | (_) | (_) | <\\__ \\ + /_/ \\_\\___/\\__|_| \\__,_|_|____/ \\___/ \\___/|_|\\_\\___/ + \s + \s + """.split("\n"))); + settings.save(settingsFile); + // + final File messagesFile = new File(plugin.getDataFolder(), "messages.yml"); + final YamlConfiguration messages = YamlConfiguration.loadConfiguration(messagesFile); + loadValues(messages, Messages.class); + messages.save(messagesFile); + + return true; + } catch (IOException | IllegalAccessException ex) { + ex.printStackTrace(); + return false; + } + } + + public static void loadValues(ConfigurationSection section, Class clazz) throws IllegalAccessException { + for (Field field : clazz.getDeclaredFields()) { + if (field.get(null) instanceof Setting setting) + setting.load(section); + } + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/settings/MessageSettings.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/settings/MessageSettings.java deleted file mode 100644 index c837e03..0000000 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/settings/MessageSettings.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * CitizensBooks - * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ro.niconeko.astralbooks.settings; - -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; -import ro.niconeko.astralbooks.AstralBooksPlugin; -import ro.niconeko.astralbooks.utils.Message; - -public class MessageSettings extends Settings { - private ConfigurationSection section = new YamlConfiguration(); - - public MessageSettings(AstralBooksPlugin plugin) { - super(plugin); - } - - @Override - public void load(ConfigurationSection section) { - this.section = section; - for (Message msg : Message.values()) - super.getOrSetStringFunction(section, msg.getPath(), msg.getDefault(), msg.getComments()); - } - - public String getMessage(Message msg) { - return super.parseMessage(this.section.getString(Message.HEADER.getPath(), Message.HEADER.getDefault())) - + super.parseMessage(this.section.getString(msg.getPath(), msg.getDefault())); - } - - public String getMessageNoHeader(Message msg) { - return super.parseMessage(this.section.getString(msg.getPath(), msg.getPath())); - } -} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/settings/PluginSettings.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/settings/PluginSettings.java deleted file mode 100644 index ec3695a..0000000 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/settings/PluginSettings.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * CitizensBooks - * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ro.niconeko.astralbooks.settings; - -import lombok.Getter; -import lombok.NonNull; -import lombok.Setter; -import org.bukkit.configuration.ConfigurationSection; -import ro.niconeko.astralbooks.AstralBooksPlugin; -import ro.niconeko.astralbooks.storage.settings.StorageSettings; - -import java.util.List; -import java.util.Optional; - -@Getter -public class PluginSettings extends Settings { - private boolean metricsEnabled = true; - private boolean updateCheck = true; - @Setter private boolean joinBookEnabled = false; - private boolean joinBookAlwaysShow = false; - private boolean joinBookEnableDelay = false; - private int joinBookDelay = 0; - private boolean bookSignSecurityEnabled = false; - - public PluginSettings(AstralBooksPlugin plugin) { - super(plugin); - } - - @Override - public void load(ConfigurationSection section) { - this.metricsEnabled = super.getOrSetBooleanFunction(section, "metrics", this.metricsEnabled, Optional.of(List.of( - "Metrics can be viewed at https://bstats.org/plugin/bukkit/AstralBooks/18026", - "It requires server restart to take effect!" - ))); - this.updateCheck = super.getOrSetBooleanFunction(section, "update_check", this.updateCheck); - this.joinBookEnabled = super.getOrSetBooleanFunction(section, "join_book_enabled", this.joinBookEnabled); - this.joinBookAlwaysShow = super.getOrSetBooleanFunction(section, "join_book_always_show", this.joinBookAlwaysShow); - this.joinBookEnableDelay = super.getOrSetBooleanFunction(section, "join_book_enable_delay", this.joinBookEnableDelay); - this.joinBookDelay = super.getOrSetIntFunction(section, "join_book_delay", this.joinBookDelay); - this.bookSignSecurityEnabled = super.getOrSetBooleanFunction(section, "sign_book_enable_security", this.bookSignSecurityEnabled, Optional.of(List.of( - "Logs every signed book on the server.", - "Works on 1.18+ servers." - ))); - this.storageSettings.load(super.getOrCreateSection(section, "storage")); - this.messageSettings.load(super.getOrCreateSection(section, "messages")); - } - - @NonNull - private final StorageSettings storageSettings = new StorageSettings(super.plugin); - - @NonNull - private final MessageSettings messageSettings = new MessageSettings(super.plugin); -} \ No newline at end of file diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/settings/Settings.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/settings/Settings.java deleted file mode 100644 index 27f5d90..0000000 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/settings/Settings.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * CitizensBooks - * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ro.niconeko.astralbooks.settings; - -import org.bukkit.ChatColor; -import org.bukkit.configuration.ConfigurationSection; -import ro.niconeko.astralbooks.AstralBooksPlugin; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Optional; - -@SuppressWarnings("OptionalUsedAsFieldOrParameterType") -public abstract class Settings { - protected final AstralBooksPlugin plugin; - - public Settings(AstralBooksPlugin plugin) { - this.plugin = plugin; - } - - public abstract void load(ConfigurationSection section); - - public final String parseMessage(String msg) { - return ChatColor.translateAlternateColorCodes('&', msg); - } - - public final ConfigurationSection getOrCreateSection(ConfigurationSection config, String path) { - return getOrCreateSection(config, path, Optional.empty()); - } - - public final ConfigurationSection getOrCreateSection(ConfigurationSection config, String path, Optional> comments) { - ConfigurationSection value = config.isConfigurationSection(path) ? config.getConfigurationSection(path) : config.createSection(path); - this.plugin.getAPI().getDistribution().setConfigComment(config, path, comments); - return value; - } - - public final String getOrSetStringFunction(ConfigurationSection config, String path, String defaultValue) { - return getOrSetStringFunction(config, path, defaultValue, Optional.empty()); - } - - public final String getOrSetStringFunction(ConfigurationSection config, String path, String defaultValue, Optional> comments) { - String value = defaultValue; - if (config.isString(path)) { - value = config.getString(path); - } else { - config.set(path, value); - this.plugin.getAPI().getDistribution().setConfigComment(config, path, comments); - } - return value; - } - - public final int getOrSetIntFunction(ConfigurationSection config, String path, int defaultValue) { - return getOrSetIntFunction(config, path, defaultValue, Optional.empty()); - } - - public final int getOrSetIntFunction(ConfigurationSection config, String path, int defaultValue, Optional> comments) { - int value = defaultValue; - if (config.isInt(path)) { - value = config.getInt(path); - } else { - config.set(path, value); - this.plugin.getAPI().getDistribution().setConfigComment(config, path, comments); - } - return value; - } - - public final long getOrSetLongFunction(ConfigurationSection config, String path, long defaultValue) { - return getOrSetLongFunction(config, path, defaultValue, Optional.empty()); - } - - public final long getOrSetLongFunction(ConfigurationSection config, String path, long defaultValue, Optional> comments) { - long value = defaultValue; - if (config.isLong(path)) { - value = config.getLong(path); - } else { - config.set(path, value); - this.plugin.getAPI().getDistribution().setConfigComment(config, path, comments); - } - return value; - } - - public final ConfigurationSection getOrSetSectionFunction(ConfigurationSection config, String path, ConfigurationSection defaultValue) { - return getOrSetSectionFunction(config, path, defaultValue, Optional.empty()); - } - - public final ConfigurationSection getOrSetSectionFunction(ConfigurationSection config, String path, ConfigurationSection defaultValue, Optional> comments) { - ConfigurationSection value = defaultValue; - if (config.isConfigurationSection(path)) { - value = config.getConfigurationSection(path); - } else { - config.set(path, value); - this.plugin.getAPI().getDistribution().setConfigComment(config, path, comments); - } - return value; - } - - public final boolean getOrSetBooleanFunction(ConfigurationSection config, String path, boolean defaultValue) { - return getOrSetBooleanFunction(config, path, defaultValue, Optional.empty()); - } - - public final boolean getOrSetBooleanFunction(ConfigurationSection config, String path, boolean defaultValue, Optional> comments) { - boolean value = defaultValue; - if (config.isBoolean(path)) { - value = config.getBoolean(path); - } else { - config.set(path, value); - this.plugin.getAPI().getDistribution().setConfigComment(config, path, comments); - } - return value; - } - - public final List getOrSetStringCollectionFunction(ConfigurationSection config, String path, Collection defaultValue) { - return getOrSetStringCollectionFunction(config, path, defaultValue, Optional.empty()); - } - - public final List getOrSetStringCollectionFunction(ConfigurationSection config, String path, Collection defaultValue, Optional> comments) { - List value = new ArrayList<>(defaultValue); - if (config.isList(path)) { - value = config.getStringList(path); - } else { - config.set(path, value); - this.plugin.getAPI().getDistribution().setConfigComment(config, path, comments); - } - defaultValue.clear(); - return value; - } - -} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/PluginStorage.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/PluginStorage.java index 33f723e..7a623ea 100644 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/PluginStorage.java +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/PluginStorage.java @@ -31,11 +31,12 @@ import org.bukkit.scheduler.BukkitTask; import ro.niconeko.astralbooks.AstralBooksCore; import ro.niconeko.astralbooks.AstralBooksPlugin; -import ro.niconeko.astralbooks.utils.tuples.PairTuple; -import ro.niconeko.astralbooks.utils.tuples.TripletTuple; import ro.niconeko.astralbooks.storage.settings.StorageSettings; +import ro.niconeko.astralbooks.values.Settings; import ro.niconeko.astralbooks.storage.types.impl.*; import ro.niconeko.astralbooks.utils.Side; +import ro.niconeko.astralbooks.utils.tuples.PairTuple; +import ro.niconeko.astralbooks.utils.tuples.TripletTuple; import java.io.File; import java.io.FileReader; @@ -77,7 +78,7 @@ public void convertFrom(StorageType type) { } public boolean load(StorageSettings settings) throws SQLException { - if (this.plugin.getSettings().isJoinBookEnabled()) { + if (Settings.JOIN_BOOK_ENABLED.get()) { if (joinBookFile.exists()) this.joinBookDatabase = this.readJsonFile(this.joinBookFile); this.needsJoinBookAutoSave = false; @@ -96,7 +97,7 @@ public boolean load(StorageSettings settings) throws SQLException { this.cache.unload(); if (this.storage != null) this.storage.unload(); - this.storage = switch (settings.getDatabaseType()) { + this.storage = switch (settings.TYPE.get()) { case JSON -> new JsonStorage(plugin); case MYSQL -> new MySQLStorage(plugin); case SQLITE -> new SQLiteStorage(plugin); @@ -104,8 +105,8 @@ public boolean load(StorageSettings settings) throws SQLException { case MARIADB -> new MariaDBStorage(plugin); }; this.cache = this.storage.cache; - this.cache.load(); - return this.storage.load(); + this.cache.load(Settings.STORAGE.get()); + return this.storage.load(Settings.STORAGE.get()); } public void unload() { diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/Storage.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/Storage.java index f9319d9..3aa76ce 100644 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/Storage.java +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/Storage.java @@ -19,10 +19,10 @@ import org.bukkit.inventory.ItemStack; import ro.niconeko.astralbooks.AstralBooksPlugin; -import ro.niconeko.astralbooks.utils.tuples.PairTuple; -import ro.niconeko.astralbooks.utils.tuples.TripletTuple; import ro.niconeko.astralbooks.storage.settings.StorageSettings; import ro.niconeko.astralbooks.utils.Side; +import ro.niconeko.astralbooks.utils.tuples.PairTuple; +import ro.niconeko.astralbooks.utils.tuples.TripletTuple; import java.sql.Connection; import java.sql.DriverManager; @@ -56,11 +56,11 @@ public final boolean isLoaded() { return this.loaded; } - protected boolean load() throws SQLException { + protected boolean load(StorageSettings settings) throws SQLException { try { this.lock.lock(); this.plugin.getLogger().info("Loading " + this.storageType.getFormattedName() + " database..."); - this.loadSettings(this.plugin.getSettings().getStorageSettings()); + this.loadSettings(settings); Class.forName(this.getDriver()); this.connection = DriverManager.getConnection(this.getURL()); this.connection.setAutoCommit(true); @@ -102,7 +102,7 @@ protected String getURL() { throw new IllegalStateException("Tried to get " + this.storageType.getFormattedName() + " url... please report this issue!"); } - protected abstract void loadSettings(StorageSettings storageSettings); + protected abstract void loadSettings(StorageSettings settings); protected abstract boolean createTables(); diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/StorageCache.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/StorageCache.java index 14f670c..5c168ba 100644 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/StorageCache.java +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/StorageCache.java @@ -23,8 +23,9 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import ro.niconeko.astralbooks.AstralBooksPlugin; -import ro.niconeko.astralbooks.utils.tuples.PairTuple; +import ro.niconeko.astralbooks.storage.settings.StorageSettings; import ro.niconeko.astralbooks.utils.Side; +import ro.niconeko.astralbooks.utils.tuples.PairTuple; import java.util.Date; import java.util.HashSet; @@ -53,8 +54,8 @@ protected StorageCache(AstralBooksPlugin plugin, Storage storage) { this.storage = storage; } - public void load() { - this.poolExecutor = Executors.newFixedThreadPool(this.plugin.getSettings().getStorageSettings().getDatabaseThreads()); + public void load(StorageSettings settings) { + this.poolExecutor = Executors.newFixedThreadPool(settings.THREADS.get()); this.filterBooks = CacheBuilder.newBuilder() .expireAfterAccess(5, TimeUnit.MINUTES) .build(new CacheLoader<>() { diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/StorageConvertor.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/StorageConvertor.java index f57b11e..9c09568 100644 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/StorageConvertor.java +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/StorageConvertor.java @@ -23,6 +23,7 @@ import ro.niconeko.astralbooks.utils.tuples.PairTuple; import ro.niconeko.astralbooks.utils.tuples.TripletTuple; import ro.niconeko.astralbooks.utils.Side; +import ro.niconeko.astralbooks.values.Settings; import java.sql.SQLException; import java.util.Date; @@ -61,8 +62,8 @@ public void convert() { } }, 1, TimeUnit.SECONDS); try { - this.previousStorage.cache.load(); - this.previousStorage.load(); + this.previousStorage.cache.load(Settings.STORAGE.get()); + this.previousStorage.load(Settings.STORAGE.get()); } catch (SQLException ex) { this.plugin.getLogger().log(Level.WARNING, "Failed to load previous storage type! Please check configuration...", ex); failed.set(true); diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/StorageType.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/StorageType.java index e352835..60e2d62 100644 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/StorageType.java +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/StorageType.java @@ -18,36 +18,41 @@ package ro.niconeko.astralbooks.storage; import lombok.Getter; +import org.jetbrains.annotations.NotNull; +@Getter public enum StorageType { - JSON("json", "Json"), - MYSQL("mysql", "MySQL"), - SQLITE("sqlite", "SQLite"), - H2("h2", "H2"), - MARIADB("mariadb", "MariaDB"); + JSON("Json"), + MYSQL("MySQL"), + SQLITE("SQLite"), + H2("H2"), + MARIADB("MariaDB"); - private final String type; - @Getter private final String formattedName; + private final String formattedName; - StorageType(String type, String formattedName) { - this.type = type; + StorageType(String formattedName) { this.formattedName = formattedName; } + @NotNull @Override public String toString() { - return this.type; + return switch (this) { + case H2 -> "h2"; + case MYSQL -> "mysql"; + case JSON -> "json"; + case SQLITE -> "sqlite"; + case MARIADB -> "mariadb"; + }; } public static StorageType fromString(String type) { - if (type.equalsIgnoreCase("mysql")) - return MYSQL; - else if (type.equalsIgnoreCase("sqlite")) - return SQLITE; - else if (type.equalsIgnoreCase("json")) - return JSON; - else if (type.equalsIgnoreCase("mariadb")) - return MARIADB; - return H2; + return switch (type.toUpperCase()) { + case "MARIADB" -> MARIADB; + case "MYSQL" -> MYSQL; + case "SQLITE" -> SQLITE; + case "JSON" -> JSON; + default -> H2; + }; } } diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/settings/EmbedStorageSettings.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/settings/EmbedStorageSettings.java new file mode 100644 index 0000000..7b6d2e3 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/settings/EmbedStorageSettings.java @@ -0,0 +1,38 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.storage.settings; + +import ro.niconeko.astralbooks.utils.Section; +import ro.niconeko.astralbooks.utils.settings.*; + +import java.util.List; + +public class EmbedStorageSettings extends Section { + public final StringSetting FILE_NAME = new StringSetting("file_name", "localhost"); + public final BooleanSetting ENCRYPTION_ENABLED = new BooleanSetting("encryption_enabled", false, + List.of( + "Enable AES encryption.", + "Don't change if you don't know what you're doing!", + "Only for H2 database." + )); + public final IntegerSetting SAVE_INTERVAL = new IntegerSetting("save_interval", 60, List.of("Only for Json database.")); + + public EmbedStorageSettings() { + super("embed"); + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/settings/RemoteStorageSettings.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/settings/RemoteStorageSettings.java new file mode 100644 index 0000000..188fee6 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/settings/RemoteStorageSettings.java @@ -0,0 +1,38 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.storage.settings; + +import ro.niconeko.astralbooks.utils.Section; +import ro.niconeko.astralbooks.utils.settings.*; + +import java.util.List; + +public class RemoteStorageSettings extends Section { + public final StringSetting HOST = new StringSetting("host", "localhost"); + public final PortSetting PORT = new PortSetting("port", 3306); + public final StringSetting DATABASE = new StringSetting("database", "astralbooks"); + public final StringSetting USERNAME = new StringSetting("username", "root"); + public final StringSetting PASSWORD = new StringSetting("password", ""); + public final BooleanSetting SSL_ENABLED = new BooleanSetting("ssl_enabled", false, List.of("If SSL encryption is enabled")); + public final StringSetting TABLE_PREFIX = new StringSetting("table_prefix", "abooks_", List.of("The prefix for the table name")); + public final StringSetting SERVER_NAME = new StringSetting("server_name", "default", List.of("Use this if you have multiple servers using the same database")); + + public RemoteStorageSettings() { + super("remote"); + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/settings/StorageEmbedSettings.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/settings/StorageEmbedSettings.java deleted file mode 100644 index 3e6cad1..0000000 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/settings/StorageEmbedSettings.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * CitizensBooks - * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ro.niconeko.astralbooks.storage.settings; - -import lombok.Getter; -import org.bukkit.configuration.ConfigurationSection; -import ro.niconeko.astralbooks.AstralBooksPlugin; -import ro.niconeko.astralbooks.settings.Settings; - -import java.util.List; -import java.util.Optional; - -@Getter -public class StorageEmbedSettings extends Settings { - private String fileName = "database"; - private boolean EncryptionEnabled = false; - private int saveInterval = 60; - - public StorageEmbedSettings(AstralBooksPlugin plugin) { - super(plugin); - } - - @Override - public void load(ConfigurationSection section) { - this.fileName = super.getOrSetStringFunction(section, "file_name", this.fileName); - this.EncryptionEnabled = super.getOrSetBooleanFunction(section, "encryption_enabled", this.EncryptionEnabled, - Optional.of(List.of( - "Enable AES encryption.", - "Don't change if you don't know what you're doing!", - "Only for H2 database." - ))); - this.saveInterval = super.getOrSetIntFunction(section, "save_interval", this.saveInterval, Optional.of(List.of("Only for Json database."))); - } -} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/settings/StorageRemoteSettings.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/settings/StorageRemoteSettings.java deleted file mode 100644 index 1a47efc..0000000 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/settings/StorageRemoteSettings.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * CitizensBooks - * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ro.niconeko.astralbooks.storage.settings; - -import lombok.Getter; -import org.bukkit.configuration.ConfigurationSection; -import ro.niconeko.astralbooks.AstralBooksPlugin; -import ro.niconeko.astralbooks.settings.Settings; - -import java.util.List; -import java.util.Optional; - -@Getter -public class StorageRemoteSettings extends Settings { - private String host = "localhost"; - private int port = 3306; - private String database = "astralbooks"; - private String username = "root"; - private String password = ""; - private boolean SSLEnabled = false; - private String tablePrefix = "abooks_"; - private String serverName = "default"; - - public StorageRemoteSettings(AstralBooksPlugin plugin) { - super(plugin); - } - - @Override - public void load(ConfigurationSection section) { - this.host = super.getOrSetStringFunction(section, "host", this.host); - this.port = super.getOrSetIntFunction(section, "port", this.port); - this.database = super.getOrSetStringFunction(section, "database", this.database); - this.username = super.getOrSetStringFunction(section, "username", this.username); - this.password = super.getOrSetStringFunction(section, "password", this.password); - this.SSLEnabled = super.getOrSetBooleanFunction(section, "ssl_enabled", this.SSLEnabled, Optional.of(List.of("If SSL encryption is enabled."))); - this.tablePrefix = super.getOrSetStringFunction(section, "table_prefix", this.tablePrefix, Optional.of(List.of("The prefix for the table name."))); - this.serverName = super.getOrSetStringFunction(section, "server_name", this.serverName, Optional.of(List.of("Use this if you have multiple servers using the same database."))); - } -} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/settings/StorageSettings.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/settings/StorageSettings.java index ffe825f..fd1e9b1 100644 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/settings/StorageSettings.java +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/settings/StorageSettings.java @@ -17,39 +17,19 @@ package ro.niconeko.astralbooks.storage.settings; -import lombok.Getter; -import org.bukkit.configuration.ConfigurationSection; -import ro.niconeko.astralbooks.AstralBooksPlugin; -import ro.niconeko.astralbooks.settings.Settings; import ro.niconeko.astralbooks.storage.StorageType; +import ro.niconeko.astralbooks.utils.Section; +import ro.niconeko.astralbooks.utils.settings.*; -import java.util.List; -import java.util.Optional; +public class StorageSettings extends Section { + public final StorageTypeSetting TYPE = new StorageTypeSetting("type", StorageType.H2); + public final IntegerSetting THREADS = new IntegerSetting("threads", 2); + public final BooleanSetting SECURITY_BOOK_PURGE_ENABLED = new BooleanSetting("security_book_purge_enabled", true); + public final IntegerSetting SECURITY_BOOK_PURGE_OLDER_THAN = new IntegerSetting("security_book_purge_older_than", 30); + public final SectionSetting REMOTE = new SectionSetting<>(new RemoteStorageSettings()); + public final SectionSetting EMBED = new SectionSetting<>(new EmbedStorageSettings()); -@Getter -public class StorageSettings extends Settings { - private StorageType databaseType = StorageType.H2; - private int databaseThreads = 2; - private boolean securityBookPurgeEnabled = true; - private int securityBookPurgeOlderThan = 30; - private final StorageRemoteSettings RemoteSettings = new StorageRemoteSettings(super.plugin); - private final StorageEmbedSettings EmbedSettings = new StorageEmbedSettings(super.plugin); - - public StorageSettings(AstralBooksPlugin plugin) { - super(plugin); - } - - @Override - public void load(ConfigurationSection section) { - this.databaseType = StorageType.fromString(super.getOrSetStringFunction(section, "type", this.databaseType.toString(), Optional.of(List.of("Options: h2, sqlite, mysql, json")))); - this.databaseThreads = super.getOrSetIntFunction(section, "threads", this.databaseThreads, Optional.of(List.of("Number of threads the cache will use"))); - this.securityBookPurgeEnabled = super.getOrSetBooleanFunction(section, "security_books_purge_enabled", this.securityBookPurgeEnabled, Optional.of(List.of( - "Enable if you want to clean old saved books created by players" - ))); - this.securityBookPurgeOlderThan = super.getOrSetIntFunction(section, "security_books_purge_older_than", this.securityBookPurgeOlderThan, Optional.of(List.of( - "In days, default: 30" - ))); - this.RemoteSettings.load(super.getOrCreateSection(section, "remote")); - this.EmbedSettings.load(super.getOrCreateSection(section, "embed")); + public StorageSettings() { + super("storage"); } } diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/types/EmbedStorage.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/types/EmbedStorage.java index b408e5a..c406ebe 100644 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/types/EmbedStorage.java +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/types/EmbedStorage.java @@ -20,7 +20,7 @@ import ro.niconeko.astralbooks.AstralBooksPlugin; import ro.niconeko.astralbooks.storage.Storage; import ro.niconeko.astralbooks.storage.StorageType; -import ro.niconeko.astralbooks.storage.settings.StorageEmbedSettings; +import ro.niconeko.astralbooks.storage.settings.EmbedStorageSettings; import ro.niconeko.astralbooks.storage.settings.StorageSettings; import ro.niconeko.astralbooks.utils.Side; import ro.niconeko.astralbooks.utils.tuples.PairTuple; @@ -41,11 +41,11 @@ protected EmbedStorage(AstralBooksPlugin plugin, StorageType storageType) { @Override protected void loadSettings(StorageSettings settings) { - StorageEmbedSettings embedSettings = settings.getEmbedSettings(); - this.fileName = embedSettings.getFileName(); - this.encryptionEnabled = embedSettings.isEncryptionEnabled(); - this.autoSaveInterval = embedSettings.getSaveInterval(); - super.purgeSecurityBooksOlderThan = settings.getSecurityBookPurgeOlderThan(); + EmbedStorageSettings embedStorageSettings = settings.EMBED.get(); + this.fileName = embedStorageSettings.FILE_NAME.get(); + this.encryptionEnabled = embedStorageSettings.ENCRYPTION_ENABLED.get(); + this.autoSaveInterval = embedStorageSettings.SAVE_INTERVAL.get(); + super.purgeSecurityBooksOlderThan = settings.SECURITY_BOOK_PURGE_OLDER_THAN.get(); } @Override diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/types/RemoteStorage.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/types/RemoteStorage.java index 7f7cea1..f1e09e6 100644 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/types/RemoteStorage.java +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/types/RemoteStorage.java @@ -22,7 +22,7 @@ import ro.niconeko.astralbooks.AstralBooksPlugin; import ro.niconeko.astralbooks.storage.Storage; import ro.niconeko.astralbooks.storage.StorageType; -import ro.niconeko.astralbooks.storage.settings.StorageRemoteSettings; +import ro.niconeko.astralbooks.storage.settings.RemoteStorageSettings; import ro.niconeko.astralbooks.storage.settings.StorageSettings; import ro.niconeko.astralbooks.utils.Side; import ro.niconeko.astralbooks.utils.tuples.PairTuple; @@ -54,17 +54,17 @@ protected RemoteStorage(AstralBooksPlugin plugin, StorageType storageType) { } @Override - protected void loadSettings(StorageSettings storageSettings) { - StorageRemoteSettings remoteSettings = storageSettings.getRemoteSettings(); - this.user = remoteSettings.getUsername(); - this.pass = remoteSettings.getPassword(); - this.host = remoteSettings.getHost(); - this.port = remoteSettings.getPort(); - this.database = remoteSettings.getDatabase(); - this.sslEnabled = remoteSettings.isSSLEnabled(); - this.tablePrefix = remoteSettings.getTablePrefix(); - this.serverName = remoteSettings.getServerName(); - super.purgeSecurityBooksOlderThan = storageSettings.getSecurityBookPurgeOlderThan(); + protected void loadSettings(StorageSettings settings) { + RemoteStorageSettings remoteStorageSettings = settings.REMOTE.get(); + this.user = remoteStorageSettings.USERNAME.get(); + this.pass = remoteStorageSettings.PASSWORD.get(); + this.host = remoteStorageSettings.HOST.get(); + this.port = remoteStorageSettings.PORT.get(); + this.database = remoteStorageSettings.DATABASE.get(); + this.sslEnabled = remoteStorageSettings.SSL_ENABLED.get(); + this.tablePrefix = remoteStorageSettings.TABLE_PREFIX.get(); + this.serverName = remoteStorageSettings.SERVER_NAME.get(); + super.purgeSecurityBooksOlderThan = settings.SECURITY_BOOK_PURGE_OLDER_THAN.get(); } @Override diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/types/impl/JsonStorage.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/types/impl/JsonStorage.java index fe22fe6..3f3f186 100644 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/types/impl/JsonStorage.java +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/storage/types/impl/JsonStorage.java @@ -27,6 +27,7 @@ import ro.niconeko.astralbooks.AstralBooksCore; import ro.niconeko.astralbooks.AstralBooksPlugin; import ro.niconeko.astralbooks.storage.StorageType; +import ro.niconeko.astralbooks.storage.settings.StorageSettings; import ro.niconeko.astralbooks.utils.tuples.PairTuple; import ro.niconeko.astralbooks.utils.tuples.TripletTuple; import ro.niconeko.astralbooks.storage.types.EmbedStorage; @@ -59,11 +60,11 @@ public JsonStorage(AstralBooksPlugin plugin) { } @Override - protected boolean load() { + protected boolean load(StorageSettings settings) { try { this.lock.lock(); super.plugin.getLogger().info("Loading " + super.storageType.getFormattedName() + " database..."); - super.loadSettings(super.plugin.getSettings().getStorageSettings()); + super.loadSettings(settings); this.readJsonStorage(); JsonElement filtersJson = this.jsonStorage.get("filters"); if (filtersJson != null && filtersJson.isJsonObject()) diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/BossBarConfig.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/BossBarConfig.java new file mode 100644 index 0000000..16c0c66 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/BossBarConfig.java @@ -0,0 +1,75 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.utils; + +import lombok.Getter; +import org.bukkit.boss.BarColor; +import org.bukkit.boss.BarStyle; + +@Getter +public class BossBarConfig { + private int in = 0, out = 0, stay = 20 * 6; + private double progress = 100; + private BarColor barColor = BarColor.RED; + private BarStyle barStyle = BarStyle.SOLID; + + public BossBarConfig(String config) { + String[] configs = config.split(","); + for (String configItem : configs) { + String[] keyValue = configItem.split(":"); + if (keyValue.length == 2) { + String key = keyValue[0].trim().toLowerCase(); + String value = keyValue[1].trim(); + switch (key) { + case "in" -> { + try { + in = Integer.parseInt(value); + } catch (Exception ex) { + in = 0; + } + } + case "out" -> { + try { + out = Integer.parseInt(value); + } catch (Exception ex) { + out = 0; + } + } + case "stay" -> { + try { + stay = Integer.parseInt(value); + } catch (Exception ex) { + stay = 20 * 6; + } + } + case "progress" -> { + try { + progress = Double.parseDouble(value); + if (progress > 100) progress = 100; + if (progress < 0) progress = 0; + } catch (Exception ex) { + progress = 100; + } + } + case "color" -> barColor = BossBarUtils.toBarColor(value); + case "style" -> barStyle = BossBarUtils.toBarStyle(value); + } + } + } + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/BossBarUtils.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/BossBarUtils.java new file mode 100644 index 0000000..588403a --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/BossBarUtils.java @@ -0,0 +1,67 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.utils; + +import org.bukkit.boss.BarColor; +import org.bukkit.boss.BarStyle; + +public class BossBarUtils { + public static BarStyle toBarStyle(String style) { + return switch (style.toLowerCase()) { + case "segmented_6", "seg_6" -> BarStyle.SEGMENTED_6; + case "segmented_10", "seg_10" -> BarStyle.SEGMENTED_10; + case "segmented_12", "seg_12" -> BarStyle.SEGMENTED_12; + case "segmented_20", "seg_20" -> BarStyle.SEGMENTED_20; + default -> BarStyle.SOLID; + }; + } + + public static String fromBarStyle(BarStyle style) { + return switch (style) { + case SEGMENTED_6 -> "seg_6"; + case SEGMENTED_10 -> "seg_10"; + case SEGMENTED_12 -> "seg_12"; + case SEGMENTED_20 -> "seg_20"; + case SOLID -> "solid"; + }; + } + + public static BarColor toBarColor(String color) { + return switch (color.toLowerCase()) { + case "green" -> BarColor.GREEN; + case "yellow" -> BarColor.YELLOW; + case "blue" -> BarColor.BLUE; + case "purple" -> BarColor.PURPLE; + case "pink" -> BarColor.PINK; + case "white" -> BarColor.WHITE; + default -> BarColor.RED; + }; + } + + public static String fromBarColor(BarColor color) { + return switch (color) { + case RED -> "red"; + case GREEN -> "green"; + case YELLOW -> "yellow"; + case BLUE -> "blue"; + case PURPLE -> "purple"; + case PINK -> "pink"; + case WHITE -> "white"; + }; + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/Color.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/Color.java new file mode 100644 index 0000000..dd0ee16 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/Color.java @@ -0,0 +1,58 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.utils; + +import net.md_5.bungee.api.ChatColor; + +public class Color { + private final int rgb; + + public Color(String str) { + this(Integer.valueOf(str.substring(0, 2), 16), + Integer.valueOf(str.substring(2, 4), 16), + Integer.valueOf(str.substring(4, 6), 16)); + } + + public Color(int red, int green, int blue) { + this.rgb = (red << 16) + (green << 8) + blue; + } + + public int red() { + return (rgb >> 16) & 0xFF; + } + + public int green() { + return (rgb >> 8) & 0xFF; + } + + public int blue() { + return rgb & 0xFF; + } + + public String hex() { + return String.format("%06x", rgb); + } + + public String minecraftHex() { + String hex = hex(); + return ChatColor.COLOR_CHAR + "x" + ChatColor.COLOR_CHAR + hex.charAt(0) + + ChatColor.COLOR_CHAR + hex.charAt(1) + ChatColor.COLOR_CHAR + hex.charAt(2) + + ChatColor.COLOR_CHAR + hex.charAt(3) + ChatColor.COLOR_CHAR + hex.charAt(4) + + ChatColor.COLOR_CHAR + hex.charAt(5); + } +} \ No newline at end of file diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/Message.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/Message.java deleted file mode 100644 index f64faf7..0000000 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/Message.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * CitizensBooks - * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ro.niconeko.astralbooks.utils; - -import java.util.List; -import java.util.Optional; - -@SuppressWarnings("OptionalUsedAsFieldOrParameterType") -public enum Message { - HEADER("header", "&f[&6AstralBooks&f] &r"), - NO_PERMISSION("no_permission", "&cYou don't have permission!"), - CONFIG_RELOADED("config_reloaded", "&aConfig reloaded."), - SET_BOOK_SUCCESSFULLY("set_book_successfully", "&aYou have set the book for %npc%&a!"), - REMOVED_BOOK_SUCCESSFULLY("removed_book_successfully", "&aYou have removed the book for %npc%&a!"), - NO_NPC_SELECTED("no_npc_selected", "&cYou need to have an NPC selected!"), - NO_WRITTEN_BOOK_IN_HAND("no_written_book_in_hand", "&cYou need to have a written book in your hand!"), - NO_WRITABLE_BOOK_IN_HAND("no_writable_book_in_hand", "&cYou need to have a writable book in your hand!"), - NO_ITEM_IN_HAND("no_item_in_hand", "&cYou need to have an item in your hand!"), - NO_BOOK_FOR_NPC("no_book_for_npc", "&cThis NPC doesn't have a book!"), - NO_BOOK_FOR_FILTER("no_book_for_filter", "&cThis filter doesn't have a book!"), - FILTER_SAVED("filter_saved", "&aFilter %filter_name% was saved."), - FILTER_REMOVED("filter_removed", "&aFilter %filter_name% was removed."), - BOOK_RECEIVED("book_received", "&aYou received the book in your inventory!"), - CITIZENS_NOT_ENABLED("citizens_not_enabled", "&cCitizens plugin is not enabled! This command requires Citizens to be installed!"), - SET_CUSTOM_COMMAND_SUCCESSFULLY("set_custom_command_successfully", "&aCommand %command% has been set!"), - REMOVED_CUSTOM_COMMAND_SUCCESSFULLY("removed_custom_command_successfully", "&aCommand %command% has been removed!"), - CONSOLE_CANNOT_USE_COMMAND("console_cannot_use_command", "&cYou have to be a player if you want to use this command!"), - PLAYER_CANNOT_USE_COMMAND("player_cannot_use_command", "&cConsole command only!"), - NEW_VERSION_AVAILABLE("new_version_available", "&aA new version of AstralBooks is available!"), - FILTER_APPLIED_TO_ITEM("filter_applied_to_item", "&aFilter %filter_name% has been applied to your holding item."), - FILTER_REMOVED_FROM_ITEM("filter_removed_from_item", "&aThe filter has been removed from your holding item."), - PLAYER_NOT_FOUND("player_not_found", "&cPlayer not found!"), - FILTER_NOT_FOUND("filter_not_found", "&cFilter not found!"), - SET_JOIN_BOOK_SUCCESSFULLY("set_join_book_successfully", "&aYou have set the join book!"), - REMOVED_JOIN_BOOK_SUCCESSFULLY("removed_join_book_successfully", "&aYou have removed the join book!"), - FILTER_NAME_INVALID("filter_name_invalid", "&cThe filter name should only contain letters, numbers, dashes and underscores!"), - COMMAND_NAME_INVALID("command_name_invalid", "&cThe command name should only contain letters, numbers, dashes and underscores!"), - PERMISSION_INVALID("permission_invalid", "&cThe permission should only contain letters, numbers, dots, dashes and underscores!"), - OPERATION_FAILED("operation_failed", "&cThe operation failed! Please check the console for errors!"), - FILTERS_LIST_PAGE_NOT_FOUND("filters_list_page_not_found", "&cThere's no filters at page %page%"), - FILTERS_LIST_PRESENT("filters_list_present", "&aHere's the list of filters present:"), - FILTERS_LIST_NO_FILTER_PRESENT("filter_list_no_filter_present", "&cThere is no filter installed!"), - OPENED_BOOK_FOR_PLAYERS("opened_books_for_player", "&aYou've successfully opened a book for %success% player(s). There was %failed% failed attempts."), - OPENED_BOOK_FOR_PLAYER("opened_book_for_player", "&aYou've successfully opened a book for %player%."), - BOOK_APPLY_TO_BLOCK_TIMEOUT("book_apply_to_block_timeout", "&aYou have 1 minute to apply the book! Right click the block you want to apply the book!"), - BOOK_APPLY_TO_ENTITY_TIMEOUT("book_apply_to_entity_timeout", "&aYou have 1 minute to apply the book! Right click the entity you want to apply the book!"), - BOOK_REMOVE_FROM_BLOCK_TIMEOUT("book_remove_from_block_timeout", "&aYou have 1 minute to remove the book! Right click the block you want the book to get removed!"), - BOOK_REMOVE_FROM_ENTITY_TIMEOUT("book_remove_from_entity_timeout", "&aYou have 1 minute to remove the book! Right click the entity you want the book to get removed!"), - BOOK_APPLIED_SUCCESSFULLY_TO_BLOCK("book_applied_successfully_to_block", "&aThe book have been applied to block! (%block_x%, %block_y%, %block_z%)"), - BOOK_APPLIED_SUCCESSFULLY_TO_ENTITY("book_applied_successfully_to_entity", "&aThe book have been applied to entity! (%type%)"), - BOOK_REMOVED_SUCCESSFULLY_FROM_BLOCK("book_removed_successfully_from_block", "&aThe book have been removed from block! (%block_x%, %block_y%, %block_z%)"), - BOOK_REMOVED_SUCCESSFULLY_FROM_ENTITY("book_removed_successfully_from_entity", "&aThe book have been removed from entity! (%type%)"), - ENTITY_IS_NPC("entity_is_npc", "&cThe entity is an Citizens NPC. Use &f/abook npc &cto set a book for this type of entity!"), - BOOK_SECURITY_NOT_ENABLED("book_security_not_enabled", "&cBook security is not enabled!"), - BOOK_SECURITY_NOT_FOUND("book_security_not_found", "&cNo security book found!"), - BOOK_SECURITY_LIST_PRESENT("book_security_list_found", "&aHere's the list of books saved:"), - BOOK_SECURITY_DATE_FORMAT("book_security_date_format", "dd/MM/yyyy-HH:mm:ss", Optional.of(List.of("https://help.gooddata.com/cloudconnect/manual/date-and-time-format.html"))), - - USAGE_NPC_SET("usage.npc.set", "&aUsage: &f/abook npc set [right/left]"), - USAGE_NPC_REMOVE("usage.npc.remove", "&aUsage: &f/abook npc remove [right/left]"), - USAGE_NPC_GETBOOK("usage.npc.getbook", "&aUsage: &f/abook npc getbook [right/left]"), - USAGE_HELP("usage.help", "&aUsage: &f/abook help [page]"), - USAGE_OPENBOOK("usage.openbook", "&aUsage: &f/abook openbook"), - USAGE_CLOSEBOOK("usage.closebook", "&aUsage: &f/abook closebook "), - USAGE_SETCMD("usage.setcmd", "&aUsage: &f/abook setcmd <command> <filter name> [permission]"), - USAGE_REMCMD("usage.remove", "&aUsage: &f/abook remcmd <command>"), - USAGE_SETJOIN("usage.setjoin", "&aUsage: &f/abook setjoin"), - USAGE_REMJOIN("usage.remjoin", "&aUsage: &f/abook remjoin"), - USAGE_FORCEOPEN("usage.forceopen", "&aUsage: &f/abook forceopen <filter name> <player>"), - USAGE_FILTER_SET("usage.filter.set", "&aUsage: &f/abook filter set <filter name>"), - USAGE_FILTER_REMOVE("usage.filter.remove", "&aUsage: &f/abook filter remove <filter name>"), - USAGE_FILTER_GETBOOK("usage.filter.getbook", "&aUsage: &f/abook filter getbook <filter name>"), - USAGE_FILTER_LIST("usage.filter.list", "&aUsage: &f/abook filter list [page]"), - USAGE_ACTIONITEM_SET("usage.actionitem.set", "&aUsage: &f/abook actionitem set <filter name> [right/left]"), - USAGE_ACTIONITEM_REMOVE("usage.actionitem.remove", "&aUsage: &f/abook actionitem remove [right/left]"), - USAGE_INTERACTION_SET_BLOCK("usage.interaction.set.block", "&aUsage: &f/abook interaction set block [right/left]"), - USAGE_INTERACTION_SET_ENTITY("usage.interaction.set.entity", "&aUsage: &f/abook interaction set entity [right/left]"), - USAGE_INTERACTION_REMOVE_BLOCK("usage.interaction.remove.block", "&aUsage: &f/abook interaction remove block [right/left]"), - USAGE_INTERACTION_REMOVE_ENTITY("usage.interaction.remove.entity", "&aUsage: &f/abook interaction remove entity [right/left]"), - USAGE_SECURITY_LIST("usage.security.list", "&aUsage: &f/abook security list <*/player> [page]"), - USAGE_SECURITY_GETBOOK("usage.security.getbook", "&aUsage: &f/abook security getbook <player> <timestamp>"), - - HELP_INFO("help.info", "&e< &6Commands and Usage &f| &6Page index (%page%/3) &e >"), - HELP_ARGUMENTS("help.arguments", "&f(&c<> &f= &erequired argument&f, &c[] &f= &eoptional argument&f)"), - HELP_ABOUT("help.about", "&f/abook about"), - HELP_HELP("help.help", "&f/abook help [page] $ &9Show help page."), - HELP_NPC_SET("help.npc.set", "&f/abook npc set [right/left] $ &9Set book for npc."), - HELP_NPC_REMOVE("help.npc.remove", "&f/abook npc remove [right/left] $ &9Remove book for npc."), - HELP_NPC_GETBOOK("help.npc.getbook", "&f/abook npc getbook [right/left] $ &9Get the book of npc."), - HELP_OPENBOOK("help.openbook", "&f/abook openbook$ &9Open a writen book."), - HELP_CLOSEBOOK("help.closebook", "&f/abook closebook <author> <title> $ &9Closes a writable book."), - HELP_RELOAD("help.reload", "&f/abook reload $ &9Reload config file."), - HELP_SETCMD("help.setcmd", "&f/abook setcmd <command> <filter name> [permission] $ &9Set command by the given filter name."), - HELP_REMCMD("help.remcmd", "&f/abook remcmd <command> $ &9Remove command."), - HELP_SETJOIN("help.setjoin", "&f/abook setjoin $ &9Set the join book."), - HELP_REMJOIN("help.remjoin", "&f/abook remjoin $ &9Remove the join book."), - HELP_FORCEOPEN("help.forceopen", "&f/abook forceopen <filter name> <player> $ &9Force a player to open a book."), - HELP_FILTER_SET("help.filter.set", "&f/abook filter set <filter name> $ &9Set a filter by the given name."), - HELP_FILTER_REMOVE("help.filter.remove", "&f/abook filter remove <filter name> $ &9Remove a filter by the given name."), - HELP_FILTER_GETBOOK("help.filter.getbook", "&f/abook filter getbook <filter name> $ &9Get the book of filter by the given name."), - HELP_FILTER_LIST("help.filter.list", "&f/abook filter list [page] $ &9List the filters present/installed."), - HELP_ACTIONITEM_SET("help.actionitem.set", "&f/abook actionitem set <filter name> [right/left] $ &9Put a filter on the item you hold."), - HELP_ACTIONITEM_REMOVE("help.actionitem.remove", "&f/abook actionitem remove [right/left] $ &9Remove the filter from the item you hold."), - HELP_INTERACTION_SET_BLOCK("help.interaction.set.block", "&f/abook interaction set block [right/left] $ &9Apply a book on a block."), - HELP_INTERACTION_SET_ENTITY("help.interaction.set.entity", "&f/abook interaction set entity [right/left] $ &9Apply a book on an entity."), - HELP_INTERACTION_REMOVE_BLOCK("help.interaction.remove.block", "&f/abook interaction remove block [right/left] $ &9Remove a book from a block."), - HELP_INTERACTION_REMOVE_ENTITY("help.interaction.remove.entity", "&f/abook interaction remove entity [right/left] $ &9Remove a book from an entity."), - HELP_SECURITY_LIST("help.security.list", "&f/abook security list <*/player> [page] $ &9List all books created by a player or all players."), - HELP_SECURITY_GETBOOK("help.security.getbook", "&f/abook security getbook <player> <timestamp> $ &9Get the book a player has created."); - - private final String key, def; - private final Optional<List<String>> comments; - - Message(String key, String def, Optional<List<String>> comments) { - this.key = key; - this.def = def; - this.comments = comments; - } - - Message(String key, String def) { - this(key, def, Optional.empty()); - } - - public final String getPath() { - return this.key; - } - - public final String getDefault() { - return this.def; - } - - public final Optional<List<String>> getComments() { - return this.comments; - } -} \ No newline at end of file diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/MessageUtils.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/MessageUtils.java new file mode 100644 index 0000000..dc7228d --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/MessageUtils.java @@ -0,0 +1,114 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.utils; + +import net.md_5.bungee.api.ChatColor; +import net.md_5.bungee.api.ChatMessageType; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import ro.niconeko.astralbooks.managers.BossBarManager; +import ro.niconeko.astralbooks.managers.HooksManager; +import ro.niconeko.astralbooks.values.Messages; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class MessageUtils { + private static final Pattern HEX_PATTERN = Pattern.compile("#([A-Fa-f0-9]{6})"); + private static final Pattern GRADIENT_PATTERN = Pattern.compile("\\[G:#([A-Fa-f0-9]{6}):#([A-Fa-f0-9]{6})](.*?)\\[/G]"); + + private static final Pattern TITLE_PATTERN = Pattern.compile("^<T(?::\\((.*?)\\))?:\\[(.*?)](?::\\[(.*?)])?>$"); + private static final Pattern BOSSBAR_PATTERN = Pattern.compile("^<B(?::\\((.*?)\\))?>"); + private static final Pattern ACTIONBAR_PATTERN = Pattern.compile("^<A>"); + + public static void sendMessage(CommandSender sender, String message) { + Matcher matcher; + String msg; + if ((matcher = ACTIONBAR_PATTERN.matcher(message)).find()) { + if (sender instanceof Player player) { + msg = message.substring(matcher.end()); + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(parseMessage(sender, msg))); + } + } else if ((matcher = BOSSBAR_PATTERN.matcher(message)).find()) { + if (sender instanceof Player player) { + msg = message.substring(matcher.end()); + String config = matcher.group(1); + BossBarConfig bossBarConfig = new BossBarConfig(config); + BossBarManager.sendBossBar(player, bossBarConfig, (p) -> parseMessage(p, msg)); + } + } else if ((matcher = TITLE_PATTERN.matcher(message)).find()) { + if (sender instanceof Player player) { + String config = matcher.group(1); + String title = matcher.group(2); + String subtitle = matcher.group(3); + TitleConfig titleConfig = new TitleConfig(config); + player.sendTitle(parseMessage(sender, title), parseMessage(sender, subtitle), titleConfig.getIn(), titleConfig.getStay(), titleConfig.getOut()); + } + } else + sender.spigot().sendMessage(TextUtils.components(parseMessage(sender, message))); + } + + public static String parseMessage(CommandSender sender, String message) { + message = message.replaceAll("\\[header]", Messages.HEADER.get()); + if (HooksManager.PAPI.isEnabled()) { + if (sender instanceof Player player) { + return HooksManager.PAPI.parse(hex(gradient(legacy(message)))).apply(player); + } + return HooksManager.PAPI.parseSup(hex(gradient(legacy(message)))).get(); + } + return hex(gradient(legacy(message))); + } + + public static String hex(String message) { + Matcher matcher = HEX_PATTERN.matcher(message); + StringBuilder buffer = new StringBuilder(message.length() + 4 * 8); + while (matcher.find()) + matcher.appendReplacement(buffer, new Color(matcher.group(1)).minecraftHex()); + return matcher.appendTail(buffer).toString(); + } + + public static String legacy(String message) { + return ChatColor.translateAlternateColorCodes('&', message); + } + + public static String gradient(String message) { + Matcher matcher = GRADIENT_PATTERN.matcher(message); + StringBuilder buffer = new StringBuilder(message.length() + 4 * 8); + while (matcher.find()) + matcher.appendReplacement(buffer, toGradient( + new Color(matcher.group(1)), + new Color(matcher.group(2)), + matcher.group(3))); + return matcher.appendTail(buffer).toString(); + } + + private static String toGradient(Color start, Color end, String content) { + content = ChatColor.stripColor(content); + StringBuilder message = new StringBuilder(content.length() + (content.length() * 7)); + int length = content.length(); + for (int index = 0; index < length; index++) { + int red = (int) (start.red() + (float) (end.red() - start.red()) / (length - 1) * index); + int green = (int) (start.green() + (float) (end.green() - start.green()) / (length - 1) * index); + int blue = (int) (start.blue() + (float) (end.blue() - start.blue()) / (length - 1) * index); + message.append(new Color(red, green, blue).minecraftHex()) + .append(content.charAt(index)); + } + return message.toString(); + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/Permission.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/Permission.java new file mode 100644 index 0000000..fcbd9fc --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/Permission.java @@ -0,0 +1,30 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.utils; + +import org.bukkit.command.CommandSender; +import ro.niconeko.astralbooks.managers.HooksManager; + +public record Permission(String permission) { + public boolean has(CommandSender sender) { + if (HooksManager.PERMISSIONS.isEnabled()) { + return HooksManager.PERMISSIONS.hasPermission(sender, permission); + } + return sender.hasPermission(permission); + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/Replaceable.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/Replaceable.java new file mode 100644 index 0000000..4e9b3b1 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/Replaceable.java @@ -0,0 +1,45 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.utils; + +import com.mojang.brigadier.context.CommandContext; +import net.minecraft.commands.CommandListenerWrapper; + +import java.util.function.Function; + +import static com.mojang.brigadier.arguments.StringArgumentType.getString; + +public class Replaceable implements Function<String, String> { + public final CommandContext<CommandListenerWrapper> context; + private Function<String, String> func; + + public Replaceable(CommandContext<CommandListenerWrapper> context, String str, String value) { + this.context = context; + this.func = s -> s.replace(str, getString(this.context, value)); + } + + public Replaceable replace(String str, String value) { + this.func = this.func.andThen(s -> s.replace(str, getString(this.context, value))); + return this; + } + + @Override + public String apply(String message) { + return this.func.apply(message); + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/Section.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/Section.java new file mode 100644 index 0000000..67578a3 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/Section.java @@ -0,0 +1,43 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.utils; + +import lombok.Getter; + +import java.util.List; + +@Getter +public abstract class Section { + private final String name; + private final List<String> comments; + private final List<String> inlineComments; + + public Section(final String name, List<String> comments, List<String> inlineComments) { + this.name = name; + this.comments = comments; + this.inlineComments = inlineComments; + } + + public Section(final String name, List<String> comments) { + this(name, comments, List.of()); + } + + public Section(final String name) { + this(name, List.of()); + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/TextUtils.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/TextUtils.java new file mode 100644 index 0000000..76bdf9c --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/TextUtils.java @@ -0,0 +1,105 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.utils; + +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.TextComponent; +import net.md_5.bungee.api.chat.hover.content.Text; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class TextUtils { + private final static Pattern TEXT_COMPONENT_PATTERN = Pattern.compile("\\[T](.*?)\\[/T]"); + + private final static Pattern HOVER_COMPONENT_PATTERN = Pattern.compile("\\[H](.*?)\\[/H]"); + private final static Pattern RUN_COMMAND_COMPONENT_PATTERN = Pattern.compile("\\[C](.*?)\\[/C]"); + private final static Pattern SUGGEST_COMMAND_COMPONENT_PATTERN = Pattern.compile("\\[SC](.*?)\\[/SC]"); + private final static Pattern COPY_COMPONENT_PATTERN = Pattern.compile("\\[CC](.*?)\\[/CC]"); + private final static Pattern URL_COMPONENT_PATTERN = Pattern.compile("\\[URL](.*?)\\[/URL]"); + + public static String noComponents(String text) { + String splitText = splitComponents(text).toString(); + Matcher matcher = TEXT_COMPONENT_PATTERN.matcher(splitText); + StringBuilder result = new StringBuilder(); + List<String> matches = new ArrayList<>(); + while (matcher.find()) + matches.add(matcher.group(1)); + List<String> splits = List.of(splitText.split(TEXT_COMPONENT_PATTERN.pattern())); + for (int i = 0; i < matches.size(); i++) { + result.append(splits.get(i)); + result.append(matches.get(i)); + } + if (splits.size() > matches.size()) + result.append(splits.get(splits.size() - 1)); + return result.toString(); + } + + public static BaseComponent[] components(String text) { + List<BaseComponent> components = new ArrayList<>(); + Matcher matcher = TEXT_COMPONENT_PATTERN.matcher(text); + List<String> matches = new ArrayList<>(); + while (matcher.find()) + matches.add(matcher.group(1)); + List<String> splits = List.of(text.split(TEXT_COMPONENT_PATTERN.pattern())); + for (int i = 0; i < matches.size(); i++) { + components.add(new TextComponent(TextComponent.fromLegacyText(splits.get(i)))); + components.add(textComponent(matches.get(i))); + } + if (splits.size() > matches.size()) + components.add(new TextComponent(TextComponent.fromLegacyText(splits.get(splits.size() - 1)))); + return components.toArray(new BaseComponent[0]); + } + + public static TextComponent textComponent(String text) { + TextComponent component = new TextComponent(TextComponent.fromLegacyText(splitComponents(text).toString())); + Matcher hoverMatcher = HOVER_COMPONENT_PATTERN.matcher(text); + Matcher runCommandMatcher = RUN_COMMAND_COMPONENT_PATTERN.matcher(text); + Matcher suggestCommandMatcher = SUGGEST_COMMAND_COMPONENT_PATTERN.matcher(text); + Matcher copyCommandMatcher = COPY_COMPONENT_PATTERN.matcher(text); + Matcher urlCommandMatcher = URL_COMPONENT_PATTERN.matcher(text); + if (hoverMatcher.find()) + component.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(TextComponent.fromLegacyText(hoverMatcher.group(1))))); + if (runCommandMatcher.find()) + component.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, runCommandMatcher.group(1))); + else if (suggestCommandMatcher.find()) + component.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, suggestCommandMatcher.group(1))); + else if (copyCommandMatcher.find()) + component.setClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, copyCommandMatcher.group(1))); + else if (urlCommandMatcher.find()) + component.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, urlCommandMatcher.group(1))); + return component; + } + + @NotNull + private static StringBuilder splitComponents(String text) { + StringBuilder result = new StringBuilder(); + for (String split1 : text.split(HOVER_COMPONENT_PATTERN.pattern())) + for (String split2 : split1.split(RUN_COMMAND_COMPONENT_PATTERN.pattern())) + for (String split3 : split2.split(SUGGEST_COMMAND_COMPONENT_PATTERN.pattern())) + for (String split4 : split3.split(COPY_COMPONENT_PATTERN.pattern())) + for (String split5 : split4.split(URL_COMPONENT_PATTERN.pattern())) + result.append(split5); + return result; + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/TitleConfig.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/TitleConfig.java new file mode 100644 index 0000000..4850ed5 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/TitleConfig.java @@ -0,0 +1,59 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.utils; + +import lombok.Getter; + +@Getter +public class TitleConfig { + private int in = 20, out = 20, stay = 20 * 6; + + public TitleConfig(String config) { + String[] configs = config.split(","); + for (String configItem : configs) { + String[] keyValue = configItem.split(":"); + if (keyValue.length == 2) { + String key = keyValue[0].trim().toLowerCase(); + String value = keyValue[1].trim(); + switch (key) { + case "in" -> { + try { + in = Integer.parseInt(value); + } catch (Exception ex) { + in = 20; + } + } + case "out" -> { + try { + out = Integer.parseInt(value); + } catch (Exception ex) { + out = 20; + } + } + case "stay" -> { + try { + stay = Integer.parseInt(value); + } catch (Exception ex) { + stay = 20 * 6; + } + } + } + } + } + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/UpdateChecker.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/UpdateChecker.java index 97f4ba5..d4a5e8f 100644 --- a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/UpdateChecker.java +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/UpdateChecker.java @@ -24,6 +24,9 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import ro.niconeko.astralbooks.AstralBooksPlugin; +import ro.niconeko.astralbooks.values.Messages; +import ro.niconeko.astralbooks.values.Permissions; +import ro.niconeko.astralbooks.values.Settings; import javax.net.ssl.HttpsURLConnection; import java.io.*; @@ -46,16 +49,15 @@ public UpdateChecker(AstralBooksPlugin plugin) { //Checking for updates if (this.checkForUpdate()) { Bukkit.getScheduler().runTask(this.plugin, () -> { - this.plugin.getLogger().info("An update for AstralBooks (v" + latestVersion + ") is available at:"); - this.plugin.getLogger().info("https://www.spigotmc.org/resources/astralbooks-a-book-for-everything." + resourceId + "/"); - Bukkit.getScheduler().runTask( - this.plugin, () -> Bukkit.getOnlinePlayers().stream() - .filter(player -> this.plugin.getAPI().hasPermission(player, "astralbooks.notify") || player.isOp()).forEach(player -> player.sendMessage(this.plugin.getSettings().getMessageSettings().getMessage(Message.NEW_VERSION_AVAILABLE) - .replace("%latest_version%", latestVersion == null ? "" : latestVersion).replace("%current_version%", this.plugin.getDescription().getVersion())))); + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&cAn update for AstralBooks (v" + latestVersion + ") is available!"); + MessageUtils.sendMessage(Bukkit.getConsoleSender(), "&aPlease download it from https://www.spigotmc.org/resources/astralbooks-a-book-for-everything." + resourceId + "/"); + Bukkit.getScheduler().runTask(this.plugin, + () -> Bukkit.getOnlinePlayers().stream().filter(Permissions.NOTIFY::has).forEach( + player -> Messages.NEW_VERSION_AVAILABLE.send( + player, str -> str.replace("%latest_version%", latestVersion == null ? "" : latestVersion).replace("%current_version%", this.plugin.getDescription().getVersion())))); }); } else - Bukkit.getScheduler().runTask(this.plugin, () -> - this.plugin.getLogger().info("No new version available!")); + Bukkit.getScheduler().runTask(this.plugin, () -> this.plugin.getLogger().info("No new version available!")); }, 0, 30 * 60 * 20); } @@ -88,14 +90,11 @@ public static boolean updateAvailable() { @EventHandler(priority = EventPriority.MONITOR) public void onJoin(PlayerJoinEvent event) { - if (!this.plugin.getSettings().isUpdateCheck()) - return; + if (!Settings.UPDATE_CHECK.get()) return; Player player = event.getPlayer(); - if (!this.plugin.getAPI().hasPermission(player, "astralbooks.notify")) - return; - if (!updateAvailable) - return; - player.sendMessage(this.plugin.getSettings().getMessageSettings().getMessage(Message.NEW_VERSION_AVAILABLE) - .replace("%latest_version%", latestVersion == null ? "" : latestVersion).replace("%current_version%", this.plugin.getDescription().getVersion())); + if (!Permissions.NOTIFY.has(player)) return; + if (!updateAvailable) return; + Messages.NEW_VERSION_AVAILABLE.send( + player, str -> str.replace("%latest_version%", latestVersion == null ? "" : latestVersion).replace("%current_version%", this.plugin.getDescription().getVersion())); } } diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/BooleanSetting.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/BooleanSetting.java new file mode 100644 index 0000000..ffd2d39 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/BooleanSetting.java @@ -0,0 +1,45 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.utils.settings; + +import org.bukkit.configuration.ConfigurationSection; + +import java.util.List; + +public class BooleanSetting extends Setting<Boolean> { + + public BooleanSetting(String value, Boolean defaultValue, List<String> comments, List<String> inlineComments) { + super(value, defaultValue, comments, inlineComments); + } + + public BooleanSetting(String value, Boolean defaultValue, List<String> comments) { + super(value, defaultValue, comments, List.of()); + } + + public BooleanSetting(String value, Boolean defaultValue) { + super(value, defaultValue, List.of(), List.of()); + } + + @Override + public final BooleanSetting load(ConfigurationSection section) { + if (section.isBoolean(super.key)) + super.value = section.getBoolean(super.key); + else super.setup(section); + return this; + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/IntegerSetting.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/IntegerSetting.java new file mode 100644 index 0000000..dfff9a0 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/IntegerSetting.java @@ -0,0 +1,45 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.utils.settings; + +import org.bukkit.configuration.ConfigurationSection; + +import java.util.List; + +public class IntegerSetting extends Setting<Integer> { + + public IntegerSetting(String value, Integer defaultValue, List<String> comments, List<String> inlineComments) { + super(value, defaultValue, comments, inlineComments); + } + + public IntegerSetting(String value, Integer defaultValue, List<String> comments) { + super(value, defaultValue, comments, List.of()); + } + + public IntegerSetting(String value, Integer defaultValue) { + super(value, defaultValue, List.of(), List.of()); + } + + @Override + public final IntegerSetting load(ConfigurationSection section) { + if (section.isBoolean(super.key)) + super.value = section.getInt(super.key); + else super.setup(section); + return this; + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/ListedMessageSetting.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/ListedMessageSetting.java new file mode 100644 index 0000000..3d2adc9 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/ListedMessageSetting.java @@ -0,0 +1,70 @@ +package ro.niconeko.astralbooks.utils.settings; + +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.ConfigurationSection; +import ro.niconeko.astralbooks.utils.MessageUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; + +public class ListedMessageSetting extends Setting<List<List<String>>> { + + public ListedMessageSetting(String key, List<List<String>> defaultValue, List<String> comments, List<String> inlineComments) { + super(key, defaultValue, comments, inlineComments); + } + + public ListedMessageSetting(String key, List<List<String>> defaultValue, List<String> comments) { + super(key, defaultValue, comments, List.of()); + } + + public ListedMessageSetting(String key, List<List<String>> defaultValue) { + super(key, defaultValue, List.of(), List.of()); + } + + @Override + public final ListedMessageSetting load(ConfigurationSection section) { + if (section.isList(super.key)) { + List<List<String>> result = new ArrayList<>(); + int index = 0; + for (String string : section.getStringList(super.key)) { + if (string.equals("[separator]")) + index++; + else { + if (index >= result.size()) + result.add(new ArrayList<>()); + result.get(index).add(string); + } + } + this.value = result; + } else { + List<String> result = new ArrayList<>(); + for (List<String> list : super.defaultValue) { + result.addAll(list); + result.add("[separator]"); + } + section.set(super.key, result); + if (!this.comments.isEmpty()) section.setComments(this.key, this.comments); + if (!this.inlineComments.isEmpty()) section.setInlineComments(this.key, this.inlineComments); + this.value = this.defaultValue; + } + return this; + } + + public int send(CommandSender sender, int page) { + return this.send(sender, page, Function.identity()); + } + + public int send(CommandSender sender, int page, Function<String, String> replacer) { + if (page < 0) + page = 0; + if (page >= super.value.size()) + page = super.value.size() - 1; + for (String message : super.value.get(page)) { + message = replacer.apply(message); + if (message != null && !message.isEmpty()) + MessageUtils.sendMessage(sender, message); + } + return super.value.size(); + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/MessageSetting.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/MessageSetting.java new file mode 100644 index 0000000..c61217e --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/MessageSetting.java @@ -0,0 +1,74 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.utils.settings; + +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.ConfigurationSection; +import ro.niconeko.astralbooks.utils.MessageUtils; + +import java.util.List; +import java.util.function.Function; + +public class MessageSetting extends Setting<List<String>> { + + public MessageSetting(String key, List<String> defaultValue, List<String> comments, List<String> inlineComments) { + super(key, defaultValue, comments, inlineComments); + } + + public MessageSetting(String key, List<String> defaultValue, List<String> comments) { + super(key, defaultValue, comments, List.of()); + } + + public MessageSetting(String key, List<String> defaultValue) { + super(key, defaultValue, List.of(), List.of()); + } + + @Override + public final MessageSetting load(ConfigurationSection section) { + if (section.isString(super.key)) + super.value = List.of(section.getString(super.key)); + else if (section.isList(super.key)) + super.value = section.getStringList(super.key); + else this.setup(section); + return this; + } + + @Override + protected void setup(ConfigurationSection section) { + if (this.defaultValue.size() > 1) + section.set(this.key, this.defaultValue); + else + section.set(this.key, this.defaultValue.get(0)); + if (!this.comments.isEmpty()) section.setComments(this.key, this.comments); + if (!this.inlineComments.isEmpty()) section.setInlineComments(this.key, this.inlineComments); + this.value = this.defaultValue; + } + + public int send(CommandSender sender) { + return this.send(sender, Function.identity()); + } + + public int send(CommandSender sender, Function<String, String> replacer) { + for (String message : super.value) { + message = replacer.apply(message); + if (message != null && !message.isEmpty()) + MessageUtils.sendMessage(sender, message); + } + return super.value.size(); + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/PortSetting.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/PortSetting.java new file mode 100644 index 0000000..2ed8c1c --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/PortSetting.java @@ -0,0 +1,59 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.utils.settings; + +import org.bukkit.configuration.ConfigurationSection; + +import java.util.List; + +public class PortSetting extends Setting<Integer> { + + public PortSetting(String key, String defaultValue, List<String> comments, List<String> inlineComments) { + super(key, Integer.parseInt(defaultValue), comments, inlineComments); + } + + public PortSetting(String key, String defaultValue, List<String> comments) { + super(key, Integer.parseInt(defaultValue), comments, List.of()); + } + + public PortSetting(String key, String defaultValue) { + super(key, Integer.parseInt(defaultValue), List.of(), List.of()); + } + + public PortSetting(String key, int defaultValue, List<String> comments, List<String> inlineComments) { + super(key, defaultValue, comments, inlineComments); + } + + public PortSetting(String key, int defaultValue, List<String> comments) { + super(key, defaultValue, comments, List.of()); + } + + public PortSetting(String key, int defaultValue) { + super(key, defaultValue, List.of(), List.of()); + } + + @Override + public final PortSetting load(ConfigurationSection section) { + if (section.isInt(super.key)) + super.value = section.getInt(super.key); + else if (section.isString(super.key)) + super.value = Integer.parseInt(section.getString(super.key)); + else super.setup(section); + return this; + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/SectionSetting.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/SectionSetting.java new file mode 100644 index 0000000..b4a7090 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/SectionSetting.java @@ -0,0 +1,54 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.utils.settings; + +import lombok.SneakyThrows; +import org.bukkit.configuration.ConfigurationSection; +import ro.niconeko.astralbooks.utils.Section; + +import java.lang.reflect.Field; + +public class SectionSetting<T extends Section> extends Setting<T> { + + public SectionSetting(T section) { + super(section.getName(), section, section.getComments(), section.getInlineComments()); + } + + @SneakyThrows + @Override + public SectionSetting<T> load(ConfigurationSection section) { + super.value = super.defaultValue; + ConfigurationSection upper; + if (section.isConfigurationSection(super.key)) + upper = section.getConfigurationSection(super.key); + else { + upper = section.createSection(super.key); + upper.setComments(super.key, super.value.getComments()); + upper.setInlineComments(super.key, super.value.getInlineComments()); + } + this.loadValues(upper); + return this; + } + + private void loadValues(ConfigurationSection section) throws IllegalAccessException { + for (Field field : super.value.getClass().getDeclaredFields()) { + if (field.get(super.value) instanceof Setting<?> setting) + setting.load(section); + } + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/Setting.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/Setting.java new file mode 100644 index 0000000..3646bc2 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/Setting.java @@ -0,0 +1,55 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.utils.settings; + +import org.bukkit.configuration.ConfigurationSection; + +import java.util.List; + +public abstract class Setting<T> { + protected T value; + protected final String key; + protected final T defaultValue; + protected final List<String> comments; + protected final List<String> inlineComments; + + protected Setting(final String key, final T defaultValue, final List<String> comments, final List<String> inlineComments) { + this.key = key; + this.defaultValue = defaultValue; + this.comments = comments; + this.inlineComments = inlineComments; + } + + protected void setup(ConfigurationSection section) { + section.set(this.key, this.defaultValue); + if (!this.comments.isEmpty()) section.setComments(this.key, this.comments); + if (!this.inlineComments.isEmpty()) section.setInlineComments(this.key, this.inlineComments); + this.value = this.defaultValue; + } + + public abstract Setting<T> load(ConfigurationSection section); + + public final T get() { + return this.value; + } + + public final Setting<T> set(T value) { + this.value = value; + return this; + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/StorageTypeSetting.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/StorageTypeSetting.java new file mode 100644 index 0000000..18f193c --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/StorageTypeSetting.java @@ -0,0 +1,59 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.utils.settings; + +import org.bukkit.configuration.ConfigurationSection; +import ro.niconeko.astralbooks.storage.StorageType; + +import java.util.List; + +public class StorageTypeSetting extends Setting<StorageType> { + + public StorageTypeSetting(String key, StorageType defaultValue, List<String> comments, List<String> inlineComments) { + super(key, defaultValue, comments, inlineComments); + } + + public StorageTypeSetting(String key, StorageType defaultValue, List<String> comments) { + super(key, defaultValue, comments, List.of()); + } + + public StorageTypeSetting(String key, StorageType defaultValue) { + super(key, defaultValue, List.of(), List.of()); + } + + @Override + public final StorageTypeSetting load(ConfigurationSection section) { + if (section.isString(super.key)) + super.value = StorageType.fromString(section.getString(super.key)); + else { + super.value = this.defaultValue; + section.set(super.key, this.defaultValue.toString()); + if (!this.comments.isEmpty()) section.setComments(super.key, this.comments); + if (!this.inlineComments.isEmpty()) section.setInlineComments(super.key, this.inlineComments); + } + return this; + } + + @Override + protected void setup(ConfigurationSection section) { + section.set(this.key, this.defaultValue.toString()); + if (!this.comments.isEmpty()) section.setComments(this.key, this.comments); + if (!this.inlineComments.isEmpty()) section.setInlineComments(this.key, this.inlineComments); + this.value = this.defaultValue; + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/StringSetting.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/StringSetting.java new file mode 100644 index 0000000..d21facb --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/utils/settings/StringSetting.java @@ -0,0 +1,45 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.utils.settings; + +import org.bukkit.configuration.ConfigurationSection; + +import java.util.List; + +public class StringSetting extends Setting<String> { + + public StringSetting(String key, String defaultValue, List<String> comments, List<String> inlineComments) { + super(key, defaultValue, comments, inlineComments); + } + + public StringSetting(String key, String defaultValue, List<String> comments) { + super(key, defaultValue, comments, List.of()); + } + + public StringSetting(String key, String defaultValue) { + super(key, defaultValue, List.of(), List.of()); + } + + @Override + public final StringSetting load(ConfigurationSection section) { + if (section.isString(super.key)) + super.value = section.getString(super.key); + else super.setup(section); + return this; + } +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/values/Messages.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/values/Messages.java new file mode 100644 index 0000000..f6b7182 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/values/Messages.java @@ -0,0 +1,94 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.values; + +import ro.niconeko.astralbooks.utils.settings.ListedMessageSetting; +import ro.niconeko.astralbooks.utils.settings.MessageSetting; +import ro.niconeko.astralbooks.utils.settings.StringSetting; + +import java.util.List; + +public class Messages { + public static final StringSetting HEADER = new StringSetting("header", "#ffcf96&lAstralBooks &8» "); + public static final MessageSetting NO_PERMISSION = new MessageSetting("no_permission", List.of("[header]#ff8080You do not have permission!")); + public static final MessageSetting CONFIG_RELOADED = new MessageSetting("config_reloaded", List.of("[header]#cdfad5Config reloaded!")); + public static final MessageSetting SET_BOOK_SUCCESSFULLY = new MessageSetting("set_book_successfully", List.of("[header]#cdfad5You have set the book for %npc%!")); + public static final MessageSetting REMOVED_BOOK_SUCCESSFULLY = new MessageSetting("removed_book_successfully", List.of("[header]#cdfad5You have removed the book for %npc%!")); + public static final MessageSetting NO_NPC_SELECTED = new MessageSetting("no_npc_selected", List.of("[header]#ff8080You need to have an NPC selected!")); + public static final MessageSetting NO_WRITTEN_BOOK_IN_HAND = new MessageSetting("no_written_book_in_hand", List.of("[header]#ff8080You need to have a written book in your hand!")); + public static final MessageSetting NO_WRITABLE_BOOK_IN_HAND = new MessageSetting("no_writable_book_in_hand", List.of("[header]#ff8080You need to have a writable book in your hand!")); + public static final MessageSetting NO_ITEM_IN_HAND = new MessageSetting("no_item_in_hand", List.of("[header]#ff8080You need to have an item in your hand!")); + public static final MessageSetting NO_BOOK_FOR_NPC = new MessageSetting("no_book_for_npc", List.of("[header]#ff8080This NPC doesn't have a book!")); + public static final MessageSetting NO_BOOK_FOR_FILTER = new MessageSetting("no_book_for_filter", List.of("[header]#ff8080This filter doesn't have a book!")); + public static final MessageSetting FILTER_SAVED = new MessageSetting("filter_saved", List.of("[header]#cdfad5Filter %filter_name% was saved.")); + public static final MessageSetting FILTER_REMOVED = new MessageSetting("filter_removed", List.of("[header]#cdfad5Filter %filter_name% was removed.")); + public static final MessageSetting BOOK_RECEIVED = new MessageSetting("book_received", List.of("[header]#cdfad5You received the book in your inventory!")); + public static final MessageSetting CITIZENS_NOT_ENABLED = new MessageSetting("citizens_not_enabled", List.of("[header]#ff8080Citizens plugin is not enabled! This command requires Citizens to be installed!")); + public static final MessageSetting SET_CUSTOM_COMMAND_SUCCESSFULLY = new MessageSetting("set_custom_command_successfully", List.of("[header]#cdfad5Command %command% has been set!")); + public static final MessageSetting REMOVED_CUSTOM_COMMAND_SUCCESSFULLY = new MessageSetting("removed_custom_command_successfully", List.of("[header]#cdfad5Command %command% has been removed!")); + public static final MessageSetting CONSOLE_CANNOT_USE_COMMAND = new MessageSetting("console_cannot_use_command", List.of("[header]#ff8080You have to be a player if you want to use this command!")); + public static final MessageSetting PLAYER_CANNOT_USE_COMMAND = new MessageSetting("player_cannot_use_command", List.of("[header]#ff8080Console command only!")); + public static final MessageSetting NEW_VERSION_AVAILABLE = new MessageSetting("new_version_available", List.of("[header]#cdfad5A new version of AstralBooks is available!")); + public static final MessageSetting FILTER_APPLIED_TO_ITEM = new MessageSetting("filter_applied_to_item", List.of("[header]#cdfad5Filter %filter_name% has been applied to your holding item.")); + public static final MessageSetting FILTER_REMOVED_FROM_ITEM = new MessageSetting("filter_removed_from_item", List.of("[header]#cdfad5The filter has been removed from your holding item.")); + public static final MessageSetting PLAYER_NOT_FOUND = new MessageSetting("player_not_found", List.of("[header]#ff8080Player not found!")); + public static final MessageSetting FILTER_NOT_FOUND = new MessageSetting("filter_not_found", List.of("[header]#ff8080Filter not found!")); + public static final MessageSetting SET_JOIN_BOOK_SUCCESSFULLY = new MessageSetting("set_join_book_successfully", List.of("[header]#cdfad5You have set the join book!")); + public static final MessageSetting REMOVED_JOIN_BOOK_SUCCESSFULLY = new MessageSetting("removed_join_book_successfully", List.of("[header]#cdfad5You have removed the join book!")); + public static final MessageSetting FILTER_NAME_INVALID = new MessageSetting("filter_name_invalid", List.of("[header]#ff8080The filter name should only contain letters, numbers, dashes and underscores!")); + public static final MessageSetting COMMAND_NAME_INVALID = new MessageSetting("command_name_invalid", List.of("[header]#ff8080The command name should only contain letters, numbers, dashes and underscores!")); + public static final MessageSetting PERMISSION_INVALID = new MessageSetting("permission_invalid", List.of("[header]#ff8080The permission should only contain letters, numbers, dots, dashes and underscores!")); + public static final MessageSetting OPERATION_FAILED = new MessageSetting("operation_failed", List.of("[header]#ff8080The operation failed! Please check the console for errors!")); + public static final MessageSetting FILTERS_LIST_PAGE_NOT_FOUND = new MessageSetting("filters_list_page_not_found", List.of("[header]#ff8080There's no filters at page %page%")); + public static final MessageSetting FILTERS_LIST_PRESENT = new MessageSetting("filters_list_present", List.of("[header]#cdfad5Here's the list of filters present:")); + public static final MessageSetting FILTERS_LIST_NO_FILTER_PRESENT = new MessageSetting("filter_list_no_filter_present", List.of("[header]#ff8080There is no filter installed!")); + public static final MessageSetting OPENED_BOOK_FOR_PLAYERS = new MessageSetting("opened_books_for_player", List.of("[header]#cdfad5You've successfully opened a book for %success% player(s). There was %failed% failed attempts.")); + public static final MessageSetting OPENED_BOOK_FOR_PLAYER = new MessageSetting("opened_book_for_player", List.of("[header]#cdfad5You've successfully opened a book for %player%.")); + public static final MessageSetting BOOK_APPLY_TO_BLOCK_TIMEOUT = new MessageSetting("book_apply_to_block_timeout", List.of("[header]#cdfad5You have 1 minute to apply the book! Right click the block you want to apply the book!")); + public static final MessageSetting BOOK_APPLY_TO_ENTITY_TIMEOUT = new MessageSetting("book_apply_to_entity_timeout", List.of("[header]#cdfad5You have 1 minute to apply the book! Right click the entity you want to apply the book!")); + public static final MessageSetting BOOK_REMOVE_FROM_BLOCK_TIMEOUT = new MessageSetting("book_remove_from_block_timeout", List.of("[header]#cdfad5You have 1 minute to remove the book! Right click the block you want the book to get removed!")); + public static final MessageSetting BOOK_REMOVE_FROM_ENTITY_TIMEOUT = new MessageSetting("book_remove_from_entity_timeout", List.of("[header]#cdfad5You have 1 minute to remove the book! Right click the entity you want the book to get removed!")); + public static final MessageSetting BOOK_APPLIED_SUCCESSFULLY_TO_BLOCK = new MessageSetting("book_applied_successfully_to_block", List.of("[header]#cdfad5The book have been applied to block! (%block_x%, %block_y%, %block_z%)")); + public static final MessageSetting BOOK_APPLIED_SUCCESSFULLY_TO_ENTITY = new MessageSetting("book_applied_successfully_to_entity", List.of("[header]#cdfad5The book have been applied to entity! (%type%)")); + public static final MessageSetting BOOK_REMOVED_SUCCESSFULLY_FROM_BLOCK = new MessageSetting("book_removed_successfully_from_block", List.of("[header]#cdfad5The book have been removed from block! (%block_x%, %block_y%, %block_z%)")); + public static final MessageSetting BOOK_REMOVED_SUCCESSFULLY_FROM_ENTITY = new MessageSetting("book_removed_successfully_from_entity", List.of("[header]#cdfad5The book have been removed from entity! (%type%)")); + public static final MessageSetting ENTITY_IS_NPC = new MessageSetting("entity_is_npc", List.of("[header]#ff8080The entity is an Citizens NPC. Use &f/abook npc #ff8080to set a book for this type of entity!")); + public static final MessageSetting BOOK_SECURITY_NOT_ENABLED = new MessageSetting("book_security_not_enabled", List.of("[header]#ff8080Book security is not enabled!")); + public static final MessageSetting BOOK_SECURITY_NOT_FOUND = new MessageSetting("book_security_not_found", List.of("[header]#ff8080No security book found!")); + public static final MessageSetting BOOK_SECURITY_LIST_PRESENT = new MessageSetting("book_security_list_found", List.of("[header]#cdfad5Here's the list of books saved:")); + public static final StringSetting BOOK_SECURITY_DATE_FORMAT = new StringSetting("book_security_date_format", "dd/MM/yyyy-HH:mm:ss", List.of("https://help.gooddata.com/cloudconnect/manual/date-and-time-format.html")); + + + public static final MessageSetting COMMAND_MAIN_HELP = new MessageSetting("command.main.help", List.of("[header]#ff8080For a list of subcommands: [T]/afurnaces help[H]Click to execute.[/H][C]/afurnaces help[/C][/T]")); + public static final MessageSetting COMMAND_MAIN_UNKNOWN = new MessageSetting("command.main.unknown", List.of("[header]#ff8080Unknown subcommand: #cdfad5%command%")); + public static final ListedMessageSetting COMMAND_HELP_LIST = new ListedMessageSetting("command.help.list", List.of( + List.of( + "&8&m #ffcf96&lAstralBooks&8&m ", + " ", + " #ff8080&l<> &f- Required, #cdfad5&l[] &f- Optional", + " ", + " [T]#ffcf96/abooks help[H]Click to execute.[/H][C]/abooks help[/C][/T] #f6fdc3- #cdfad5Shows those help messages", + " [T]#ffcf96/abooks reload[H]Click to execute.[/H][C]/abooks reload[/C][/T] #f6fdc3- #cdfad5Reloads the plugin", + " ", + " [T]&8« &7Prev Page &8«[H]Click to go to previous page.[/H][/T]&8&m [T]&8» &7Next Page &8»[H]Click to go to next page.[/H][C]/afurnaces help 2[/C][/T] " + ) + )); + public static final MessageSetting COMMAND_HELP_USAGE = new MessageSetting("command.help.usage", List.of("[header]#ff8080Usage: [T]/afurnaces help <page>[H]Click to copy to chat.[/H][SC]/afurnaces help [/SC][/T]")); + public static final MessageSetting COMMAND_HELP_INVALID_PAGE = new MessageSetting("command.help.invalid_page", List.of("[header]#ff8080Invalid page: #cdfad5%page%")); + +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/values/Permissions.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/values/Permissions.java new file mode 100644 index 0000000..13d68e9 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/values/Permissions.java @@ -0,0 +1,56 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.values; + +import org.bukkit.command.CommandSender; +import ro.niconeko.astralbooks.managers.HooksManager; +import ro.niconeko.astralbooks.utils.Permission; + +public class Permissions { + public final static Permission COMMAND_HELP = new Permission("astralbooks.command.help"); + public final static Permission COMMAND_SECURITY = new Permission("astralbooks.command.security"); + public final static Permission COMMAND_SECURITY_LIST = new Permission("astralbooks.command.security.list"); + public final static Permission COMMAND_SECURITY_GETBOOK = new Permission("astralbooks.command.security.getbook"); + public final static Permission COMMAND_INTERACTION = new Permission("astralbooks.command.interaction"); + public final static Permission COMMAND_INTERACTION_SET = new Permission("astralbooks.command.interaction.set"); + public final static Permission COMMAND_INTERACTION_SET_BLOCK = new Permission("astralbooks.command.interaction.set.block"); + public final static Permission COMMAND_INTERACTION_SET_ENTITY = new Permission("astralbooks.command.interaction.set.entity"); + public final static Permission COMMAND_INTERACTION_REMOVE = new Permission("astralbooks.command.interaction.remove"); + public final static Permission COMMAND_INTERACTION_REMOVE_BLOCK = new Permission("astralbooks.command.interaction.remove.block"); + public final static Permission COMMAND_INTERACTION_REMOVE_ENTITY = new Permission("astralbooks.command.interaction.remove.entity"); + public final static Permission COMMAND_NPC = new Permission("astralbooks.command.npc"); + public final static Permission COMMAND_NPC_SET = new Permission("astralbooks.command.npc.set"); + public final static Permission COMMAND_NPC_REMOVE = new Permission("astralbooks.command.npc.remove"); + public final static Permission COMMAND_NPC_GETBOOK = new Permission("astralbooks.command.npc.getbook"); + public final static Permission COMMAND_ACTIONITEM = new Permission("astralbooks.command.actionitem"); + public final static Permission COMMAND_ACTIONITEM_SET = new Permission("astralbooks.command.actionitem.set"); + public final static Permission COMMAND_ACTIONITEM_REMOVE = new Permission("astralbooks.command.actionitem.remove"); + public final static Permission COMMAND_FORCEOPEN = new Permission("astralbooks.command.forceopen"); + public final static Permission COMMAND_RELOAD = new Permission("astralbooks.command.reload"); + public final static Permission NO_JOIN_BOOK = new Permission("astralbooks.nojoinbook"); + public final static Permission NOTIFY = new Permission("astralbooks.notify"); + public static final Permission COMMAND = new Permission("astralbooks.command"); + + public static boolean has(CommandSender sender, String permission) { + if (HooksManager.PERMISSIONS.isEnabled()) { + return HooksManager.PERMISSIONS.hasPermission(sender, permission); + } + return sender.hasPermission(permission); + } + +} diff --git a/astralbooks-core/src/main/java/ro/niconeko/astralbooks/values/Settings.java b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/values/Settings.java new file mode 100644 index 0000000..c89c2a9 --- /dev/null +++ b/astralbooks-core/src/main/java/ro/niconeko/astralbooks/values/Settings.java @@ -0,0 +1,37 @@ +/* + * CitizensBooks + * Copyright (c) 2023 @ Drăghiciu 'NicoNekoDev' Nicolae + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ro.niconeko.astralbooks.values; + +import ro.niconeko.astralbooks.storage.settings.StorageSettings; +import ro.niconeko.astralbooks.utils.settings.*; + +import java.util.List; + +public class Settings { + public static final BooleanSetting METRICS_ENABLED = new BooleanSetting("metrics", true, List.of( + "Metrics can be viewed at https://bstats.org/plugin/bukkit/AstralBooks/18026", + "It requires server restart to take effect!" + )); + public static final BooleanSetting UPDATE_CHECK = new BooleanSetting("update_check", true); + public static final BooleanSetting JOIN_BOOK_ENABLED = new BooleanSetting("join_book_enabled", false); + public static final BooleanSetting JOIN_BOOK_ALWAYS_SHOW = new BooleanSetting("join_book_always_show", false); + public static final BooleanSetting JOIN_BOOK_DELAY_ENABLED = new BooleanSetting("join_book_delay_enabled", false); + public static final IntegerSetting JOIN_BOOK_DELAY = new IntegerSetting("join_book_delay", 0); + public static final BooleanSetting SIGN_BOOK_SECURITY_ENABLED = new BooleanSetting("sign_book_security_enabled", false); + public static final SectionSetting<StorageSettings> STORAGE = new SectionSetting<>(new StorageSettings()); +} \ No newline at end of file diff --git a/astralbooks-core/src/main/resources/command.commodore b/astralbooks-core/src/main/resources/command.commodore deleted file mode 100644 index 6d24e28..0000000 --- a/astralbooks-core/src/main/resources/command.commodore +++ /dev/null @@ -1,116 +0,0 @@ -abook { - help { - page brigadier:integer; - } - security { - list { - player brigadier:string single_word { - page brigadier:integer; - } - *; - } - getbook { - player brigadier:string single_word { - timestamp brigadier:long; - } - } - } - interaction { - set { - block { - right; - left; - } - entity { - right; - left; - } - } - remove { - block { - right; - left; - } - entity { - right; - left; - } - } - } - actionitem { - set { - filter brigadier:string single_word { - right; - left; - } - } - remove { - right; - left; - } - } - forcedecrypt; - forceopen { - filter brigadier:string single_word { - player brigadier:string single_word; - *; - } - } - closebook { - author brigadier:string single_word { - title brigadier:string greedy_phrase; - } - } - about; - reload; - setjoin; - remjoin; - openbook; - setcmd { - command brigadier:string single_word { - filter brigadier:string single_word { - permission brigadier:string single_word; - } - } - } - remcmd { - command brigadier:string single_word; - } - filter { - set { - name brigadier:string single_word; - } - remove { - name brigadier:string single_word; - } - getbook { - name brigadier:string single_word; - } - list { - page brigadier:integer; - } - } - remcmd { - command brigadier:string single_word; - } - npc { - set { - name brigadier:string single_word { - right; - left; - } - } - remove { - name brigadier:string single_word { - right; - left; - } - } - getbook { - name brigadier:string single_word { - right; - left; - } - } - } -} \ No newline at end of file diff --git a/astralbooks-core/src/main/resources/plugin.yml b/astralbooks-core/src/main/resources/plugin.yml index 7b953c5..a9f0ead 100644 --- a/astralbooks-core/src/main/resources/plugin.yml +++ b/astralbooks-core/src/main/resources/plugin.yml @@ -4,101 +4,4 @@ author: NicoNekoDev main: ro.niconeko.astralbooks.AstralBooksPlugin softdepend: [ PlaceholderAPI, Citizens, LuckPerms, Vault, AuthMe, Authme, CitizensBooks ] website: https://www.spigotmc.org/resources/astralbooks-a-book-for-everything.37465/ -api-version: 1.13 -commands: - abook: - description: Basic AstralBooks command. - permission: astralbooks.command.* -permissions: - astralbooks.*: - children: - astralbooks.command.help: true - astralbooks.command.npc.set: true - astralbooks.command.npc.remove: true - astralbooks.command.npc.getbook: true - astralbooks.command.openbook: true - astralbooks.command.closebook: true - astralbooks.command.reload: true - astralbooks.command.setcmd: true - astralbooks.command.remcmd: true - astralbooks.command.filter.set: true - astralbooks.command.filter.remove: true - astralbooks.command.filter.getbook: true - astralbooks.command.forcedecrypt: true - astralbooks.command.forceopen: true - astralbooks.command.actionitem.set: true - astralbooks.command.actionitem.remove: true - astralbooks.command.setjoin: true - astralbooks.command.remjoin: true - astralbooks.nojoinbook: true - astralbooks.notify: true - astralbooks.command.*: - children: - astralbooks.command.help: true - astralbooks.command.npc.set: true - astralbooks.command.npc.remove: true - astralbooks.command.npc.getbook: true - astralbooks.command.openbook: true - astralbooks.command.closebook: true - astralbooks.command.reload: true - astralbooks.command.setcmd: true - astralbooks.command.remcmd: true - astralbooks.command.filter.set: true - astralbooks.command.filter.remove: true - astralbooks.command.filter.getbook: true - astralbooks.command.forcedecrypt: true - astralbooks.command.forceopen: true - astralbooks.command.actionitem.set: true - astralbooks.command.actionitem.remove: true - astralbooks.command.setjoin: true - astralbooks.command.remjoin: true - astralbooks.command.filter.*: - children: - astralbooks.command.filter.set: true - astralbooks.command.filter.remove: true - astralbooks.command.filter.getbook: true - astralbooks.command.actionitem.*: - children: - astralbooks.command.actionitem.set: true - astralbooks.command.actionitem.remove: true - astralbooks.command.npc.*: - children: - astralbooks.command.npc.set: true - astralbooks.command.npc.remove: true - astralbooks.command.npc.getbook: true - astralbooks.command.help: - default: false - astralbooks.command.npc.set: - default: false - astralbooks.command.npc.remove: - default: false - astralbooks.command.npc.getbook: - default: false - astralbooks.command.openbook: - default: false - astralbooks.command.reload: - default: false - astralbooks.command.setcmd: - default: false - astralbooks.command.remcmd: - default: false - astralbooks.command.filter.set: - default: false - astralbooks.command.filter.remove: - default: false - astralbooks.command.filter.getbook: - default: false - astralbooks.command.actionitem.set: - default: false - astralbooks.command.actionitem.remove: - default: false - astralbooks.command.setjoin: - default: false - astralbooks.command.remjoin: - default: false - astralbooks.command.closebook: - default: false - astralbooks.notify: - default: op - astralbooks.nojoinbook: - default: false \ No newline at end of file +api-version: 1.13 \ No newline at end of file diff --git a/astralbooks-v1_17_R1/src/main/java/ro/niconeko/astralbooks/dist/v1_17_R1/DistributionHandler.java b/astralbooks-v1_17_R1/src/main/java/ro/niconeko/astralbooks/dist/v1_17_R1/DistributionHandler.java index 925977f..ca821fe 100644 --- a/astralbooks-v1_17_R1/src/main/java/ro/niconeko/astralbooks/dist/v1_17_R1/DistributionHandler.java +++ b/astralbooks-v1_17_R1/src/main/java/ro/niconeko/astralbooks/dist/v1_17_R1/DistributionHandler.java @@ -22,10 +22,14 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; import net.citizensnpcs.api.npc.NPC; +import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.protocol.game.ClientboundOpenBookPacket; import net.minecraft.world.InteractionHand; +import org.bukkit.Bukkit; import org.bukkit.Material; +import org.bukkit.craftbukkit.v1_17_R1.CraftServer; import org.bukkit.craftbukkit.v1_17_R1.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_17_R1.inventory.CraftMetaBook; import org.bukkit.entity.Player; @@ -49,6 +53,12 @@ public String getVersion() { return "1_17_R1"; } + @Override + @SuppressWarnings("unchecked") + public void register(LiteralArgumentBuilder<?> builder) { + ((CraftServer) Bukkit.getServer()).getServer().vanillaCommandDispatcher.getDispatcher().register((LiteralArgumentBuilder<CommandSourceStack>) builder); + } + @Override public void sendRightClick(Player player) { ((CraftPlayer) player).getHandle().connection.send(new ClientboundOpenBookPacket(InteractionHand.MAIN_HAND)); diff --git a/astralbooks-v1_18_R1/src/main/java/ro/niconeko/astralbooks/dist/v1_18_R1/DistributionHandler.java b/astralbooks-v1_18_R1/src/main/java/ro/niconeko/astralbooks/dist/v1_18_R1/DistributionHandler.java index d6a6d1e..74b7178 100644 --- a/astralbooks-v1_18_R1/src/main/java/ro/niconeko/astralbooks/dist/v1_18_R1/DistributionHandler.java +++ b/astralbooks-v1_18_R1/src/main/java/ro/niconeko/astralbooks/dist/v1_18_R1/DistributionHandler.java @@ -22,11 +22,15 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; import net.citizensnpcs.api.npc.NPC; +import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.protocol.game.ClientboundOpenBookPacket; import net.minecraft.world.InteractionHand; +import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.craftbukkit.v1_18_R1.CraftServer; import org.bukkit.craftbukkit.v1_18_R1.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_18_R1.inventory.CraftMetaBook; import org.bukkit.entity.Player; @@ -45,6 +49,17 @@ public DistributionHandler(AstralBooksPlugin plugin) throws NoSuchFieldException super(plugin, CraftMetaBook.class.getDeclaredField("pages")); } + @Override + public String getVersion() { + return "1_18_R1"; + } + + @Override + @SuppressWarnings("unchecked") + public void register(LiteralArgumentBuilder<?> builder) { + ((CraftServer) Bukkit.getServer()).getServer().vanillaCommandDispatcher.getDispatcher().register((LiteralArgumentBuilder<CommandSourceStack>) builder); + } + @Override public void sendRightClick(Player player) { ((CraftPlayer) player).getHandle().connection.send(new ClientboundOpenBookPacket(InteractionHand.MAIN_HAND)); @@ -88,11 +103,6 @@ public ItemStack convertJsonToBook(JsonObject jsonBook) throws IllegalAccessExce return newBook; } - @Override - public String getVersion() { - return "1_18_R1"; - } - @Override public void setConfigComment(ConfigurationSection config, String path, Optional<List<String>> comments) { comments.ifPresent(strings -> config.setComments(path, strings)); diff --git a/astralbooks-v1_18_R2/src/main/java/ro/niconeko/astralbooks/dist/v1_18_R2/DistributionHandler.java b/astralbooks-v1_18_R2/src/main/java/ro/niconeko/astralbooks/dist/v1_18_R2/DistributionHandler.java index 370e374..1d92321 100644 --- a/astralbooks-v1_18_R2/src/main/java/ro/niconeko/astralbooks/dist/v1_18_R2/DistributionHandler.java +++ b/astralbooks-v1_18_R2/src/main/java/ro/niconeko/astralbooks/dist/v1_18_R2/DistributionHandler.java @@ -22,11 +22,15 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; import net.citizensnpcs.api.npc.NPC; +import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.protocol.game.ClientboundOpenBookPacket; import net.minecraft.world.InteractionHand; +import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.craftbukkit.v1_18_R2.CraftServer; import org.bukkit.craftbukkit.v1_18_R2.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_18_R2.inventory.CraftMetaBook; import org.bukkit.entity.Player; @@ -45,6 +49,17 @@ public DistributionHandler(AstralBooksPlugin plugin) throws NoSuchFieldException super(plugin, CraftMetaBook.class.getDeclaredField("pages")); } + @Override + public String getVersion() { + return "1_18_R2"; + } + + @Override + @SuppressWarnings("unchecked") + public void register(LiteralArgumentBuilder<?> builder) { + ((CraftServer) Bukkit.getServer()).getServer().vanillaCommandDispatcher.getDispatcher().register((LiteralArgumentBuilder<CommandSourceStack>) builder); + } + @Override public void sendRightClick(Player player) { ((CraftPlayer) player).getHandle().connection.send(new ClientboundOpenBookPacket(InteractionHand.MAIN_HAND)); @@ -88,11 +103,6 @@ public ItemStack convertJsonToBook(JsonObject jsonBook) throws IllegalAccessExce return newBook; } - @Override - public String getVersion() { - return "1_18_R2"; - } - @Override public void setConfigComment(ConfigurationSection config, String path, Optional<List<String>> comments) { comments.ifPresent(strings -> config.setComments(path, strings)); diff --git a/astralbooks-v1_19_R1/src/main/java/ro/niconeko/astralbooks/dist/v1_19_R1/DistributionHandler.java b/astralbooks-v1_19_R1/src/main/java/ro/niconeko/astralbooks/dist/v1_19_R1/DistributionHandler.java index 26bf71f..f0b343d 100644 --- a/astralbooks-v1_19_R1/src/main/java/ro/niconeko/astralbooks/dist/v1_19_R1/DistributionHandler.java +++ b/astralbooks-v1_19_R1/src/main/java/ro/niconeko/astralbooks/dist/v1_19_R1/DistributionHandler.java @@ -22,11 +22,15 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; import net.citizensnpcs.api.npc.NPC; +import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.protocol.game.ClientboundOpenBookPacket; import net.minecraft.world.InteractionHand; +import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.craftbukkit.v1_19_R1.CraftServer; import org.bukkit.craftbukkit.v1_19_R1.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_19_R1.inventory.CraftMetaBook; import org.bukkit.entity.Player; @@ -45,6 +49,17 @@ public DistributionHandler(AstralBooksPlugin plugin) throws NoSuchFieldException super(plugin, CraftMetaBook.class.getDeclaredField("pages")); } + @Override + public String getVersion() { + return "1_19_R1"; + } + + @Override + @SuppressWarnings("unchecked") + public void register(LiteralArgumentBuilder<?> builder) { + ((CraftServer) Bukkit.getServer()).getServer().vanillaCommandDispatcher.getDispatcher().register((LiteralArgumentBuilder<CommandSourceStack>) builder); + } + @Override public void sendRightClick(Player player) { ((CraftPlayer) player).getHandle().connection.send(new ClientboundOpenBookPacket(InteractionHand.MAIN_HAND)); @@ -88,11 +103,6 @@ public ItemStack convertJsonToBook(JsonObject jsonBook) throws IllegalAccessExce return newBook; } - @Override - public String getVersion() { - return "1_19_R1"; - } - @Override public void setConfigComment(ConfigurationSection config, String path, Optional<List<String>> comments) { comments.ifPresent(strings -> config.setComments(path, strings)); diff --git a/astralbooks-v1_19_R2/src/main/java/ro/niconeko/astralbooks/dist/v1_19_R2/DistributionHandler.java b/astralbooks-v1_19_R2/src/main/java/ro/niconeko/astralbooks/dist/v1_19_R2/DistributionHandler.java index 2f1a6cb..54e5ce9 100644 --- a/astralbooks-v1_19_R2/src/main/java/ro/niconeko/astralbooks/dist/v1_19_R2/DistributionHandler.java +++ b/astralbooks-v1_19_R2/src/main/java/ro/niconeko/astralbooks/dist/v1_19_R2/DistributionHandler.java @@ -22,11 +22,15 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; import net.citizensnpcs.api.npc.NPC; +import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.protocol.game.ClientboundOpenBookPacket; import net.minecraft.world.InteractionHand; +import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.craftbukkit.v1_19_R2.CraftServer; import org.bukkit.craftbukkit.v1_19_R2.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_19_R2.inventory.CraftMetaBook; import org.bukkit.entity.Player; @@ -45,6 +49,17 @@ public DistributionHandler(AstralBooksPlugin plugin) throws NoSuchFieldException super(plugin, CraftMetaBook.class.getDeclaredField("pages")); } + @Override + public String getVersion() { + return "1_19_R2"; + } + + @Override + @SuppressWarnings("unchecked") + public void register(LiteralArgumentBuilder<?> builder) { + ((CraftServer) Bukkit.getServer()).getServer().vanillaCommandDispatcher.getDispatcher().register((LiteralArgumentBuilder<CommandSourceStack>) builder); + } + @Override public void sendRightClick(Player player) { ((CraftPlayer) player).getHandle().connection.send(new ClientboundOpenBookPacket(InteractionHand.MAIN_HAND)); @@ -88,11 +103,6 @@ public ItemStack convertJsonToBook(JsonObject jsonBook) throws IllegalAccessExce return newBook; } - @Override - public String getVersion() { - return "1_19_R2"; - } - @Override public void setConfigComment(ConfigurationSection config, String path, Optional<List<String>> comments) { comments.ifPresent(strings -> config.setComments(path, strings)); diff --git a/astralbooks-v1_19_R3/src/main/java/ro/niconeko/astralbooks/dist/v1_19_R3/DistributionHandler.java b/astralbooks-v1_19_R3/src/main/java/ro/niconeko/astralbooks/dist/v1_19_R3/DistributionHandler.java index 80fdc5e..173628f 100644 --- a/astralbooks-v1_19_R3/src/main/java/ro/niconeko/astralbooks/dist/v1_19_R3/DistributionHandler.java +++ b/astralbooks-v1_19_R3/src/main/java/ro/niconeko/astralbooks/dist/v1_19_R3/DistributionHandler.java @@ -22,11 +22,15 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; import net.citizensnpcs.api.npc.NPC; +import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.protocol.game.ClientboundOpenBookPacket; import net.minecraft.world.InteractionHand; +import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.craftbukkit.v1_19_R3.CraftServer; import org.bukkit.craftbukkit.v1_19_R3.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_19_R3.inventory.CraftMetaBook; import org.bukkit.entity.Player; @@ -45,6 +49,17 @@ public DistributionHandler(AstralBooksPlugin plugin) throws NoSuchFieldException super(plugin, CraftMetaBook.class.getDeclaredField("pages")); } + @Override + public String getVersion() { + return "1_19_R3"; + } + + @Override + @SuppressWarnings("unchecked") + public void register(LiteralArgumentBuilder<?> builder) { + ((CraftServer) Bukkit.getServer()).getServer().vanillaCommandDispatcher.getDispatcher().register((LiteralArgumentBuilder<CommandSourceStack>) builder); + } + @Override public void sendRightClick(Player player) { ((CraftPlayer) player).getHandle().connection.send(new ClientboundOpenBookPacket(InteractionHand.MAIN_HAND)); @@ -88,11 +103,6 @@ public ItemStack convertJsonToBook(JsonObject jsonBook) throws IllegalAccessExce return newBook; } - @Override - public String getVersion() { - return "1_19_R3"; - } - @Override public void setConfigComment(ConfigurationSection config, String path, Optional<List<String>> comments) { comments.ifPresent(strings -> config.setComments(path, strings)); diff --git a/astralbooks-v1_20_R1/src/main/java/ro/niconeko/astralbooks/dist/v1_20_R1/DistributionHandler.java b/astralbooks-v1_20_R1/src/main/java/ro/niconeko/astralbooks/dist/v1_20_R1/DistributionHandler.java index a439776..315cfbb 100644 --- a/astralbooks-v1_20_R1/src/main/java/ro/niconeko/astralbooks/dist/v1_20_R1/DistributionHandler.java +++ b/astralbooks-v1_20_R1/src/main/java/ro/niconeko/astralbooks/dist/v1_20_R1/DistributionHandler.java @@ -22,11 +22,15 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; import net.citizensnpcs.api.npc.NPC; +import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.protocol.game.ClientboundOpenBookPacket; import net.minecraft.world.InteractionHand; +import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.craftbukkit.v1_20_R1.CraftServer; import org.bukkit.craftbukkit.v1_20_R1.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_20_R1.inventory.CraftMetaBook; import org.bukkit.entity.Player; @@ -45,6 +49,17 @@ public DistributionHandler(AstralBooksPlugin plugin) throws NoSuchFieldException super(plugin, CraftMetaBook.class.getDeclaredField("pages")); } + @Override + public String getVersion() { + return "1_20_R1"; + } + + @Override + @SuppressWarnings("unchecked") + public void register(LiteralArgumentBuilder<?> builder) { + ((CraftServer) Bukkit.getServer()).getServer().vanillaCommandDispatcher.getDispatcher().register((LiteralArgumentBuilder<CommandSourceStack>) builder); + } + @Override public void sendRightClick(Player player) { ((CraftPlayer) player).getHandle().connection.send(new ClientboundOpenBookPacket(InteractionHand.MAIN_HAND)); @@ -88,11 +103,6 @@ public ItemStack convertJsonToBook(JsonObject jsonBook) throws IllegalAccessExce return newBook; } - @Override - public String getVersion() { - return "1_20_R1"; - } - @Override public void setConfigComment(ConfigurationSection config, String path, Optional<List<String>> comments) { comments.ifPresent(strings -> config.setComments(path, strings)); diff --git a/astralbooks-v1_20_R2/src/main/java/ro/niconeko/astralbooks/dist/v1_20_R2/DistributionHandler.java b/astralbooks-v1_20_R2/src/main/java/ro/niconeko/astralbooks/dist/v1_20_R2/DistributionHandler.java index 0c8046a..7013ee7 100644 --- a/astralbooks-v1_20_R2/src/main/java/ro/niconeko/astralbooks/dist/v1_20_R2/DistributionHandler.java +++ b/astralbooks-v1_20_R2/src/main/java/ro/niconeko/astralbooks/dist/v1_20_R2/DistributionHandler.java @@ -22,11 +22,16 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; import net.citizensnpcs.api.npc.NPC; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.network.protocol.game.ClientboundCommandsPacket; import net.minecraft.network.protocol.game.ClientboundOpenBookPacket; import net.minecraft.world.InteractionHand; +import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.craftbukkit.v1_20_R2.CraftServer; import org.bukkit.craftbukkit.v1_20_R2.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_20_R2.inventory.CraftMetaBook; import org.bukkit.entity.Player; @@ -45,6 +50,17 @@ public DistributionHandler(AstralBooksPlugin plugin) throws NoSuchFieldException super(plugin, CraftMetaBook.class.getDeclaredField("pages")); } + @Override + public String getVersion() { + return "1_20_R2"; + } + + @Override + @SuppressWarnings("unchecked") + public void register(LiteralArgumentBuilder<?> builder) { + ((CraftServer) Bukkit.getServer()).getServer().vanillaCommandDispatcher.getDispatcher().register((LiteralArgumentBuilder<CommandSourceStack>) builder); + } + @Override public void sendRightClick(Player player) { ((CraftPlayer) player).getHandle().connection.send(new ClientboundOpenBookPacket(InteractionHand.MAIN_HAND)); @@ -88,11 +104,6 @@ public ItemStack convertJsonToBook(JsonObject jsonBook) throws IllegalAccessExce return newBook; } - @Override - public String getVersion() { - return "1_20_R2"; - } - @Override public void setConfigComment(ConfigurationSection config, String path, Optional<List<String>> comments) { comments.ifPresent(strings -> config.setComments(path, strings)); diff --git a/astralbooks-v1_20_R3/src/main/java/ro/niconeko/astralbooks/dist/v1_20_R3/DistributionHandler.java b/astralbooks-v1_20_R3/src/main/java/ro/niconeko/astralbooks/dist/v1_20_R3/DistributionHandler.java index 4824b68..5c27b6b 100644 --- a/astralbooks-v1_20_R3/src/main/java/ro/niconeko/astralbooks/dist/v1_20_R3/DistributionHandler.java +++ b/astralbooks-v1_20_R3/src/main/java/ro/niconeko/astralbooks/dist/v1_20_R3/DistributionHandler.java @@ -22,11 +22,17 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; import net.citizensnpcs.api.npc.NPC; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.network.protocol.game.ClientboundCommandsPacket; import net.minecraft.network.protocol.game.ClientboundOpenBookPacket; import net.minecraft.world.InteractionHand; +import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.craftbukkit.v1_20_R3.CraftServer; import org.bukkit.craftbukkit.v1_20_R3.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_20_R3.inventory.CraftMetaBook; import org.bukkit.entity.Player; @@ -45,6 +51,17 @@ public DistributionHandler(AstralBooksPlugin plugin) throws NoSuchFieldException super(plugin, CraftMetaBook.class.getDeclaredField("pages")); } + @Override + public String getVersion() { + return "1_20_R3"; + } + + @Override + @SuppressWarnings("unchecked") + public void register(LiteralArgumentBuilder<?> builder) { + ((CraftServer) Bukkit.getServer()).getServer().vanillaCommandDispatcher.getDispatcher().register((LiteralArgumentBuilder<CommandSourceStack>) builder); + } + @Override public void sendRightClick(Player player) { ((CraftPlayer) player).getHandle().connection.send(new ClientboundOpenBookPacket(InteractionHand.MAIN_HAND)); @@ -88,11 +105,6 @@ public ItemStack convertJsonToBook(JsonObject jsonBook) throws IllegalAccessExce return newBook; } - @Override - public String getVersion() { - return "1_20_R3"; - } - @Override public void setConfigComment(ConfigurationSection config, String path, Optional<List<String>> comments) { comments.ifPresent(strings -> config.setComments(path, strings)); diff --git a/pom.xml b/pom.xml index f92da08..3dce0a5 100644 --- a/pom.xml +++ b/pom.xml @@ -24,7 +24,7 @@ <packaging>pom</packaging> <properties> - <revision>3.0.9</revision> + <revision>3.1.0-SNAPSHOT</revision> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>17</java.version> @@ -74,6 +74,10 @@ <id>dmulloy2-repo</id> <url>https://repo.dmulloy2.net/repository/public/</url> </repository> + <repository> + <id>minecraft-libraries</id> + <url>https://libraries.minecraft.net</url> + </repository> </repositories> <dependencies> @@ -119,12 +123,6 @@ <version>5.6.0-SNAPSHOT</version> <scope>provided</scope> </dependency> - <dependency> - <groupId>net.luckperms</groupId> - <artifactId>api</artifactId> - <version>5.4</version> - <scope>provided</scope> - </dependency> <dependency> <groupId>com.github.MilkBowl</groupId> <artifactId>VaultAPI</artifactId>