diff --git a/README.md b/README.md index 628c8ebf..e730d763 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Gitbook -CustomFishing is a Paper plugin that provides minigames and a powerful condition & action library for fishing. +CustomFishing is a Paper plugin that provides minigames and a powerful playerContext & action library for fishing. With the new concept of weight system, CustomFishing brings unlimited customization possibilities and best performance. ## How to build diff --git a/api/build.gradle.kts b/api/build.gradle.kts index c4df5e65..6240aca3 100644 --- a/api/build.gradle.kts +++ b/api/build.gradle.kts @@ -1,11 +1,44 @@ -dependencies { - compileOnly("io.papermc.paper:paper-api:1.20.4-R0.1-SNAPSHOT") - compileOnly("com.comphenix.protocol:ProtocolLib:5.1.0") - compileOnly("de.tr7zw:item-nbt-api:2.12.4") +plugins { + id("io.github.goooler.shadow") version "8.1.7" } +repositories { + maven("https://repo.codemc.io/repository/maven-public/") + maven("https://jitpack.io/") +} + +dependencies { + implementation(project(":common")) + implementation("dev.dejvokep:boosted-yaml:${rootProject.properties["boosted_yaml_version"]}") + implementation("net.kyori:adventure-api:${rootProject.properties["adventure_bundle_version"]}") { + exclude(module = "adventure-bom") + exclude(module = "checker-qual") + exclude(module = "annotations") + } + implementation("com.saicone.rtag:rtag:1.5.3") + implementation("com.saicone.rtag:rtag-item:1.5.3") + compileOnly("dev.folia:folia-api:${rootProject.properties["paper_version"]}-R0.1-SNAPSHOT") + compileOnly("com.google.code.gson:gson:${rootProject.properties["gson_version"]}") +} + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +tasks.withType { + options.encoding = "UTF-8" + options.release.set(17) + dependsOn(tasks.clean) +} + + tasks { shadowJar { - relocate ("de.tr7zw.changeme", "net.momirealms.customfishing.libraries") + relocate("net.kyori", "net.momirealms.customfishing.libraries") + relocate("dev.dejvokep", "net.momirealms.customfishing.libraries") } -} +} \ No newline at end of file diff --git a/api/src/main/java/net/momirealms/customfishing/api/CustomFishingPlugin.java b/api/src/main/java/net/momirealms/customfishing/api/BukkitCustomFishingPlugin.java similarity index 66% rename from api/src/main/java/net/momirealms/customfishing/api/CustomFishingPlugin.java rename to api/src/main/java/net/momirealms/customfishing/api/BukkitCustomFishingPlugin.java index 649c0612..3e64b622 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/CustomFishingPlugin.java +++ b/api/src/main/java/net/momirealms/customfishing/api/BukkitCustomFishingPlugin.java @@ -17,17 +17,36 @@ package net.momirealms.customfishing.api; +import net.momirealms.customfishing.api.integration.IntegrationManager; import net.momirealms.customfishing.api.manager.*; -import net.momirealms.customfishing.api.scheduler.Scheduler; +import net.momirealms.customfishing.api.mechanic.action.ActionManager; +import net.momirealms.customfishing.api.mechanic.bag.BagManager; +import net.momirealms.customfishing.api.mechanic.block.BlockManager; +import net.momirealms.customfishing.api.mechanic.competition.CompetitionManager; +import net.momirealms.customfishing.api.mechanic.effect.EffectManager; +import net.momirealms.customfishing.api.mechanic.entity.EntityManager; +import net.momirealms.customfishing.api.mechanic.fishing.FishingManager; +import net.momirealms.customfishing.api.mechanic.game.GameManager; +import net.momirealms.customfishing.api.mechanic.hook.HookManager; +import net.momirealms.customfishing.api.mechanic.item.ItemManager; +import net.momirealms.customfishing.api.mechanic.loot.LootManager; +import net.momirealms.customfishing.api.mechanic.market.MarketManager; +import net.momirealms.customfishing.api.mechanic.requirement.RequirementManager; +import net.momirealms.customfishing.api.mechanic.statistic.StatisticsManager; +import net.momirealms.customfishing.api.mechanic.totem.TotemManager; +import net.momirealms.customfishing.common.command.CustomFishingCommandManager; +import net.momirealms.customfishing.common.plugin.CustomFishingPlugin; +import net.momirealms.customfishing.common.plugin.scheduler.SchedulerAdapter; +import org.bukkit.Location; +import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.java.JavaPlugin; -import org.jetbrains.annotations.NotNull; -public abstract class CustomFishingPlugin extends JavaPlugin { +public abstract class BukkitCustomFishingPlugin extends JavaPlugin implements CustomFishingPlugin { protected boolean initialized; - protected Scheduler scheduler; - protected CommandManager commandManager; + protected SchedulerAdapter scheduler; + protected CustomFishingCommandManager commandManager; protected VersionManager versionManager; protected ItemManager itemManager; protected RequirementManager requirementManager; @@ -37,7 +56,6 @@ public abstract class CustomFishingPlugin extends JavaPlugin { protected EffectManager effectManager; protected EntityManager entityManager; protected BlockManager blockManager; - protected AdventureManager adventure; protected BagManager bagManager; protected GameManager gameManager; protected MarketManager marketManager; @@ -49,29 +67,20 @@ public abstract class CustomFishingPlugin extends JavaPlugin { protected TotemManager totemManager; protected HookManager hookManager; - private static CustomFishingPlugin instance; + private static BukkitCustomFishingPlugin instance; - public CustomFishingPlugin() { + public BukkitCustomFishingPlugin() { instance = this; } - public static CustomFishingPlugin get() { + public static BukkitCustomFishingPlugin get() { return getInstance(); } - @NotNull - public static CustomFishingPlugin getInstance() { + public static BukkitCustomFishingPlugin getInstance() { return instance; } - public Scheduler getScheduler() { - return scheduler; - } - - public CommandManager getCommandManager() { - return commandManager; - } - public VersionManager getVersionManager() { return versionManager; } diff --git a/api/src/main/java/net/momirealms/customfishing/api/common/Key.java b/api/src/main/java/net/momirealms/customfishing/api/common/Key.java deleted file mode 100644 index a276f10c..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/common/Key.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.common; - -public record Key(String namespace, String value) { - - public static Key of(String namespace, String value) { - return new Key(namespace, value); - } - - @Override - public int hashCode() { - int result = this.namespace.hashCode(); - result = (31 * result) + this.value.hashCode(); - return result; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof Key key)) return false; - return this.namespace.equals(key.namespace()) && this.value.equals(key.value()); - } - - @Override - public String toString() { - return namespace + ":" + value; - } -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/data/LegacyDataStorageInterface.java b/api/src/main/java/net/momirealms/customfishing/api/data/LegacyDataStorageInterface.java deleted file mode 100644 index 190206bc..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/data/LegacyDataStorageInterface.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.data; - -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; - -public interface LegacyDataStorageInterface extends DataStorageInterface { - - /** - * Retrieve legacy player data from the SQL database. - * - * @param uuid The UUID of the player. - * @return A CompletableFuture containing the optional legacy player data. - */ - CompletableFuture> getLegacyPlayerData(UUID uuid); -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/event/CustomFishingReloadEvent.java b/api/src/main/java/net/momirealms/customfishing/api/event/CustomFishingReloadEvent.java index 1219d485..41defa68 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/event/CustomFishingReloadEvent.java +++ b/api/src/main/java/net/momirealms/customfishing/api/event/CustomFishingReloadEvent.java @@ -17,7 +17,7 @@ package net.momirealms.customfishing.api.event; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; @@ -25,9 +25,9 @@ import org.jetbrains.annotations.NotNull; public class CustomFishingReloadEvent extends Event { private static final HandlerList handlerList = new HandlerList(); - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; - public CustomFishingReloadEvent(CustomFishingPlugin plugin) { + public CustomFishingReloadEvent(BukkitCustomFishingPlugin plugin) { this.plugin = plugin; } @@ -41,7 +41,7 @@ public class CustomFishingReloadEvent extends Event { return getHandlerList(); } - public CustomFishingPlugin getPluginInstance() { + public BukkitCustomFishingPlugin getPluginInstance() { return plugin; } } diff --git a/api/src/main/java/net/momirealms/customfishing/api/event/FishHookLandEvent.java b/api/src/main/java/net/momirealms/customfishing/api/event/FishHookLandEvent.java index 8adeace1..dc9a1daa 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/event/FishHookLandEvent.java +++ b/api/src/main/java/net/momirealms/customfishing/api/event/FishHookLandEvent.java @@ -33,7 +33,7 @@ public class FishHookLandEvent extends PlayerEvent { private final Target target; private final FishHook fishHook; private final Effect effect; - private boolean isFirst; + private final boolean isFirst; /** * Constructs a new FishHookLandEvent. diff --git a/api/src/main/java/net/momirealms/customfishing/api/event/RodCastEvent.java b/api/src/main/java/net/momirealms/customfishing/api/event/RodCastEvent.java index 7d496973..c8980d0d 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/event/RodCastEvent.java +++ b/api/src/main/java/net/momirealms/customfishing/api/event/RodCastEvent.java @@ -17,7 +17,6 @@ package net.momirealms.customfishing.api.event; -import net.momirealms.customfishing.api.mechanic.condition.FishingPreparation; import net.momirealms.customfishing.api.mechanic.effect.Effect; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; diff --git a/api/src/main/java/net/momirealms/customfishing/api/integration/EnchantmentInterface.java b/api/src/main/java/net/momirealms/customfishing/api/integration/EnchantmentProvider.java similarity index 81% rename from api/src/main/java/net/momirealms/customfishing/api/integration/EnchantmentInterface.java rename to api/src/main/java/net/momirealms/customfishing/api/integration/EnchantmentProvider.java index 04a92876..5235fab1 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/integration/EnchantmentInterface.java +++ b/api/src/main/java/net/momirealms/customfishing/api/integration/EnchantmentProvider.java @@ -17,19 +17,19 @@ package net.momirealms.customfishing.api.integration; +import net.kyori.adventure.key.Key; +import net.momirealms.customfishing.common.util.Pair; import org.bukkit.inventory.ItemStack; import java.util.List; -public interface EnchantmentInterface { +public interface EnchantmentProvider extends ExternalProvider { /** * Get a list of enchantments with level for itemStack - * format: plugin:enchantment:level - * example: minecraft:sharpness:5 * * @param itemStack itemStack * @return enchantment list */ - List getEnchants(ItemStack itemStack); + List> getEnchants(ItemStack itemStack); } diff --git a/api/src/main/java/net/momirealms/customfishing/api/integration/EntityProvider.java b/api/src/main/java/net/momirealms/customfishing/api/integration/EntityProvider.java new file mode 100644 index 00000000..9cfea439 --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/integration/EntityProvider.java @@ -0,0 +1,43 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customfishing.api.integration; + +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.jetbrains.annotations.NotNull; + +import java.util.HashMap; +import java.util.Map; + +public interface EntityProvider extends ExternalProvider { + + /** + * Spawns an entity at the specified location with the given properties. + * + * @param location The location where the entity will be spawned. + * @param id The identifier of the entity to be spawned. + * @param propertyMap A map containing additional properties for the entity. + * @return The spawned entity. + */ + @NotNull + Entity spawn(@NotNull Location location, @NotNull String id, @NotNull Map propertyMap); + + default Entity spawn(@NotNull Location location, @NotNull String id) { + return spawn(location, id, new HashMap<>()); + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/integration/ExternalProvider.java b/api/src/main/java/net/momirealms/customfishing/api/integration/ExternalProvider.java new file mode 100644 index 00000000..778049e7 --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/integration/ExternalProvider.java @@ -0,0 +1,11 @@ +package net.momirealms.customfishing.api.integration; + +public interface ExternalProvider { + + /** + * Gets the identification of the external provider. + * + * @return The identification string of the external provider. + */ + String identifier(); +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/integration/IntegrationManager.java b/api/src/main/java/net/momirealms/customfishing/api/integration/IntegrationManager.java new file mode 100644 index 00000000..f5d223a9 --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/integration/IntegrationManager.java @@ -0,0 +1,107 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customfishing.api.integration; + +import org.jetbrains.annotations.Nullable; + +/** + * Interface for managing integration providers in the custom fishing API. + * This allows for the registration and retrieval of various types of providers + * such as Leveler, Enchantment, and Season providers. + */ +public interface IntegrationManager { + + /** + * Registers a LevelerProvider. + * + * @param level the LevelerProvider to register + * @return true if registration is successful, false otherwise + */ + boolean registerLevelerProvider(LevelerProvider level); + + /** + * Unregisters a LevelerProvider by its ID. + * + * @param id the ID of the LevelerProvider to unregister + * @return true if unregistration is successful, false otherwise + */ + boolean unregisterLevelerProvider(String id); + + /** + * Registers an EnchantmentProvider. + * + * @param enchantment the EnchantmentProvider to register + * @return true if registration is successful, false otherwise + */ + boolean registerEnchantmentProvider(EnchantmentProvider enchantment); + + /** + * Unregisters an EnchantmentProvider by its ID. + * + * @param id the ID of the EnchantmentProvider to unregister + * @return true if unregistration is successful, false otherwise + */ + boolean unregisterEnchantmentProvider(String id); + + /** + * Registers a SeasonProvider. + * + * @param season the SeasonProvider to register + * @return true if registration is successful, false otherwise + */ + boolean registerSeasonProvider(SeasonProvider season); + + /** + * Unregisters a SeasonProvider by its ID. + * + * @param id the ID of the SeasonProvider to unregister + * @return true if unregistration is successful, false otherwise + */ + boolean unregisterSeasonProvider(String id); + + boolean registerEntityProvider(EntityProvider entity); + + boolean unregisterEntityProvider(String identifier); + + /** + * Retrieves a registered LevelerProvider by its ID. + * + * @param id the ID of the LevelerProvider to retrieve + * @return the LevelerProvider if found, or null if not found + */ + @Nullable + LevelerProvider getLevelerProvider(String id); + + /** + * Retrieves a registered EnchantmentProvider by its ID. + * + * @param id the ID of the EnchantmentProvider to retrieve + * @return the EnchantmentProvider if found, or null if not found + */ + @Nullable + EnchantmentProvider getEnchantmentProvider(String id); + + /** + * Retrieves a registered SeasonProvider by its ID. + * + * @param id the ID of the SeasonProvider to retrieve + * @return the SeasonProvider if found, or null if not found + */ + @Nullable + SeasonProvider getSeasonProvider(String id); +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/Value.java b/api/src/main/java/net/momirealms/customfishing/api/integration/ItemProvider.java similarity index 67% rename from api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/Value.java rename to api/src/main/java/net/momirealms/customfishing/api/integration/ItemProvider.java index 1dbea0c4..de13d9d8 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/Value.java +++ b/api/src/main/java/net/momirealms/customfishing/api/integration/ItemProvider.java @@ -15,13 +15,18 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.mechanic.misc; +package net.momirealms.customfishing.api.integration; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import java.util.Map; +public interface ItemProvider extends ExternalProvider { -public interface Value { + @NotNull + ItemStack buildItem(Player player, String id); - double get(Player player, Map values); + @Nullable + String itemID(ItemStack itemStack); } diff --git a/api/src/main/java/net/momirealms/customfishing/api/integration/LevelInterface.java b/api/src/main/java/net/momirealms/customfishing/api/integration/LevelerProvider.java similarity index 95% rename from api/src/main/java/net/momirealms/customfishing/api/integration/LevelInterface.java rename to api/src/main/java/net/momirealms/customfishing/api/integration/LevelerProvider.java index da326178..60141114 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/integration/LevelInterface.java +++ b/api/src/main/java/net/momirealms/customfishing/api/integration/LevelerProvider.java @@ -19,7 +19,7 @@ package net.momirealms.customfishing.api.integration; import org.bukkit.entity.Player; -public interface LevelInterface { +public interface LevelerProvider extends ExternalProvider { /** * Add exp to a certain skill or job diff --git a/api/src/main/java/net/momirealms/customfishing/api/integration/SeasonInterface.java b/api/src/main/java/net/momirealms/customfishing/api/integration/SeasonProvider.java similarity index 84% rename from api/src/main/java/net/momirealms/customfishing/api/integration/SeasonInterface.java rename to api/src/main/java/net/momirealms/customfishing/api/integration/SeasonProvider.java index bae8da60..03cb5fb9 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/integration/SeasonInterface.java +++ b/api/src/main/java/net/momirealms/customfishing/api/integration/SeasonProvider.java @@ -17,10 +17,11 @@ package net.momirealms.customfishing.api.integration; +import net.momirealms.customfishing.api.mechanic.misc.season.Season; import org.bukkit.World; import org.jetbrains.annotations.NotNull; -public interface SeasonInterface { +public interface SeasonProvider extends ExternalProvider { /** * Get a world's season @@ -28,5 +29,6 @@ public interface SeasonInterface { * @param world world * @return spring, summer, autumn, winter or disabled */ - @NotNull String getSeason(World world); + @NotNull + Season getSeason(World world); } diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/AdventureManager.java b/api/src/main/java/net/momirealms/customfishing/api/manager/AdventureManager.java deleted file mode 100644 index 1f7c9c0b..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/AdventureManager.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.manager; - -import net.kyori.adventure.key.Key; -import net.kyori.adventure.sound.Sound; -import net.kyori.adventure.text.Component; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -public interface AdventureManager { - - /** - * Get component from text - * @param text text - * @return component - */ - Component getComponentFromMiniMessage(String text); - - /** - * Send a message to a command sender - * @param sender sender - * @param msg message - */ - void sendMessage(CommandSender sender, String msg); - - /** - * Send a message with prefix - * - * @param sender command sender - * @param s message - */ - void sendMessageWithPrefix(CommandSender sender, String s); - - /** - * Send a message to console - * @param msg message - */ - void sendConsoleMessage(String msg); - - /** - * Send a message to a player - * @param player player - * @param msg message - */ - void sendPlayerMessage(Player player, String msg); - - /** - * Send a title to a player - * @param player player - * @param title title - * @param subtitle subtitle - * @param in in (ms) - * @param duration duration (ms) - * @param out out (ms) - */ - void sendTitle(Player player, String title, String subtitle, int in, int duration, int out); - - /** - * Send a title to a player - * @param player player - * @param title title - * @param subtitle subtitle - * @param in in (ms) - * @param duration duration (ms) - * @param out out (ms) - */ - void sendTitle(Player player, Component title, Component subtitle, int in, int duration, int out); - - /** - * Send actionbar - * @param player player - * @param msg msg - */ - void sendActionbar(Player player, String msg); - - /** - * Play a sound to a player - * @param player player - * @param source sound source - * @param key sound key - * @param volume volume - * @param pitch pitch - */ - void sendSound(Player player, Sound.Source source, Key key, float volume, float pitch); - - void sendSound(Player player, Sound sound); - - /** - * Replace legacy color codes to MiniMessage format - * @param legacy legacy text - * @return MiniMessage format text - */ - String legacyToMiniMessage(String legacy); - - /** - * if a char is legacy color code - * @param c char - * @return is legacy color - */ - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - boolean isColorCode(char c); - - /** - * Get legacy format text - * @param component component - * @return legacy format text - */ - String componentToLegacy(Component component); - - /** - * Get json - * @param component component - * @return json - */ - String componentToJson(Component component); - - /** - * Get paper component - * @param component shaded component - * @return paper component - */ - Object shadedComponentToOriginalComponent(Component component); -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/IntegrationManager.java b/api/src/main/java/net/momirealms/customfishing/api/manager/IntegrationManager.java deleted file mode 100644 index c78a91e9..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/IntegrationManager.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.manager; - -import net.momirealms.customfishing.api.integration.EnchantmentInterface; -import net.momirealms.customfishing.api.integration.LevelInterface; -import net.momirealms.customfishing.api.integration.SeasonInterface; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -public interface IntegrationManager { - - /** - * Registers a level plugin with the specified name. - * - * @param plugin The name of the level plugin. - * @param level The implementation of the LevelInterface. - * @return true if the registration was successful, false if the plugin name is already registered. - */ - boolean registerLevelPlugin(String plugin, LevelInterface level); - - /** - * Unregisters a level plugin with the specified name. - * - * @param plugin The name of the level plugin to unregister. - * @return true if the unregistration was successful, false if the plugin name is not found. - */ - boolean unregisterLevelPlugin(String plugin); - - /** - * Registers an enchantment provided by a plugin. - * - * @param plugin The name of the plugin providing the enchantment. - * @param enchantment The enchantment to register. - * @return true if the registration was successful, false if the enchantment name is already in use. - */ - boolean registerEnchantment(String plugin, EnchantmentInterface enchantment); - - /** - * Unregisters an enchantment provided by a plugin. - * - * @param plugin The name of the plugin providing the enchantment. - * @return true if the enchantment was successfully unregistered, false if the enchantment was not found. - */ - boolean unregisterEnchantment(String plugin); - - /** - * Get the LevelInterface provided by a plugin. - * - * @param plugin The name of the plugin providing the LevelInterface. - * @return The LevelInterface provided by the specified plugin, or null if the plugin is not registered. - */ - @Nullable LevelInterface getLevelPlugin(String plugin); - - /** - * Get an enchantment plugin by its plugin name. - * - * @param plugin The name of the enchantment plugin. - * @return The enchantment plugin interface, or null if not found. - */ - @Nullable EnchantmentInterface getEnchantmentPlugin(String plugin); - - /** - * Get a list of enchantment keys with level applied to the given ItemStack. - * - * @param itemStack The ItemStack to check for enchantments. - * @return A list of enchantment names applied to the ItemStack. - */ - List getEnchantments(ItemStack itemStack); - - /** - * Get the current season interface, if available. - * - * @return The current season interface, or null if not available. - */ - @Nullable SeasonInterface getSeasonInterface(); - - /** - * Set the current season interface. - * - * @param season The season interface to set. - */ - void setSeasonInterface(SeasonInterface season); -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/ItemManager.java b/api/src/main/java/net/momirealms/customfishing/api/manager/ItemManager.java deleted file mode 100644 index 25759e9c..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/ItemManager.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.manager; - -import net.momirealms.customfishing.api.common.Key; -import net.momirealms.customfishing.api.mechanic.condition.Condition; -import net.momirealms.customfishing.api.mechanic.item.BuildableItem; -import net.momirealms.customfishing.api.mechanic.item.ItemBuilder; -import net.momirealms.customfishing.api.mechanic.item.ItemLibrary; -import org.bukkit.Location; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Map; -import java.util.Set; - -public interface ItemManager { - - /** - * Build an ItemStack with a specified namespace and value for a player. - * - * @param player The player for whom the ItemStack is being built. - * @param namespace The namespace of the item. - * @param value The value of the item. - * @return The constructed ItemStack. - */ - @Nullable - ItemStack build(Player player, String namespace, String value); - - /** - * Build an ItemStack with a specified namespace and value, replacing placeholders, - * for a player. - * - * @param player The player for whom the ItemStack is being built. - * @param namespace The namespace of the item. - * @param value The value of the item. - * @param placeholders The placeholders to replace in the item's attributes. - * @return The constructed ItemStack, or null if the item doesn't exist. - */ - @Nullable - ItemStack build(Player player, String namespace, String value, Map placeholders); - - /** - * Build an ItemStack using an ItemBuilder for a player. - * - * @param player The player for whom the ItemStack is being built. - * @param builder The ItemBuilder used to construct the ItemStack. - * @return The constructed ItemStack. - */ - @NotNull ItemStack build(Player player, ItemBuilder builder); - - /** - * Build an ItemStack using the provided ItemBuilder, player, and placeholders. - * - * @param player The player for whom the item is being built. - * @param builder The ItemBuilder that defines the item's properties. - * @param placeholders A map of placeholders and their corresponding values to be applied to the item. - * @return The constructed ItemStack. - */ - @NotNull ItemStack build(Player player, ItemBuilder builder, Map placeholders); - - /** - * Build an ItemStack for a player based on the provided item ID. - * - * @param player The player for whom the ItemStack is being built. - * @param id The item ID, which include an identification (e.g., "Oraxen:id"). - * @return The constructed ItemStack or null if the ID is not valid. - */ - @Nullable ItemStack buildAnyPluginItemByID(Player player, String id); - - /** - * Get the item ID associated with the given ItemStack, if available. - * - * @param itemStack The ItemStack to retrieve the item ID from. - * @return The item ID without type or null if not found or if the ItemStack is null or empty. - */ - @Nullable String getCustomFishingItemID(ItemStack itemStack); - - /** - * Get the item ID associated with the given ItemStack by checking all available item libraries. - * The detection order is determined by the configuration. - * - * @param itemStack The ItemStack to retrieve the item ID from. - * @return The item ID or "AIR" if not found or if the ItemStack is null or empty. - */ - @NotNull String getAnyPluginItemID(ItemStack itemStack); - - /** - * Create a ItemBuilder instance for an item configuration section - *

- * xxx_item: <- section - * material: xxx - * custom-model-data: xxx - * - * @param section The configuration section containing item settings. - * @param type The type of the item (e.g., "rod", "bait"). - * @param id The unique identifier for the item. - * @return A CFBuilder instance representing the configured item, or null if the section is null. - */ - @Nullable ItemBuilder getItemBuilder(ConfigurationSection section, String type, String id); - - /** - * Get a set of all item keys in the CustomFishing plugin. - * - * @return A set of item keys. - */ - Set getAllItemsKey(); - - /** - * Retrieve a BuildableItem by its namespace and value. - * - * @param namespace The namespace of the BuildableItem. - * @param value The value of the BuildableItem. - * @return The BuildableItem with the specified namespace and value, or null if not found. - */ - @Nullable - BuildableItem getBuildableItem(String namespace, String value); - - /** - * Get an itemStack's appearance (material + custom model data) - * - * @param player player - * @param material id - * @return appearance - */ - ItemStack getItemStackAppearance(Player player, String material); - - /** - * Register an item library. - * - * @param itemLibrary The item library to register. - * @return True if the item library was successfully registered, false if it already exists. - */ - boolean registerItemLibrary(ItemLibrary itemLibrary); - - /** - * Unregister an item library. - * - * @param identification The item library to unregister. - * @return True if the item library was successfully unregistered, false if it doesn't exist. - */ - boolean unRegisterItemLibrary(String identification); - - /** - * Drops an item based on the provided loot, applying velocity from a hook location to a player location. - * - * @param player The player for whom the item is intended. - * @param hookLocation The location where the item will initially drop. - * @param playerLocation The target location towards which the item's velocity is applied. - * @param itemStack The loot to drop - * @param condition A map of placeholders for item customization. - */ - void dropItem(Player player, Location hookLocation, Location playerLocation, ItemStack itemStack, Condition condition); - - /** - * Checks if the provided ItemStack is a custom fishing item - * - * @param itemStack The ItemStack to check. - * @return True if the ItemStack is a custom fishing item; otherwise, false. - */ - boolean isCustomFishingItem(ItemStack itemStack); - - /** - * Decreases the durability of an ItemStack by a specified amount and optionally updates its lore. - * - * @param itemStack The ItemStack to modify. - * @param amount The amount by which to decrease the durability. - * @param updateLore Whether to update the lore of the ItemStack. - */ - void decreaseDurability(Player player, ItemStack itemStack, int amount, boolean updateLore); - - /** - * Increases the durability of an ItemStack by a specified amount and optionally updates its lore. - * - * @param itemStack The ItemStack to modify. - * @param amount The amount by which to increase the durability. - * @param updateLore Whether to update the lore of the ItemStack. - */ - void increaseDurability(ItemStack itemStack, int amount, boolean updateLore); - - /** - * Sets the durability of an ItemStack to a specific amount and optionally updates its lore. - * - * @param itemStack The ItemStack to modify. - * @param amount The new durability value. - * @param updateLore Whether to update the lore of the ItemStack. - */ - void setDurability(ItemStack itemStack, int amount, boolean updateLore); -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/VersionManager.java b/api/src/main/java/net/momirealms/customfishing/api/manager/VersionManager.java index ae3d37ba..bb3a0c67 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/VersionManager.java +++ b/api/src/main/java/net/momirealms/customfishing/api/manager/VersionManager.java @@ -23,14 +23,16 @@ public interface VersionManager { boolean isVersionNewerThan1_19(); - boolean isVersionNewerThan1_19_R3(); + boolean isVersionNewerThan1_19_4(); - boolean isVersionNewerThan1_19_R2(); + boolean isVersionNewerThan1_19_3(); CompletableFuture checkUpdate(); boolean isVersionNewerThan1_20(); + boolean isNewerThan1_20_5(); + boolean isSpigot(); public boolean hasRegionScheduler(); diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/GlobalSettings.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/GlobalSettings.java index 0192b1d9..bc87b73f 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/GlobalSettings.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/GlobalSettings.java @@ -17,10 +17,9 @@ package net.momirealms.customfishing.api.mechanic; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.mechanic.action.Action; import net.momirealms.customfishing.api.mechanic.action.ActionTrigger; -import net.momirealms.customfishing.api.mechanic.condition.Condition; import net.momirealms.customfishing.api.mechanic.effect.EffectModifier; import org.bukkit.configuration.ConfigurationSection; @@ -47,7 +46,7 @@ public class GlobalSettings { if (section == null) return; for (Map.Entry entry : section.getValues(false).entrySet()) { if (entry.getValue() instanceof ConfigurationSection inner) { - HashMap map = CustomFishingPlugin.get().getActionManager().getActionMap(inner); + HashMap map = BukkitCustomFishingPlugin.get().getActionManager().getActionMap(inner); switch (entry.getKey()) { case "loot" -> lootActions = map; case "rod" -> rodActions = map; @@ -79,13 +78,13 @@ public class GlobalSettings { * Triggers loot-related actions for a specific trigger and condition. * * @param trigger The trigger to activate actions for. - * @param condition The condition that triggered the actions. + * @param playerContext The condition that triggered the actions. */ - public static void triggerLootActions(ActionTrigger trigger, Condition condition) { + public static void triggerLootActions(ActionTrigger trigger, PlayerContext playerContext) { Action[] actions = lootActions.get(trigger); if (actions != null) { for (Action action : actions) { - action.trigger(condition); + action.trigger(playerContext); } } } @@ -94,13 +93,13 @@ public class GlobalSettings { * Triggers rod-related actions for a specific trigger and condition. * * @param trigger The trigger to activate actions for. - * @param condition The condition that triggered the actions. + * @param playerContext The condition that triggered the actions. */ - public static void triggerRodActions(ActionTrigger trigger, Condition condition) { + public static void triggerRodActions(ActionTrigger trigger, PlayerContext playerContext) { Action[] actions = rodActions.get(trigger); if (actions != null) { for (Action action : actions) { - action.trigger(condition); + action.trigger(playerContext); } } } @@ -109,13 +108,13 @@ public class GlobalSettings { * Triggers bait-related actions for a specific trigger and condition. * * @param trigger The trigger to activate actions for. - * @param condition The condition that triggered the actions. + * @param playerContext The condition that triggered the actions. */ - public static void triggerBaitActions(ActionTrigger trigger, Condition condition) { + public static void triggerBaitActions(ActionTrigger trigger, PlayerContext playerContext) { Action[] actions = baitActions.get(trigger); if (actions != null) { for (Action action : actions) { - action.trigger(condition); + action.trigger(playerContext); } } } @@ -124,13 +123,13 @@ public class GlobalSettings { * Triggers hook-related actions for a specific trigger and condition. * * @param trigger The trigger to activate actions for. - * @param condition The condition that triggered the actions. + * @param playerContext The condition that triggered the actions. */ - public static void triggerHookActions(ActionTrigger trigger, Condition condition) { + public static void triggerHookActions(ActionTrigger trigger, PlayerContext playerContext) { Action[] actions = hookActions.get(trigger); if (actions != null) { for (Action action : actions) { - action.trigger(condition); + action.trigger(playerContext); } } } diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/TempFishingState.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/TempFishingState.java index 503ef51e..c3e8a898 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/TempFishingState.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/TempFishingState.java @@ -17,7 +17,6 @@ package net.momirealms.customfishing.api.mechanic; -import net.momirealms.customfishing.api.mechanic.condition.FishingPreparation; import net.momirealms.customfishing.api.mechanic.effect.Effect; import net.momirealms.customfishing.api.mechanic.loot.Loot; diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/action/Action.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/action/Action.java index af44d142..6276916d 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/action/Action.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/action/Action.java @@ -17,10 +17,14 @@ package net.momirealms.customfishing.api.mechanic.action; -import net.momirealms.customfishing.api.mechanic.condition.Condition; +import net.momirealms.customfishing.api.mechanic.context.Context; -public interface Action { - - void trigger(Condition condition); +public interface Action { + /** + * Triggers the action based on the provided condition. + * + * @param context the context + */ + void trigger(Context context); } diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/action/ActionExpansion.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/action/ActionExpansion.java index bd48cfd1..6fc0ff8c 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/action/ActionExpansion.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/action/ActionExpansion.java @@ -17,13 +17,39 @@ package net.momirealms.customfishing.api.mechanic.action; -public abstract class ActionExpansion { +/** + * Abstract class representing an expansion of an action in the custom fishing API. + * This class should be extended to provide specific implementations of actions. + * + * @param the type parameter for the action factory + */ +public abstract class ActionExpansion { + /** + * Retrieves the version of this action expansion. + * + * @return a String representing the version of the action expansion + */ public abstract String getVersion(); + /** + * Retrieves the author of this action expansion. + * + * @return a String representing the author of the action expansion + */ public abstract String getAuthor(); + /** + * Retrieves the type of this action. + * + * @return a String representing the type of action + */ public abstract String getActionType(); - public abstract ActionFactory getActionFactory(); + /** + * Retrieves the action factory associated with this action expansion. + * + * @return an ActionFactory of type T that creates instances of the action + */ + public abstract ActionFactory getActionFactory(); } diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/action/ActionFactory.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/action/ActionFactory.java index fdaae29d..deb59304 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/action/ActionFactory.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/action/ActionFactory.java @@ -17,7 +17,18 @@ package net.momirealms.customfishing.api.mechanic.action; -public interface ActionFactory { +/** + * Interface representing a factory for creating actions. + * + * @param the type of object that the action will operate on + */ +public interface ActionFactory { - Action build(Object args, double chance); + /** + * Constructs an action based on the provided arguments. + * + * @param args the args containing the arguments needed to build the action + * @return the constructed action + */ + Action process(Object args); } diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/ActionManager.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/action/ActionManager.java similarity index 80% rename from api/src/main/java/net/momirealms/customfishing/api/manager/ActionManager.java rename to api/src/main/java/net/momirealms/customfishing/api/mechanic/action/ActionManager.java index 334bd6bf..7ef3913e 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/ActionManager.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/action/ActionManager.java @@ -15,17 +15,16 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.manager; +package net.momirealms.customfishing.api.mechanic.action; -import net.momirealms.customfishing.api.mechanic.action.Action; -import net.momirealms.customfishing.api.mechanic.action.ActionFactory; -import net.momirealms.customfishing.api.mechanic.action.ActionTrigger; -import net.momirealms.customfishing.api.mechanic.condition.Condition; -import org.bukkit.configuration.ConfigurationSection; +import dev.dejvokep.boostedyaml.block.implementation.Section; +import net.momirealms.customfishing.api.mechanic.context.Context; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.HashMap; -public interface ActionManager { +public interface ActionManager { /** * Registers an ActionFactory for a specific action type. @@ -35,7 +34,7 @@ public interface ActionManager { * @param actionFactory The ActionFactory responsible for creating actions of the specified type. * @return True if the registration was successful (the action type was not already registered), false otherwise. */ - boolean registerAction(String type, ActionFactory actionFactory); + boolean registerAction(String type, ActionFactory actionFactory); /** * Unregisters an ActionFactory for a specific action type. @@ -59,7 +58,7 @@ public interface ActionManager { * @param section The ConfigurationSection containing the action configuration. * @return An Action object created based on the configuration, or an EmptyAction instance if the action type is invalid. */ - Action getAction(ConfigurationSection section); + Action getAction(Section section); /** * Retrieves a mapping of ActionTriggers to arrays of Actions from a ConfigurationSection. @@ -74,7 +73,7 @@ public interface ActionManager { * @param section The ConfigurationSection containing action mappings. * @return A HashMap where keys are ActionTriggers and values are arrays of Action objects. */ - HashMap getActionMap(ConfigurationSection section); + HashMap[]> getActionMap(Section section); /** * Retrieves an array of Action objects from a ConfigurationSection. @@ -89,7 +88,8 @@ public interface ActionManager { * @param section The ConfigurationSection containing action configurations. * @return An array of Action objects created based on the configurations in the section. */ - Action[] getActions(ConfigurationSection section); + @NotNull + Action[] getActions(@NotNull Section section); /** * Retrieves an ActionFactory associated with a specific action type. @@ -97,7 +97,8 @@ public interface ActionManager { * @param type The action type for which to retrieve the ActionFactory. * @return The ActionFactory associated with the specified action type, or null if not found. */ - ActionFactory getActionFactory(String type); + @Nullable + ActionFactory getActionFactory(@NotNull String type); /** * Retrieves a mapping of success times to corresponding arrays of actions from a ConfigurationSection. @@ -111,18 +112,19 @@ public interface ActionManager { * @param section The ConfigurationSection containing success times actions. * @return A HashMap where success times associated with actions. */ - HashMap getTimesActionMap(ConfigurationSection section); + @NotNull + HashMap[]> getTimesActionMap(@NotNull Section section); /** * Triggers a list of actions with the given condition. * If the list of actions is not null, each action in the list is triggered. * * @param actions The list of actions to trigger. - * @param condition The condition associated with the actions. + * @param context The context associated with the actions. */ - static void triggerActions(Condition condition, Action... actions) { + static void trigger(@NotNull Context context, @Nullable Action... actions) { if (actions != null) - for (Action action : actions) - action.trigger(condition); + for (Action action : actions) + action.trigger(context); } } diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/BagManager.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/bag/BagManager.java similarity index 96% rename from api/src/main/java/net/momirealms/customfishing/api/manager/BagManager.java rename to api/src/main/java/net/momirealms/customfishing/api/mechanic/bag/BagManager.java index f83c36d2..8e75fe08 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/BagManager.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/bag/BagManager.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.manager; +package net.momirealms.customfishing.api.mechanic.bag; import net.momirealms.customfishing.api.data.user.OfflineUser; import net.momirealms.customfishing.api.mechanic.action.Action; @@ -30,7 +30,7 @@ import java.util.UUID; public interface BagManager { /** - * Is bag enabled + * Is bag mechanics enabled * * @return enabled or not */ diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/block/BlockDataModifier.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/block/BlockDataModifier.java index 6ba31318..e2995779 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/block/BlockDataModifier.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/block/BlockDataModifier.java @@ -21,5 +21,6 @@ import org.bukkit.block.data.BlockData; import org.bukkit.entity.Player; public interface BlockDataModifier { + void apply(Player player, BlockData blockData); } \ No newline at end of file diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/BlockManager.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/block/BlockManager.java similarity index 94% rename from api/src/main/java/net/momirealms/customfishing/api/manager/BlockManager.java rename to api/src/main/java/net/momirealms/customfishing/api/mechanic/block/BlockManager.java index baa69366..ab99950e 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/BlockManager.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/block/BlockManager.java @@ -15,11 +15,8 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.manager; +package net.momirealms.customfishing.api.mechanic.block; -import net.momirealms.customfishing.api.mechanic.block.BlockDataModifierBuilder; -import net.momirealms.customfishing.api.mechanic.block.BlockLibrary; -import net.momirealms.customfishing.api.mechanic.block.BlockStateModifierBuilder; import net.momirealms.customfishing.api.mechanic.loot.Loot; import org.bukkit.Location; import org.bukkit.block.Block; diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/block/BlockStateModifier.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/block/BlockStateModifier.java index 60af5f23..6cd59654 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/block/BlockStateModifier.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/block/BlockStateModifier.java @@ -21,5 +21,6 @@ import org.bukkit.block.BlockState; import org.bukkit.entity.Player; public interface BlockStateModifier { + void apply(Player player, BlockState blockState); } \ No newline at end of file diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/ActionBarConfig.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/ActionBarConfig.java deleted file mode 100644 index 06a39372..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/ActionBarConfig.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.mechanic.competition; - -public class ActionBarConfig extends AbstractCompetitionInfo { - - public static class Builder { - - private final ActionBarConfig config; - - public Builder() { - this.config = new ActionBarConfig(); - } - - public Builder showToAll(boolean showToAll) { - this.config.showToAll = showToAll; - return this; - } - - public Builder refreshRate(int rate) { - this.config.refreshRate = rate; - return this; - } - - public Builder switchInterval(int interval) { - this.config.switchInterval = interval; - return this; - } - - public Builder text(String[] texts) { - this.config.texts = texts; - return this; - } - - public ActionBarConfig build() { - return this.config; - } - } -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/BossBarConfig.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/BossBarConfig.java deleted file mode 100644 index 32458903..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/BossBarConfig.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.mechanic.competition; - -import org.bukkit.boss.BarColor; - -public class BossBarConfig extends AbstractCompetitionInfo { - - private BarColor color; - private Overlay overlay; - - public BarColor getColor() { - return color; - } - - public Overlay getOverlay() { - return overlay; - } - - public static class Builder { - - private final BossBarConfig config; - - public Builder() { - this.config = new BossBarConfig(); - } - - public Builder showToAll(boolean showToAll) { - this.config.showToAll = showToAll; - return this; - } - - public Builder refreshRate(int rate) { - this.config.refreshRate = rate; - return this; - } - - public Builder switchInterval(int interval) { - this.config.switchInterval = interval; - return this; - } - - public Builder text(String[] texts) { - this.config.texts = texts; - return this; - } - - public Builder color(BarColor color) { - this.config.color = color; - return this; - } - - public Builder overlay(Overlay overlay) { - this.config.overlay = overlay; - return this; - } - - public BossBarConfig build() { - return this.config; - } - } - - public enum Overlay { - NOTCHED_6, - NOTCHED_10, - NOTCHED_12, - NOTCHED_20, - PROGRESS - } -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/CompetitionConfig.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/CompetitionConfig.java index adc698a0..077d7373 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/CompetitionConfig.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/CompetitionConfig.java @@ -18,6 +18,8 @@ package net.momirealms.customfishing.api.mechanic.competition; import net.momirealms.customfishing.api.mechanic.action.Action; +import net.momirealms.customfishing.api.mechanic.competition.info.ActionBarConfigImpl; +import net.momirealms.customfishing.api.mechanic.competition.info.BossBarConfigImpl; import net.momirealms.customfishing.api.mechanic.requirement.Requirement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -29,8 +31,8 @@ public class CompetitionConfig { private final String key; private int duration; private int minPlayers; - private BossBarConfig bossBarConfig; - private ActionBarConfig actionBarConfig; + private BossBarConfigImpl bossBarConfigImpl; + private ActionBarConfigImpl actionBarConfigImpl; private Action[] skipActions; private Action[] startActions; private Action[] endActions; @@ -110,13 +112,13 @@ public class CompetitionConfig { } @Nullable - public BossBarConfig getBossBarConfig() { - return bossBarConfig; + public BossBarConfigImpl getBossBarConfig() { + return bossBarConfigImpl; } @Nullable - public ActionBarConfig getActionBarConfig() { - return actionBarConfig; + public ActionBarConfigImpl getActionBarConfig() { + return actionBarConfigImpl; } public static Builder builder(String key) { @@ -162,14 +164,14 @@ public class CompetitionConfig { } @SuppressWarnings("UnusedReturnValue") - public Builder actionbar(ActionBarConfig actionBarConfig) { - config.actionBarConfig = actionBarConfig; + public Builder actionbar(ActionBarConfigImpl actionBarConfigImpl) { + config.actionBarConfigImpl = actionBarConfigImpl; return this; } @SuppressWarnings("UnusedReturnValue") - public Builder bossbar(BossBarConfig bossBarConfig) { - config.bossBarConfig = bossBarConfig; + public Builder bossbar(BossBarConfigImpl bossBarConfigImpl) { + config.bossBarConfigImpl = bossBarConfigImpl; return this; } diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/CompetitionGoal.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/CompetitionGoal.java index 306471a9..bbb169b6 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/CompetitionGoal.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/CompetitionGoal.java @@ -17,17 +17,64 @@ package net.momirealms.customfishing.api.mechanic.competition; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.util.Index; + import java.util.concurrent.ThreadLocalRandom; -public enum CompetitionGoal { +public final class CompetitionGoal { - CATCH_AMOUNT, - TOTAL_SCORE, - MAX_SIZE, - TOTAL_SIZE, - RANDOM; + public static final CompetitionGoal CATCH_AMOUNT = new CompetitionGoal(Key.key("customfishing", "catch_amount")); + public static final CompetitionGoal TOTAL_SCORE = new CompetitionGoal(Key.key("customfishing", "total_score")); + public static final CompetitionGoal MAX_SIZE = new CompetitionGoal(Key.key("customfishing", "max_size")); + public static final CompetitionGoal TOTAL_SIZE = new CompetitionGoal(Key.key("customfishing", "total_size")); + public static final CompetitionGoal RANDOM = new CompetitionGoal(Key.key("customfishing", "random")); + private static final CompetitionGoal[] values = new CompetitionGoal[] { + CATCH_AMOUNT, TOTAL_SCORE, MAX_SIZE, TOTAL_SIZE, RANDOM + }; + + private static final Index index = Index.create(CompetitionGoal::key, values()); + + /** + * Gets an array containing all defined competition goals. + * + * @return An array of all competition goals. + */ + public static CompetitionGoal[] values() { + return values; + } + + /** + * Gets the index of competition goals by their keys. + * + * @return An index mapping keys to competition goals. + */ + public static Index index() { + return index; + } + + /** + * Gets a randomly selected competition goal. + * + * @return A randomly selected competition goal. + */ public static CompetitionGoal getRandom() { return CompetitionGoal.values()[ThreadLocalRandom.current().nextInt(CompetitionGoal.values().length - 1)]; } + + private final Key key; + + private CompetitionGoal(Key key) { + this.key = key; + } + + /** + * Gets the key representing this competition goal. + * + * @return The key of the competition goal. + */ + public Key key() { + return key; + } } diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/CompetitionManager.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/CompetitionManager.java similarity index 91% rename from api/src/main/java/net/momirealms/customfishing/api/manager/CompetitionManager.java rename to api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/CompetitionManager.java index d78ade4a..4795d037 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/CompetitionManager.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/CompetitionManager.java @@ -15,11 +15,8 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.manager; +package net.momirealms.customfishing.api.mechanic.competition; -import net.momirealms.customfishing.api.mechanic.competition.CompetitionConfig; -import net.momirealms.customfishing.api.mechanic.competition.CompetitionGoal; -import net.momirealms.customfishing.api.mechanic.competition.FishingCompetition; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/CompetitionPlayer.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/CompetitionPlayer.java index 5a18ef9e..4463987c 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/CompetitionPlayer.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/CompetitionPlayer.java @@ -21,7 +21,7 @@ import org.jetbrains.annotations.NotNull; public class CompetitionPlayer implements Comparable{ - public static CompetitionPlayer empty = new CompetitionPlayer("", 0); + private static CompetitionPlayer empty = new CompetitionPlayer("", 0); private long time; private final String player; private double score; @@ -32,12 +32,13 @@ public class CompetitionPlayer implements Comparable{ this.time = System.currentTimeMillis(); } - public void addScore(double score){ + public void addScore(double score) { this.score += score; + if (score <= 0) return; this.time = System.currentTimeMillis(); } - public void setScore(double score){ + public void setScore(double score) { this.score = score; this.time = System.currentTimeMillis(); } diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/FishingCompetition.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/FishingCompetition.java index 1e5d7b1d..b2c9a62e 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/FishingCompetition.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/FishingCompetition.java @@ -29,7 +29,7 @@ public interface FishingCompetition { /** * Start the fishing competition */ - void start(); + void start(boolean triggerEvent); /** * Stop the fishing competition diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/Ranking.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/Ranking.java index 728ac725..7adc09a9 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/Ranking.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/Ranking.java @@ -17,7 +17,7 @@ package net.momirealms.customfishing.api.mechanic.competition; -import net.momirealms.customfishing.api.common.Pair; +import net.momirealms.customfishing.common.util.Pair; import org.jetbrains.annotations.Nullable; import java.util.Iterator; diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/AbstractCompetitionInfo.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/info/AbstractCompetitionInfo.java similarity index 78% rename from api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/AbstractCompetitionInfo.java rename to api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/info/AbstractCompetitionInfo.java index 434395d7..ecf84ed1 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/AbstractCompetitionInfo.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/info/AbstractCompetitionInfo.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.mechanic.competition; +package net.momirealms.customfishing.api.mechanic.competition.info; /** * Abstract base class for competition information. @@ -28,12 +28,19 @@ public abstract class AbstractCompetitionInfo { protected boolean showToAll; protected String[] texts; + protected AbstractCompetitionInfo(int refreshRate, int switchInterval, boolean showToAll, String[] texts) { + this.refreshRate = refreshRate; + this.switchInterval = switchInterval; + this.showToAll = showToAll; + this.texts = texts; + } + /** * Get the refresh rate for updating competition information. * * @return The refresh rate in ticks. */ - public int getRefreshRate() { + public int refreshRate() { return refreshRate; } @@ -42,7 +49,7 @@ public abstract class AbstractCompetitionInfo { * * @return The switch interval in ticks. */ - public int getSwitchInterval() { + public int switchInterval() { return switchInterval; } @@ -51,7 +58,7 @@ public abstract class AbstractCompetitionInfo { * * @return True if information is shown to all players, otherwise only to participants. */ - public boolean isShowToAll() { + public boolean showToAll() { return showToAll; } @@ -60,7 +67,7 @@ public abstract class AbstractCompetitionInfo { * * @return An array of competition information texts. */ - public String[] getTexts() { + public String[] texts() { return texts; } } diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/info/ActionBarConfig.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/info/ActionBarConfig.java new file mode 100644 index 00000000..b8122d10 --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/info/ActionBarConfig.java @@ -0,0 +1,91 @@ +package net.momirealms.customfishing.api.mechanic.competition.info; + +public interface ActionBarConfig { + + int DEFAULT_REFRESH_RATE = 20; + int DEFAULT_SWITCH_INTERVAL = 200; + boolean DEFAULT_VISIBILITY = true; + String[] DEFAULT_TEXTS = new String[]{""}; + + /** + * Get the refresh rate for updating the competition information on the action bar. + * + * @return The refresh rate in ticks. + */ + int refreshRate(); + + /** + * Get the switch interval for displaying different competition texts. + * + * @return The switch interval in ticks. + */ + int switchInterval(); + + /** + * Check if competition information should be shown to all players. + * + * @return True if information is shown to all players, otherwise only to participants. + */ + boolean showToAll(); + + /** + * Get an array of competition information texts. + * + * @return An array of competition information texts. + */ + String[] texts(); + + /** + * Creates a new builder instance for constructing {@code ActionBarConfig} objects. + * + * @return A new {@code Builder} instance. + */ + static Builder builder() { + return new ActionBarConfigImpl.BuilderImpl(); + } + + /** + * Builder interface for constructing {@code ActionBarConfig} objects. + */ + interface Builder { + + /** + * Sets whether the competition information should be shown to all players. + * + * @param showToAll True to show information to all players, false to show only to participants. + * @return The current {@code Builder} instance. + */ + Builder showToAll(boolean showToAll); + + /** + * Sets the refresh rate for updating the competition information. + * + * @param rate The refresh rate in ticks. + * @return The current {@code Builder} instance. + */ + Builder refreshRate(int rate); + + /** + * Sets the interval for switching between different competition texts. + * + * @param interval The switch interval in ticks. + * @return The current {@code Builder} instance. + */ + Builder switchInterval(int interval); + + /** + * Sets the texts to be displayed on the action bar during the competition. + * + * @param texts An array of competition information texts. + * @return The current {@code Builder} instance. + */ + Builder text(String[] texts); + + /** + * Builds the {@code ActionBarConfig} object with the configured settings. + * + * @return The constructed {@code ActionBarConfig} object. + */ + ActionBarConfig build(); + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/info/ActionBarConfigImpl.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/info/ActionBarConfigImpl.java new file mode 100644 index 00000000..f7510460 --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/info/ActionBarConfigImpl.java @@ -0,0 +1,56 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customfishing.api.mechanic.competition.info; + +public class ActionBarConfigImpl extends AbstractCompetitionInfo implements ActionBarConfig { + + public ActionBarConfigImpl(int refreshRate, int switchInterval, boolean showToAll, String[] texts) { + super(refreshRate, switchInterval, showToAll, texts); + } + + public static class BuilderImpl implements Builder { + private int refreshRate = DEFAULT_REFRESH_RATE; + private int switchInterval = DEFAULT_SWITCH_INTERVAL; + private boolean showToAll = DEFAULT_VISIBILITY; + private String[] texts = DEFAULT_TEXTS; + @Override + public BuilderImpl showToAll(boolean showToAll) { + this.showToAll = showToAll; + return this; + } + @Override + public BuilderImpl refreshRate(int rate) { + this.refreshRate = rate; + return this; + } + @Override + public BuilderImpl switchInterval(int interval) { + this.switchInterval = interval; + return this; + } + @Override + public BuilderImpl text(String[] texts) { + this.texts = texts; + return this; + } + @Override + public ActionBarConfigImpl build() { + return new ActionBarConfigImpl(refreshRate, switchInterval, showToAll, texts); + } + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/info/BossBarConfig.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/info/BossBarConfig.java new file mode 100644 index 00000000..08c55a0e --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/info/BossBarConfig.java @@ -0,0 +1,125 @@ +package net.momirealms.customfishing.api.mechanic.competition.info; + +import net.kyori.adventure.bossbar.BossBar; + +public interface BossBarConfig { + + int DEFAULT_REFRESH_RATE = 20; + int DEFAULT_SWITCH_INTERVAL = 200; + boolean DEFAULT_VISIBILITY = true; + String[] DEFAULT_TEXTS = new String[]{""}; + BossBar.Color DEFAULT_COLOR = BossBar.Color.BLUE; + BossBar.Overlay DEFAULT_OVERLAY = BossBar.Overlay.PROGRESS; + + /** + * Get the refresh rate for updating competition information. + * + * @return The refresh rate in ticks. + */ + int refreshRate(); + + /** + * Get the switch interval for displaying different competition texts. + * + * @return The switch interval in ticks. + */ + int switchInterval(); + + /** + * Check if competition information should be shown to all players. + * + * @return True if information is shown to all players, otherwise only to participants. + */ + boolean showToAll(); + + /** + * Get an array of competition information texts. + * + * @return An array of competition information texts. + */ + String[] texts(); + + /** + * Gets the color of the boss bar. + * + * @return The color of the boss bar. + */ + BossBar.Color color(); + + /** + * Gets the overlay style of the boss bar. + * + * @return The overlay style of the boss bar. + */ + BossBar.Overlay overlay(); + + /** + * Creates a new builder instance for constructing {@code BossBarConfig} objects. + * + * @return A new {@code Builder} instance. + */ + static Builder builder() { + return new BossBarConfigImpl.BuilderImpl(); + } + + /** + * Builder interface for constructing {@code BossBarConfig} objects. + */ + interface Builder { + + /** + * Sets whether the competition information should be shown to all players. + * + * @param showToAll True to show information to all players, false to show only to participants. + * @return The current {@code Builder} instance. + */ + Builder showToAll(boolean showToAll); + + /** + * Sets the refresh rate for updating the competition information. + * + * @param rate The refresh rate in ticks. + * @return The current {@code Builder} instance. + */ + Builder refreshRate(int rate); + + /** + * Sets the interval for switching between different competition texts. + * + * @param interval The switch interval in ticks. + * @return The current {@code Builder} instance. + */ + Builder switchInterval(int interval); + + /** + * Sets the texts to be displayed on the boss bar during the competition. + * + * @param texts An array of competition information texts. + * @return The current {@code Builder} instance. + */ + Builder text(String[] texts); + + /** + * Sets the color of the boss bar. + * + * @param color The color of the boss bar. + * @return The current {@code Builder} instance. + */ + Builder color(BossBar.Color color); + + /** + * Sets the overlay style of the boss bar. + * + * @param overlay The overlay style of the boss bar. + * @return The current {@code Builder} instance. + */ + Builder overlay(BossBar.Overlay overlay); + + /** + * Builds the {@code BossBarConfig} object with the configured settings. + * + * @return The constructed {@code BossBarConfig} object. + */ + BossBarConfig build(); + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/info/BossBarConfigImpl.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/info/BossBarConfigImpl.java new file mode 100644 index 00000000..a00ed7d6 --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/competition/info/BossBarConfigImpl.java @@ -0,0 +1,85 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customfishing.api.mechanic.competition.info; + +import net.kyori.adventure.bossbar.BossBar; + +public class BossBarConfigImpl extends AbstractCompetitionInfo implements BossBarConfig { + + private final BossBar.Color color; + private final BossBar.Overlay overlay; + + public BossBarConfigImpl(int refreshRate, int switchInterval, boolean showToAll, String[] texts, BossBar.Color color, BossBar.Overlay overlay) { + super(refreshRate, switchInterval, showToAll, texts); + this.color = color; + this.overlay = overlay; + } + + @Override + public BossBar.Color color() { + return color; + } + + @Override + public BossBar.Overlay overlay() { + return overlay; + } + + public static class BuilderImpl implements Builder { + private int refreshRate = DEFAULT_REFRESH_RATE; + private int switchInterval = DEFAULT_SWITCH_INTERVAL; + private boolean showToAll = DEFAULT_VISIBILITY; + private String[] texts = DEFAULT_TEXTS; + private BossBar.Overlay overlay = DEFAULT_OVERLAY; + public BossBar.Color color = DEFAULT_COLOR; + @Override + public BuilderImpl showToAll(boolean showToAll) { + this.showToAll = showToAll; + return this; + } + @Override + public BuilderImpl refreshRate(int rate) { + this.refreshRate = rate; + return this; + } + @Override + public BuilderImpl switchInterval(int interval) { + this.switchInterval = interval; + return this; + } + @Override + public BuilderImpl text(String[] texts) { + this.texts = texts; + return this; + } + @Override + public BuilderImpl color(BossBar.Color color) { + this.color = color; + return this; + } + @Override + public BuilderImpl overlay(BossBar.Overlay overlay) { + this.overlay = overlay; + return this; + } + @Override + public BossBarConfigImpl build() { + return new BossBarConfigImpl(refreshRate, switchInterval, showToAll, texts, color, overlay); + } + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/condition/Condition.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/condition/Condition.java deleted file mode 100644 index 8d41e070..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/condition/Condition.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.mechanic.condition; - -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.HashMap; -import java.util.Map; - -/** - * Represents a condition with associated data - */ -public class Condition { - - protected Location location; - protected final Player player; - protected final @NotNull Map args; - - /** - * Creates a new Condition object based on a player's location. - * - * @param player The player associated with this condition. - */ - public Condition(@NotNull Player player) { - this(player.getLocation(), player, new HashMap<>()); - } - - /** - * Creates a new Condition object with specified arguments. - * - * @param player The player associated with this condition. - * @param args A map of arguments associated with this condition. - */ - public Condition(@NotNull Player player, @NotNull Map args) { - this(player.getLocation(), player, args); - } - - /** - * Creates a new Condition object with a specific location, player, and arguments. - * - * @param location The location associated with this condition. - * @param player The player associated with this condition. - * @param args A map of arguments associated with this condition. - */ - public Condition(Location location, Player player, @NotNull Map args) { - this.location = location; - this.player = player; - this.args = args; - if (player != null) - this.args.put("{player}", player.getName()); - if (location != null) { - this.args.put("{x}", String.valueOf(location.getX())); - this.args.put("{y}", String.valueOf(location.getY())); - this.args.put("{z}", String.valueOf(location.getZ())); - this.args.put("{world}", location.getWorld().getName()); - } - } - - /** - * Sets the location associated with this condition. - * - * @param location The new location to set. - */ - public void setLocation(@NotNull Location location) { - this.location = location; - this.args.put("{x}", String.valueOf(location.getX())); - this.args.put("{y}", String.valueOf(location.getY())); - this.args.put("{z}", String.valueOf(location.getZ())); - this.args.put("{world}", location.getWorld().getName()); - } - - /** - * Gets the location associated with this condition. - * - * @return The location associated with this condition. - */ - public Location getLocation() { - return location; - } - - /** - * Gets the player associated with this condition. - * - * @return The player associated with this condition. - */ - public Player getPlayer() { - return player; - } - - /** - * Gets the map of arguments associated with this condition. - * - * @return A map of arguments associated with this condition. - */ - @NotNull - public Map getArgs() { - return args; - } - - /** - * Gets the value of a specific argument by its key. - * - * @param key The key of the argument to retrieve. - * @return The value of the argument or null if not found. - */ - @Nullable - public String getArg(String key) { - return args.get(key); - } - - /** - * Inserts or updates an argument with the specified key and value. - * - * @param key The key of the argument to insert or update. - * @param value The value to set for the argument. - */ - public void insertArg(String key, String value) { - args.put(key, value); - } - - /** - * Deletes an argument with the specified key. - * - * @param key The key of the argument to delete. - * @return The value of the deleted argument or null if not found. - */ - public String delArg(String key) { - return args.remove(key); - } -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/condition/FishingPreparation.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/condition/FishingPreparation.java deleted file mode 100644 index 2ce5b509..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/condition/FishingPreparation.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.mechanic.condition; - -import net.momirealms.customfishing.api.mechanic.action.ActionTrigger; -import net.momirealms.customfishing.api.mechanic.effect.FishingEffect; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public abstract class FishingPreparation extends Condition { - - public FishingPreparation(Player player) { - super(player); - } - - /** - * Retrieves the ItemStack representing the fishing rod. - * - * @return The ItemStack representing the fishing rod. - */ - @NotNull - public abstract ItemStack getRodItemStack(); - - /** - * Retrieves the ItemStack representing the bait (if available). - * - * @return The ItemStack representing the bait, or null if no bait is set. - */ - @Nullable - public abstract ItemStack getBaitItemStack(); - - /** - * Checks if player meet the requirements for fishing gears - * - * @return True if can fish, false otherwise. - */ - public abstract boolean canFish(); - - /** - * Merges a FishingEffect into this fishing rod, applying effect modifiers. - * - * @param effect The FishingEffect to merge into this rod. - */ - public abstract void mergeEffect(FishingEffect effect); - - /** - * Triggers actions associated with a specific action trigger. - * - * @param actionTrigger The action trigger that initiates the actions. - */ - public abstract void triggerActions(ActionTrigger actionTrigger); -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/config/BukkitConfigManager.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/config/BukkitConfigManager.java new file mode 100644 index 00000000..68ca2965 --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/config/BukkitConfigManager.java @@ -0,0 +1,163 @@ +package net.momirealms.customfishing.api.mechanic.config; + +import dev.dejvokep.boostedyaml.YamlDocument; +import dev.dejvokep.boostedyaml.dvs.versioning.BasicVersioning; +import dev.dejvokep.boostedyaml.settings.dumper.DumperSettings; +import dev.dejvokep.boostedyaml.settings.general.GeneralSettings; +import dev.dejvokep.boostedyaml.settings.loader.LoaderSettings; +import dev.dejvokep.boostedyaml.settings.updater.UpdaterSettings; +import net.momirealms.customfishing.api.mechanic.context.Context; +import net.momirealms.customfishing.api.mechanic.context.ContextKeys; +import net.momirealms.customfishing.api.mechanic.misc.function.FormatFunction; +import net.momirealms.customfishing.api.mechanic.misc.function.ItemPropertyFunction; +import net.momirealms.customfishing.api.mechanic.misc.value.MathValue; +import net.momirealms.customfishing.api.mechanic.misc.value.TextValue; +import net.momirealms.customfishing.common.config.ConfigManager; +import net.momirealms.customfishing.common.config.node.Node; +import net.momirealms.customfishing.common.helper.AdventureHelper; +import net.momirealms.customfishing.common.item.Item; +import net.momirealms.customfishing.common.plugin.CustomFishingPlugin; +import net.momirealms.customfishing.common.util.ListUtils; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Function; + +public class BukkitConfigManager implements ConfigManager { + + private final CustomFishingPlugin plugin; + + private final HashMap> formatFunctions = new HashMap<>(); + + public BukkitConfigManager(CustomFishingPlugin plugin) { + this.plugin = plugin; + this.registerBuiltInItemProperties(); + } + + private void registerBuiltInItemProperties() { + this.registerItemFunction(arg -> { + MathValue mathValue = MathValue.auto(arg); + return (item, context) -> item.customModelData((int) mathValue.evaluate(context)); + }, 4000, "custom-model-data"); + this.registerItemFunction(arg -> { + TextValue textValue = TextValue.auto((String) arg); + return (item, context) -> { + item.displayName(AdventureHelper.miniMessageToJson(textValue.render(context))); + }; + }, 3000, "display", "name"); + this.registerItemFunction(arg -> { + List list = ListUtils.toList(arg); + List> lore = new ArrayList<>(); + for (String text : list) { + lore.add(TextValue.auto(text)); + } + return (item, context) -> { + item.lore(lore.stream() + .map(it -> AdventureHelper.miniMessageToJson(it.render(context))) + .toList()); + }; + }, 2000, "display", "lore"); + this.registerItemFunction(arg -> { + boolean enable = (boolean) arg; + return (item, context) -> { + if (!enable) return; + item.setTag(context.arg(ContextKeys.ID), "CustomFishing", "id"); + item.setTag(context.arg(ContextKeys.TYPE), "CustomFishing", "type"); + }; + }, 1000, "tag"); + } + + private void registerItemFunction(Function, Context>> function, int priority, String... nodes) { + registerNodeFunction(nodes, new ItemPropertyFunction(priority, function)); + } + + public void registerNodeFunction(String[] nodes, FormatFunction formatFunction) { + Map> functionMap = formatFunctions; + for (int i = 0; i < nodes.length; i++) { + if (functionMap.containsKey(nodes[i])) { + Node functionNode = functionMap.get(nodes[i]); + if (functionNode.nodeValue() != null) { + throw new IllegalArgumentException("Format function '" + nodes[i] + "' already exists"); + } + functionMap = functionNode.getChildTree(); + } else { + if (i != nodes.length - 1) { + Node newNode = new Node<>(); + functionMap.put(nodes[i], newNode); + functionMap = newNode.getChildTree(); + } else { + functionMap.put(nodes[i], new Node<>(formatFunction)); + } + } + } + } + + protected Path resolveConfig(String filePath) { + if (filePath == null || filePath.equals("")) { + throw new IllegalArgumentException("ResourcePath cannot be null or empty"); + } + + filePath = filePath.replace('\\', '/'); + + Path configFile = plugin.getConfigDirectory().resolve(filePath); + + // if the config doesn't exist, create it based on the template in the resources dir + if (!Files.exists(configFile)) { + try { + Files.createDirectories(configFile.getParent()); + } catch (IOException e) { + // ignore + } + + try (InputStream is = plugin.getResourceStream(filePath)) { + + if (is == null) { + throw new IllegalArgumentException("The embedded resource '" + filePath + "' cannot be found"); + } + + Files.copy(is, configFile); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + return configFile; + } + + @Override + public YamlDocument loadConfig(String filePath) { + return loadConfig(filePath, '.'); + } + + @Override + public YamlDocument loadConfig(String filePath, char routeSeparator) { + try { + return YamlDocument.create( + resolveConfig(filePath).toFile(), + plugin.getResourceStream(filePath), + GeneralSettings.builder().setRouteSeparator(routeSeparator).build(), + LoaderSettings + .builder() + .setAutoUpdate(true) + .build(), + DumperSettings.DEFAULT, + UpdaterSettings + .builder() + .setVersioning(new BasicVersioning("config-version")) + .build() + ); + } catch (IOException e) { + plugin.getPluginLogger().severe("Failed to load config " + filePath, e); + return null; + } + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/config/ItemConfig.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/config/ItemConfig.java new file mode 100644 index 00000000..4a7ad3c2 --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/config/ItemConfig.java @@ -0,0 +1,62 @@ +package net.momirealms.customfishing.api.mechanic.config; + +import dev.dejvokep.boostedyaml.block.implementation.Section; +import net.momirealms.customfishing.api.mechanic.context.Context; +import net.momirealms.customfishing.api.mechanic.item.CustomFishingItem; +import net.momirealms.customfishing.api.mechanic.misc.function.FormatFunction; +import net.momirealms.customfishing.api.mechanic.misc.function.ItemPropertyFunction; +import net.momirealms.customfishing.api.mechanic.misc.function.PriorityFunction; +import net.momirealms.customfishing.common.config.node.Node; +import net.momirealms.customfishing.common.item.Item; +import net.momirealms.customfishing.common.util.Key; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; + +public class ItemConfig { + + private final String id; + private final String material; + private final List, Context>>> tagConsumers = new ArrayList<>(); + + public ItemConfig(String id, Section section, Map> functionMap) { + this.id = id; + this.material = section.getString("material"); + analyze(section, functionMap); + } + + private void analyze(Section section, Map> functionMap) { + Map dataMap = section.getStringRouteMappedValues(false); + for (Map.Entry entry : dataMap.entrySet()) { + String key = entry.getKey(); + Node node = functionMap.get(key); + if (node == null) continue; + FormatFunction function = node.nodeValue(); + if (function != null) { + if (function instanceof ItemPropertyFunction propertyFunction) { + BiConsumer, Context> result = propertyFunction.accept(entry.getValue()); + tagConsumers.add(new PriorityFunction<>(, result)); + } + continue; + } + if (entry.getValue() instanceof Section innerSection) { + analyze(innerSection, node.getChildTree()); + } + } + } + + public Key key() { + return Key.of("item", id); + } + + public CustomFishingItem getItem() { + return CustomFishingItem.builder() + .material(material) + .tagConsumers(tagConsumers) + .build(); + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/context/Context.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/context/Context.java new file mode 100644 index 00000000..9900e79c --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/context/Context.java @@ -0,0 +1,62 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customfishing.api.mechanic.context; + +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.Map; + +/** + * The Context interface represents a generic context for custom fishing mechanics. + * It allows for storing and retrieving arguments, as well as getting the holder + * of the context. This can be used to maintain state or pass parameters within + * the custom fishing mechanics. + * + * @param the type of the holder object for this context + */ +public interface Context { + + /** + * Retrieves the map of arguments associated with this context. + * + * @return a map where the keys are argument names and the values are argument values. + */ + Map, Object> args(); + + Context arg(ContextKeys key, C value); + + C arg(ContextKeys key); + + /** + * Gets the holder of this context. + * + * @return the holder object of type T. + */ + T getHolder(); + + /** + * Creates a player-specific context. + * + * @param player the player to be used as the holder of the context. + * @return a new Context instance with the specified player as the holder. + */ + static Context player(@NotNull Player player) { + return new PlayerContextImpl(player); + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/context/ContextKeys.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/context/ContextKeys.java new file mode 100644 index 00000000..182b011a --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/context/ContextKeys.java @@ -0,0 +1,70 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customfishing.api.mechanic.context; + +import org.bukkit.Location; + +import java.util.Objects; + +public class ContextKeys { + + public static final ContextKeys LOCATION = of("location", Location.class); + public static final ContextKeys X = of("x", Integer.class); + public static final ContextKeys Y = of("y", Integer.class); + public static final ContextKeys Z = of("z", Integer.class); + public static final ContextKeys WORLD = of("world", String.class); + public static final ContextKeys ID = of("id", String.class); + public static final ContextKeys TYPE = of("type", String.class); + + private final String key; + private final Class type; + + private ContextKeys(String key, Class type) { + this.key = key; + this.type = type; + } + + public String key() { + return key; + } + + public Class type() { + return type; + } + + public static ContextKeys of(String key, Class type) { + return new ContextKeys(key, type); + } + + @Override + public final boolean equals(final Object other) { + if (this == other) { + return true; + } else if (other != null && this.getClass() == other.getClass()) { + ContextKeys that = (ContextKeys) other; + return Objects.equals(this.key, that.key); + } else { + return false; + } + } + + @Override + public final int hashCode() { + return Objects.hashCode(this.key); + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/context/PlayerContextImpl.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/context/PlayerContextImpl.java new file mode 100644 index 00000000..dc1dc1df --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/context/PlayerContextImpl.java @@ -0,0 +1,97 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customfishing.api.mechanic.context; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.HashMap; +import java.util.Map; + +/** + * The PlayerContextImpl class implements the Context interface specifically + * for the Player type. It allows for storing and retrieving arguments related + * to a player in the custom fishing mechanics. + */ +public final class PlayerContextImpl implements Context { + + private final Player player; + private final HashMap, Object> args = new HashMap<>(); + + /** + * Constructs a new PlayerContextImpl with the specified player. + * + * @param player the player to be associated with this context. + */ + public PlayerContextImpl(@NotNull Player player) { + this.player = player; + final Location location = player.getLocation(); + arg(ContextKeys.LOCATION, location) + .arg(ContextKeys.X, location.getBlockX()) + .arg(ContextKeys.Y, location.getBlockY()) + .arg(ContextKeys.Z, location.getBlockZ()) + .arg(ContextKeys.WORLD, location.getWorld().getName()); + } + + /** + * Retrieves the map of arguments associated with this context. + * + * @return a map where the keys are argument names and the values are argument values. + */ + @Override + public Map, Object> args() { + return args; + } + + /** + * Adds an argument to the context and returns the context itself + * to allow for method chaining. + * + * @param key the name of the argument to add. + * @param value the value of the argument to add. + * @return the PlayerContextImpl instance to allow for method chaining. + */ + @Override + public PlayerContextImpl arg(ContextKeys key, C value) { + args.put(key, value); + return this; + } + + /** + * Retrieves the value of a specific argument from the context. + * + * @param key the name of the argument to retrieve. + * @return the value of the argument, or null if no argument with the given key exists. + */ + @Override + @SuppressWarnings("unchecked") + public C arg(ContextKeys key) { + return (C) args.get(key); + } + + /** + * Gets the player associated with this context. + * + * @return the player object associated with this context. + */ + @Override + public Player getHolder() { + return player; + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/BaseEffect.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/BaseEffect.java index 53c716a8..caa8796a4 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/BaseEffect.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/BaseEffect.java @@ -1,20 +1,20 @@ package net.momirealms.customfishing.api.mechanic.effect; -import net.momirealms.customfishing.api.mechanic.misc.Value; +import net.momirealms.customfishing.api.mechanic.misc.value.MathValue; import org.bukkit.entity.Player; import java.util.Map; public class BaseEffect { - private final Value waitTime; - private final Value waitTimeMultiplier; - private final Value difficulty; - private final Value difficultyMultiplier; - private final Value gameTime; - private final Value gameTimeMultiplier; + private final MathValue waitTime; + private final MathValue waitTimeMultiplier; + private final MathValue difficulty; + private final MathValue difficultyMultiplier; + private final MathValue gameTime; + private final MathValue gameTimeMultiplier; - public BaseEffect(Value waitTime, Value waitTimeMultiplier, Value difficulty, Value difficultyMultiplier, Value gameTime, Value gameTimeMultiplier) { + public BaseEffect(MathValue waitTime, MathValue waitTimeMultiplier, MathValue difficulty, MathValue difficultyMultiplier, MathValue gameTime, MathValue gameTimeMultiplier) { this.waitTime = waitTime; this.waitTimeMultiplier = waitTimeMultiplier; this.difficulty = difficulty; diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/Effect.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/Effect.java index a63f7e90..b7933062 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/Effect.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/Effect.java @@ -17,40 +17,45 @@ package net.momirealms.customfishing.api.mechanic.effect; -import net.momirealms.customfishing.api.common.Pair; -import net.momirealms.customfishing.api.mechanic.misc.WeightModifier; +import net.momirealms.customfishing.common.util.Pair; +import org.bukkit.entity.Player; import java.util.List; +import java.util.function.BiFunction; public interface Effect { - boolean canLavaFishing(); + boolean allowLavaFishing(); - double getMultipleLootChance(); + double multipleLootChance(); - double getSize(); + double sizeAdder(); - double getSizeMultiplier(); + double sizeMultiplier(); - double getScore(); + double scoreAdder(); - double getScoreMultiplier(); + double scoreMultiplier(); - double getWaitTime(); + double waitTimeAdder(); double getWaitTimeMultiplier(); - double getGameTime(); + double gameTimeAdder(); - double getGameTimeMultiplier(); + double gameTimeMultiplier(); - double getDifficulty(); + double difficultyAdder(); - double getDifficultyMultiplier(); + double difficultyMultiplier(); - List> getWeightModifier(); + List>> weightModifier(); - List> getWeightModifierIgnored(); + List>> weightModifierIgnored(); void merge(Effect effect); + + interface Builder { + + } } diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/EffectCarrier.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/EffectCarrier.java index 103edce2..cd70ca91 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/EffectCarrier.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/EffectCarrier.java @@ -17,10 +17,9 @@ package net.momirealms.customfishing.api.mechanic.effect; -import net.momirealms.customfishing.api.common.Key; +import net.kyori.adventure.key.Key; import net.momirealms.customfishing.api.mechanic.action.Action; import net.momirealms.customfishing.api.mechanic.action.ActionTrigger; -import net.momirealms.customfishing.api.mechanic.condition.Condition; import net.momirealms.customfishing.api.mechanic.requirement.Requirement; import org.jetbrains.annotations.Nullable; @@ -102,10 +101,10 @@ public class EffectCarrier { } @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean isConditionMet(Condition condition) { + public boolean isConditionMet(PlayerContext playerContext) { if (requirements == null) return true; for (Requirement requirement : requirements) { - if (!requirement.isConditionMet(condition)) { + if (!requirement.check(playerContext)) { return false; } } diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/EffectImpl.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/EffectImpl.java new file mode 100644 index 00000000..114393ec --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/EffectImpl.java @@ -0,0 +1,4 @@ +package net.momirealms.customfishing.api.mechanic.effect; + +public class EffectImpl { +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/EffectManager.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/EffectManager.java similarity index 91% rename from api/src/main/java/net/momirealms/customfishing/api/manager/EffectManager.java rename to api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/EffectManager.java index caccbfd4..f288b28f 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/EffectManager.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/EffectManager.java @@ -15,13 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.manager; +package net.momirealms.customfishing.api.mechanic.effect; -import net.momirealms.customfishing.api.common.Key; -import net.momirealms.customfishing.api.mechanic.effect.BaseEffect; -import net.momirealms.customfishing.api.mechanic.effect.EffectCarrier; -import net.momirealms.customfishing.api.mechanic.effect.EffectModifier; -import net.momirealms.customfishing.api.mechanic.effect.FishingEffect; +import net.kyori.adventure.key.Key; import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/EffectModifier.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/EffectModifier.java index 6df659cf..8bbf20ac 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/EffectModifier.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/EffectModifier.java @@ -17,9 +17,10 @@ package net.momirealms.customfishing.api.mechanic.effect; -import net.momirealms.customfishing.api.mechanic.condition.Condition; +import net.momirealms.customfishing.api.mechanic.context.Context; +import org.bukkit.entity.Player; public interface EffectModifier { - void modify(FishingEffect effect, Condition condition); + void modify(FishingEffect effect, Context playerContext); } diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/FishingEffect.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/FishingEffect.java index f8408f48..8d294532 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/FishingEffect.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/effect/FishingEffect.java @@ -18,7 +18,6 @@ package net.momirealms.customfishing.api.mechanic.effect; import net.momirealms.customfishing.api.common.Pair; -import net.momirealms.customfishing.api.mechanic.misc.WeightModifier; import java.util.ArrayList; import java.util.List; @@ -214,7 +213,7 @@ public class FishingEffect implements Effect { * @return True if lava fishing is enabled, false otherwise. */ @Override - public boolean canLavaFishing() { + public boolean allowLavaFishing() { return lavaFishing; } @@ -224,7 +223,7 @@ public class FishingEffect implements Effect { * @return The multiple loot chance value. */ @Override - public double getMultipleLootChance() { + public double multipleLootChance() { return multipleLootChance; } @@ -234,7 +233,7 @@ public class FishingEffect implements Effect { * @return The size multiplier value. */ @Override - public double getSizeMultiplier() { + public double sizeMultiplier() { return sizeMultiplier; } @@ -244,7 +243,7 @@ public class FishingEffect implements Effect { * @return The size value. */ @Override - public double getSize() { + public double sizeAdder() { return size; } @@ -254,7 +253,7 @@ public class FishingEffect implements Effect { * @return The score multiplier value. */ @Override - public double getScoreMultiplier() { + public double scoreMultiplier() { return scoreMultiplier; } @@ -274,7 +273,7 @@ public class FishingEffect implements Effect { * @return The wait time . */ @Override - public double getWaitTime() { + public double waitTimeAdder() { return waitTime; } @@ -284,7 +283,7 @@ public class FishingEffect implements Effect { * @return The game time value. */ @Override - public double getGameTime() { + public double gameTimeAdder() { return gameTime; } @@ -294,7 +293,7 @@ public class FishingEffect implements Effect { * @return The game time value multiplier. */ @Override - public double getGameTimeMultiplier() { + public double gameTimeMultiplier() { return gameTimeMultiplier; } @@ -304,7 +303,7 @@ public class FishingEffect implements Effect { * @return The score value. */ @Override - public double getScore() { + public double scoreAdder() { return score; } @@ -314,7 +313,7 @@ public class FishingEffect implements Effect { * @return The difficulty value. */ @Override - public double getDifficulty() { + public double difficultyAdder() { return difficulty; } @@ -324,7 +323,7 @@ public class FishingEffect implements Effect { * @return The difficulty multiplier value. */ @Override - public double getDifficultyMultiplier() { + public double difficultyMultiplier() { return difficultyMultiplier; } @@ -334,7 +333,7 @@ public class FishingEffect implements Effect { * @return The list of weight modifiers. */ @Override - public List> getWeightModifier() { + public List> weightModifier() { return weightModifier; } @@ -344,7 +343,7 @@ public class FishingEffect implements Effect { * @return The list of weight modifiers ignoring conditions. */ @Override - public List> getWeightModifierIgnored() { + public List> weightModifierIgnored() { return weightModifierIgnored; } @@ -356,18 +355,18 @@ public class FishingEffect implements Effect { @Override public void merge(Effect another) { if (another == null) return; - if (another.canLavaFishing()) this.lavaFishing = true; - this.scoreMultiplier += (another.getScoreMultiplier() -1); - this.score += another.getScore(); - this.sizeMultiplier += (another.getSizeMultiplier() -1); - this.size += another.getSize(); - this.difficultyMultiplier += (another.getDifficultyMultiplier() -1); - this.difficulty += another.getDifficulty(); - this.gameTimeMultiplier += (another.getGameTimeMultiplier() - 1); - this.gameTime += another.getGameTime(); + if (another.allowLavaFishing()) this.lavaFishing = true; + this.scoreMultiplier += (another.scoreMultiplier() -1); + this.score += another.scoreAdder(); + this.sizeMultiplier += (another.sizeMultiplier() -1); + this.size += another.sizeAdder(); + this.difficultyMultiplier += (another.difficultyMultiplier() -1); + this.difficulty += another.difficultyAdder(); + this.gameTimeMultiplier += (another.gameTimeMultiplier() - 1); + this.gameTime += another.gameTimeAdder(); this.waitTimeMultiplier += (another.getWaitTimeMultiplier() -1); - this.multipleLootChance += another.getMultipleLootChance(); - this.weightModifierIgnored.addAll(another.getWeightModifierIgnored()); - this.weightModifier.addAll(another.getWeightModifier()); + this.multipleLootChance += another.multipleLootChance(); + this.weightModifierIgnored.addAll(another.weightModifierIgnored()); + this.weightModifier.addAll(another.weightModifier()); } } diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/entity/EntityConfig.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/entity/EntityConfig.java index 8590a413..84e5b4ac 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/entity/EntityConfig.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/entity/EntityConfig.java @@ -17,76 +17,104 @@ package net.momirealms.customfishing.api.mechanic.entity; +import org.jetbrains.annotations.NotNull; + +import java.util.HashMap; import java.util.Map; -public class EntityConfig implements EntitySettings { +/** + * The EntityConfig interface defines the configuration for an entity used in custom fishing mechanics. + * It includes methods to retrieve various properties of the entity such as vectors and an ID, as well + * as a nested Builder interface for constructing instances of EntityConfig. + */ +public interface EntityConfig { - private String entity; - private double horizontalVector; - private double verticalVector; - private Map propertyMap; - private boolean persist; + double DEFAULT_HORIZONTAL_VECTOR = 1; + double DEFAULT_VERTICAL_VECTOR = 1; + String DEFAULT_ENTITY_ID = ""; + Map DEFAULT_PROPERTY_MAP = Map.of(); - @Override - public boolean isPersist() { - return persist; + /** + * Retrieves the horizontal vector value for the entity. + * + * @return the horizontal vector value as a double + */ + double getHorizontalVector(); + + /** + * Retrieves the vertical vector value for the entity. + * + * @return the vertical vector value as a double + */ + double getVerticalVector(); + + /** + * Retrieves the unique identifier for the entity. + * + * @return the entity ID as a non-null String + */ + @NotNull + String getEntityID(); + + /** + * Retrieves a map of properties associated with the entity. + * + * @return a non-null map where keys are property names and values are property values + */ + @NotNull + Map getPropertyMap(); + + /** + * Creates a new Builder instance for constructing an EntityConfig. + * + * @return a new Builder instance + */ + static Builder builder() { + return new EntityConfigImpl.BuilderImpl(); } - @Override - public double getHorizontalVector() { - return horizontalVector; - } + /** + * Builder interface for constructing instances of EntityConfig. + */ + interface Builder { - @Override - public double getVerticalVector() { - return verticalVector; - } + /** + * Sets the entity ID for the EntityConfig being built. + * + * @param value the entity ID as a String + * @return the current Builder instance + */ + Builder entityID(String value); - @Override - public String getEntityID() { - return entity; - } + /** + * Sets the vertical vector value for the EntityConfig being built. + * + * @param value the vertical vector value as a double + * @return the current Builder instance + */ + Builder verticalVector(double value); - @Override - public Map getPropertyMap() { - return propertyMap; - } + /** + * Sets the horizontal vector value for the EntityConfig being built. + * + * @param value the horizontal vector value as a double + * @return the current Builder instance + */ + Builder horizontalVector(double value); - public static class Builder { + /** + * Sets the property map for the EntityConfig being built. + * + * @param value a map of properties where keys are property names and values are property values + * @return the current Builder instance + */ + Builder propertyMap(Map value); - private final EntityConfig config; - - public Builder() { - this.config = new EntityConfig(); - } - - public Builder entityID(String value) { - this.config.entity = value; - return this; - } - - public Builder persist(boolean value) { - this.config.persist = value; - return this; - } - - public Builder verticalVector(double value) { - this.config.verticalVector = value; - return this; - } - - public Builder horizontalVector(double value) { - this.config.horizontalVector = value; - return this; - } - - public Builder propertyMap(Map value) { - this.config.propertyMap = value; - return this; - } - - public EntityConfig build() { - return config; - } + /** + * Builds and returns the EntityConfig instance based on the current state of the Builder. + * + * @return a new EntityConfig instance + */ + EntityConfig build(); } } diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/entity/EntityConfigImpl.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/entity/EntityConfigImpl.java new file mode 100644 index 00000000..b224a6f7 --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/entity/EntityConfigImpl.java @@ -0,0 +1,90 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customfishing.api.mechanic.entity; + +import org.jetbrains.annotations.NotNull; + +import java.util.Map; + +public class EntityConfigImpl implements EntityConfig { + + private final String id; + private final double horizontalVector; + private final double verticalVector; + private final Map propertyMap; + + public EntityConfigImpl(String id, double horizontalVector, double verticalVector, Map propertyMap) { + this.id = id; + this.horizontalVector = horizontalVector; + this.verticalVector = verticalVector; + this.propertyMap = propertyMap; + } + + @Override + public double getHorizontalVector() { + return horizontalVector; + } + + @Override + public double getVerticalVector() { + return verticalVector; + } + + @NotNull + @Override + public String getEntityID() { + return id; + } + + @NotNull + @Override + public Map getPropertyMap() { + return propertyMap; + } + + public static class BuilderImpl implements Builder { + private String entity = DEFAULT_ENTITY_ID; + private double horizontalVector = DEFAULT_HORIZONTAL_VECTOR; + private double verticalVector = DEFAULT_VERTICAL_VECTOR; + private Map propertyMap = DEFAULT_PROPERTY_MAP; + @Override + public BuilderImpl entityID(String value) { + this.entity = value; + return this; + } + @Override + public BuilderImpl verticalVector(double value) { + this.verticalVector = value; + return this; + } + @Override + public BuilderImpl horizontalVector(double value) { + this.horizontalVector = value; + return this; + } + @Override + public BuilderImpl propertyMap(Map value) { + this.propertyMap = value; + return this; + } + @Override + public EntityConfigImpl build() { + return new EntityConfigImpl(entity, horizontalVector, verticalVector, propertyMap); + } + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/entity/EntityLibrary.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/entity/EntityLibrary.java deleted file mode 100644 index 74f4358e..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/entity/EntityLibrary.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.mechanic.entity; - -import org.bukkit.Location; -import org.bukkit.entity.Entity; - -import java.util.Map; - -public interface EntityLibrary { - - String identification(); - - Entity spawn(Location location, String id, Map propertyMap); -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/EntityManager.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/entity/EntityManager.java similarity index 62% rename from api/src/main/java/net/momirealms/customfishing/api/manager/EntityManager.java rename to api/src/main/java/net/momirealms/customfishing/api/mechanic/entity/EntityManager.java index 25de6e97..45b88fbb 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/EntityManager.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/entity/EntityManager.java @@ -15,30 +15,13 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.manager; +package net.momirealms.customfishing.api.mechanic.entity; -import net.momirealms.customfishing.api.mechanic.entity.EntityLibrary; import net.momirealms.customfishing.api.mechanic.loot.Loot; import org.bukkit.Location; public interface EntityManager { - /** - * Registers an entity library for use in the plugin. - * - * @param entityLibrary The entity library to register. - * @return {@code true} if the entity library was successfully registered, {@code false} if it already exists. - */ - boolean registerEntityLibrary(EntityLibrary entityLibrary); - - /** - * Unregisters an entity library by its identification key. - * - * @param identification The identification key of the entity library to unregister. - * @return {@code true} if the entity library was successfully unregistered, {@code false} if it does not exist. - */ - boolean unregisterEntityLibrary(String identification); - /** * Summons an entity based on the given loot configuration to a specified location. * diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/entity/EntitySettings.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/entity/EntitySettings.java deleted file mode 100644 index 57ae5d76..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/entity/EntitySettings.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.mechanic.entity; - -import java.util.Map; - -public interface EntitySettings { - boolean isPersist(); - - double getHorizontalVector(); - - double getVerticalVector(); - - String getEntityID(); - - Map getPropertyMap(); -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/FishingManager.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/fishing/FishingManager.java similarity index 93% rename from api/src/main/java/net/momirealms/customfishing/api/manager/FishingManager.java rename to api/src/main/java/net/momirealms/customfishing/api/mechanic/fishing/FishingManager.java index bb9eabbe..529b1bd1 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/FishingManager.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/fishing/FishingManager.java @@ -15,10 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.manager; +package net.momirealms.customfishing.api.mechanic.fishing; import net.momirealms.customfishing.api.mechanic.TempFishingState; -import net.momirealms.customfishing.api.mechanic.condition.Condition; import net.momirealms.customfishing.api.mechanic.effect.Effect; import net.momirealms.customfishing.api.mechanic.game.GameInstance; import net.momirealms.customfishing.api.mechanic.game.GameSettings; @@ -81,10 +80,10 @@ public interface FishingManager { * Starts a fishing game for the specified player with the given condition and effect. * * @param player The player starting the fishing game. - * @param condition The condition used to determine the game. + * @param playerContext The condition used to determine the game. * @param effect The effect applied to the game. */ - boolean startFishingGame(Player player, Condition condition, Effect effect); + boolean startFishingGame(Player player, PlayerContext playerContext, Effect effect); /** * Starts a fishing game for the specified player with the given settings and game instance. diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/game/AbstractGamingPlayer.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/game/AbstractGamingPlayer.java index 3a163850..fcd2abf5 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/game/AbstractGamingPlayer.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/game/AbstractGamingPlayer.java @@ -17,8 +17,8 @@ package net.momirealms.customfishing.api.mechanic.game; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.manager.FishingManager; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; +import net.momirealms.customfishing.api.mechanic.fishing.FishingManager; import net.momirealms.customfishing.api.mechanic.effect.Effect; import net.momirealms.customfishing.api.scheduler.CancellableTask; import org.bukkit.Material; @@ -41,13 +41,13 @@ public abstract class AbstractGamingPlayer implements GamingPlayer, Runnable { this.player = player; this.fishHook = hook; this.settings = settings; - this.manager = CustomFishingPlugin.get().getFishingManager(); + this.manager = BukkitCustomFishingPlugin.get().getFishingManager(); this.deadline = (long) (System.currentTimeMillis() + settings.getTime() * 1000L); this.arrangeTask(); } public void arrangeTask() { - this.task = CustomFishingPlugin.get().getScheduler().runTaskSyncTimer(this, fishHook.getLocation(), 1, 1); + this.task = BukkitCustomFishingPlugin.get().getScheduler().runTaskSyncTimer(this, fishHook.getLocation(), 1, 1); } @Override diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/game/BasicGameConfig.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/game/BasicGameConfig.java index 5983cc79..97cb5a84 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/game/BasicGameConfig.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/game/BasicGameConfig.java @@ -79,8 +79,8 @@ public class BasicGameConfig { @Nullable public GameSettings getGameSetting(Effect effect) { return new GameSettings( - ThreadLocalRandom.current().nextInt(minTime, maxTime + 1) * effect.getGameTimeMultiplier() + effect.getGameTime(), - (int) Math.min(100, Math.max(1, ThreadLocalRandom.current().nextInt(minDifficulty, maxDifficulty + 1) * effect.getDifficultyMultiplier() + effect.getDifficulty())) + ThreadLocalRandom.current().nextInt(minTime, maxTime + 1) * effect.gameTimeMultiplier() + effect.gameTimeAdder(), + (int) Math.min(100, Math.max(1, ThreadLocalRandom.current().nextInt(minDifficulty, maxDifficulty + 1) * effect.difficultyMultiplier() + effect.difficultyAdder())) ); } } \ No newline at end of file diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/GameManager.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/game/GameManager.java similarity index 84% rename from api/src/main/java/net/momirealms/customfishing/api/manager/GameManager.java rename to api/src/main/java/net/momirealms/customfishing/api/mechanic/game/GameManager.java index 305a35af..2ef335cb 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/GameManager.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/game/GameManager.java @@ -15,13 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.manager; +package net.momirealms.customfishing.api.mechanic.game; import net.momirealms.customfishing.api.common.Pair; -import net.momirealms.customfishing.api.mechanic.condition.Condition; -import net.momirealms.customfishing.api.mechanic.game.BasicGameConfig; -import net.momirealms.customfishing.api.mechanic.game.GameFactory; -import net.momirealms.customfishing.api.mechanic.game.GameInstance; import org.jetbrains.annotations.Nullable; import java.util.HashMap; @@ -65,8 +61,8 @@ public interface GameManager { /** * Retrieves a map of game names and their associated weights based on the specified conditions. * - * @param condition The condition to evaluate game weights. + * @param playerContext The condition to evaluate game weights. * @return A {@code HashMap} containing game names as keys and their associated weights as values. */ - HashMap getGameWithWeight(Condition condition); + HashMap getGameWithWeight(PlayerContext playerContext); } diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/HookManager.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/hook/HookManager.java similarity index 96% rename from api/src/main/java/net/momirealms/customfishing/api/manager/HookManager.java rename to api/src/main/java/net/momirealms/customfishing/api/mechanic/hook/HookManager.java index d0649926..c3a7d701 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/HookManager.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/hook/HookManager.java @@ -15,9 +15,8 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.manager; +package net.momirealms.customfishing.api.mechanic.hook; -import net.momirealms.customfishing.api.mechanic.hook.HookSetting; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.Nullable; diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/item/BuildableItem.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/item/BuildableItem.java deleted file mode 100644 index 9ac17591..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/item/BuildableItem.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.mechanic.item; - -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import java.util.HashMap; -import java.util.Map; - -public interface BuildableItem { - - default ItemStack build() { - return build(null, new HashMap<>()); - } - - default ItemStack build(Player player) { - return build(player, new HashMap<>()); - } - - ItemStack build(Player player, Map placeholders); - - /** - * Whether the item would be removed from cache when reloading - */ - boolean persist(); -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/item/CustomFishingItem.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/item/CustomFishingItem.java new file mode 100644 index 00000000..ae8995f3 --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/item/CustomFishingItem.java @@ -0,0 +1,69 @@ +package net.momirealms.customfishing.api.mechanic.item; + +import net.momirealms.customfishing.api.mechanic.context.Context; +import net.momirealms.customfishing.api.mechanic.misc.function.PriorityFunction; +import net.momirealms.customfishing.common.item.Item; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.TreeSet; +import java.util.function.BiConsumer; + +public interface CustomFishingItem { + + String DEFAULT_MATERIAL = "PAPER"; + + /** + * Returns the material type of the custom fishing item. + * + * @return the material type as a String. + */ + String material(); + + /** + * Returns a list of tag consumers which are functions that take an item and context as parameters + * and perform some operation on them. + * + * @return a set of BiConsumer instances. + */ + List, Context>> tagConsumers(); + + /** + * Creates a new Builder instance to construct a CustomFishingItem. + * + * @return a new Builder instance. + */ + static Builder builder() { + return new CustomFishingItemImpl.BuilderImpl(); + } + + /** + * Builder interface for constructing instances of CustomFishingItem. + */ + interface Builder { + + /** + * Sets the material type for the CustomFishingItem being built. + * + * @param material the material type as a String. + * @return the Builder instance for method chaining. + */ + Builder material(String material); + + /** + * Sets the list of tag consumers for the CustomFishingItem being built. + * + * @param tagConsumers a list of BiConsumer instances. + * @return the Builder instance for method chaining. + */ + Builder tagConsumers(List, Context>>> tagConsumers); + + /** + * Builds and returns a new CustomFishingItem instance. + * + * @return a new CustomFishingItem instance. + */ + CustomFishingItem build(); + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/item/CustomFishingItemImpl.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/item/CustomFishingItemImpl.java new file mode 100644 index 00000000..2fb1935c --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/item/CustomFishingItemImpl.java @@ -0,0 +1,57 @@ +package net.momirealms.customfishing.api.mechanic.item; + +import net.momirealms.customfishing.api.mechanic.context.Context; +import net.momirealms.customfishing.api.mechanic.misc.function.PriorityFunction; +import net.momirealms.customfishing.common.item.Item; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.TreeSet; +import java.util.function.BiConsumer; + +public class CustomFishingItemImpl implements CustomFishingItem { + + private final String material; + + private final List, Context>> tagConsumers; + + public CustomFishingItemImpl(String material, List, Context>> tagConsumers) { + this.material = material; + this.tagConsumers = tagConsumers; + } + + @Override + public String material() { + return material; + } + + @Override + public List, Context>> tagConsumers() { + return tagConsumers; + } + + public static class BuilderImpl implements Builder { + + private String material = DEFAULT_MATERIAL; + + private final TreeSet, Context>>> tagConsumers = new TreeSet<>(); + + @Override + public Builder material(String material) { + this.material = material; + return this; + } + + @Override + public Builder tagConsumers(List, Context>>> tagConsumers) { + this.tagConsumers.addAll(tagConsumers); + return this; + } + + @Override + public CustomFishingItem build() { + return new CustomFishingItemImpl(material, tagConsumers.stream().map(PriorityFunction::get).toList()); + } + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/item/ItemBuilder.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/item/ItemBuilder.java deleted file mode 100644 index 97d3e4fb..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/item/ItemBuilder.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.mechanic.item; - -import de.tr7zw.changeme.nbtapi.NBTItem; -import net.momirealms.customfishing.api.common.Pair; -import net.momirealms.customfishing.api.common.Tuple; -import net.momirealms.customfishing.api.mechanic.misc.Value; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemFlag; -import org.jetbrains.annotations.NotNull; - -import java.util.Collection; -import java.util.List; -import java.util.Map; - -public interface ItemBuilder extends BuildableItem { - - ItemBuilder customModelData(int value); - - ItemBuilder name(String name); - - ItemBuilder amount(int amount); - - ItemBuilder amount(int min_amount, int max_amount); - - ItemBuilder tag(boolean tag, String type, String id); - - ItemBuilder unbreakable(boolean unbreakable); - - ItemBuilder placeable(boolean placeable); - - ItemBuilder lore(List lore); - - ItemBuilder nbt(Map nbt); - - ItemBuilder itemFlag(List itemFlags); - - ItemBuilder nbt(ConfigurationSection section); - - ItemBuilder enchantment(List> enchantments, boolean store); - - ItemBuilder randomEnchantments(List> enchantments, boolean store); - - ItemBuilder enchantmentPool(List> amountPairs, List, Value>> enchantments, boolean store); - - ItemBuilder maxDurability(int max); - - ItemBuilder price(float base, float bonus); - - ItemBuilder size(Pair size); - - ItemBuilder stackable(boolean stackable); - - ItemBuilder preventGrabbing(boolean prevent); - - ItemBuilder head(String base64); - - ItemBuilder randomDamage(boolean damage); - - @NotNull - String getId(); - - @NotNull - String getLibrary(); - - int getAmount(); - - Collection getEditors(); - - ItemBuilder removeEditor(String type); - - ItemBuilder registerCustomEditor(String type, ItemPropertyEditor editor); - - interface ItemPropertyEditor { - - void edit(Player player, NBTItem nbtItem, Map placeholders); - - default void edit(Player player, NBTItem nbtItem) { - edit(player, nbtItem, null); - } - } -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/item/ItemLibrary.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/item/ItemManager.java similarity index 76% rename from api/src/main/java/net/momirealms/customfishing/api/mechanic/item/ItemLibrary.java rename to api/src/main/java/net/momirealms/customfishing/api/mechanic/item/ItemManager.java index a4419a9b..28f03726 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/item/ItemLibrary.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/item/ItemManager.java @@ -17,14 +17,14 @@ package net.momirealms.customfishing.api.mechanic.item; +import net.kyori.adventure.key.Key; +import net.momirealms.customfishing.api.mechanic.context.Context; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; -public interface ItemLibrary { +public interface ItemManager { - String identification(); - - ItemStack buildItem(Player player, String id); - - String getItemID(ItemStack itemStack); + @Nullable + ItemStack build(Context context, Key key); } diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/loot/CFLoot.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/loot/CFLoot.java deleted file mode 100644 index 0b7419a3..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/loot/CFLoot.java +++ /dev/null @@ -1,328 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.mechanic.loot; - -import net.momirealms.customfishing.api.mechanic.action.Action; -import net.momirealms.customfishing.api.mechanic.action.ActionTrigger; -import net.momirealms.customfishing.api.mechanic.condition.Condition; -import net.momirealms.customfishing.api.mechanic.effect.BaseEffect; -import net.momirealms.customfishing.api.mechanic.statistic.StatisticsKey; -import org.jetbrains.annotations.NotNull; - -import java.util.HashMap; - -public class CFLoot implements Loot { - - private final String id; - private final LootType type; - private final HashMap actionMap; - private final HashMap successTimesActionMap; - private String nick; - private boolean showInFinder; - private boolean disableGame; - private boolean disableGlobalAction; - private boolean disableStats; - private boolean instanceGame; - private double score; - private String[] lootGroup; - private StatisticsKey statisticsKey; - private BaseEffect effect; - - public CFLoot(String id, LootType type) { - this.id = id; - this.type = type; - this.actionMap = new HashMap<>(); - this.successTimesActionMap = new HashMap<>(); - } - - public static Builder builder(String id, LootType type) { - return new Builder(id, type); - } - - /** - * Builder class for CFLoot. - */ - public static class Builder { - - private final CFLoot loot; - - public Builder(String id, LootType type) { - this.loot = new CFLoot(id, type); - } - - /** - * Set the file path for this loot. - * - * @param path file path - * @return The builder. - */ - public Builder filePath(String path) { - return this; - } - - /** - * Set the nickname for this loot. - * - * @param nick The nickname. - * @return The builder. - */ - public Builder nick(String nick) { - this.loot.nick = nick; - return this; - } - - /** - * Set whether this loot should be shown in the finder. - * - * @param show True if it should be shown, false otherwise. - * @return The builder. - */ - public Builder showInFinder(boolean show) { - this.loot.showInFinder = show; - return this; - } - - /** - * Set whether this loot should have an instance game. - * - * @param instant True if it should be an instance game, false otherwise. - * @return The builder. - */ - public Builder instantGame(boolean instant) { - this.loot.instanceGame = instant; - return this; - } - - /** - * Set whether games are disabled for this loot. - * - * @param disable True if games are disabled, false otherwise. - * @return The builder. - */ - public Builder disableGames(boolean disable) { - this.loot.disableGame = disable; - return this; - } - - /** - * Set whether statistics are disabled for this loot. - * - * @param disable True if statistics are disabled, false otherwise. - * @return The builder. - */ - public Builder disableStats(boolean disable) { - this.loot.disableStats = disable; - return this; - } - - /** - * Set whether global actions are disabled for this loot. - * - * @param disable True if statistics are disabled, false otherwise. - * @return The builder. - */ - public Builder disableGlobalActions(boolean disable) { - this.loot.disableGlobalAction = disable; - return this; - } - - /** - * Set the score for this loot. - * - * @param score The score. - * @return The builder. - */ - public Builder score(double score) { - this.loot.score = score; - return this; - } - - /** - * Set the loot group for this loot. - * - * @param groups The loot group. - * @return The builder. - */ - public Builder lootGroup(String[] groups) { - this.loot.lootGroup = groups; - return this; - } - - /** - * Set the statistics key for this loot - * - * @param statisticsKey statistics key - * @return The builder. - */ - public Builder statsKey(StatisticsKey statisticsKey) { - this.loot.statisticsKey = statisticsKey; - return this; - } - - /** - * Set the effects for the loot - * - * @param effect effect - * @return The builder. - */ - public Builder baseEffect(BaseEffect effect) { - this.loot.effect = effect; - return this; - } - - /** - * Add actions triggered by a specific trigger. - * - * @param trigger The trigger for the actions. - * @param actions The actions to add. - * @return The builder. - */ - public Builder addActions(ActionTrigger trigger, Action[] actions) { - this.loot.actionMap.put(trigger, actions); - return this; - } - - /** - * Add actions triggered by multiple triggers. - * - * @param actionMap A map of triggers to actions. - * @return The builder. - */ - public Builder addActions(HashMap actionMap) { - this.loot.actionMap.putAll(actionMap); - return this; - } - - /** - * Add actions triggered by the number of successes. - * - * @param times The number of successes for triggering the actions. - * @param actions The actions to add. - * @return The builder. - */ - public Builder addTimesActions(int times, Action[] actions) { - this.loot.successTimesActionMap.put(times, actions); - return this; - } - - /** - * Add actions triggered by multiple numbers of successes. - * - * @param actionMap A map of numbers of successes to actions. - * @return The builder. - */ - public Builder addTimesActions(HashMap actionMap) { - this.loot.successTimesActionMap.putAll(actionMap); - return this; - } - - /** - * Build the CFLoot object. - * - * @return The built CFLoot object. - */ - public CFLoot build() { - return loot; - } - } - - @Override - public boolean instanceGame() { - return this.instanceGame; - } - - @Override - public String getID() { - return this.id; - } - - @Override - public LootType getType() { - return this.type; - } - - @Override - public @NotNull String getNick() { - return this.nick; - } - - @Override - public StatisticsKey getStatisticKey() { - return this.statisticsKey; - } - - @Override - public boolean showInFinder() { - return this.showInFinder; - } - - @Override - public double getScore() { - return this.score; - } - - @Override - public boolean disableGame() { - return this.disableGame; - } - - @Override - public boolean disableStats() { - return this.disableStats; - } - - @Override - public boolean disableGlobalAction() { - return this.disableGlobalAction; - } - - @Override - public String[] getLootGroup() { - return lootGroup; - } - - @Override - public Action[] getActions(ActionTrigger actionTrigger) { - return actionMap.get(actionTrigger); - } - - @Override - public void triggerActions(ActionTrigger actionTrigger, Condition condition) { - Action[] actions = getActions(actionTrigger); - if (actions != null) { - for (Action action : actions) { - action.trigger(condition); - } - } - } - - @Override - public BaseEffect getBaseEffect() { - return effect; - } - - @Override - public Action[] getSuccessTimesActions(int times) { - return successTimesActionMap.get(times); - } - - @Override - public HashMap getSuccessTimesActionMap() { - return successTimesActionMap; - } -} \ No newline at end of file diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/loot/Loot.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/loot/Loot.java index 020c4991..9baa2517 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/loot/Loot.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/loot/Loot.java @@ -19,9 +19,9 @@ package net.momirealms.customfishing.api.mechanic.loot; import net.momirealms.customfishing.api.mechanic.action.Action; import net.momirealms.customfishing.api.mechanic.action.ActionTrigger; -import net.momirealms.customfishing.api.mechanic.condition.Condition; import net.momirealms.customfishing.api.mechanic.effect.BaseEffect; -import net.momirealms.customfishing.api.mechanic.statistic.StatisticsKey; +import net.momirealms.customfishing.api.mechanic.statistic.StatisticsKeys; +import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -63,7 +63,7 @@ public interface Loot { @NotNull String getNick(); - StatisticsKey getStatisticKey(); + StatisticsKeys getStatisticKey(); /** * Check if this loot should be shown in the finder. @@ -113,9 +113,9 @@ public interface Loot { * Trigger actions associated with a specific action trigger. * * @param actionTrigger The action trigger. - * @param condition The condition under which the actions are triggered. + * @param playerContext The condition under which the actions are triggered. */ - void triggerActions(ActionTrigger actionTrigger, Condition condition); + void triggerActions(ActionTrigger actionTrigger, PlayerContext playerContext); /** * Get effects that bond to this loot @@ -130,12 +130,12 @@ public interface Loot { * @param times The number of successes. * @return The actions triggered by the specified number of successes. */ - Action[] getSuccessTimesActions(int times); + Action[] getRecordActions(int times); /** * Get a map of actions triggered by different numbers of successes. * * @return A map of actions triggered by success times. */ - HashMap getSuccessTimesActionMap(); + HashMap[]> getRecordActionMap(); } diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/LootManager.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/loot/LootManager.java similarity index 79% rename from api/src/main/java/net/momirealms/customfishing/api/manager/LootManager.java rename to api/src/main/java/net/momirealms/customfishing/api/mechanic/loot/LootManager.java index 75acc6f8..f982e473 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/LootManager.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/loot/LootManager.java @@ -15,11 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.manager; +package net.momirealms.customfishing.api.mechanic.loot; -import net.momirealms.customfishing.api.mechanic.condition.Condition; import net.momirealms.customfishing.api.mechanic.effect.Effect; -import net.momirealms.customfishing.api.mechanic.loot.Loot; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -63,34 +61,34 @@ public interface LootManager { /** * Retrieves loot configurations with weights based on a given condition. * - * @param condition The condition used to filter loot configurations. + * @param playerContext The condition used to filter loot configurations. * @return A mapping of loot configuration keys to their associated weights. */ - HashMap getLootWithWeight(Condition condition); + HashMap getLootWithWeight(PlayerContext playerContext); /** * Get a collection of possible loot keys based on a given condition. * - * @param condition The condition to determine possible loot. + * @param playerContext The condition to determine possible loot. * @return A collection of loot keys. */ - Collection getPossibleLootKeys(Condition condition); + Collection getPossibleLootKeys(PlayerContext playerContext); /** * Get a map of possible loot keys with their corresponding weights, considering fishing effect and condition. * * @param initialEffect The effect to apply weight modifiers. - * @param condition The condition to determine possible loot. + * @param playerContext The condition to determine possible loot. * @return A map of loot keys and their weights. */ - @NotNull Map getPossibleLootKeysWithWeight(Effect initialEffect, Condition condition); + @NotNull Map getPossibleLootKeysWithWeight(Effect initialEffect, PlayerContext playerContext); /** * Get the next loot item based on fishing effect and condition. * * @param effect The effect to apply weight modifiers. - * @param condition The condition to determine possible loot. + * @param playerContext The condition to determine possible loot. * @return The next loot item, or null if it doesn't exist. */ - @Nullable Loot getNextLoot(Effect effect, Condition condition); + @Nullable Loot getNextLoot(Effect effect, PlayerContext playerContext); } diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/MarketManager.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/market/MarketManager.java similarity index 97% rename from api/src/main/java/net/momirealms/customfishing/api/manager/MarketManager.java rename to api/src/main/java/net/momirealms/customfishing/api/mechanic/market/MarketManager.java index 1388e503..c1bfa514 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/MarketManager.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/market/MarketManager.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.manager; +package net.momirealms.customfishing.api.mechanic.market; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; @@ -44,7 +44,7 @@ public interface MarketManager { * * @return An integer representing the current date. */ - int getDate(); + int getRealTimeDate(); /** * Calculates the price of an ItemStack based on custom data or a predefined price map. diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/WeightModifier.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/WeightModifier.java deleted file mode 100644 index d481639a..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/WeightModifier.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.mechanic.misc; - -import org.bukkit.entity.Player; - -public interface WeightModifier { - - double modify(Player player, double weight); -} \ No newline at end of file diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/function/FormatFunction.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/function/FormatFunction.java new file mode 100644 index 00000000..066b7b39 --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/function/FormatFunction.java @@ -0,0 +1,4 @@ +package net.momirealms.customfishing.api.mechanic.misc.function; + +public interface FormatFunction { +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/function/ItemPropertyFunction.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/function/ItemPropertyFunction.java new file mode 100644 index 00000000..d92bfa8a --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/function/ItemPropertyFunction.java @@ -0,0 +1,27 @@ +package net.momirealms.customfishing.api.mechanic.misc.function; + +import net.momirealms.customfishing.api.mechanic.context.Context; +import net.momirealms.customfishing.common.item.Item; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.function.BiConsumer; +import java.util.function.Function; + +public class ItemPropertyFunction implements FormatFunction { + + private Function, Context>> function; + private int priority; + + public ItemPropertyFunction(int priority, Function, Context>> function) { + this.function = function; + } + + public BiConsumer, Context> accept(Object object) { + return function.apply(object); + } + + public int getPriority() { + return priority; + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/function/PriorityFunction.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/function/PriorityFunction.java new file mode 100644 index 00000000..ca5a9119 --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/function/PriorityFunction.java @@ -0,0 +1,23 @@ +package net.momirealms.customfishing.api.mechanic.misc.function; + +import org.jetbrains.annotations.NotNull; + +public class PriorityFunction implements Comparable> { + + private final int priority; + private final T function; + + public PriorityFunction(int priority, T function) { + this.priority = priority; + this.function = function; + } + + public T get() { + return function; + } + + @Override + public int compareTo(@NotNull PriorityFunction o) { + return Integer.compare(this.priority, o.priority); + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/season/Season.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/season/Season.java new file mode 100644 index 00000000..a419eb90 --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/season/Season.java @@ -0,0 +1,9 @@ +package net.momirealms.customfishing.api.mechanic.misc.season; + +public enum Season { + SPRING, + SUMMER, + AUTUMN, + WINTER, + DISABLE +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/ExpressionMathValueImpl.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/ExpressionMathValueImpl.java new file mode 100644 index 00000000..8760e518 --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/ExpressionMathValueImpl.java @@ -0,0 +1,17 @@ +package net.momirealms.customfishing.api.mechanic.misc.value; + +import net.momirealms.customfishing.api.mechanic.context.Context; + +public class ExpressionMathValueImpl implements MathValue { + + private String raw; + + public ExpressionMathValueImpl(String raw) { + this.raw = raw; + } + + @Override + public double evaluate(Context context) { + return 0; + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/MathValue.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/MathValue.java new file mode 100644 index 00000000..a16e448f --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/MathValue.java @@ -0,0 +1,79 @@ +/* + * Copyright (C) <2022> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.momirealms.customfishing.api.mechanic.misc.value; + +import net.momirealms.customfishing.api.mechanic.context.Context; + +/** + * The MathValue interface represents a mathematical value that can be evaluated + * within a specific context. This interface allows for the evaluation of mathematical + * expressions or plain numerical values in the context of custom fishing mechanics. + * + * @param the type of the holder object for the context + */ +public interface MathValue { + + /** + * Evaluates the mathematical value within the given context. + * + * @param context the context in which the value is evaluated + * @return the evaluated value as a double + */ + double evaluate(Context context); + + /** + * Creates a MathValue based on a mathematical expression. + * + * @param expression the mathematical expression to evaluate + * @param the type of the holder object for the context + * @return a MathValue instance representing the given expression + */ + static MathValue expression(String expression) { + return new ExpressionMathValueImpl<>(expression); + } + + /** + * Creates a MathValue based on a plain numerical value. + * + * @param value the numerical value to represent + * @param the type of the holder object for the context + * @return a MathValue instance representing the given plain value + */ + static MathValue plain(double value) { + return new PlainMathValueImpl<>(value); + } + + /** + * Automatically creates a MathValue based on the given object. + * If the object is a String, it is treated as a mathematical expression. + * If the object is a numerical type (Double, Integer, Long, Float), it is treated as a plain value. + * + * @param o the object to evaluate and create a MathValue from + * @param the type of the holder object for the context + * @return a MathValue instance representing the given object, either as an expression or a plain value + * @throws IllegalArgumentException if the object type is not supported + */ + static MathValue auto(Object o) { + if (o instanceof String s) { + return expression(s); + } else if (o instanceof Number n) { + return plain(n.doubleValue()); + } + throw new IllegalArgumentException("Unsupported type: " + o.getClass()); + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/PlaceholderTextValueImpl.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/PlaceholderTextValueImpl.java new file mode 100644 index 00000000..12099cc7 --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/PlaceholderTextValueImpl.java @@ -0,0 +1,17 @@ +package net.momirealms.customfishing.api.mechanic.misc.value; + +import net.momirealms.customfishing.api.mechanic.context.Context; + +public class PlaceholderTextValueImpl implements TextValue { + + private final String raw; + + public PlaceholderTextValueImpl(String raw) { + this.raw = raw; + } + + @Override + public String render(Context context) { + return raw; + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/PlainMathValueImpl.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/PlainMathValueImpl.java new file mode 100644 index 00000000..861cf2e2 --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/PlainMathValueImpl.java @@ -0,0 +1,17 @@ +package net.momirealms.customfishing.api.mechanic.misc.value; + +import net.momirealms.customfishing.api.mechanic.context.Context; + +public class PlainMathValueImpl implements MathValue { + + private final double value; + + public PlainMathValueImpl(double value) { + this.value = value; + } + + @Override + public double evaluate(Context context) { + return value; + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/PlainTextValueImpl.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/PlainTextValueImpl.java new file mode 100644 index 00000000..e79dff94 --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/PlainTextValueImpl.java @@ -0,0 +1,17 @@ +package net.momirealms.customfishing.api.mechanic.misc.value; + +import net.momirealms.customfishing.api.mechanic.context.Context; + +public class PlainTextValueImpl implements TextValue { + + private final String raw; + + public PlainTextValueImpl(String raw) { + this.raw = raw; + } + + @Override + public String render(Context context) { + return raw; + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/TextValue.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/TextValue.java new file mode 100644 index 00000000..4094784b --- /dev/null +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/misc/value/TextValue.java @@ -0,0 +1,65 @@ +package net.momirealms.customfishing.api.mechanic.misc.value; + +import net.momirealms.customfishing.api.mechanic.context.Context; + +import java.util.regex.Pattern; + +/** + * The TextValue interface represents a text value that can be rendered + * within a specific context. This interface allows for the rendering of + * placeholder-based or plain text values in the context of custom fishing mechanics. + * + * @param the type of the holder object for the context + */ +public interface TextValue { + + Pattern pattern = Pattern.compile("\\{[^{}]+}"); + + /** + * Renders the text value within the given context. + * + * @param context the context in which the text value is rendered + * @return the rendered text as a String + */ + String render(Context context); + + /** + * Creates a TextValue based on a placeholder text. + * Placeholders can be dynamically replaced with context-specific values. + * + * @param text the placeholder text to render + * @param the type of the holder object for the context + * @return a TextValue instance representing the given placeholder text + */ + static TextValue placeholder(String text) { + return new PlaceholderTextValueImpl<>(text); + } + + /** + * Creates a TextValue based on plain text. + * + * @param text the plain text to render + * @param the type of the holder object for the context + * @return a TextValue instance representing the given plain text + */ + static TextValue plain(String text) { + return new PlainTextValueImpl<>(text); + } + + /** + * Automatically creates a TextValue based on the given argument. + * If the argument contains placeholders (detected by a regex pattern), + * a PlaceholderTextValueImpl instance is created. Otherwise, a PlainTextValueImpl + * instance is created. + * + * @param arg the text to evaluate and create a TextValue from + * @param the type of the holder object for the context + * @return a TextValue instance representing the given text, either as a placeholder or plain text + */ + static TextValue auto(String arg) { + if (pattern.matcher(arg).find()) + return placeholder(arg); + else + return plain(arg); + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/requirement/Requirement.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/requirement/Requirement.java index 3fac8c48..40d635fb 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/requirement/Requirement.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/requirement/Requirement.java @@ -17,15 +17,21 @@ package net.momirealms.customfishing.api.mechanic.requirement; -import net.momirealms.customfishing.api.mechanic.condition.Condition; +import net.momirealms.customfishing.api.mechanic.context.Context; -public interface Requirement { +/** + * Interface representing a requirement that must be met in the custom fishing API. + * This can be used to define conditions that need to be satisfied within a given context. + * + * @param the type parameter for the context + */ +public interface Requirement { /** - * Is condition met the requirement + * Evaluates whether the requirement is met within the given context. * - * @param condition condition - * @return meet or not + * @param context the context in which the requirement is evaluated + * @return true if the requirement is met, false otherwise */ - boolean isConditionMet(Condition condition); -} + boolean isSatisfied(Context context); +} \ No newline at end of file diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/requirement/RequirementExpansion.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/requirement/RequirementExpansion.java index 11d04713..0e274c47 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/requirement/RequirementExpansion.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/requirement/RequirementExpansion.java @@ -21,7 +21,7 @@ package net.momirealms.customfishing.api.mechanic.requirement; * An abstract class representing a requirement expansion * Requirement expansions are used to define custom requirements for various functionalities. */ -public abstract class RequirementExpansion { +public abstract class RequirementExpansion { /** * Get the version of this requirement expansion. @@ -49,5 +49,5 @@ public abstract class RequirementExpansion { * * @return The requirement factory. */ - public abstract RequirementFactory getRequirementFactory(); + public abstract RequirementFactory getRequirementFactory(); } diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/requirement/RequirementFactory.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/requirement/RequirementFactory.java index adbb1030..a3657b15 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/requirement/RequirementFactory.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/requirement/RequirementFactory.java @@ -22,19 +22,21 @@ import net.momirealms.customfishing.api.mechanic.action.Action; import java.util.List; /** - * An interface for a requirement factory that builds requirements. + * Interface representing a factory for creating requirements. + * + * @param the type of object that the requirement will operate on */ -public interface RequirementFactory { +public interface RequirementFactory { /** - * Build a requirement with the given arguments, not met actions, and check action flag. + * Build a requirement with the given arguments, not satisfied actions, and check run actions flag. * - * @param args The arguments used to build the requirement. - * @param notMetActions Actions to be triggered when the requirement is not met (can be null). - * @param advanced Flag indicating whether to check the action when building the requirement. + * @param args The arguments used to build the requirement. + * @param notSatisfiedActions Actions to be triggered when the requirement is not met (can be null). + * @param runActions Flag indicating whether to run the action if the requirement is not met. * @return The built requirement. */ - Requirement build(Object args, List notMetActions, boolean advanced); + Requirement process(Object args, List> notSatisfiedActions, boolean runActions); /** * Build a requirement with the given arguments. @@ -42,7 +44,7 @@ public interface RequirementFactory { * @param args The arguments used to build the requirement. * @return The built requirement. */ - default Requirement build(Object args) { - return build(args, null, false); + default Requirement process(Object args) { + return process(args, List.of(), false); } } diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/RequirementManager.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/requirement/RequirementManager.java similarity index 62% rename from api/src/main/java/net/momirealms/customfishing/api/manager/RequirementManager.java rename to api/src/main/java/net/momirealms/customfishing/api/mechanic/requirement/RequirementManager.java index d18a6cd2..3866f2f4 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/RequirementManager.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/requirement/RequirementManager.java @@ -15,26 +15,14 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.manager; +package net.momirealms.customfishing.api.mechanic.requirement; -import net.momirealms.customfishing.api.mechanic.condition.Condition; -import net.momirealms.customfishing.api.mechanic.requirement.Requirement; -import net.momirealms.customfishing.api.mechanic.requirement.RequirementFactory; -import org.bukkit.configuration.ConfigurationSection; +import dev.dejvokep.boostedyaml.block.implementation.Section; +import net.momirealms.customfishing.api.mechanic.context.Context; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public interface RequirementManager { - - /** - * Legacy format support - * @param key key - * @param requirements requirements - * @param weight weight - * @return success or not - */ - @Deprecated - boolean putLegacyLootToMap(String key, Requirement[] requirements, double weight); +public interface RequirementManager { /** * Registers a custom requirement type with its corresponding factory. @@ -43,7 +31,7 @@ public interface RequirementManager { * @param requirementFactory The factory responsible for creating instances of the requirement. * @return True if registration was successful, false if the type is already registered. */ - boolean registerRequirement(String type, RequirementFactory requirementFactory); + boolean registerRequirement(@NotNull String type, @NotNull RequirementFactory requirementFactory); /** * Unregisters a custom requirement type. @@ -51,16 +39,17 @@ public interface RequirementManager { * @param type The type identifier of the requirement to unregister. * @return True if unregistration was successful, false if the type is not registered. */ - boolean unregisterRequirement(String type); + boolean unregisterRequirement(@NotNull String type); /** * Retrieves an array of requirements based on a configuration section. * * @param section The configuration section containing requirement definitions. - * @param advanced A flag indicating whether to use advanced requirements. + * @param runActions A flag indicating whether to use advanced requirements. * @return An array of Requirement objects based on the configuration section */ - @Nullable Requirement[] getRequirements(ConfigurationSection section, boolean advanced); + @Nullable + Requirement[] getRequirements(@NotNull Section section, boolean runActions); /** * If a requirement type exists @@ -68,7 +57,7 @@ public interface RequirementManager { * @param type type * @return exists or not */ - boolean hasRequirement(String type); + boolean hasRequirement(@NotNull String type); /** * Retrieves a Requirement object based on a configuration section and advanced flag. @@ -78,10 +67,11 @@ public interface RequirementManager { * value: xxx * * @param section The configuration section containing requirement definitions. - * @param advanced A flag indicating whether to use advanced requirements. + * @param runActions A flag indicating whether to use advanced requirements. * @return A Requirement object based on the configuration section, or an EmptyRequirement if the section is null or invalid. */ - @NotNull Requirement getRequirement(ConfigurationSection section, boolean advanced); + @NotNull + Requirement getRequirement(@NotNull Section section, boolean runActions); /** * Gets a requirement based on the provided type and value. @@ -95,7 +85,8 @@ public interface RequirementManager { * @param value The value associated with the requirement. * @return A Requirement instance based on the type and value, or an EmptyRequirement if the type is invalid. */ - @NotNull Requirement getRequirement(String type, Object value); + @NotNull + Requirement getRequirement(@NotNull String type, @NotNull Object value); /** * Retrieves a RequirementFactory based on the specified requirement type. @@ -103,19 +94,13 @@ public interface RequirementManager { * @param type The requirement type for which to retrieve a factory. * @return A RequirementFactory for the specified type, or null if no factory is found. */ - @Nullable RequirementFactory getRequirementFactory(String type); + @Nullable + RequirementFactory getRequirementFactory(@NotNull String type); - /** - * Checks if an array of requirements is met for a given condition. - * - * @param condition The Condition object to check against the requirements. - * @param requirements An array of Requirement instances to be evaluated. - * @return True if all requirements are met, false otherwise. Returns true if the requirements array is null. - */ - static boolean isRequirementMet(Condition condition, Requirement... requirements) { + static boolean isSatisfied(Context context, @Nullable Requirement... requirements) { if (requirements == null) return true; - for (Requirement requirement : requirements) { - if (!requirement.isConditionMet(condition)) { + for (Requirement requirement : requirements) { + if (!requirement.isSatisfied(context)) { return false; } } diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/statistic/Statistics.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/statistic/Statistics.java index 081fb28e..80556acd 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/statistic/Statistics.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/statistic/Statistics.java @@ -19,8 +19,9 @@ package net.momirealms.customfishing.api.mechanic.statistic; import net.momirealms.customfishing.api.data.StatisticData; import net.momirealms.customfishing.api.mechanic.action.Action; -import net.momirealms.customfishing.api.mechanic.condition.Condition; +import net.momirealms.customfishing.api.mechanic.context.Context; import net.momirealms.customfishing.api.mechanic.loot.Loot; +import org.bukkit.entity.Player; import java.util.HashMap; import java.util.Map; @@ -50,23 +51,23 @@ public class Statistics { * Adds an amount of loot to the statistics. * * @param loot The loot item. - * @param condition The condition associated with the loot. + * @param playerContext The condition associated with the loot. * @param amount The amount of loot to add. */ - public synchronized void addLootAmount(Loot loot, Condition condition, int amount) { + public synchronized void addLootAmount(Loot loot, Context playerContext, int amount) { if (amount < 1) { return; } if (amount == 1) { - addSingleLootAmount(loot, condition); + addSingleLootAmount(loot, playerContext); return; } - Integer previous = statisticMap.get(loot.getStatisticKey().getAmountKey()); + Integer previous = statisticMap.get(loot.getStatisticKey().amountKey()); if (previous == null) previous = 0; int after = previous + amount; - statisticMap.put(loot.getStatisticKey().getAmountKey(), after); + statisticMap.put(loot.getStatisticKey().amountKey(), after); total += amount; - doSuccessTimesAction(previous, after, condition, loot); + doSuccessTimesAction(previous, after, playerContext, loot); } /** @@ -74,16 +75,16 @@ public class Statistics { * * @param previous The previous success times. * @param after The updated success times. - * @param condition The condition associated with the loot. + * @param playerContext The condition associated with the loot. * @param loot The loot item. */ - private void doSuccessTimesAction(Integer previous, int after, Condition condition, Loot loot) { - HashMap actionMap = loot.getSuccessTimesActionMap(); + private void doSuccessTimesAction(Integer previous, int after, Context playerContext, Loot loot) { + HashMap[]> actionMap = loot.getRecordActionMap(); if (actionMap != null) { - for (Map.Entry entry : actionMap.entrySet()) { + for (Map.Entry[]> entry : actionMap.entrySet()) { if (entry.getKey() > previous && entry.getKey() <= after) { - for (Action action : entry.getValue()) { - action.trigger(condition); + for (Action action : entry.getValue()) { + action.trigger(playerContext); } } } @@ -101,18 +102,18 @@ public class Statistics { * Adds a single loot amount to the statistics. * * @param loot The loot item. - * @param condition The condition associated with the loot. + * @param playerContext The condition associated with the loot. */ - private void addSingleLootAmount(Loot loot, Condition condition) { + private void addSingleLootAmount(Loot loot, Context playerContext) { Integer previous = statisticMap.get(loot.getID()); if (previous == null) previous = 0; int after = previous + 1; statisticMap.put(loot.getID(), after); total += 1; - Action[] actions = loot.getSuccessTimesActionMap().get(after); + Action[] actions = loot.getRecordActionMap().get(after); if (actions != null) - for (Action action : actions) { - action.trigger(condition); + for (Action action : actions) { + action.trigger(playerContext); } } diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/statistic/StatisticsKey.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/statistic/StatisticsKey.java deleted file mode 100644 index 6d3c1b16..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/statistic/StatisticsKey.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.momirealms.customfishing.api.mechanic.statistic; - -public class StatisticsKey { - - private final String amountKey; - private final String sizeKey; - - public StatisticsKey(String amountKey, String sizeKey) { - this.amountKey = amountKey; - this.sizeKey = sizeKey; - } - - public String getAmountKey() { - return amountKey; - } - - public String getSizeKey() { - return sizeKey; - } -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/CommandManager.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/statistic/StatisticsKeys.java similarity index 84% rename from api/src/main/java/net/momirealms/customfishing/api/manager/CommandManager.java rename to api/src/main/java/net/momirealms/customfishing/api/mechanic/statistic/StatisticsKeys.java index 975ec5e4..b79647b2 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/CommandManager.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/statistic/StatisticsKeys.java @@ -15,11 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.manager; +package net.momirealms.customfishing.api.mechanic.statistic; -public interface CommandManager { - - void load(); - - void unload(); -} +public record StatisticsKeys(String amountKey, String sizeKey) { +} \ No newline at end of file diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/StatisticsManager.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/statistic/StatisticsManager.java similarity index 85% rename from api/src/main/java/net/momirealms/customfishing/api/manager/StatisticsManager.java rename to api/src/main/java/net/momirealms/customfishing/api/mechanic/statistic/StatisticsManager.java index 64ad6544..faf0f689 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/StatisticsManager.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/statistic/StatisticsManager.java @@ -15,9 +15,8 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.manager; +package net.momirealms.customfishing.api.mechanic.statistic; -import net.momirealms.customfishing.api.mechanic.statistic.Statistics; import org.jetbrains.annotations.Nullable; import java.util.List; @@ -31,7 +30,8 @@ public interface StatisticsManager { * @param uuid The UUID of the player for whom statistics are retrieved. * @return The player's statistics or null if the player is not found. */ - @Nullable Statistics getStatistics(UUID uuid); + @Nullable + Statistics getStatistics(UUID uuid); /** * Get a list of strings associated with a specific key in a category map. @@ -39,5 +39,6 @@ public interface StatisticsManager { * @param key The key to look up in the category map. * @return A list of strings associated with the key or null if the key is not found. */ - @Nullable List getCategory(String key); + @Nullable + List getCategory(String key); } diff --git a/api/src/main/java/net/momirealms/customfishing/api/manager/TotemManager.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/totem/TotemManager.java similarity index 95% rename from api/src/main/java/net/momirealms/customfishing/api/manager/TotemManager.java rename to api/src/main/java/net/momirealms/customfishing/api/mechanic/totem/TotemManager.java index 02c3dd9b..737801d6 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/manager/TotemManager.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/totem/TotemManager.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.manager; +package net.momirealms.customfishing.api.mechanic.totem; import net.momirealms.customfishing.api.mechanic.effect.EffectCarrier; import org.bukkit.Location; diff --git a/api/src/main/java/net/momirealms/customfishing/api/mechanic/totem/block/type/EqualType.java b/api/src/main/java/net/momirealms/customfishing/api/mechanic/totem/block/type/EqualType.java index 8323aac5..6ebe37fd 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/mechanic/totem/block/type/EqualType.java +++ b/api/src/main/java/net/momirealms/customfishing/api/mechanic/totem/block/type/EqualType.java @@ -17,7 +17,7 @@ package net.momirealms.customfishing.api.mechanic.totem.block.type; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import org.bukkit.block.Block; import java.io.Serializable; @@ -41,7 +41,7 @@ public class EqualType implements TypeCondition, Serializable { */ @Override public boolean isMet(Block type) { - return this.type.equals(CustomFishingPlugin.get().getBlockManager().getAnyPluginBlockID(type)); + return this.type.equals(BukkitCustomFishingPlugin.get().getBlockManager().getAnyPluginBlockID(type)); } /** diff --git a/api/src/main/java/net/momirealms/customfishing/api/scheduler/CancellableTask.java b/api/src/main/java/net/momirealms/customfishing/api/scheduler/CancellableTask.java deleted file mode 100644 index 257d4a4c..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/scheduler/CancellableTask.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.scheduler; - -public interface CancellableTask { - - /** - * Cancel the task - */ - void cancel(); - - /** - * Get if the task is cancelled or not - * - * @return cancelled or not - */ - boolean isCancelled(); -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/scheduler/Scheduler.java b/api/src/main/java/net/momirealms/customfishing/api/scheduler/Scheduler.java deleted file mode 100644 index 515a4c51..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/scheduler/Scheduler.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.scheduler; - -import org.bukkit.Location; - -import java.util.concurrent.TimeUnit; - -public interface Scheduler { - - /** - * Runs a task synchronously on the main server thread or region thread. - * - * @param runnable The task to run. - * @param location The location associated with the task. - */ - void runTaskSync(Runnable runnable, Location location); - - /** - * Runs a task synchronously with a specified delay and period. - * - * @param runnable The task to run. - * @param location The location associated with the task. - * @param delayTicks The delay in ticks before the first execution. - * @param periodTicks The period between subsequent executions in ticks. - * @return A CancellableTask for managing the scheduled task. - */ - CancellableTask runTaskSyncTimer(Runnable runnable, Location location, long delayTicks, long periodTicks); - - /** - * Runs a task asynchronously with a specified delay. - * - * @param runnable The task to run. - * @param delay The delay before the task execution. - * @param timeUnit The time unit for the delay. - * @return A CancellableTask for managing the scheduled task. - */ - CancellableTask runTaskAsyncLater(Runnable runnable, long delay, TimeUnit timeUnit); - - /** - * Runs a task asynchronously. - * - * @param runnable The task to run. - */ - void runTaskAsync(Runnable runnable); - - /** - * Runs a task synchronously with a specified delay. - * - * @param runnable The task to run. - * @param location The location associated with the task. - * @param delay The delay before the task execution. - * @param timeUnit The time unit for the delay. - * @return A CancellableTask for managing the scheduled task. - */ - CancellableTask runTaskSyncLater(Runnable runnable, Location location, long delay, TimeUnit timeUnit); - - /** - * Runs a task synchronously with a specified delay in ticks. - * - * @param runnable The task to run. - * @param location The location associated with the task. - * @param delayTicks The delay in ticks before the task execution. - * @return A CancellableTask for managing the scheduled task. - */ - CancellableTask runTaskSyncLater(Runnable runnable, Location location, long delayTicks); - - /** - * Runs a task asynchronously with a specified delay and period. - * - * @param runnable The task to run. - * @param delay The delay before the first execution. - * @param period The period between subsequent executions. - * @param timeUnit The time unit for the delay and period. - * @return A CancellableTask for managing the scheduled task. - */ - CancellableTask runTaskAsyncTimer(Runnable runnable, long delay, long period, TimeUnit timeUnit); -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/util/FontUtils.java b/api/src/main/java/net/momirealms/customfishing/api/util/FontUtils.java deleted file mode 100644 index cd311e70..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/util/FontUtils.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.util; - -/** - * Utility class for working with fonts in text. - */ -public class FontUtils { - - private FontUtils() { - throw new UnsupportedOperationException("This class cannot be instantiated"); - } - - /** - * Surrounds the given text with a specified font tag. - * - * @param text The text to be surrounded with the font tag. - * @param font The font to use in the font tag. - * @return The input text surrounded by the font tag. - */ - public static String surroundWithFont(String text, String font) { - return "" + text + ""; - } -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/util/InventoryUtils.java b/api/src/main/java/net/momirealms/customfishing/api/util/InventoryUtils.java deleted file mode 100644 index bb1645b6..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/util/InventoryUtils.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.util; - -import net.kyori.adventure.text.Component; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.ItemStack; -import org.bukkit.util.io.BukkitObjectInputStream; -import org.bukkit.util.io.BukkitObjectOutputStream; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * Utility class for working with Bukkit Inventories and item stacks. - */ -public class InventoryUtils { - - private InventoryUtils() { - throw new UnsupportedOperationException("This class cannot be instantiated"); - } - - /** - * Create a custom inventory with a specified size and title component. - * - * @param inventoryHolder The holder of the inventory. - * @param size The size of the inventory. - * @param component The title component of the inventory. - * @return The created Inventory instance. - */ - public static Inventory createInventory(InventoryHolder inventoryHolder, int size, Component component) { - try { - boolean isSpigot = CustomFishingPlugin.get().getVersionManager().isSpigot(); - Method createInvMethod = ReflectionUtils.bukkitClass.getMethod( - "createInventory", - InventoryHolder.class, - int.class, - isSpigot ? String.class : ReflectionUtils.componentClass - ); - return (Inventory) createInvMethod.invoke( - null, - inventoryHolder, - size, - isSpigot ? CustomFishingPlugin.get().getAdventure().componentToLegacy(component) : CustomFishingPlugin.get().getAdventure().shadedComponentToOriginalComponent(component) - ); - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException exception) { - exception.printStackTrace(); - return null; - } - } - - /** - * Create a custom inventory with a specified type and title component. - * - * @param inventoryHolder The holder of the inventory. - * @param type The type of the inventory. - * @param component The title component of the inventory. - * @return The created Inventory instance. - */ - public static Inventory createInventory(InventoryHolder inventoryHolder, InventoryType type, Component component) { - try { - boolean isSpigot = CustomFishingPlugin.get().getVersionManager().isSpigot(); - Method createInvMethod = ReflectionUtils.bukkitClass.getMethod( - "createInventory", - InventoryHolder.class, - InventoryType.class, - isSpigot ? String.class : ReflectionUtils.componentClass - ); - return (Inventory) createInvMethod.invoke( - null, - inventoryHolder, - type, - isSpigot ? CustomFishingPlugin.get().getAdventure().componentToLegacy(component) : CustomFishingPlugin.get().getAdventure().shadedComponentToOriginalComponent(component) - ); - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException exception) { - exception.printStackTrace(); - return null; - } - } - - /** - * Serialize an array of ItemStacks to a Base64-encoded string. - * - * @param contents The ItemStack array to serialize. - * @return The Base64-encoded string representing the serialized ItemStacks. - */ - public static @NotNull String stacksToBase64(ItemStack[] contents) { - if (contents.length == 0) { - return ""; - } - try { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); - dataOutput.writeInt(contents.length); - for (ItemStack itemStack : contents) { - dataOutput.writeObject(itemStack); - } - dataOutput.close(); - byte[] byteArr = outputStream.toByteArray(); - outputStream.close(); - return Base64Coder.encodeLines(byteArr); - } catch (IOException e) { - LogUtils.warn("Encoding error", e); - } - return ""; - } - - /** - * Deserialize an ItemStack array from a Base64-encoded string. - * - * @param base64 The Base64-encoded string representing the serialized ItemStacks. - * @return An array of ItemStacks deserialized from the input string. - */ - @Nullable - public static ItemStack[] getInventoryItems(String base64) { - ItemStack[] itemStacks = null; - try { - itemStacks = stacksFromBase64(base64); - } catch (IllegalArgumentException exception) { - exception.printStackTrace(); - } - return itemStacks; - } - - private static ItemStack[] stacksFromBase64(String data) { - if (data == null || data.equals("")) return new ItemStack[]{}; - - ByteArrayInputStream inputStream; - try { - inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); - } catch (IllegalArgumentException e) { - return new ItemStack[]{}; - } - BukkitObjectInputStream dataInput = null; - ItemStack[] stacks = null; - try { - dataInput = new BukkitObjectInputStream(inputStream); - stacks = new ItemStack[dataInput.readInt()]; - } catch (IOException e) { - e.printStackTrace(); - } - if (stacks == null) return new ItemStack[]{}; - for (int i = 0; i < stacks.length; i++) { - try { - stacks[i] = (ItemStack) dataInput.readObject(); - } catch (IOException | ClassNotFoundException | NullPointerException e) { - try { - dataInput.close(); - } catch (IOException exception) { - LogUtils.severe("Failed to read fishing bag data"); - } - return null; - } - } - try { - dataInput.close(); - } catch (IOException ignored) { - } - return stacks; - } -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/util/LogUtils.java b/api/src/main/java/net/momirealms/customfishing/api/util/LogUtils.java deleted file mode 100644 index b99d4112..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/util/LogUtils.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.util; - -import net.momirealms.customfishing.api.CustomFishingPlugin; -import org.jetbrains.annotations.NotNull; - -import java.util.logging.Level; - -/** - * Utility class for logging messages with various log levels. - */ -public final class LogUtils { - - /** - * Log an informational message. - * - * @param message The message to log. - */ - public static void info(@NotNull String message) { - CustomFishingPlugin.getInstance().getLogger().info(message); - } - - /** - * Log a warning message. - * - * @param message The message to log. - */ - public static void warn(@NotNull String message) { - CustomFishingPlugin.getInstance().getLogger().warning(message); - } - - /** - * Log a severe error message. - * - * @param message The message to log. - */ - public static void severe(@NotNull String message) { - CustomFishingPlugin.getInstance().getLogger().severe(message); - } - - /** - * Log a warning message with a throwable exception. - * - * @param message The message to log. - * @param throwable The throwable exception to log. - */ - public static void warn(@NotNull String message, Throwable throwable) { - CustomFishingPlugin.getInstance().getLogger().log(Level.WARNING, message, throwable); - } - - /** - * Log a severe error message with a throwable exception. - * - * @param message The message to log. - * @param throwable The throwable exception to log. - */ - public static void severe(@NotNull String message, Throwable throwable) { - CustomFishingPlugin.getInstance().getLogger().log(Level.SEVERE, message, throwable); - } - - private LogUtils() { - throw new UnsupportedOperationException("This class cannot be instantiated"); - } -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/util/OffsetUtils.java b/api/src/main/java/net/momirealms/customfishing/api/util/OffsetUtils.java deleted file mode 100644 index bfb0956e..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/util/OffsetUtils.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.util; - -import org.bukkit.configuration.ConfigurationSection; - -/** - * Utility class for generating offset characters based on a font configuration. - */ -@SuppressWarnings("DuplicatedCode") -public class OffsetUtils { - - private OffsetUtils() { - throw new UnsupportedOperationException("This class cannot be instantiated"); - } - - private static String font; - private static String negative_1; - private static String negative_2; - private static String negative_4; - private static String negative_8; - private static String negative_16; - private static String negative_32; - private static String negative_64; - private static String negative_128; - private static String positive_1; - private static String positive_2; - private static String positive_4; - private static String positive_8; - private static String positive_16; - private static String positive_32; - private static String positive_64; - private static String positive_128; - - /** - * Load font configuration from a given section. - * - * @param section The configuration section containing font settings. - */ - public static void loadConfig(ConfigurationSection section) { - if (section != null) { - font = section.getString("font", "customfishing:offset_chars"); - positive_1 = section.getString("1"); - positive_2 = section.getString("2"); - positive_4 = section.getString("4"); - positive_8 = section.getString("8"); - positive_16 = section.getString("16"); - positive_32 = section.getString("32"); - positive_64 = section.getString("64"); - positive_128 = section.getString("128"); - negative_1 = section.getString("-1"); - negative_2 = section.getString("-2"); - negative_4 = section.getString("-4"); - negative_8 = section.getString("-8"); - negative_16 = section.getString("-16"); - negative_32 = section.getString("-32"); - negative_64 = section.getString("-64"); - negative_128 = section.getString("-128"); - } - } - - /** - * Get the shortest negative offset characters for a given number. - * - * @param n The number for which to generate offset characters. - * @return Offset characters as a string. - */ - public static String getShortestNegChars(int n) { - StringBuilder stringBuilder = new StringBuilder(); - while (n >= 128) { - stringBuilder.append(negative_128); - n -= 128; - } - if (n - 64 >= 0) { - stringBuilder.append(negative_64); - n -= 64; - } - if (n - 32 >= 0) { - stringBuilder.append(negative_32); - n -= 32; - } - if (n - 16 >= 0) { - stringBuilder.append(negative_16); - n -= 16; - } - if (n - 8 >= 0) { - stringBuilder.append(negative_8); - n -= 8; - } - if (n - 4 >= 0) { - stringBuilder.append(negative_4); - n -= 4; - } - if (n - 2 >= 0) { - stringBuilder.append(negative_2); - n -= 2; - } - if (n - 1 >= 0) { - stringBuilder.append(negative_1); - } - return stringBuilder.toString(); - } - - /** - * Get the shortest positive offset characters for a given number. - * - * @param n The number for which to generate offset characters. - * @return Offset characters as a string. - */ - public static String getShortestPosChars(int n) { - StringBuilder stringBuilder = new StringBuilder(); - while (n >= 128) { - stringBuilder.append(positive_128); - n -= 128; - } - if (n - 64 >= 0) { - stringBuilder.append(positive_64); - n -= 64; - } - if (n - 32 >= 0) { - stringBuilder.append(positive_32); - n -= 32; - } - if (n - 16 >= 0) { - stringBuilder.append(positive_16); - n -= 16; - } - if (n - 8 >= 0) { - stringBuilder.append(positive_8); - n -= 8; - } - if (n - 4 >= 0) { - stringBuilder.append(positive_4); - n -= 4; - } - if (n - 2 >= 0) { - stringBuilder.append(positive_2); - n -= 2; - } - if (n - 1 >= 0) { - stringBuilder.append(positive_1); - } - return stringBuilder.toString(); - } - - /** - * Get offset characters for a given number. This method selects between positive and negative - * offset characters based on the sign of the number. - * - * @param n The number for which to generate offset characters. - * @return Offset characters as a string. - */ - public static String getOffsetChars(int n) { - if (n > 0) { - return "" + getShortestPosChars(n) + ""; - } else { - return "" + getShortestNegChars(-n) + ""; - } - } -} diff --git a/api/src/main/java/net/momirealms/customfishing/api/util/ReflectionUtils.java b/api/src/main/java/net/momirealms/customfishing/api/util/ReflectionUtils.java deleted file mode 100644 index 5283a8de..00000000 --- a/api/src/main/java/net/momirealms/customfishing/api/util/ReflectionUtils.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.api.util; - -import com.comphenix.protocol.utility.MinecraftReflection; -import net.momirealms.customfishing.api.CustomFishingPlugin; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -public class ReflectionUtils { - - public static Object removeBossBarPacket; - public static Constructor progressConstructor; - public static Constructor updateConstructor; - public static Method iChatComponentMethod; - public static Method gsonDeserializeMethod; - public static Object gsonInstance; - public static Class componentClass; - public static Class bukkitClass; - - public static void load() { - if (CustomFishingPlugin.get().getVersionManager().isMojmap()) { - try { - Class bar = Class.forName("net.minecraft.network.protocol.game.ClientboundBossEventPacket"); - Field remove = bar.getDeclaredField("REMOVE_OPERATION"); - remove.setAccessible(true); - removeBossBarPacket = remove.get(null); - Class packetBossClassF = Class.forName("net.minecraft.network.protocol.game.ClientboundBossEventPacket$UpdateProgressOperation"); - progressConstructor = packetBossClassF.getDeclaredConstructor(float.class); - progressConstructor.setAccessible(true); - Class packetBossClassE = Class.forName("net.minecraft.network.protocol.game.ClientboundBossEventPacket$UpdateNameOperation"); - updateConstructor = packetBossClassE.getDeclaredConstructor(MinecraftReflection.getIChatBaseComponentClass()); - updateConstructor.setAccessible(true); - Class craftChatMessageClass = Class.forName("org.bukkit.craftbukkit.util.CraftChatMessage"); - iChatComponentMethod = craftChatMessageClass.getDeclaredMethod("fromJSON", String.class); - iChatComponentMethod.setAccessible(true); - } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException | NoSuchMethodException exception) { - LogUtils.severe("Error occurred when loading reflections", exception); - } - } else { - try { - Class bar = Class.forName("net.minecraft.network.protocol.game.PacketPlayOutBoss"); - Field remove = bar.getDeclaredField("f"); - remove.setAccessible(true); - removeBossBarPacket = remove.get(null); - Class packetBossClassF = Class.forName("net.minecraft.network.protocol.game.PacketPlayOutBoss$f"); - progressConstructor = packetBossClassF.getDeclaredConstructor(float.class); - progressConstructor.setAccessible(true); - Class packetBossClassE = Class.forName("net.minecraft.network.protocol.game.PacketPlayOutBoss$e"); - updateConstructor = packetBossClassE.getDeclaredConstructor(MinecraftReflection.getIChatBaseComponentClass()); - updateConstructor.setAccessible(true); - iChatComponentMethod = MinecraftReflection.getChatSerializerClass().getMethod("a", String.class); - iChatComponentMethod.setAccessible(true); - } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException | NoSuchMethodException exception) { - LogUtils.severe("Error occurred when loading reflections", exception); - } - } - if (CustomFishingPlugin.get().getVersionManager().isSpigot()) return; - try { - componentClass = Class.forName("net;kyori;adventure;text;Component".replace(";", ".")); - bukkitClass = Class.forName("org;bukkit;Bukkit".replace(";", ".")); - Class gsonComponentSerializerClass = Class.forName("net;kyori;adventure;text;serializer;gson;GsonComponentSerializer".replace(";", ".")); - Class gsonComponentSerializerImplClass = Class.forName("net;kyori;adventure;text;serializer;gson;GsonComponentSerializerImpl".replace(";", ".")); - Method gsonMethod = gsonComponentSerializerClass.getMethod("gson"); - gsonInstance = gsonMethod.invoke(null); - gsonDeserializeMethod = gsonComponentSerializerImplClass.getMethod("deserialize", String.class); - gsonDeserializeMethod.setAccessible(true); - } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException exception) { - LogUtils.severe("Error occurred when loading reflections", exception); - } - } -} \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index cc7d9a9e..93c60486 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,80 +1,43 @@ +import java.io.ByteArrayOutputStream + plugins { id("java") - id("application") - id("maven-publish") - id("io.github.goooler.shadow") version "8.1.7" } -allprojects { +val commitID : String = versionBanner() +ext["commitID"] = commitID - version = "2.2.0" +subprojects { - apply() apply(plugin = "java") - apply(plugin = "application") - apply(plugin = "io.github.goooler.shadow") - apply(plugin = "org.gradle.maven-publish") - - application { - mainClass.set("") - } + apply(plugin = "java-library") repositories { mavenCentral() - maven("https://maven.aliyun.com/repository/public/") - maven("https://papermc.io/repo/repository/maven-public/") - maven("https://oss.sonatype.org/content/groups/public/") - maven("https://repo.dmulloy2.net/repository/public/") - maven("https://repo.extendedclip.com/content/repositories/placeholderapi/") - maven("https://repo.codemc.org/repository/maven-public/") - maven("https://maven.enginehub.org/repo/") - maven("https://jitpack.io/") - maven("https://mvn.lumine.io/repository/maven-public/") - maven("https://repo.rapture.pw/repository/maven-releases/") - maven("https://nexus.phoenixdevt.fr/repository/maven-public/") - maven("https://r.irepo.space/maven/") - maven("https://repo.auxilor.io/repository/maven-public/") - maven("https://repo.william278.net/releases/") - maven("https://s01.oss.sonatype.org/content/repositories/snapshots/") - maven("https://repo.minebench.de/") - maven("https://repo.xenondevs.xyz/releases/") - maven("https://repo.oraxen.com/releases") - maven("https://nexus.betonquest.org/repository/betonquest/") - maven("https://s01.oss.sonatype.org/content/repositories/snapshots/") + } + + tasks.processResources { + filteringCharset = "UTF-8" + + filesMatching(arrayListOf("library-version.properties")) { + expand(rootProject.properties) + } + + filesMatching(arrayListOf("plugin.yml", "*.yml", "*/*.yml")) { + expand( + Pair("git_version", commitID), + Pair("project_version", rootProject.properties["project_version"]), + Pair("config_version", rootProject.properties["config_version"]) + ) + } } } -subprojects { - tasks.processResources { - val props = mapOf("version" to version) - inputs.properties(props) - filteringCharset = "UTF-8" - filesMatching("*plugin.yml") { - expand(props) - } - } - - tasks.withType { - options.encoding = "UTF-8" - options.release.set(17) - } - - tasks.shadowJar { - destinationDirectory.set(file("$rootDir/target")) - archiveClassifier.set("") - archiveFileName.set("CustomFishing-" + project.name + "-" + project.version + ".jar") - } - - if ("api" == project.name) { - publishing { - publications { - create("mavenJava") { - groupId = "net.momirealms" - artifactId = "CustomFishing" - version = rootProject.version.toString() - artifact(tasks.shadowJar) - } - } - } +fun versionBanner(): String { + val os = ByteArrayOutputStream() + project.exec { + commandLine = "git rev-parse --short=8 HEAD".split(" ") + standardOutput = os } + return String(os.toByteArray()).trim() } \ No newline at end of file diff --git a/bukkit-loader/build.gradle.kts b/bukkit-loader/build.gradle.kts new file mode 100644 index 00000000..e69de29b diff --git a/bukkit-loader/src/main/java/net/momirealms/Main.java b/bukkit-loader/src/main/java/net/momirealms/Main.java new file mode 100644 index 00000000..6a66b517 --- /dev/null +++ b/bukkit-loader/src/main/java/net/momirealms/Main.java @@ -0,0 +1,7 @@ +package net.momirealms; + +public class Main { + public static void main(String[] args) { + System.out.println("Hello world!"); + } +} \ No newline at end of file diff --git a/common/build.gradle.kts b/common/build.gradle.kts new file mode 100644 index 00000000..efb983d2 --- /dev/null +++ b/common/build.gradle.kts @@ -0,0 +1,37 @@ +repositories { + maven("https://repo.codemc.io/repository/maven-public/") + maven("https://jitpack.io/") +} + +dependencies { + compileOnly("net.kyori:adventure-api:${rootProject.properties["adventure_bundle_version"]}") { + exclude(module = "adventure-bom") + exclude(module = "checker-qual") + exclude(module = "annotations") + } + compileOnly("org.incendo:cloud-core:${rootProject.properties["cloud_core_version"]}") + compileOnly("org.incendo:cloud-minecraft-extras:${rootProject.properties["cloud_minecraft_extras_version"]}") + compileOnly("dev.dejvokep:boosted-yaml:${rootProject.properties["boosted_yaml_version"]}") + compileOnly("org.jetbrains:annotations:${rootProject.properties["jetbrains_annotations_version"]}") + compileOnly("org.slf4j:slf4j-api:${rootProject.properties["slf4j_version"]}") + compileOnly("org.apache.logging.log4j:log4j-core:${rootProject.properties["log4j_version"]}") + compileOnly("net.kyori:adventure-text-minimessage:${rootProject.properties["adventure_bundle_version"]}") + compileOnly("net.kyori:adventure-text-serializer-gson:${rootProject.properties["adventure_bundle_version"]}") + compileOnly("com.google.code.gson:gson:${rootProject.properties["gson_version"]}") + compileOnly("com.github.ben-manes.caffeine:caffeine:${rootProject.properties["caffeine_version"]}") + compileOnly("com.saicone.rtag:rtag:${rootProject.properties["rtag_version"]}") +} + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +tasks.withType { + options.encoding = "UTF-8" + options.release.set(17) + dependsOn(tasks.clean) +} \ No newline at end of file diff --git a/common/src/main/java/net/momirealms/customfishing/common/command/AbstractCommandFeature.java b/common/src/main/java/net/momirealms/customfishing/common/command/AbstractCommandFeature.java new file mode 100644 index 00000000..a0ea4ada --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/command/AbstractCommandFeature.java @@ -0,0 +1,68 @@ +package net.momirealms.customfishing.common.command; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TranslatableComponent; +import net.momirealms.customfishing.common.sender.SenderFactory; +import org.incendo.cloud.Command; +import org.incendo.cloud.CommandManager; +import org.incendo.cloud.context.CommandContext; + +public abstract class AbstractCommandFeature implements CommandFeature { + + protected final CustomFishingCommandManager customFishingCommandManager; + protected CommandConfig commandConfig; + + public AbstractCommandFeature(CustomFishingCommandManager customFishingCommandManager) { + this.customFishingCommandManager = customFishingCommandManager; + } + + protected abstract SenderFactory getSenderFactory(); + + public abstract Command.Builder assembleCommand(CommandManager manager, Command.Builder builder); + + @Override + @SuppressWarnings("unchecked") + public Command registerCommand(CommandManager manager, Command.Builder builder) { + Command command = (Command) assembleCommand(manager, builder).build(); + manager.command(command); + return command; + } + + @Override + public void registerRelatedFunctions() { + // empty + } + + @Override + public void unregisterRelatedFunctions() { + // empty + } + + @Override + @SuppressWarnings("unchecked") + public void handleFeedback(CommandContext context, TranslatableComponent.Builder key, Component... args) { + if (context.flags().hasFlag("silent")) { + return; + } + customFishingCommandManager.handleCommandFeedback((C) context.sender(), key, args); + } + + @Override + public void handleFeedback(C sender, TranslatableComponent.Builder key, Component... args) { + customFishingCommandManager.handleCommandFeedback(sender, key, args); + } + + @Override + public CustomFishingCommandManager getCustomFishingCommandManager() { + return customFishingCommandManager; + } + + @Override + public CommandConfig getCommandConfig() { + return commandConfig; + } + + public void setCommandConfig(CommandConfig commandConfig) { + this.commandConfig = commandConfig; + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/command/AbstractCustomFishingCommandManager.java b/common/src/main/java/net/momirealms/customfishing/common/command/AbstractCustomFishingCommandManager.java new file mode 100644 index 00000000..0e1541ad --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/command/AbstractCustomFishingCommandManager.java @@ -0,0 +1,155 @@ +package net.momirealms.customfishing.common.command; + +import dev.dejvokep.boostedyaml.YamlDocument; +import dev.dejvokep.boostedyaml.block.implementation.Section; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.ComponentLike; +import net.kyori.adventure.text.TranslatableComponent; +import net.momirealms.customfishing.common.locale.CustomFishingCaptionFormatter; +import net.momirealms.customfishing.common.locale.CustomFishingCaptionProvider; +import net.momirealms.customfishing.common.locale.TranslationManager; +import net.momirealms.customfishing.common.plugin.CustomFishingPlugin; +import net.momirealms.customfishing.common.sender.Sender; +import net.momirealms.customfishing.common.util.ArrayUtils; +import org.apache.logging.log4j.util.TriConsumer; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.incendo.cloud.Command; +import org.incendo.cloud.CommandManager; +import org.incendo.cloud.caption.Caption; +import org.incendo.cloud.caption.StandardCaptionKeys; +import org.incendo.cloud.component.CommandComponent; +import org.incendo.cloud.exception.*; +import org.incendo.cloud.exception.handling.ExceptionContext; +import org.incendo.cloud.minecraft.extras.MinecraftExceptionHandler; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; + +public abstract class AbstractCustomFishingCommandManager implements CustomFishingCommandManager { + + protected final HashSet> registeredRootCommandComponents = new HashSet<>(); + protected final HashSet> registeredFeatures = new HashSet<>(); + protected final CommandManager commandManager; + protected final CustomFishingPlugin plugin; + private final CustomFishingCaptionFormatter captionFormatter = new CustomFishingCaptionFormatter(); + private final MinecraftExceptionHandler.Decorator decorator = (formatter, ctx, msg) -> msg; + + private TriConsumer feedbackConsumer; + + public AbstractCustomFishingCommandManager(CustomFishingPlugin plugin, CommandManager commandManager) { + this.commandManager = commandManager; + this.plugin = plugin; + this.inject(); + this.feedbackConsumer = defaultFeedbackConsumer(); + } + + @Override + public void setFeedbackConsumer(@NotNull TriConsumer feedbackConsumer) { + this.feedbackConsumer = feedbackConsumer; + } + + @Override + public TriConsumer defaultFeedbackConsumer() { + return ((sender, node, component) -> { + wrapSender(sender).sendMessage( + component, true + ); + }); + } + + protected abstract Sender wrapSender(C c); + + private void inject() { + getCommandManager().captionRegistry().registerProvider(new CustomFishingCaptionProvider<>()); + injectExceptionHandler(InvalidSyntaxException.class, MinecraftExceptionHandler.createDefaultInvalidSyntaxHandler(), StandardCaptionKeys.EXCEPTION_INVALID_SYNTAX); + injectExceptionHandler(InvalidCommandSenderException.class, MinecraftExceptionHandler.createDefaultInvalidSenderHandler(), StandardCaptionKeys.EXCEPTION_INVALID_SENDER); + injectExceptionHandler(NoPermissionException.class, MinecraftExceptionHandler.createDefaultNoPermissionHandler(), StandardCaptionKeys.EXCEPTION_NO_PERMISSION); + injectExceptionHandler(ArgumentParseException.class, MinecraftExceptionHandler.createDefaultArgumentParsingHandler(), StandardCaptionKeys.EXCEPTION_INVALID_ARGUMENT); + injectExceptionHandler(CommandExecutionException.class, MinecraftExceptionHandler.createDefaultCommandExecutionHandler(), StandardCaptionKeys.EXCEPTION_UNEXPECTED); + } + + private void injectExceptionHandler(Class type, MinecraftExceptionHandler.MessageFactory factory, Caption key) { + getCommandManager().exceptionController().registerHandler(type, ctx -> { + final @Nullable ComponentLike message = factory.message(captionFormatter, (ExceptionContext) ctx); + if (message != null) { + handleCommandFeedback(ctx.context().sender(), key.key(), decorator.decorate(captionFormatter, ctx, message.asComponent()).asComponent()); + } + }); + } + + @Override + public CommandConfig getCommandConfig(YamlDocument document, String featureID) { + Section section = document.getSection(featureID); + if (section == null) return null; + return new CommandConfig.Builder() + .permission(section.getString("permission")) + .usages(section.getStringList("usage")) + .enable(section.getBoolean("enable", false)) + .build(); + } + + @Override + public Collection> buildCommandBuilders(CommandConfig config) { + ArrayList> list = new ArrayList<>(); + for (String usage : config.getUsages()) { + if (!usage.startsWith("/")) continue; + String command = usage.substring(1).trim(); + String[] split = command.split(" "); + Command.Builder builder = new CommandBuilder.BasicCommandBuilder<>(getCommandManager(), split[0]) + .setCommandNode(ArrayUtils.subArray(split, 1)) + .setPermission(config.getPermission()) + .getBuiltCommandBuilder(); + list.add(builder); + } + return list; + } + + @Override + public void registerFeature(CommandFeature feature, CommandConfig config) { + if (!config.isEnable()) throw new RuntimeException("Registering a disabled command feature is not allowed"); + for (Command.Builder builder : buildCommandBuilders(config)) { + Command command = feature.registerCommand(commandManager, builder); + this.registeredRootCommandComponents.add(command.rootComponent()); + } + feature.registerRelatedFunctions(); + this.registeredFeatures.add(feature); + ((AbstractCommandFeature) feature).setCommandConfig(config); + } + + @Override + public void registerDefaultFeatures() { + YamlDocument document = plugin.getConfigManager().loadConfig(commandsFile); + this.getFeatures().values().forEach(feature -> { + CommandConfig config = getCommandConfig(document, feature.getFeatureID()); + if (config.isEnable()) { + registerFeature(feature, config); + } + }); + } + + @Override + public void unregisterFeatures() { + this.registeredRootCommandComponents.forEach(component -> this.commandManager.commandRegistrationHandler().unregisterRootCommand(component)); + this.registeredRootCommandComponents.clear(); + this.registeredFeatures.forEach(CommandFeature::unregisterRelatedFunctions); + this.registeredFeatures.clear(); + } + + @Override + public CommandManager getCommandManager() { + return commandManager; + } + + @Override + public void handleCommandFeedback(C sender, TranslatableComponent.Builder key, Component... args) { + TranslatableComponent component = key.arguments(args).build(); + this.feedbackConsumer.accept(sender, component.key(), TranslationManager.render(component)); + } + + @Override + public void handleCommandFeedback(C sender, String node, Component component) { + this.feedbackConsumer.accept(sender, node, component); + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/command/CommandBuilder.java b/common/src/main/java/net/momirealms/customfishing/common/command/CommandBuilder.java new file mode 100644 index 00000000..5a866b77 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/command/CommandBuilder.java @@ -0,0 +1,41 @@ +package net.momirealms.customfishing.common.command; + +import org.incendo.cloud.Command; +import org.incendo.cloud.CommandManager; + +public interface CommandBuilder { + + CommandBuilder setPermission(String permission); + + CommandBuilder setCommandNode(String... subNodes); + + Command.Builder getBuiltCommandBuilder(); + + class BasicCommandBuilder implements CommandBuilder { + + private Command.Builder commandBuilder; + + public BasicCommandBuilder(CommandManager commandManager, String rootNode) { + this.commandBuilder = commandManager.commandBuilder(rootNode); + } + + @Override + public CommandBuilder setPermission(String permission) { + this.commandBuilder = this.commandBuilder.permission(permission); + return this; + } + + @Override + public CommandBuilder setCommandNode(String... subNodes) { + for (String sub : subNodes) { + this.commandBuilder = this.commandBuilder.literal(sub); + } + return this; + } + + @Override + public Command.Builder getBuiltCommandBuilder() { + return commandBuilder; + } + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/command/CommandConfig.java b/common/src/main/java/net/momirealms/customfishing/common/command/CommandConfig.java new file mode 100644 index 00000000..5c02be53 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/command/CommandConfig.java @@ -0,0 +1,60 @@ +package net.momirealms.customfishing.common.command; + +import java.util.ArrayList; +import java.util.List; + +public class CommandConfig { + + private boolean enable = false; + private List usages = new ArrayList<>(); + private String permission = null; + + private CommandConfig() { + } + + public CommandConfig(boolean enable, List usages, String permission) { + this.enable = enable; + this.usages = usages; + this.permission = permission; + } + + public boolean isEnable() { + return enable; + } + + public List getUsages() { + return usages; + } + + public String getPermission() { + return permission; + } + + public static class Builder { + + private final CommandConfig config; + + public Builder() { + this.config = new CommandConfig<>(); + } + + public Builder usages(List usages) { + config.usages = usages; + return this; + } + + public Builder permission(String permission) { + config.permission = permission; + return this; + } + + public Builder enable(boolean enable) { + config.enable = enable; + return this; + } + + public CommandConfig build() { + return config; + } + } +} \ No newline at end of file diff --git a/common/src/main/java/net/momirealms/customfishing/common/command/CommandFeature.java b/common/src/main/java/net/momirealms/customfishing/common/command/CommandFeature.java new file mode 100644 index 00000000..381cdeeb --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/command/CommandFeature.java @@ -0,0 +1,26 @@ +package net.momirealms.customfishing.common.command; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TranslatableComponent; +import org.incendo.cloud.Command; +import org.incendo.cloud.CommandManager; +import org.incendo.cloud.context.CommandContext; + +public interface CommandFeature { + + Command registerCommand(CommandManager cloudCommandManager, Command.Builder builder); + + String getFeatureID(); + + void registerRelatedFunctions(); + + void unregisterRelatedFunctions(); + + void handleFeedback(CommandContext context, TranslatableComponent.Builder key, Component... args); + + void handleFeedback(C sender, TranslatableComponent.Builder key, Component... args); + + CustomFishingCommandManager getCustomFishingCommandManager(); + + CommandConfig getCommandConfig(); +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/command/CustomFishingCommandManager.java b/common/src/main/java/net/momirealms/customfishing/common/command/CustomFishingCommandManager.java new file mode 100644 index 00000000..46b1af74 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/command/CustomFishingCommandManager.java @@ -0,0 +1,39 @@ +package net.momirealms.customfishing.common.command; + +import dev.dejvokep.boostedyaml.YamlDocument; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TranslatableComponent; +import net.kyori.adventure.util.Index; +import org.apache.logging.log4j.util.TriConsumer; +import org.incendo.cloud.Command; +import org.incendo.cloud.CommandManager; +import org.jetbrains.annotations.NotNull; + +import java.util.Collection; + +public interface CustomFishingCommandManager { + + String commandsFile = "commands.yml"; + + void unregisterFeatures(); + + void registerFeature(CommandFeature feature, CommandConfig config); + + void registerDefaultFeatures(); + + Index> getFeatures(); + + void setFeedbackConsumer(@NotNull TriConsumer feedbackConsumer); + + TriConsumer defaultFeedbackConsumer(); + + CommandConfig getCommandConfig(YamlDocument document, String featureID); + + Collection> buildCommandBuilders(CommandConfig config); + + CommandManager getCommandManager(); + + void handleCommandFeedback(C sender, TranslatableComponent.Builder key, Component... args); + + void handleCommandFeedback(C sender, String node, Component component); +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/config/ConfigManager.java b/common/src/main/java/net/momirealms/customfishing/common/config/ConfigManager.java new file mode 100644 index 00000000..9645cf6f --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/config/ConfigManager.java @@ -0,0 +1,10 @@ +package net.momirealms.customfishing.common.config; + +import dev.dejvokep.boostedyaml.YamlDocument; + +public interface ConfigManager { + + YamlDocument loadConfig(String filePath); + + YamlDocument loadConfig(String filePath, char routeSeparator); +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/config/node/Node.java b/common/src/main/java/net/momirealms/customfishing/common/config/node/Node.java new file mode 100644 index 00000000..3b69acc8 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/config/node/Node.java @@ -0,0 +1,35 @@ +package net.momirealms.customfishing.common.config.node; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; + +public class Node { + + private final T value; + private final HashMap> childTree = new HashMap<>(); + + public Node(T value) { + this.value = value; + } + + public Node() { + this(null); + } + + @Nullable + public T nodeValue() { + return value; + } + + @NotNull + public HashMap> getChildTree() { + return childTree; + } + + @Nullable + public Node getChild(String node) { + return childTree.get(node); + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/dependency/Dependency.java b/common/src/main/java/net/momirealms/customfishing/common/dependency/Dependency.java new file mode 100644 index 00000000..bd50a477 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/dependency/Dependency.java @@ -0,0 +1,333 @@ +/* + * This file is part of LuckPerms, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package net.momirealms.customfishing.common.dependency; + +import net.momirealms.customfishing.common.dependency.relocation.Relocation; +import org.jetbrains.annotations.Nullable; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +/** + * The dependencies used by CustomFishing. + */ +public enum Dependency { + + ASM( + "org.ow2.asm", + "asm", + "maven", + "asm" + ), + ASM_COMMONS( + "org.ow2.asm", + "asm-commons", + "maven", + "asm-commons" + ), + JAR_RELOCATOR( + "me.lucko", + "jar-relocator", + "maven", + "jar-relocator" + ), + H2_DRIVER( + "com.h2database", + "h2", + "maven", + "h2-driver" + ), + SQLITE_DRIVER( + "org.xerial", + "sqlite-jdbc", + "maven", + "sqlite-driver" + ), + CLOUD_CORE( + "org{}incendo", + "cloud-core", + "maven", + "cloud-core", + Relocation.of("cloud", "org{}incendo{}cloud"), + Relocation.of("geantyref", "io{}leangen{}geantyref") + ), + CLOUD_BRIGADIER( + "org{}incendo", + "cloud-brigadier", + "maven", + "cloud-brigadier", + Relocation.of("cloud", "org{}incendo{}cloud"), + Relocation.of("geantyref", "io{}leangen{}geantyref") + ), + CLOUD_SERVICES( + "org{}incendo", + "cloud-services", + "maven", + "cloud-services", + Relocation.of("cloud", "org{}incendo{}cloud"), + Relocation.of("geantyref", "io{}leangen{}geantyref") + ), + CLOUD_BUKKIT( + "org{}incendo", + "cloud-bukkit", + "maven", + "cloud-bukkit", + Relocation.of("cloud", "org{}incendo{}cloud"), + Relocation.of("geantyref", "io{}leangen{}geantyref") + ), + CLOUD_PAPER( + "org{}incendo", + "cloud-paper", + "maven", + "cloud-paper", + Relocation.of("cloud", "org{}incendo{}cloud"), + Relocation.of("geantyref", "io{}leangen{}geantyref") + ), + CLOUD_MINECRAFT_EXTRAS( + "org{}incendo", + "cloud-minecraft-extras", + "maven", + "cloud-minecraft-extras", + Relocation.of("cloud", "org{}incendo{}cloud"), + Relocation.of("adventure", "net{}kyori{}adventure"), + Relocation.of("option", "net{}kyori{}option"), + Relocation.of("examination", "net{}kyori{}examination"), + Relocation.of("geantyref", "io{}leangen{}geantyref") + ), + BOOSTED_YAML( + "dev{}dejvokep", + "boosted-yaml", + "maven", + "boosted-yaml", + Relocation.of("boostedyaml", "dev{}dejvokep{}boostedyaml") + ), + BYTEBUDDY( + "net{}bytebuddy", + "byte-buddy", + "maven", + "byte-buddy", + Relocation.of("bytebuddy", "net{}bytebuddy") + ), + MARIADB_DRIVER( + "org{}mariadb{}jdbc", + "mariadb-java-client", + "maven", + "mariadb-java-client", + Relocation.of("mariadb", "org{}mariadb") + ), + MYSQL_DRIVER( + "com{}mysql", + "mysql-connector-j", + "maven", + "mysql-connector-j", + Relocation.of("mysql", "com{}mysql") + ), + HIKARI_CP( + "com{}zaxxer", + "HikariCP", + "maven", + "hikari-cp", + Relocation.of("hikari", "com{}zaxxer{}hikari") + ), + MONGODB_DRIVER_CORE( + "org{}mongodb", + "mongodb-driver-core", + "maven", + "mongodb-driver-core", + Relocation.of("mongodb", "com{}mongodb"), + Relocation.of("bson", "org{}bson") + ), + MONGODB_DRIVER_SYNC( + "org{}mongodb", + "mongodb-driver-sync", + "maven", + "mongodb-driver-sync", + Relocation.of("mongodb", "com{}mongodb"), + Relocation.of("bson", "org{}bson") + ) { + @Override + public String getVersion() { + return Dependency.MONGODB_DRIVER_CORE.getVersion(); + } + }, + MONGODB_DRIVER_BSON( + "org{}mongodb", + "bson", + "maven", + "mongodb-bson", + Relocation.of("mongodb", "com{}mongodb"), + Relocation.of("bson", "org{}bson") + ) { + @Override + public String getVersion() { + return Dependency.MONGODB_DRIVER_CORE.getVersion(); + } + }, + COMMONS_POOL_2( + "org{}apache{}commons", + "commons-pool2", + "maven", + "commons-pool", + Relocation.of("commonspool2", "org{}apache{}commons{}pool2") + ), + BSTATS_BASE( + "org{}bstats", + "bstats-base", + "maven", + "bstats-base", + Relocation.of("bstats", "org{}bstats") + ), + BSTATS_BUKKIT( + "org{}bstats", + "bstats-bukkit", + "maven", + "bstats-bukkit", + Relocation.of("bstats", "org{}bstats") + ) { + @Override + public String getVersion() { + return Dependency.BSTATS_BASE.getVersion(); + } + }, + GEANTY_REF( + "io{}leangen{}geantyref", + "geantyref", + "maven", + "geantyref", + Relocation.of("geantyref", "io{}leangen{}geantyref") + ), + GSON( + "com.google.code.gson", + "gson", + "maven", + "gson" + ), + CAFFEINE( + "com{}github{}ben-manes{}caffeine", + "caffeine", + "maven", + "caffeine", + Relocation.of("caffeine", "com{}github{}benmanes{}caffeine") + ), + LETTUCE( + "io{}lettuce", + "lettuce-core", + "maven", + "lettuce-core", + Relocation.of("lettuce", "io{}lettuce") + ), + JEDIS( + "redis{}clients", + "jedis", + "maven", + "jedis", + Relocation.of("jedis", "redis{}clients{}jedis"), + Relocation.of("commonspool2", "org{}apache{}commons{}pool2") + ); + + private final List relocations; + private final String repo; + private final String groupId; + private String rawArtifactId; + private String customArtifactID; + + private static final String MAVEN_FORMAT = "%s/%s/%s/%s-%s.jar"; + + Dependency(String groupId, String rawArtifactId, String repo, String customArtifactID) { + this(groupId, rawArtifactId, repo, customArtifactID, new Relocation[0]); + } + + Dependency(String groupId, String rawArtifactId, String repo, String customArtifactID, Relocation... relocations) { + this.rawArtifactId = rawArtifactId; + this.groupId = groupId; + this.relocations = new ArrayList<>(Arrays.stream(relocations).toList()); + this.repo = repo; + this.customArtifactID = customArtifactID; + } + + public Dependency setCustomArtifactID(String customArtifactID) { + this.customArtifactID = customArtifactID; + return this; + } + + public Dependency setRawArtifactID(String artifactId) { + this.rawArtifactId = artifactId; + return this; + } + + public String getVersion() { + return DependencyProperties.getDependencyVersion(customArtifactID); + } + + private static String rewriteEscaping(String s) { + return s.replace("{}", "."); + } + + public String getFileName(String classifier) { + String name = customArtifactID.toLowerCase(Locale.ROOT).replace('_', '-'); + String extra = classifier == null || classifier.isEmpty() + ? "" + : "-" + classifier; + return name + "-" + this.getVersion() + extra + ".jar"; + } + + String getMavenRepoPath() { + return String.format(MAVEN_FORMAT, + rewriteEscaping(groupId).replace(".", "/"), + rewriteEscaping(rawArtifactId), + getVersion(), + rewriteEscaping(rawArtifactId), + getVersion() + ); + } + + public List getRelocations() { + return this.relocations; + } + + /** + * Creates a {@link MessageDigest} suitable for computing the checksums + * of dependencies. + * + * @return the digest + */ + public static MessageDigest createDigest() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + } + + @Nullable + public String getRepo() { + return repo; + } +} diff --git a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/DependencyDownloadException.java b/common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyDownloadException.java similarity index 96% rename from plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/DependencyDownloadException.java rename to common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyDownloadException.java index f48aa426..6bbf30a7 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/DependencyDownloadException.java +++ b/common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyDownloadException.java @@ -23,7 +23,7 @@ * SOFTWARE. */ -package net.momirealms.customfishing.libraries.dependencies; +package net.momirealms.customfishing.common.dependency; /** * Exception thrown if a dependency cannot be downloaded. diff --git a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/DependencyManager.java b/common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyManager.java similarity index 96% rename from plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/DependencyManager.java rename to common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyManager.java index 2f09a5a0..81f1b229 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/DependencyManager.java +++ b/common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyManager.java @@ -23,7 +23,7 @@ * SOFTWARE. */ -package net.momirealms.customfishing.libraries.dependencies; +package net.momirealms.customfishing.common.dependency; import java.util.Collection; import java.util.Set; diff --git a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/DependencyManagerImpl.java b/common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyManagerImpl.java similarity index 68% rename from plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/DependencyManagerImpl.java rename to common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyManagerImpl.java index 878bb175..7364164a 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/DependencyManagerImpl.java +++ b/common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyManagerImpl.java @@ -23,19 +23,15 @@ * SOFTWARE. */ -package net.momirealms.customfishing.libraries.dependencies; +package net.momirealms.customfishing.common.dependency; -import com.google.common.collect.ImmutableSet; -import net.momirealms.customfishing.CustomFishingPluginImpl; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.util.LogUtils; -import net.momirealms.customfishing.libraries.classpath.ClassPathAppender; -import net.momirealms.customfishing.libraries.dependencies.classloader.IsolatedClassLoader; -import net.momirealms.customfishing.libraries.dependencies.relocation.Relocation; -import net.momirealms.customfishing.libraries.dependencies.relocation.RelocationHandler; -import org.checkerframework.checker.nullness.qual.MonotonicNonNull; +import net.momirealms.customfishing.common.dependency.classloader.IsolatedClassLoader; +import net.momirealms.customfishing.common.dependency.relocation.Relocation; +import net.momirealms.customfishing.common.dependency.relocation.RelocationHandler; +import net.momirealms.customfishing.common.plugin.CustomFishingPlugin; +import net.momirealms.customfishing.common.plugin.classpath.ClassPathAppender; +import net.momirealms.customfishing.common.util.FileUtils; -import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; @@ -43,6 +39,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executor; /** * Loads and manages runtime dependencies for the plugin. @@ -58,20 +55,24 @@ public class DependencyManagerImpl implements DependencyManager { /** A map of dependencies which have already been loaded. */ private final EnumMap loaded = new EnumMap<>(Dependency.class); /** A map of isolated classloaders which have been created. */ - private final Map, IsolatedClassLoader> loaders = new HashMap<>(); + private final Map, IsolatedClassLoader> loaders = new HashMap<>(); /** Cached relocation handler instance. */ - private @MonotonicNonNull RelocationHandler relocationHandler = null; + private final RelocationHandler relocationHandler; + private final Executor loadingExecutor; + private final CustomFishingPlugin plugin; - public DependencyManagerImpl(CustomFishingPluginImpl plugin, ClassPathAppender classPathAppender) { + public DependencyManagerImpl(CustomFishingPlugin plugin) { + this.plugin = plugin; this.registry = new DependencyRegistry(); this.cacheDirectory = setupCacheDirectory(plugin); - this.classPathAppender = classPathAppender; + this.classPathAppender = plugin.getClassPathAppender(); + this.loadingExecutor = plugin.getScheduler().async(); this.relocationHandler = new RelocationHandler(this); } @Override public ClassLoader obtainClassLoaderWith(Set dependencies) { - ImmutableSet set = ImmutableSet.copyOf(dependencies); + Set set = new HashSet<>(dependencies); for (Dependency dependency : dependencies) { if (!this.loaded.containsKey(dependency)) { @@ -112,13 +113,15 @@ public class DependencyManagerImpl implements DependencyManager { continue; } - try { - loadDependency(dependency); - } catch (Throwable e) { - new RuntimeException("Unable to load dependency " + dependency.name(), e).printStackTrace(); - } finally { - latch.countDown(); - } + this.loadingExecutor.execute(() -> { + try { + loadDependency(dependency); + } catch (Throwable e) { + this.plugin.getPluginLogger().warn("Unable to load dependency " + dependency.name(), e); + } finally { + latch.countDown(); + } + }); } try { @@ -143,7 +146,8 @@ public class DependencyManagerImpl implements DependencyManager { } private Path downloadDependency(Dependency dependency) throws DependencyDownloadException { - Path file = this.cacheDirectory.resolve(dependency.getFileName(null)); + String fileName = dependency.getFileName(null); + Path file = this.cacheDirectory.resolve(fileName); // if the file already exists, don't attempt to re-download it. if (Files.exists(file)) { @@ -151,18 +155,20 @@ public class DependencyManagerImpl implements DependencyManager { } DependencyDownloadException lastError = null; - - String fileName = dependency.getFileName(null); - - // attempt to download the dependency from each repo in order. - for (DependencyRepository repo : DependencyRepository.values()) { - try { - LogUtils.info("Downloading dependency(" + fileName + ") from " + repo.getUrl() + dependency.getMavenRepoPath()); - repo.download(dependency, file); - LogUtils.info("Successfully downloaded " + fileName); - return file; - } catch (DependencyDownloadException e) { - lastError = e; + String forceRepo = dependency.getRepo(); + List repository = DependencyRepository.getByID(forceRepo); + if (!repository.isEmpty()) { + int i = 0; + while (i < repository.size()) { + try { + plugin.getPluginLogger().info("Downloading dependency(" + fileName + ") from " + repository.get(i).getUrl() + dependency.getMavenRepoPath()); + repository.get(i).download(dependency, file); + plugin.getPluginLogger().info("Successfully downloaded " + fileName); + return file; + } catch (DependencyDownloadException e) { + lastError = e; + i++; + } } } throw Objects.requireNonNull(lastError); @@ -181,16 +187,21 @@ public class DependencyManagerImpl implements DependencyManager { return remappedFile; } - LogUtils.info("Remapping " + dependency.getFileName(null)); + plugin.getPluginLogger().info("Remapping " + dependency.getFileName(null)); relocationHandler.remap(normalFile, remappedFile, rules); - LogUtils.info("Successfully remapped " + dependency.getFileName(null)); + plugin.getPluginLogger().info("Successfully remapped " + dependency.getFileName(null)); return remappedFile; } private static Path setupCacheDirectory(CustomFishingPlugin plugin) { - File folder = new File(plugin.getDataFolder(), "libs"); - folder.mkdirs(); - return folder.toPath(); + Path cacheDirectory = plugin.getDataDirectory().resolve("libs"); + try { + FileUtils.createDirectoriesIfNotExists(cacheDirectory); + } catch (IOException e) { + throw new RuntimeException("Unable to create libs directory", e); + } + + return cacheDirectory; } @Override @@ -210,8 +221,7 @@ public class DependencyManagerImpl implements DependencyManager { } if (firstEx != null) { - firstEx.printStackTrace(); + plugin.getPluginLogger().severe(firstEx.getMessage(), firstEx); } } - } diff --git a/common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyProperties.java b/common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyProperties.java new file mode 100644 index 00000000..11a11ab5 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyProperties.java @@ -0,0 +1,44 @@ +package net.momirealms.customfishing.common.dependency; + +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +public class DependencyProperties { + + private final HashMap versionMap; + + private DependencyProperties(HashMap versionMap) { + this.versionMap = versionMap; + } + + public static String getDependencyVersion(String dependencyID) { + if (!SingletonHolder.INSTANCE.versionMap.containsKey(dependencyID)) { + throw new RuntimeException("Unknown dependency: " + dependencyID); + } + return SingletonHolder.INSTANCE.versionMap.get(dependencyID); + } + + private static class SingletonHolder { + + private static final DependencyProperties INSTANCE = getInstance(); + + private static DependencyProperties getInstance() { + try (InputStream inputStream = DependencyProperties.class.getClassLoader().getResourceAsStream("library-version.properties")) { + HashMap versionMap = new HashMap<>(); + Properties properties = new Properties(); + properties.load(inputStream); + for (Map.Entry entry : properties.entrySet()) { + if (entry.getKey() instanceof String key && entry.getValue() instanceof String value) { + versionMap.put(key, value); + } + } + return new DependencyProperties(versionMap); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } +} diff --git a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/DependencyRegistry.java b/common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyRegistry.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/DependencyRegistry.java rename to common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyRegistry.java index 0218d0c0..cc58a661 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/DependencyRegistry.java +++ b/common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyRegistry.java @@ -23,7 +23,7 @@ * SOFTWARE. */ -package net.momirealms.customfishing.libraries.dependencies; +package net.momirealms.customfishing.common.dependency; import com.google.gson.JsonElement; diff --git a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/DependencyRepository.java b/common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyRepository.java similarity index 83% rename from plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/DependencyRepository.java rename to common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyRepository.java index a8538048..5a3c20b0 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/DependencyRepository.java +++ b/common/src/main/java/net/momirealms/customfishing/common/dependency/DependencyRepository.java @@ -23,9 +23,7 @@ * SOFTWARE. */ -package net.momirealms.customfishing.libraries.dependencies; - -import com.google.common.io.ByteStreams; +package net.momirealms.customfishing.common.dependency; import java.io.IOException; import java.io.InputStream; @@ -33,6 +31,8 @@ import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.TimeUnit; /** @@ -40,7 +40,10 @@ import java.util.concurrent.TimeUnit; */ public enum DependencyRepository { - MAVEN_CENTRAL("https://repo1.maven.org/maven2/") { + /** + * Maven Central + */ + MAVEN_CENTRAL("maven", "https://repo1.maven.org/maven2/") { @Override protected URLConnection openConnection(Dependency dependency) throws IOException { URLConnection connection = super.openConnection(dependency); @@ -49,22 +52,33 @@ public enum DependencyRepository { return connection; } }, - /** - * Maven Central + * Maven Central Mirror */ - MAVEN_CENTRAL_MIRROR("https://maven.aliyun.com/repository/public/"); + MAVEN_CENTRAL_MIRROR("maven", "https://maven.aliyun.com/repository/public/"); private final String url; + private final String id; - DependencyRepository(String url) { + DependencyRepository(String id, String url) { this.url = url; + this.id = id; } public String getUrl() { return url; } + public static List getByID(String id) { + ArrayList repositories = new ArrayList<>(); + for (DependencyRepository repository : values()) { + if (id.equals(repository.id)) { + repositories.add(repository); + } + } + return repositories; + } + /** * Opens a connection to the given {@code dependency}. * @@ -88,7 +102,7 @@ public enum DependencyRepository { try { URLConnection connection = openConnection(dependency); try (InputStream in = connection.getInputStream()) { - byte[] bytes = ByteStreams.toByteArray(in); + byte[] bytes = in.readAllBytes(); if (bytes.length == 0) { throw new DependencyDownloadException("Empty stream"); } @@ -123,4 +137,8 @@ public enum DependencyRepository { throw new DependencyDownloadException(e); } } + + public String getId() { + return id; + } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/classloader/IsolatedClassLoader.java b/common/src/main/java/net/momirealms/customfishing/common/dependency/classloader/IsolatedClassLoader.java similarity index 96% rename from plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/classloader/IsolatedClassLoader.java rename to common/src/main/java/net/momirealms/customfishing/common/dependency/classloader/IsolatedClassLoader.java index 0dbe284c..24be0818 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/classloader/IsolatedClassLoader.java +++ b/common/src/main/java/net/momirealms/customfishing/common/dependency/classloader/IsolatedClassLoader.java @@ -23,7 +23,7 @@ * SOFTWARE. */ -package net.momirealms.customfishing.libraries.dependencies.classloader; +package net.momirealms.customfishing.common.dependency.classloader; import java.net.URL; import java.net.URLClassLoader; diff --git a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/relocation/Relocation.java b/common/src/main/java/net/momirealms/customfishing/common/dependency/relocation/Relocation.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/relocation/Relocation.java rename to common/src/main/java/net/momirealms/customfishing/common/dependency/relocation/Relocation.java index e4513f49..c7a6c8dc 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/relocation/Relocation.java +++ b/common/src/main/java/net/momirealms/customfishing/common/dependency/relocation/Relocation.java @@ -23,7 +23,7 @@ * SOFTWARE. */ -package net.momirealms.customfishing.libraries.dependencies.relocation; +package net.momirealms.customfishing.common.dependency.relocation; import java.util.Objects; diff --git a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/relocation/RelocationHandler.java b/common/src/main/java/net/momirealms/customfishing/common/dependency/relocation/RelocationHandler.java similarity index 89% rename from plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/relocation/RelocationHandler.java rename to common/src/main/java/net/momirealms/customfishing/common/dependency/relocation/RelocationHandler.java index 8479442c..90a257be 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/relocation/RelocationHandler.java +++ b/common/src/main/java/net/momirealms/customfishing/common/dependency/relocation/RelocationHandler.java @@ -23,12 +23,11 @@ * SOFTWARE. */ -package net.momirealms.customfishing.libraries.dependencies.relocation; +package net.momirealms.customfishing.common.dependency.relocation; - -import net.momirealms.customfishing.libraries.dependencies.Dependency; -import net.momirealms.customfishing.libraries.dependencies.DependencyManager; -import net.momirealms.customfishing.libraries.dependencies.classloader.IsolatedClassLoader; +import net.momirealms.customfishing.common.dependency.Dependency; +import net.momirealms.customfishing.common.dependency.DependencyManager; +import net.momirealms.customfishing.common.dependency.classloader.IsolatedClassLoader; import java.io.File; import java.io.IOException; @@ -67,8 +66,8 @@ public class RelocationHandler { this.jarRelocatorRunMethod.setAccessible(true); } catch (Exception e) { try { - if (classLoader instanceof IsolatedClassLoader) { - ((IsolatedClassLoader) classLoader).close(); + if (classLoader instanceof IsolatedClassLoader isolatedClassLoader) { + isolatedClassLoader.close(); } } catch (IOException ex) { e.addSuppressed(ex); diff --git a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/relocation/RelocationHelper.java b/common/src/main/java/net/momirealms/customfishing/common/dependency/relocation/RelocationHelper.java similarity index 95% rename from plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/relocation/RelocationHelper.java rename to common/src/main/java/net/momirealms/customfishing/common/dependency/relocation/RelocationHelper.java index 76958563..84207a41 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/relocation/RelocationHelper.java +++ b/common/src/main/java/net/momirealms/customfishing/common/dependency/relocation/RelocationHelper.java @@ -23,7 +23,7 @@ * SOFTWARE. */ -package net.momirealms.customfishing.libraries.dependencies.relocation; +package net.momirealms.customfishing.common.dependency.relocation; public final class RelocationHelper { @@ -32,6 +32,5 @@ public final class RelocationHelper { public static final String OKHTTP3_STRING = String.valueOf(new char[]{'o', 'k', 'h', 't', 't', 'p', '3'}); private RelocationHelper() { - } } diff --git a/common/src/main/java/net/momirealms/customfishing/common/helper/AdventureHelper.java b/common/src/main/java/net/momirealms/customfishing/common/helper/AdventureHelper.java new file mode 100644 index 00000000..1f8de79a --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/helper/AdventureHelper.java @@ -0,0 +1,149 @@ +package net.momirealms.customfishing.common.helper; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.sound.Sound; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +import net.kyori.adventure.title.Title; + +import java.time.Duration; +import java.util.concurrent.TimeUnit; + +public class AdventureHelper { + + private final MiniMessage miniMessage; + private final MiniMessage miniMessageStrict; + private final GsonComponentSerializer gsonComponentSerializer; + private final Cache miniMessageToJsonCache = Caffeine.newBuilder().expireAfterWrite(5, TimeUnit.MINUTES) + + private AdventureHelper() { + this.miniMessage = MiniMessage.builder().build(); + this.miniMessageStrict = MiniMessage.builder().strict(true).build(); + this.gsonComponentSerializer = GsonComponentSerializer.builder().build(); + } + + private static class SingletonHolder { + private static final AdventureHelper INSTANCE = new AdventureHelper(); + } + + public static AdventureHelper getInstance() { + return SingletonHolder.INSTANCE; + } + + public static MiniMessage getMiniMessage() { + return getInstance().miniMessage; + } + + public static MiniMessage getStrictMiniMessage() { + return getInstance().miniMessageStrict; + } + + public static GsonComponentSerializer getGson() { + return getInstance().gsonComponentSerializer; + } + + public static String miniMessageToJson(String miniMessage) { + AdventureHelper instance = getInstance(); + return instance.miniMessageToJsonCache.get(miniMessage, (text) -> instance.gsonComponentSerializer.serialize(instance.miniMessage.deserialize(text))); + } + + public static void sendTitle(Audience audience, Component title, Component subtitle, int fadeIn, int stay, int fadeOut) { + audience.showTitle(Title.title(title, subtitle, Title.Times.times(Duration.ofMillis(fadeIn * 50L), Duration.ofMillis(stay * 50L), Duration.ofMillis(fadeOut * 50L)))); + } + + public static void sendActionBar(Audience audience, Component actionBar) { + audience.sendActionBar(actionBar); + } + + public static void sendMessage(Audience audience, Component message) { + audience.sendMessage(message); + } + + public static void playSound(Audience audience, Sound sound) { + audience.playSound(sound); + } + + public static String surroundWithMiniMessageFont(String text, Key font) { + return "" + text + ""; + } + + public static String legacyToMiniMessage(String legacy) { + StringBuilder stringBuilder = new StringBuilder(); + char[] chars = legacy.toCharArray(); + for (int i = 0; i < chars.length; i++) { + if (!isColorCode(chars[i])) { + stringBuilder.append(chars[i]); + continue; + } + if (i + 1 >= chars.length) { + stringBuilder.append(chars[i]); + continue; + } + switch (chars[i+1]) { + case '0' -> stringBuilder.append(""); + case '1' -> stringBuilder.append(""); + case '2' -> stringBuilder.append(""); + case '3' -> stringBuilder.append(""); + case '4' -> stringBuilder.append(""); + case '5' -> stringBuilder.append(""); + case '6' -> stringBuilder.append(""); + case '7' -> stringBuilder.append(""); + case '8' -> stringBuilder.append(""); + case '9' -> stringBuilder.append(""); + case 'a' -> stringBuilder.append(""); + case 'b' -> stringBuilder.append(""); + case 'c' -> stringBuilder.append(""); + case 'd' -> stringBuilder.append(""); + case 'e' -> stringBuilder.append(""); + case 'f' -> stringBuilder.append(""); + case 'r' -> stringBuilder.append(""); + case 'l' -> stringBuilder.append(""); + case 'm' -> stringBuilder.append(""); + case 'o' -> stringBuilder.append(""); + case 'n' -> stringBuilder.append(""); + case 'k' -> stringBuilder.append(""); + case 'x' -> { + if (i + 13 >= chars.length + || !isColorCode(chars[i+2]) + || !isColorCode(chars[i+4]) + || !isColorCode(chars[i+6]) + || !isColorCode(chars[i+8]) + || !isColorCode(chars[i+10]) + || !isColorCode(chars[i+12])) { + stringBuilder.append(chars[i]); + continue; + } + stringBuilder + .append("<#") + .append(chars[i+3]) + .append(chars[i+5]) + .append(chars[i+7]) + .append(chars[i+9]) + .append(chars[i+11]) + .append(chars[i+13]) + .append(">"); + i += 12; + } + default -> { + stringBuilder.append(chars[i]); + continue; + } + } + i++; + } + return stringBuilder.toString(); + } + + public static String componentToJson(Component component) { + return getGson().serialize(component); + } + + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + public static boolean isColorCode(char c) { + return c == '§' || c == '&'; + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/helper/GsonHelper.java b/common/src/main/java/net/momirealms/customfishing/common/helper/GsonHelper.java new file mode 100644 index 00000000..7548c0cb --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/helper/GsonHelper.java @@ -0,0 +1,26 @@ +package net.momirealms.customfishing.common.helper; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class GsonHelper { + + private final Gson gson; + + public GsonHelper() { + this.gson = new GsonBuilder() + .create(); + } + + public Gson getGson() { + return gson; + } + + public static Gson get() { + return SingletonHolder.INSTANCE.getGson(); + } + + private static class SingletonHolder { + private static final GsonHelper INSTANCE = new GsonHelper(); + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/item/AbstractItem.java b/common/src/main/java/net/momirealms/customfishing/common/item/AbstractItem.java new file mode 100644 index 00000000..f8b3ede0 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/item/AbstractItem.java @@ -0,0 +1,89 @@ +package net.momirealms.customfishing.common.item; + +import net.momirealms.customfishing.common.plugin.CustomFishingPlugin; + +import java.util.List; +import java.util.Optional; + +public class AbstractItem implements Item { + + private final CustomFishingPlugin plugin; + private final ItemFactory factory; + private final R item; + + AbstractItem(CustomFishingPlugin plugin, ItemFactory factory, R item) { + this.plugin = plugin; + this.factory = factory; + this.item = item; + } + + @Override + public Item customModelData(Integer data) { + factory.customModelData(item, data); + return this; + } + + @Override + public Optional customModelData() { + return factory.customModelData(item); + } + + @Override + public Optional displayName() { + return factory.displayName(item); + } + + @Override + public Item lore(List lore) { + factory.lore(item, lore); + return this; + } + + @Override + public Optional> lore() { + return factory.lore(item); + } + + @Override + public Item displayName(String displayName) { + factory.displayName(item, displayName); + return this; + } + + @Override + public Item skull(String data) { + factory.skull(item, data); + return this; + } + + @Override + public Optional getTag(Object... path) { + return factory.getTag(item, path); + } + + @Override + public Item setTag(Object value, Object... path) { + factory.setTag(item, value, path); + return this; + } + + @Override + public I getItem() { + return factory.getItem(item); + } + + @Override + public I load() { + return factory.load(item); + } + + @Override + public I loadCopy() { + return factory.loadCopy(item); + } + + @Override + public void update() { + factory.update(item); + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/item/ComponentKeys.java b/common/src/main/java/net/momirealms/customfishing/common/item/ComponentKeys.java new file mode 100644 index 00000000..7ff2814d --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/item/ComponentKeys.java @@ -0,0 +1,16 @@ +package net.momirealms.customfishing.common.item; + +import net.kyori.adventure.key.Key; + +public class ComponentKeys { + + public static final String CUSTOM_MODEL_DATA = Key.key("minecraft", "custom_model_data").asString(); + public static final String CUSTOM_NAME = Key.key("minecraft", "custom_name").asString(); + public static final String LORE = Key.key("minecraft", "lore").asString(); + public static final String DAMAGE = Key.key("minecraft", "damage").asString(); + public static final String ENCHANTMENT_GLINT_OVERRIDE = Key.key("minecraft", "enchantment_glint_override").asString(); + public static final String HIDE_TOOLTIP = Key.key("minecraft", "hide_tooltip").asString(); + public static final String MAX_STACK_SIZE = Key.key("minecraft", "max_stack_size").asString(); + public static final String PROFILE = Key.key("minecraft", "profile").asString(); + public static final String UNBREAKABLE = Key.key("minecraft", "unbreakable").asString(); +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/item/Item.java b/common/src/main/java/net/momirealms/customfishing/common/item/Item.java new file mode 100644 index 00000000..7cac0779 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/item/Item.java @@ -0,0 +1,34 @@ +package net.momirealms.customfishing.common.item; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +public interface Item { + + Item customModelData(Integer data); + + Optional customModelData(); + + Item displayName(String displayName); + + Optional displayName(); + + Item lore(List lore); + + Optional> lore(); + + Item skull(String data); + + Optional getTag(Object... path); + + Item setTag(Object value, Object... path); + + I getItem(); + + I load(); + + I loadCopy(); + + void update(); +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/item/ItemFactory.java b/common/src/main/java/net/momirealms/customfishing/common/item/ItemFactory.java new file mode 100644 index 00000000..8f8e48e7 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/item/ItemFactory.java @@ -0,0 +1,55 @@ +package net.momirealms.customfishing.common.item; + +import net.momirealms.customfishing.common.plugin.CustomFishingPlugin; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +public abstract class ItemFactory

{ + + protected final P plugin; + + protected ItemFactory(P plugin) { + this.plugin = plugin; + } + + public Item wrap(R item) { + Objects.requireNonNull(item, "item"); + return new AbstractItem<>(this.plugin, this, item); + } + + protected abstract Optional getTag(R item, Object... path); + + protected abstract void setTag(R item, Object value, Object... path); + + protected abstract void update(R item); + + protected abstract I load(R item); + + protected abstract I getItem(R item); + + protected abstract I loadCopy(R item); + + protected abstract void customModelData(R item, Integer data); + + protected abstract Optional customModelData(R item); + + protected abstract void displayName(R item, String json); + + protected abstract Optional displayName(R item); + + protected abstract void skull(R item, String skullData); + + protected abstract Optional> lore(R item); + + protected abstract void lore(R item, List lore); + + protected abstract boolean unbreakable(R item); + + protected abstract void unbreakable(R item, boolean unbreakable); + + protected abstract Optional glint(R item); + + protected abstract void glint(R item, Boolean glint); +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/locale/CustomFishingCaptionFormatter.java b/common/src/main/java/net/momirealms/customfishing/common/locale/CustomFishingCaptionFormatter.java new file mode 100644 index 00000000..d9998c8b --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/locale/CustomFishingCaptionFormatter.java @@ -0,0 +1,18 @@ +package net.momirealms.customfishing.common.locale; + +import net.kyori.adventure.text.Component; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.incendo.cloud.caption.Caption; +import org.incendo.cloud.caption.CaptionVariable; +import org.incendo.cloud.minecraft.extras.caption.ComponentCaptionFormatter; + +import java.util.List; + +public class CustomFishingCaptionFormatter implements ComponentCaptionFormatter { + + @Override + public @NonNull Component formatCaption(@NonNull Caption captionKey, @NonNull C recipient, @NonNull String caption, @NonNull List<@NonNull CaptionVariable> variables) { + Component component = ComponentCaptionFormatter.translatable().formatCaption(captionKey, recipient, caption, variables); + return TranslationManager.render(component); + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/locale/CustomFishingCaptionKeys.java b/common/src/main/java/net/momirealms/customfishing/common/locale/CustomFishingCaptionKeys.java new file mode 100644 index 00000000..75e94f05 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/locale/CustomFishingCaptionKeys.java @@ -0,0 +1,10 @@ +package net.momirealms.customfishing.common.locale; + +import org.incendo.cloud.caption.Caption; + +public final class CustomFishingCaptionKeys { + + public static final Caption ARGUMENT_PARSE_FAILURE_TIME = Caption.of("argument.parse.failure.time"); + public static final Caption ARGUMENT_PARSE_FAILURE_URL = Caption.of("argument.parse.failure.url"); + public static final Caption ARGUMENT_PARSE_FAILURE_NAMEDTEXTCOLOR = Caption.of("argument.parse.failure.namedtextcolor"); +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/locale/CustomFishingCaptionProvider.java b/common/src/main/java/net/momirealms/customfishing/common/locale/CustomFishingCaptionProvider.java new file mode 100644 index 00000000..3a45a735 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/locale/CustomFishingCaptionProvider.java @@ -0,0 +1,20 @@ +package net.momirealms.customfishing.common.locale; + +import org.checkerframework.checker.nullness.qual.NonNull; +import org.incendo.cloud.caption.CaptionProvider; +import org.incendo.cloud.caption.DelegatingCaptionProvider; + +public final class CustomFishingCaptionProvider extends DelegatingCaptionProvider { + + private static final CaptionProvider PROVIDER = CaptionProvider.constantProvider() + .putCaption(CustomFishingCaptionKeys.ARGUMENT_PARSE_FAILURE_URL, "") + .putCaption(CustomFishingCaptionKeys.ARGUMENT_PARSE_FAILURE_TIME, "") + .putCaption(CustomFishingCaptionKeys.ARGUMENT_PARSE_FAILURE_NAMEDTEXTCOLOR, "") + .build(); + + @SuppressWarnings("unchecked") + @Override + public @NonNull CaptionProvider delegate() { + return (CaptionProvider) PROVIDER; + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/locale/MessageConstants.java b/common/src/main/java/net/momirealms/customfishing/common/locale/MessageConstants.java new file mode 100644 index 00000000..b4035949 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/locale/MessageConstants.java @@ -0,0 +1,10 @@ +package net.momirealms.customfishing.common.locale; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TranslatableComponent; + +public interface MessageConstants { + + TranslatableComponent.Builder ARGUMENT_ENTITY_NOTFOUND_PLAYER = Component.translatable().key("argument.entity.notfound.player"); + +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/locale/MiniMessageTranslationRegistry.java b/common/src/main/java/net/momirealms/customfishing/common/locale/MiniMessageTranslationRegistry.java new file mode 100644 index 00000000..fe1dfa58 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/locale/MiniMessageTranslationRegistry.java @@ -0,0 +1,54 @@ +package net.momirealms.customfishing.common.locale; + +import net.kyori.adventure.key.Key; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.translation.Translator; +import org.jetbrains.annotations.NotNull; + +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; + +import static java.util.Objects.requireNonNull; + +public interface MiniMessageTranslationRegistry extends Translator { + + static @NotNull MiniMessageTranslationRegistry create(final Key name, final MiniMessage miniMessage) { + return new MiniMessageTranslationRegistryImpl(requireNonNull(name, "name"), requireNonNull(miniMessage, "MiniMessage")); + } + + void register(@NotNull String key, @NotNull Locale locale, @NotNull String format); + + void unregister(@NotNull String key); + + boolean contains(@NotNull String key); + + void defaultLocale(@NotNull Locale defaultLocale); + + default void registerAll(final @NotNull Locale locale, final @NotNull Map bundle) { + this.registerAll(locale, bundle.keySet(), bundle::get); + } + + default void registerAll(final @NotNull Locale locale, final @NotNull Set keys, final Function function) { + IllegalArgumentException firstError = null; + int errorCount = 0; + for (final String key : keys) { + try { + this.register(key, locale, function.apply(key)); + } catch (final IllegalArgumentException e) { + if (firstError == null) { + firstError = e; + } + errorCount++; + } + } + if (firstError != null) { + if (errorCount == 1) { + throw firstError; + } else if (errorCount > 1) { + throw new IllegalArgumentException(String.format("Invalid key (and %d more)", errorCount - 1), firstError); + } + } + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/locale/MiniMessageTranslationRegistryImpl.java b/common/src/main/java/net/momirealms/customfishing/common/locale/MiniMessageTranslationRegistryImpl.java new file mode 100644 index 00000000..bed2824d --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/locale/MiniMessageTranslationRegistryImpl.java @@ -0,0 +1,209 @@ +package net.momirealms.customfishing.common.locale; + +import net.kyori.adventure.internal.Internals; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.ComponentLike; +import net.kyori.adventure.text.TranslatableComponent; +import net.kyori.adventure.text.minimessage.Context; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.minimessage.ParsingException; +import net.kyori.adventure.text.minimessage.tag.Tag; +import net.kyori.adventure.text.minimessage.tag.resolver.ArgumentQueue; +import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; +import net.kyori.adventure.util.TriState; +import net.kyori.examination.Examinable; +import net.kyori.examination.ExaminableProperty; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.text.MessageFormat; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Stream; + +import static java.util.Objects.requireNonNull; + +public class MiniMessageTranslationRegistryImpl implements Examinable, MiniMessageTranslationRegistry { + private final Key name; + private final Map translations = new ConcurrentHashMap<>(); + private Locale defaultLocale = Locale.US; + private final MiniMessage miniMessage; + + MiniMessageTranslationRegistryImpl(final Key name, final MiniMessage miniMessage) { + this.name = name; + this.miniMessage = miniMessage; + } + + @Override + public void register(final @NotNull String key, final @NotNull Locale locale, final @NotNull String format) { + this.translations.computeIfAbsent(key, Translation::new).register(locale, format); + } + + @Override + public void unregister(final @NotNull String key) { + this.translations.remove(key); + } + + @Override + public boolean contains(final @NotNull String key) { + return this.translations.containsKey(key); + } + + @Override + public @NotNull Key name() { + return name; + } + + @Override + public @Nullable MessageFormat translate(@NotNull String key, @NotNull Locale locale) { + // No need to implement this method + return null; + } + + @Override + public @Nullable Component translate(@NotNull TranslatableComponent component, @NotNull Locale locale) { + Translation translation = translations.get(component.key()); + if (translation == null) { + return null; + } + String miniMessageString = translation.translate(locale); + if (miniMessageString == null) { + return null; + } + if (miniMessageString.equals("")) { + return Component.empty(); + } + final Component resultingComponent; + if (component.arguments().isEmpty()) { + resultingComponent = this.miniMessage.deserialize(miniMessageString); + } else { + resultingComponent = this.miniMessage.deserialize(miniMessageString, new ArgumentTag(component.arguments())); + } + if (component.children().isEmpty()) { + return resultingComponent; + } else { + return resultingComponent.children(component.children()); + } + } + + @Override + public @NotNull TriState hasAnyTranslations() { + if (!this.translations.isEmpty()) { + return TriState.TRUE; + } + return TriState.FALSE; + } + + @Override + public void defaultLocale(final @NotNull Locale defaultLocale) { + this.defaultLocale = requireNonNull(defaultLocale, "defaultLocale"); + } + + @Override + public @NotNull Stream examinableProperties() { + return Stream.of(ExaminableProperty.of("translations", this.translations)); + } + + @Override + public boolean equals(final Object other) { + if (this == other) return true; + if (!(other instanceof MiniMessageTranslationRegistryImpl that)) return false; + return this.name.equals(that.name) + && this.translations.equals(that.translations) + && this.defaultLocale.equals(that.defaultLocale); + } + + @Override + public int hashCode() { + return Objects.hash(this.name, this.translations, this.defaultLocale); + } + + @Override + public String toString() { + return Internals.toString(this); + } + + public static class ArgumentTag implements TagResolver { + private static final String NAME = "argument"; + private static final String NAME_1 = "arg"; + + private final List argumentComponents; + + public ArgumentTag(final @NotNull List argumentComponents) { + this.argumentComponents = Objects.requireNonNull(argumentComponents, "argumentComponents"); + } + + @Override + public @Nullable Tag resolve(final @NotNull String name, final @NotNull ArgumentQueue arguments, final @NotNull Context ctx) throws ParsingException { + final int index = arguments.popOr("No argument number provided").asInt().orElseThrow(() -> ctx.newException("Invalid argument number", arguments)); + + if (index < 0 || index >= argumentComponents.size()) { + throw ctx.newException("Invalid argument number", arguments); + } + + return Tag.inserting(argumentComponents.get(index)); + } + + @Override + public boolean has(final @NotNull String name) { + return name.equals(NAME) || name.equals(NAME_1); + } + } + + final class Translation implements Examinable { + private final String key; + private final Map formats; + + Translation(final @NotNull String key) { + this.key = requireNonNull(key, "translation key"); + this.formats = new ConcurrentHashMap<>(); + } + + void register(final @NotNull Locale locale, final @NotNull String format) { + if (this.formats.putIfAbsent(requireNonNull(locale, "locale"), requireNonNull(format, "message format")) != null) { + throw new IllegalArgumentException(String.format("Translation already exists: %s for %s", this.key, locale)); + } + } + + @Nullable String translate(final @NotNull Locale locale) { + String format = this.formats.get(requireNonNull(locale, "locale")); + if (format == null) { + format = this.formats.get(new Locale(locale.getLanguage())); // try without country + if (format == null) { + format = this.formats.get(MiniMessageTranslationRegistryImpl.this.defaultLocale); // try local default locale + } + } + return format; + } + + @Override + public @NotNull Stream examinableProperties() { + return Stream.of( + ExaminableProperty.of("key", this.key), + ExaminableProperty.of("formats", this.formats) + ); + } + + @Override + public boolean equals(final Object other) { + if (this == other) return true; + if (!(other instanceof Translation that)) return false; + return this.key.equals(that.key) && + this.formats.equals(that.formats); + } + + @Override + public int hashCode() { + return Objects.hash(this.key, this.formats); + } + + @Override + public String toString() { + return Internals.toString(this); + } + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/locale/MiniMessageTranslator.java b/common/src/main/java/net/momirealms/customfishing/common/locale/MiniMessageTranslator.java new file mode 100644 index 00000000..9a5af778 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/locale/MiniMessageTranslator.java @@ -0,0 +1,30 @@ +package net.momirealms.customfishing.common.locale; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.renderer.TranslatableComponentRenderer; +import net.kyori.adventure.translation.Translator; +import net.kyori.examination.Examinable; +import org.jetbrains.annotations.NotNull; + +import java.util.Locale; + +public interface MiniMessageTranslator extends Translator, Examinable { + + static @NotNull MiniMessageTranslator translator() { + return MiniMessageTranslatorImpl.INSTANCE; + } + + static @NotNull TranslatableComponentRenderer renderer() { + return MiniMessageTranslatorImpl.INSTANCE.renderer; + } + + static @NotNull Component render(final @NotNull Component component, final @NotNull Locale locale) { + return renderer().render(component, locale); + } + + @NotNull Iterable sources(); + + boolean addSource(final @NotNull Translator source); + + boolean removeSource(final @NotNull Translator source); +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/locale/MiniMessageTranslatorImpl.java b/common/src/main/java/net/momirealms/customfishing/common/locale/MiniMessageTranslatorImpl.java new file mode 100644 index 00000000..076720b9 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/locale/MiniMessageTranslatorImpl.java @@ -0,0 +1,75 @@ +package net.momirealms.customfishing.common.locale; + +import net.kyori.adventure.key.Key; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TranslatableComponent; +import net.kyori.adventure.text.renderer.TranslatableComponentRenderer; +import net.kyori.adventure.translation.Translator; +import net.kyori.adventure.util.TriState; +import net.kyori.examination.ExaminableProperty; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.text.MessageFormat; +import java.util.Collections; +import java.util.Locale; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Stream; + +public class MiniMessageTranslatorImpl implements MiniMessageTranslator { + + private static final Key NAME = Key.key("customfishing", "main"); + static final MiniMessageTranslatorImpl INSTANCE = new MiniMessageTranslatorImpl(); + final TranslatableComponentRenderer renderer = TranslatableComponentRenderer.usingTranslationSource(this); + private final Set sources = Collections.newSetFromMap(new ConcurrentHashMap<>()); + + @Override + public @NotNull Key name() { + return NAME; + } + + @Override + public @NotNull TriState hasAnyTranslations() { + if (!this.sources.isEmpty()) { + return TriState.TRUE; + } + return TriState.FALSE; + } + + @Override + public @Nullable MessageFormat translate(@NotNull String key, @NotNull Locale locale) { + // No need to implement this method + return null; + } + + @Override + public @Nullable Component translate(@NotNull TranslatableComponent component, @NotNull Locale locale) { + for (final Translator source : this.sources) { + final Component translation = source.translate(component, locale); + if (translation != null) return translation; + } + return null; + } + + @Override + public @NotNull Iterable sources() { + return Collections.unmodifiableSet(this.sources); + } + + @Override + public boolean addSource(final @NotNull Translator source) { + if (source == this) throw new IllegalArgumentException("MiniMessageTranslationSource"); + return this.sources.add(source); + } + + @Override + public boolean removeSource(final @NotNull Translator source) { + return this.sources.remove(source); + } + + @Override + public @NotNull Stream examinableProperties() { + return Stream.of(ExaminableProperty.of("sources", this.sources)); + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/locale/TranslationManager.java b/common/src/main/java/net/momirealms/customfishing/common/locale/TranslationManager.java new file mode 100644 index 00000000..dd084ade --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/locale/TranslationManager.java @@ -0,0 +1,146 @@ +package net.momirealms.customfishing.common.locale; + +import dev.dejvokep.boostedyaml.YamlDocument; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.translation.Translator; +import net.momirealms.customfishing.common.helper.AdventureHelper; +import net.momirealms.customfishing.common.plugin.CustomFishingPlugin; +import net.momirealms.customfishing.common.util.Pair; +import org.jetbrains.annotations.Nullable; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class TranslationManager { + + public static final Locale DEFAULT_LOCALE = Locale.ENGLISH; + private static final List locales = List.of("en"); + + private final CustomFishingPlugin plugin; + private final Set installed = ConcurrentHashMap.newKeySet(); + private MiniMessageTranslationRegistry registry; + private final Path translationsDirectory; + + public TranslationManager(CustomFishingPlugin plugin) { + this.plugin = plugin; + this.translationsDirectory = this.plugin.getConfigDirectory().resolve("translations"); + } + + public void reload() { + // remove any previous registry + if (this.registry != null) { + MiniMessageTranslator.translator().removeSource(this.registry); + this.installed.clear(); + } + + for (String lang : locales) { + this.plugin.getConfigManager().loadConfig("translations/" + lang + ".yml"); + } + + this.registry = MiniMessageTranslationRegistry.create(Key.key("customfishing", "main"), AdventureHelper.getMiniMessage()); + this.registry.defaultLocale(DEFAULT_LOCALE); + this.loadFromFileSystem(this.translationsDirectory, false); + MiniMessageTranslator.translator().addSource(this.registry); + } + + public static Component render(Component component) { + return render(component, null); + } + + public static Component render(Component component, @Nullable Locale locale) { + if (locale == null) { + locale = Locale.getDefault(); + if (locale == null) { + locale = DEFAULT_LOCALE; + } + } + return MiniMessageTranslator.render(component, locale); + } + + public void loadFromFileSystem(Path directory, boolean suppressDuplicatesError) { + List translationFiles; + try (Stream stream = Files.list(directory)) { + translationFiles = stream.filter(TranslationManager::isTranslationFile).collect(Collectors.toList()); + } catch (IOException e) { + translationFiles = Collections.emptyList(); + } + + if (translationFiles.isEmpty()) { + return; + } + + Map> loaded = new HashMap<>(); + for (Path translationFile : translationFiles) { + try { + Pair> result = loadTranslationFile(translationFile); + loaded.put(result.left(), result.right()); + } catch (Exception e) { + if (!suppressDuplicatesError || !isAdventureDuplicatesException(e)) { + this.plugin.getPluginLogger().warn("Error loading locale file: " + translationFile.getFileName(), e); + } + } + } + + // try registering the locale without a country code - if we don't already have a registration for that + loaded.forEach((locale, bundle) -> { + Locale localeWithoutCountry = new Locale(locale.getLanguage()); + if (!locale.equals(localeWithoutCountry) && !localeWithoutCountry.equals(DEFAULT_LOCALE) && this.installed.add(localeWithoutCountry)) { + try { + this.registry.registerAll(localeWithoutCountry, bundle); + } catch (IllegalArgumentException e) { + // ignore + } + } + }); + } + + public static boolean isTranslationFile(Path path) { + return path.getFileName().toString().endsWith(".yml"); + } + + private static boolean isAdventureDuplicatesException(Exception e) { + return e instanceof IllegalArgumentException && (e.getMessage().startsWith("Invalid key") || e.getMessage().startsWith("Translation already exists")); + } + + private Pair> loadTranslationFile(Path translationFile) { + String fileName = translationFile.getFileName().toString(); + String localeString = fileName.substring(0, fileName.length() - ".yml".length()); + Locale locale = parseLocale(localeString); + + if (locale == null) { + throw new IllegalStateException("Unknown locale '" + localeString + "' - unable to register."); + } + + Map bundle = new HashMap<>(); + YamlDocument document = plugin.getConfigManager().loadConfig("translations" + "\\" + translationFile.getFileName(), '@'); + Map map = document.getStringRouteMappedValues(false); + map.remove("config-version"); + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() instanceof List list) { + List strList = (List) list; + StringJoiner stringJoiner = new StringJoiner(""); + for (String str : strList) { + stringJoiner.add(str); + } + bundle.put(entry.getKey(), stringJoiner.toString()); + } else if (entry.getValue() instanceof String str) { + bundle.put(entry.getKey(), str); + } + } + + this.registry.registerAll(locale, bundle); + this.installed.add(locale); + + return Pair.of(locale, bundle); + } + + public static @Nullable Locale parseLocale(@Nullable String locale) { + return locale == null ? null : Translator.parseLocale(locale); + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/plugin/CustomFishingPlugin.java b/common/src/main/java/net/momirealms/customfishing/common/plugin/CustomFishingPlugin.java new file mode 100644 index 00000000..f781c139 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/plugin/CustomFishingPlugin.java @@ -0,0 +1,38 @@ +package net.momirealms.customfishing.common.plugin; + +import net.momirealms.customfishing.common.config.ConfigManager; +import net.momirealms.customfishing.common.dependency.DependencyManager; +import net.momirealms.customfishing.common.locale.TranslationManager; +import net.momirealms.customfishing.common.plugin.classpath.ClassPathAppender; +import net.momirealms.customfishing.common.plugin.logging.PluginLogger; +import net.momirealms.customfishing.common.plugin.scheduler.SchedulerAdapter; + +import java.io.InputStream; +import java.nio.file.Path; + +public interface CustomFishingPlugin { + + InputStream getResourceStream(String filePath); + + PluginLogger getPluginLogger(); + + ClassPathAppender getClassPathAppender(); + + SchedulerAdapter getScheduler(); + + Path getDataDirectory(); + + default Path getConfigDirectory() { + return getDataDirectory(); + } + + DependencyManager getDependencyManager(); + + TranslationManager getTranslationManager(); + + ConfigManager getConfigManager(); + + String getServerVersion(); + + String getPluginVersion(); +} diff --git a/plugin/src/main/java/net/momirealms/customfishing/libraries/classpath/ClassPathAppender.java b/common/src/main/java/net/momirealms/customfishing/common/plugin/classpath/ClassPathAppender.java similarity index 96% rename from plugin/src/main/java/net/momirealms/customfishing/libraries/classpath/ClassPathAppender.java rename to common/src/main/java/net/momirealms/customfishing/common/plugin/classpath/ClassPathAppender.java index 601853a7..71c41416 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/libraries/classpath/ClassPathAppender.java +++ b/common/src/main/java/net/momirealms/customfishing/common/plugin/classpath/ClassPathAppender.java @@ -23,7 +23,7 @@ * SOFTWARE. */ -package net.momirealms.customfishing.libraries.classpath; +package net.momirealms.customfishing.common.plugin.classpath; import java.nio.file.Path; diff --git a/plugin/src/main/java/net/momirealms/customfishing/libraries/classpath/ReflectionClassPathAppender.java b/common/src/main/java/net/momirealms/customfishing/common/plugin/classpath/ReflectionClassPathAppender.java similarity index 87% rename from plugin/src/main/java/net/momirealms/customfishing/libraries/classpath/ReflectionClassPathAppender.java rename to common/src/main/java/net/momirealms/customfishing/common/plugin/classpath/ReflectionClassPathAppender.java index 5732f66a..277ebfed 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/libraries/classpath/ReflectionClassPathAppender.java +++ b/common/src/main/java/net/momirealms/customfishing/common/plugin/classpath/ReflectionClassPathAppender.java @@ -23,7 +23,9 @@ * SOFTWARE. */ -package net.momirealms.customfishing.libraries.classpath; +package net.momirealms.customfishing.common.plugin.classpath; + +import net.momirealms.customfishing.common.plugin.CustomFishingPlugin; import java.net.MalformedURLException; import java.net.URLClassLoader; @@ -40,6 +42,10 @@ public class ReflectionClassPathAppender implements ClassPathAppender { } } + public ReflectionClassPathAppender(CustomFishingPlugin plugin) throws IllegalStateException { + this(plugin.getClass().getClassLoader()); + } + @Override public void addJarToClasspath(Path file) { try { diff --git a/plugin/src/main/java/net/momirealms/customfishing/libraries/classpath/URLClassLoaderAccess.java b/common/src/main/java/net/momirealms/customfishing/common/plugin/classpath/URLClassLoaderAccess.java similarity index 95% rename from plugin/src/main/java/net/momirealms/customfishing/libraries/classpath/URLClassLoaderAccess.java rename to common/src/main/java/net/momirealms/customfishing/common/plugin/classpath/URLClassLoaderAccess.java index 1054b247..e62907f3 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/libraries/classpath/URLClassLoaderAccess.java +++ b/common/src/main/java/net/momirealms/customfishing/common/plugin/classpath/URLClassLoaderAccess.java @@ -23,9 +23,9 @@ * SOFTWARE. */ -package net.momirealms.customfishing.libraries.classpath; +package net.momirealms.customfishing.common.plugin.classpath; -import org.checkerframework.checker.nullness.qual.NonNull; +import org.jetbrains.annotations.NotNull; import java.lang.reflect.Field; import java.lang.reflect.Method; @@ -66,7 +66,7 @@ public abstract class URLClassLoaderAccess { * * @param url the URL to add */ - public abstract void addURL(@NonNull URL url); + public abstract void addURL(@NotNull URL url); private static void throwError(Throwable cause) throws UnsupportedOperationException { throw new UnsupportedOperationException("CustomFishing is unable to inject into the plugin URLClassLoader.\n" + @@ -100,7 +100,7 @@ public abstract class URLClassLoaderAccess { } @Override - public void addURL(@NonNull URL url) { + public void addURL(@NotNull URL url) { try { ADD_URL_METHOD.invoke(super.classLoader, url); } catch (ReflectiveOperationException e) { @@ -162,7 +162,7 @@ public abstract class URLClassLoaderAccess { } @Override - public void addURL(@NonNull URL url) { + public void addURL(@NotNull URL url) { if (this.unopenedURLs == null || this.pathURLs == null) { URLClassLoaderAccess.throwError(new NullPointerException("unopenedURLs or pathURLs")); } @@ -182,7 +182,7 @@ public abstract class URLClassLoaderAccess { } @Override - public void addURL(@NonNull URL url) { + public void addURL(@NotNull URL url) { URLClassLoaderAccess.throwError(null); } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/libraries/classpath/JarInJarClassPathAppender.java b/common/src/main/java/net/momirealms/customfishing/common/plugin/logging/JavaPluginLogger.java similarity index 54% rename from plugin/src/main/java/net/momirealms/customfishing/libraries/classpath/JarInJarClassPathAppender.java rename to common/src/main/java/net/momirealms/customfishing/common/plugin/logging/JavaPluginLogger.java index 7d8b30ee..70c74c86 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/libraries/classpath/JarInJarClassPathAppender.java +++ b/common/src/main/java/net/momirealms/customfishing/common/plugin/logging/JavaPluginLogger.java @@ -23,40 +23,40 @@ * SOFTWARE. */ -package net.momirealms.customfishing.libraries.classpath; +package net.momirealms.customfishing.common.plugin.logging; -import net.momirealms.customfishing.libraries.loader.JarInJarClassLoader; +import java.util.logging.Level; +import java.util.logging.Logger; -import java.io.IOException; -import java.net.MalformedURLException; -import java.nio.file.Path; +public class JavaPluginLogger implements PluginLogger { + private final Logger logger; -public class JarInJarClassPathAppender implements ClassPathAppender { - private final JarInJarClassLoader classLoader; - - public JarInJarClassPathAppender(ClassLoader classLoader) { - if (!(classLoader instanceof JarInJarClassLoader)) { - throw new IllegalArgumentException("Loader is not a JarInJarClassLoader: " + classLoader.getClass().getName()); - } - this.classLoader = (JarInJarClassLoader) classLoader; + public JavaPluginLogger(Logger logger) { + this.logger = logger; } @Override - public void addJarToClasspath(Path file) { - try { - this.classLoader.addJarToClasspath(file.toUri().toURL()); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } + public void info(String s) { + this.logger.info(s); } @Override - public void close() { - this.classLoader.deleteJarResource(); - try { - this.classLoader.close(); - } catch (IOException e) { - e.printStackTrace(); - } + public void warn(String s) { + this.logger.warning(s); + } + + @Override + public void warn(String s, Throwable t) { + this.logger.log(Level.WARNING, s, t); + } + + @Override + public void severe(String s) { + this.logger.severe(s); + } + + @Override + public void severe(String s, Throwable t) { + this.logger.log(Level.SEVERE, s, t); } } diff --git a/common/src/main/java/net/momirealms/customfishing/common/plugin/logging/Log4jPluginLogger.java b/common/src/main/java/net/momirealms/customfishing/common/plugin/logging/Log4jPluginLogger.java new file mode 100644 index 00000000..338ab9e5 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/plugin/logging/Log4jPluginLogger.java @@ -0,0 +1,61 @@ +/* + * This file is part of LuckPerms, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package net.momirealms.customfishing.common.plugin.logging; + +import org.apache.logging.log4j.Logger; + +public class Log4jPluginLogger implements PluginLogger { + private final Logger logger; + + public Log4jPluginLogger(Logger logger) { + this.logger = logger; + } + + @Override + public void info(String s) { + this.logger.info(s); + } + + @Override + public void warn(String s) { + this.logger.warn(s); + } + + @Override + public void warn(String s, Throwable t) { + this.logger.warn(s, t); + } + + @Override + public void severe(String s) { + this.logger.error(s); + } + + @Override + public void severe(String s, Throwable t) { + this.logger.error(s, t); + } +} diff --git a/plugin/src/main/java/net/momirealms/customfishing/libraries/loader/LoadingException.java b/common/src/main/java/net/momirealms/customfishing/common/plugin/logging/PluginLogger.java similarity index 71% rename from plugin/src/main/java/net/momirealms/customfishing/libraries/loader/LoadingException.java rename to common/src/main/java/net/momirealms/customfishing/common/plugin/logging/PluginLogger.java index 26528e94..180d63ee 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/libraries/loader/LoadingException.java +++ b/common/src/main/java/net/momirealms/customfishing/common/plugin/logging/PluginLogger.java @@ -23,19 +23,24 @@ * SOFTWARE. */ -package net.momirealms.customfishing.libraries.loader; +package net.momirealms.customfishing.common.plugin.logging; /** - * Runtime exception used if there is a problem during loading + * Represents the logger instance being used by CustomFishing on the platform. + * + *

Messages sent using the logger are sent prefixed with the CustomFishing tag, + * and on some implementations will be colored depending on the message type.

*/ -public class LoadingException extends RuntimeException { +public interface PluginLogger { - public LoadingException(String message) { - super(message); - } + void info(String s); - public LoadingException(String message, Throwable cause) { - super(message, cause); - } + void warn(String s); + + void warn(String s, Throwable t); + + void severe(String s); + + void severe(String s, Throwable t); } diff --git a/common/src/main/java/net/momirealms/customfishing/common/plugin/logging/Slf4jPluginLogger.java b/common/src/main/java/net/momirealms/customfishing/common/plugin/logging/Slf4jPluginLogger.java new file mode 100644 index 00000000..a77f01a6 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/plugin/logging/Slf4jPluginLogger.java @@ -0,0 +1,61 @@ +/* + * This file is part of LuckPerms, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package net.momirealms.customfishing.common.plugin.logging; + +import org.slf4j.Logger; + +public class Slf4jPluginLogger implements PluginLogger { + private final Logger logger; + + public Slf4jPluginLogger(Logger logger) { + this.logger = logger; + } + + @Override + public void info(String s) { + this.logger.info(s); + } + + @Override + public void warn(String s) { + this.logger.warn(s); + } + + @Override + public void warn(String s, Throwable t) { + this.logger.warn(s, t); + } + + @Override + public void severe(String s) { + this.logger.error(s); + } + + @Override + public void severe(String s, Throwable t) { + this.logger.error(s, t); + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/plugin/scheduler/AbstractJavaScheduler.java b/common/src/main/java/net/momirealms/customfishing/common/plugin/scheduler/AbstractJavaScheduler.java new file mode 100644 index 00000000..6ce01738 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/plugin/scheduler/AbstractJavaScheduler.java @@ -0,0 +1,132 @@ +/* + * This file is part of LuckPerms, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package net.momirealms.customfishing.common.plugin.scheduler; + +import net.momirealms.customfishing.common.plugin.CustomFishingPlugin; + +import java.lang.Thread.UncaughtExceptionHandler; +import java.util.Arrays; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +/** + * Abstract implementation of {@link SchedulerAdapter} using a {@link ScheduledExecutorService}. + */ +public abstract class AbstractJavaScheduler implements SchedulerAdapter { + private static final int PARALLELISM = 16; + + private final CustomFishingPlugin plugin; + + private final ScheduledThreadPoolExecutor scheduler; + private final ForkJoinPool worker; + + public AbstractJavaScheduler(CustomFishingPlugin plugin) { + this.plugin = plugin; + + this.scheduler = new ScheduledThreadPoolExecutor(1, r -> { + Thread thread = Executors.defaultThreadFactory().newThread(r); + thread.setName("customfishing-scheduler"); + return thread; + }); + this.scheduler.setRemoveOnCancelPolicy(true); + this.scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); + this.worker = new ForkJoinPool(PARALLELISM, new WorkerThreadFactory(), new ExceptionHandler(), false); + } + + @Override + public Executor async() { + return this.worker; + } + + @Override + public SchedulerTask asyncLater(Runnable task, long delay, TimeUnit unit) { + ScheduledFuture future = this.scheduler.schedule(() -> this.worker.execute(task), delay, unit); + return () -> future.cancel(false); + } + + @Override + public SchedulerTask asyncRepeating(Runnable task, long interval, TimeUnit unit) { + ScheduledFuture future = this.scheduler.scheduleAtFixedRate(() -> this.worker.execute(task), interval, interval, unit); + return () -> future.cancel(false); + } + + @Override + public void shutdownScheduler() { + this.scheduler.shutdown(); + try { + if (!this.scheduler.awaitTermination(1, TimeUnit.MINUTES)) { + this.plugin.getPluginLogger().severe("Timed out waiting for the CustomFishing scheduler to terminate"); + reportRunningTasks(thread -> thread.getName().equals("customfishing-scheduler")); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + @Override + public void shutdownExecutor() { + this.worker.shutdown(); + try { + if (!this.worker.awaitTermination(1, TimeUnit.MINUTES)) { + this.plugin.getPluginLogger().severe("Timed out waiting for the CustomFishing worker thread pool to terminate"); + reportRunningTasks(thread -> thread.getName().startsWith("customfishing-worker-")); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + private void reportRunningTasks(Predicate predicate) { + Thread.getAllStackTraces().forEach((thread, stack) -> { + if (predicate.test(thread)) { + this.plugin.getPluginLogger().warn("Thread " + thread.getName() + " is blocked, and may be the reason for the slow shutdown!\n" + + Arrays.stream(stack).map(el -> " " + el).collect(Collectors.joining("\n")) + ); + } + }); + } + + private static final class WorkerThreadFactory implements ForkJoinPool.ForkJoinWorkerThreadFactory { + private static final AtomicInteger COUNT = new AtomicInteger(0); + + @Override + public ForkJoinWorkerThread newThread(ForkJoinPool pool) { + ForkJoinWorkerThread thread = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool); + thread.setDaemon(true); + thread.setName("customfishing-worker-" + COUNT.getAndIncrement()); + return thread; + } + } + + private final class ExceptionHandler implements UncaughtExceptionHandler { + @Override + public void uncaughtException(Thread t, Throwable e) { + AbstractJavaScheduler.this.plugin.getPluginLogger().warn("Thread " + t.getName() + " threw an uncaught exception", e); + } + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/plugin/scheduler/RegionExecutor.java b/common/src/main/java/net/momirealms/customfishing/common/plugin/scheduler/RegionExecutor.java new file mode 100644 index 00000000..3d03f8a0 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/plugin/scheduler/RegionExecutor.java @@ -0,0 +1,6 @@ +package net.momirealms.customfishing.common.plugin.scheduler; + +public interface RegionExecutor { + + void execute(Runnable r, T l); +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/plugin/scheduler/SchedulerAdapter.java b/common/src/main/java/net/momirealms/customfishing/common/plugin/scheduler/SchedulerAdapter.java new file mode 100644 index 00000000..b663e65c --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/plugin/scheduler/SchedulerAdapter.java @@ -0,0 +1,106 @@ +/* + * This file is part of LuckPerms, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package net.momirealms.customfishing.common.plugin.scheduler; + +import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; + +/** + * A scheduler for running tasks using the systems provided by the platform + */ +public interface SchedulerAdapter { + + /** + * Gets an async executor instance + * + * @return an async executor instance + */ + Executor async(); + + /** + * Gets a sync executor instance + * + * @return a sync executor instance + */ + RegionExecutor sync(); + + /** + * Executes a task async + * + * @param task the task + */ + default void executeAsync(Runnable task) { + async().execute(task); + } + + /** + * Executes a task sync + * + * @param task the task + */ + default void executeSync(Runnable task, T location) { + sync().execute(task, location); + } + + default void executeSync(Runnable task) { + sync().execute(task, null); + } + + /** + * Executes the given task with a delay. + * + * @param task the task + * @param delay the delay + * @param unit the unit of delay + * @return the resultant task instance + */ + SchedulerTask asyncLater(Runnable task, long delay, TimeUnit unit); + + /** + * Executes the given task repeatedly at a given interval. + * + * @param task the task + * @param interval the interval + * @param unit the unit of interval + * @return the resultant task instance + */ + SchedulerTask asyncRepeating(Runnable task, long interval, TimeUnit unit); + + /** + * Shuts down the scheduler instance. + * + *

{@link #asyncLater(Runnable, long, TimeUnit)} and {@link #asyncRepeating(Runnable, long, TimeUnit)}.

+ */ + void shutdownScheduler(); + + /** + * Shuts down the executor instance. + * + *

{@link #async()} and {@link #executeAsync(Runnable)}.

+ */ + void shutdownExecutor(); + +} diff --git a/plugin/src/main/java/net/momirealms/customfishing/libraries/loader/LoaderBootstrap.java b/common/src/main/java/net/momirealms/customfishing/common/plugin/scheduler/SchedulerTask.java similarity index 84% rename from plugin/src/main/java/net/momirealms/customfishing/libraries/loader/LoaderBootstrap.java rename to common/src/main/java/net/momirealms/customfishing/common/plugin/scheduler/SchedulerTask.java index 98ddd06d..685c39ef 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/libraries/loader/LoaderBootstrap.java +++ b/common/src/main/java/net/momirealms/customfishing/common/plugin/scheduler/SchedulerTask.java @@ -23,17 +23,16 @@ * SOFTWARE. */ -package net.momirealms.customfishing.libraries.loader; +package net.momirealms.customfishing.common.plugin.scheduler; /** - * Minimal bootstrap plugin, called by the loader plugin. + * Represents a scheduled task */ -public interface LoaderBootstrap { +public interface SchedulerTask { - void onLoad(); - - default void onEnable() {} - - default void onDisable() {} + /** + * Cancels the task. + */ + void cancel(); } diff --git a/common/src/main/java/net/momirealms/customfishing/common/sender/AbstractSender.java b/common/src/main/java/net/momirealms/customfishing/common/sender/AbstractSender.java new file mode 100644 index 00000000..8b7e0dea --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/sender/AbstractSender.java @@ -0,0 +1,116 @@ +/* + * This file is part of LuckPerms, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package net.momirealms.customfishing.common.sender; + +import net.kyori.adventure.text.Component; +import net.momirealms.customfishing.common.plugin.CustomFishingPlugin; +import net.momirealms.customfishing.common.util.Tristate; + +import java.util.UUID; + +/** + * Simple implementation of {@link Sender} using a {@link SenderFactory} + * + * @param the command sender type + */ +public final class AbstractSender implements Sender { + private final CustomFishingPlugin plugin; + private final SenderFactory factory; + private final T sender; + + private final UUID uniqueId; + private final String name; + private final boolean isConsole; + + AbstractSender(CustomFishingPlugin plugin, SenderFactory factory, T sender) { + this.plugin = plugin; + this.factory = factory; + this.sender = sender; + this.uniqueId = factory.getUniqueId(this.sender); + this.name = factory.getName(this.sender); + this.isConsole = this.factory.isConsole(this.sender); + } + + @Override + public CustomFishingPlugin getPlugin() { + return this.plugin; + } + + @Override + public UUID getUniqueId() { + return this.uniqueId; + } + + @Override + public String getName() { + return this.name; + } + + @Override + public void sendMessage(Component message) { + this.factory.sendMessage(this.sender, message); + } + + @Override + public void sendMessage(Component message, boolean ignoreEmpty) { + if (ignoreEmpty && message.equals(Component.empty())) { + return; + } + sendMessage(message); + } + + @Override + public Tristate getPermissionValue(String permission) { + return (isConsole() && this.factory.consoleHasAllPermissions()) ? Tristate.TRUE : this.factory.getPermissionValue(this.sender, permission); + } + + @Override + public boolean hasPermission(String permission) { + return (isConsole() && this.factory.consoleHasAllPermissions()) || this.factory.hasPermission(this.sender, permission); + } + + @Override + public void performCommand(String commandLine) { + this.factory.performCommand(this.sender, commandLine); + } + + @Override + public boolean isConsole() { + return this.isConsole; + } + + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (!(o instanceof AbstractSender that)) return false; + return this.getUniqueId().equals(that.getUniqueId()); + } + + @Override + public int hashCode() { + return this.uniqueId.hashCode(); + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/sender/DummyConsoleSender.java b/common/src/main/java/net/momirealms/customfishing/common/sender/DummyConsoleSender.java new file mode 100644 index 00000000..381116b8 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/sender/DummyConsoleSender.java @@ -0,0 +1,62 @@ +/* + * This file is part of LuckPerms, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package net.momirealms.customfishing.common.sender; + +import net.momirealms.customfishing.common.plugin.CustomFishingPlugin; + +import java.util.UUID; + +public abstract class DummyConsoleSender implements Sender { + private final CustomFishingPlugin platform; + + public DummyConsoleSender(CustomFishingPlugin plugin) { + this.platform = plugin; + } + + @Override + public void performCommand(String commandLine) { + } + + @Override + public boolean isConsole() { + return true; + } + + @Override + public CustomFishingPlugin getPlugin() { + return this.platform; + } + + @Override + public UUID getUniqueId() { + return Sender.CONSOLE_UUID; + } + + @Override + public String getName() { + return Sender.CONSOLE_NAME; + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/sender/Sender.java b/common/src/main/java/net/momirealms/customfishing/common/sender/Sender.java new file mode 100644 index 00000000..2805299c --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/sender/Sender.java @@ -0,0 +1,121 @@ +/* + * This file is part of LuckPerms, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package net.momirealms.customfishing.common.sender; + +import net.kyori.adventure.text.Component; +import net.momirealms.customfishing.common.plugin.CustomFishingPlugin; +import net.momirealms.customfishing.common.util.Tristate; + +import java.util.UUID; + +/** + * Wrapper interface to represent a CommandSender/CommandSource within the common command implementations. + */ +public interface Sender { + + /** The uuid used by the console sender. */ + UUID CONSOLE_UUID = new UUID(0, 0); // 00000000-0000-0000-0000-000000000000 + /** The name used by the console sender. */ + String CONSOLE_NAME = "Console"; + + /** + * Gets the plugin instance the sender is from. + * + * @return the plugin + */ + CustomFishingPlugin getPlugin(); + + /** + * Gets the sender's username + * + * @return a friendly username for the sender + */ + String getName(); + + /** + * Gets the sender's unique id. + * + *

See {@link #CONSOLE_UUID} for the console's UUID representation.

+ * + * @return the sender's uuid + */ + UUID getUniqueId(); + + /** + * Send a json message to the Sender. + * + * @param message the message to send. + */ + void sendMessage(Component message); + + /** + * Send a json message to the Sender. + * + * @param message the message to send. + * @param ignoreEmpty whether to ignore empty component + */ + void sendMessage(Component message, boolean ignoreEmpty); + + /** + * Gets the tristate a permission is set to. + * + * @param permission the permission to check for + * @return a tristate + */ + Tristate getPermissionValue(String permission); + + /** + * Check if the Sender has a permission. + * + * @param permission the permission to check for + * @return true if the sender has the permission + */ + boolean hasPermission(String permission); + + /** + * Makes the sender perform a command. + * + * @param commandLine the command + */ + void performCommand(String commandLine); + + /** + * Gets whether this sender is the console + * + * @return if the sender is the console + */ + boolean isConsole(); + + /** + * Gets whether this sender is still valid & receiving messages. + * + * @return if this sender is valid + */ + default boolean isValid() { + return true; + } + +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/sender/SenderFactory.java b/common/src/main/java/net/momirealms/customfishing/common/sender/SenderFactory.java new file mode 100644 index 00000000..c9aef1db --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/sender/SenderFactory.java @@ -0,0 +1,82 @@ +/* + * This file is part of LuckPerms, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package net.momirealms.customfishing.common.sender; + +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.text.Component; +import net.momirealms.customfishing.common.plugin.CustomFishingPlugin; +import net.momirealms.customfishing.common.util.Tristate; + +import java.util.Objects; +import java.util.UUID; + +/** + * Factory class to make a thread-safe sender instance + * + * @param

the plugin type + * @param the command sender type + */ +public abstract class SenderFactory

implements AutoCloseable { + private final P plugin; + + public SenderFactory(P plugin) { + this.plugin = plugin; + } + + protected P getPlugin() { + return this.plugin; + } + + protected abstract UUID getUniqueId(T sender); + + protected abstract String getName(T sender); + + public abstract Audience getAudience(T sender); + + protected abstract void sendMessage(T sender, Component message); + + protected abstract Tristate getPermissionValue(T sender, String node); + + protected abstract boolean hasPermission(T sender, String node); + + protected abstract void performCommand(T sender, String command); + + protected abstract boolean isConsole(T sender); + + protected boolean consoleHasAllPermissions() { + return true; + } + + public final Sender wrap(T sender) { + Objects.requireNonNull(sender, "sender"); + return new AbstractSender<>(this.plugin, this, sender); + } + + @Override + public void close() { + + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/util/ArrayUtils.java b/common/src/main/java/net/momirealms/customfishing/common/util/ArrayUtils.java new file mode 100644 index 00000000..c51371bd --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/util/ArrayUtils.java @@ -0,0 +1,37 @@ +package net.momirealms.customfishing.common.util; + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.List; + +public class ArrayUtils { + + private ArrayUtils() {} + + public static T[] subArray(T[] array, int index) { + if (index < 0) { + throw new IllegalArgumentException("Index should be a value no lower than 0"); + } + if (array.length <= index) { + @SuppressWarnings("unchecked") + T[] emptyArray = (T[]) Array.newInstance(array.getClass().getComponentType(), 0); + return emptyArray; + } + @SuppressWarnings("unchecked") + T[] subArray = (T[]) Array.newInstance(array.getClass().getComponentType(), array.length - index); + System.arraycopy(array, index, subArray, 0, array.length - index); + return subArray; + } + + public static List splitArray(T[] array, int chunkSize) { + List result = new ArrayList<>(); + for (int i = 0; i < array.length; i += chunkSize) { + int end = Math.min(array.length, i + chunkSize); + @SuppressWarnings("unchecked") + T[] chunk = (T[]) Array.newInstance(array.getClass().getComponentType(), end - i); + System.arraycopy(array, i, chunk, 0, end - i); + result.add(chunk); + } + return result; + } +} diff --git a/plugin/src/main/java/net/momirealms/customfishing/util/ClassUtils.java b/common/src/main/java/net/momirealms/customfishing/common/util/ClassUtils.java similarity index 98% rename from plugin/src/main/java/net/momirealms/customfishing/util/ClassUtils.java rename to common/src/main/java/net/momirealms/customfishing/common/util/ClassUtils.java index 1de55c96..9330a5ff 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/util/ClassUtils.java +++ b/common/src/main/java/net/momirealms/customfishing/common/util/ClassUtils.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.util; +package net.momirealms.customfishing.common.util; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/common/src/main/java/net/momirealms/customfishing/common/util/Either.java b/common/src/main/java/net/momirealms/customfishing/common/util/Either.java new file mode 100644 index 00000000..c5577b27 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/util/Either.java @@ -0,0 +1,43 @@ +package net.momirealms.customfishing.common.util; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Optional; +import java.util.function.Function; + +import static java.util.Objects.requireNonNull; + +public interface Either { + + static @NotNull Either ofPrimary(final @NotNull U value) { + return EitherImpl.of(requireNonNull(value, "value"), null); + } + + static @NotNull Either ofFallback(final @NotNull V value) { + return EitherImpl.of(null, requireNonNull(value, "value")); + } + + @NotNull + Optional primary(); + + @NotNull + Optional fallback(); + + default @Nullable U primaryOrMapFallback(final @NotNull Function mapFallback) { + return this.primary().orElseGet(() -> mapFallback.apply(this.fallback().get())); + } + + default @Nullable V fallbackOrMapPrimary(final @NotNull Function mapPrimary) { + return this.fallback().orElseGet(() -> mapPrimary.apply(this.primary().get())); + } + + default @NotNull R mapEither( + final @NotNull Function mapPrimary, + final @NotNull Function mapFallback + ) { + return this.primary() + .map(mapPrimary) + .orElseGet(() -> this.fallback().map(mapFallback).get()); + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/util/EitherImpl.java b/common/src/main/java/net/momirealms/customfishing/common/util/EitherImpl.java new file mode 100644 index 00000000..32bd8c07 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/util/EitherImpl.java @@ -0,0 +1,113 @@ +package net.momirealms.customfishing.common.util; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; +import java.util.Optional; + +final class EitherImpl implements Either { + private final @Nullable U primary; + private final @Nullable V fallback; + + private EitherImpl(Optional primary, Optional fallback) { + this.primary = primary.orElse(null); + this.fallback = fallback.orElse(null); + } + + private EitherImpl(@Nullable U primary, @Nullable V fallback) { + this.primary = primary; + this.fallback = fallback; + } + + private EitherImpl( + EitherImpl original, + @Nullable U primary, + @Nullable V fallback + ) { + this.primary = primary; + this.fallback = fallback; + } + + @Override + public @NotNull Optional primary() { + return Optional.ofNullable(primary); + } + + @Override + public @NotNull Optional fallback() { + return Optional.ofNullable(fallback); + } + + public final EitherImpl withPrimary(@Nullable U value) { + @Nullable U newValue = value; + if (this.primary == newValue) return this; + return new EitherImpl<>(this, newValue, this.fallback); + } + + public EitherImpl withPrimary(Optional optional) { + @Nullable U value = optional.orElse(null); + if (this.primary == value) return this; + return new EitherImpl<>(this, value, this.fallback); + } + + public EitherImpl withFallback(@Nullable V value) { + @Nullable V newValue = value; + if (this.fallback == newValue) return this; + return new EitherImpl<>(this, this.primary, newValue); + } + + public EitherImpl withFallback(Optional optional) { + @Nullable V value = optional.orElse(null); + if (this.fallback == value) return this; + return new EitherImpl<>(this, this.primary, value); + } + + @Override + public boolean equals(@Nullable Object another) { + if (this == another) return true; + return another instanceof EitherImpl + && equalTo((EitherImpl) another); + } + + private boolean equalTo(EitherImpl another) { + return Objects.equals(primary, another.primary) + && Objects.equals(fallback, another.fallback); + } + + @Override + public int hashCode() { + int h = 5381; + h += (h << 5) + Objects.hashCode(primary); + h += (h << 5) + Objects.hashCode(fallback); + return h; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder("Either{"); + if (primary != null) { + builder.append("primary=").append(primary); + } + if (fallback != null) { + if (builder.length() > 7) builder.append(", "); + builder.append("fallback=").append(fallback); + } + return builder.append("}").toString(); + } + + public static EitherImpl of(Optional primary, Optional fallback) { + return new EitherImpl<>(primary, fallback); + } + + public static EitherImpl of(@Nullable U primary, @Nullable V fallback) { + return new EitherImpl<>(primary, fallback); + } + + public static EitherImpl copyOf(Either instance) { + if (instance instanceof EitherImpl) { + return (EitherImpl) instance; + } + return EitherImpl.of(instance.primary(), instance.fallback()); + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/util/FileUtils.java b/common/src/main/java/net/momirealms/customfishing/common/util/FileUtils.java new file mode 100644 index 00000000..297c8946 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/util/FileUtils.java @@ -0,0 +1,65 @@ +package net.momirealms.customfishing.common.util; + +import java.io.IOException; +import java.nio.file.DirectoryStream; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.Path; + +public class FileUtils { + + private FileUtils() {} + + public static Path createFileIfNotExists(Path path) throws IOException { + if (!Files.exists(path)) { + Files.createFile(path); + } + return path; + } + + public static Path createDirectoryIfNotExists(Path path) throws IOException { + if (Files.exists(path) && (Files.isDirectory(path) || Files.isSymbolicLink(path))) { + return path; + } + + try { + Files.createDirectory(path); + } catch (FileAlreadyExistsException e) { + // ignore + } + + return path; + } + + public static Path createDirectoriesIfNotExists(Path path) throws IOException { + if (Files.exists(path) && (Files.isDirectory(path) || Files.isSymbolicLink(path))) { + return path; + } + + try { + Files.createDirectories(path); + } catch (FileAlreadyExistsException e) { + // ignore + } + + return path; + } + + public static void deleteDirectory(Path path) throws IOException { + if (!Files.exists(path) || !Files.isDirectory(path)) { + return; + } + + try (DirectoryStream contents = Files.newDirectoryStream(path)) { + for (Path file : contents) { + if (Files.isDirectory(file)) { + deleteDirectory(file); + } else { + Files.delete(file); + } + } + } + + Files.delete(path); + } +} diff --git a/common/src/main/java/net/momirealms/customfishing/common/util/Key.java b/common/src/main/java/net/momirealms/customfishing/common/util/Key.java new file mode 100644 index 00000000..e6f07aba --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/util/Key.java @@ -0,0 +1,29 @@ +package net.momirealms.customfishing.common.util; + +public record Key(String namespace, String value) { + + public static Key of(String namespace, String value) { + return new Key(namespace, value); + } + + @Override + public int hashCode() { + int result = this.namespace.hashCode(); + result = (31 * result) + this.value.hashCode(); + return result; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof Key key)) return false; + return this.namespace.equals(key.namespace()) && this.value.equals(key.value()); + } + + @Override + public String toString() { + return namespace + ":" + value; + } +} \ No newline at end of file diff --git a/common/src/main/java/net/momirealms/customfishing/common/util/ListUtils.java b/common/src/main/java/net/momirealms/customfishing/common/util/ListUtils.java new file mode 100644 index 00000000..350f7481 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/util/ListUtils.java @@ -0,0 +1,19 @@ +package net.momirealms.customfishing.common.util; + +import java.util.List; + +public class ListUtils { + + private ListUtils() { + } + + @SuppressWarnings("unchecked") + public static List toList(final Object obj) { + if (obj instanceof String s) { + return List.of(s); + } else if (obj instanceof List list) { + return (List) list; + } + throw new IllegalArgumentException("Cannot convert " + obj + " to a list"); + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/common/Pair.java b/common/src/main/java/net/momirealms/customfishing/common/util/Pair.java similarity index 94% rename from api/src/main/java/net/momirealms/customfishing/api/common/Pair.java rename to common/src/main/java/net/momirealms/customfishing/common/util/Pair.java index 2491adcd..d665bb11 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/common/Pair.java +++ b/common/src/main/java/net/momirealms/customfishing/common/util/Pair.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.common; +package net.momirealms.customfishing.common.util; public record Pair(L left, R right) { diff --git a/common/src/main/java/net/momirealms/customfishing/common/util/Tristate.java b/common/src/main/java/net/momirealms/customfishing/common/util/Tristate.java new file mode 100644 index 00000000..e3e5f1a5 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/util/Tristate.java @@ -0,0 +1,98 @@ +/* + * This file is part of LuckPerms, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package net.momirealms.customfishing.common.util; + +import org.jetbrains.annotations.NotNull; + +/** + * Represents three different states of a setting. + * + *

Possible values:

+ *

+ *
    + *
  • {@link #TRUE} - a positive setting
  • + *
  • {@link #FALSE} - a negative (negated) setting
  • + *
  • {@link #UNDEFINED} - a non-existent setting
  • + *
+ */ +public enum Tristate { + + /** + * A value indicating a positive setting + */ + TRUE(true), + + /** + * A value indicating a negative (negated) setting + */ + FALSE(false), + + /** + * A value indicating a non-existent setting + */ + UNDEFINED(false); + + /** + * Returns a {@link Tristate} from a boolean + * + * @param val the boolean value + * @return {@link #TRUE} or {@link #FALSE}, if the value is true or false, respectively. + */ + public static @NotNull Tristate of(boolean val) { + return val ? TRUE : FALSE; + } + + /** + * Returns a {@link Tristate} from a nullable boolean. + * + *

Unlike {@link #of(boolean)}, this method returns {@link #UNDEFINED} + * if the value is null.

+ * + * @param val the boolean value + * @return {@link #UNDEFINED}, {@link #TRUE} or {@link #FALSE}, if the value + * is null, true or false, respectively. + */ + public static @NotNull Tristate of(Boolean val) { + return val == null ? UNDEFINED : val ? TRUE : FALSE; + } + + private final boolean booleanValue; + + Tristate(boolean booleanValue) { + this.booleanValue = booleanValue; + } + + /** + * Returns the value of the Tristate as a boolean. + * + *

A value of {@link #UNDEFINED} converts to false.

+ * + * @return a boolean representation of the Tristate. + */ + public boolean asBoolean() { + return this.booleanValue; + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/common/Tuple.java b/common/src/main/java/net/momirealms/customfishing/common/util/Tuple.java similarity index 96% rename from api/src/main/java/net/momirealms/customfishing/api/common/Tuple.java rename to common/src/main/java/net/momirealms/customfishing/common/util/Tuple.java index 2d50e10d..5ef8f3f4 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/common/Tuple.java +++ b/common/src/main/java/net/momirealms/customfishing/common/util/Tuple.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.common; +package net.momirealms.customfishing.common.util; public class Tuple { diff --git a/common/src/main/java/net/momirealms/customfishing/common/util/UUIDUtils.java b/common/src/main/java/net/momirealms/customfishing/common/util/UUIDUtils.java new file mode 100644 index 00000000..3269b698 --- /dev/null +++ b/common/src/main/java/net/momirealms/customfishing/common/util/UUIDUtils.java @@ -0,0 +1,32 @@ +package net.momirealms.customfishing.common.util; + +import java.math.BigInteger; +import java.util.UUID; + +public class UUIDUtils { + + public static UUID fromUnDashedUUID(String id) { + return id == null ? null : new UUID( + new BigInteger(id.substring(0, 16), 16).longValue(), + new BigInteger(id.substring(16, 32), 16).longValue() + ); + } + + public static String toUnDashedUUID(UUID uuid) { + return uuid.toString().replace("-", ""); + } + + public static UUID uuidFromIntArray(int[] array) { + return new UUID((long)array[0] << 32 | (long)array[1] & 4294967295L, (long)array[2] << 32 | (long)array[3] & 4294967295L); + } + + public static int[] uuidToIntArray(UUID uuid) { + long l = uuid.getMostSignificantBits(); + long m = uuid.getLeastSignificantBits(); + return leastMostToIntArray(l, m); + } + + private static int[] leastMostToIntArray(long uuidMost, long uuidLeast) { + return new int[]{(int)(uuidMost >> 32), (int)uuidMost, (int)(uuidLeast >> 32), (int)uuidLeast}; + } +} diff --git a/api/src/main/java/net/momirealms/customfishing/api/util/WeightUtils.java b/common/src/main/java/net/momirealms/customfishing/common/util/WeightUtils.java similarity index 97% rename from api/src/main/java/net/momirealms/customfishing/api/util/WeightUtils.java rename to common/src/main/java/net/momirealms/customfishing/common/util/WeightUtils.java index 4de91cab..9170ae4f 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/util/WeightUtils.java +++ b/common/src/main/java/net/momirealms/customfishing/common/util/WeightUtils.java @@ -15,9 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.util; - -import net.momirealms.customfishing.api.common.Pair; +package net.momirealms.customfishing.common.util; import java.util.ArrayList; import java.util.Arrays; diff --git a/plugin/src/main/resources/database.yml b/common/src/main/resources/database.yml similarity index 100% rename from plugin/src/main/resources/database.yml rename to common/src/main/resources/database.yml diff --git a/common/src/main/resources/library-version.properties b/common/src/main/resources/library-version.properties new file mode 100644 index 00000000..c9c67931 --- /dev/null +++ b/common/src/main/resources/library-version.properties @@ -0,0 +1,23 @@ +asm=${asm_version} +asm-commons=${asm_commons_version} +jar-relocator=${jar_relocator_version} +h2-driver=${h2_driver_version} +sqlite-driver=${sqlite_driver_version} +cloud-core=${cloud_core_version} +cloud-brigadier=${cloud_brigadier_version} +cloud-services=${cloud_services_version} +cloud-bukkit=${cloud_bukkit_version} +cloud-paper=${cloud_paper_version} +cloud-minecraft-extras=${cloud_minecraft_extras_version} +boosted-yaml=${boosted_yaml_version} +byte-buddy=${byte_buddy_version} +mongodb-driver-core=${mongodb_driver_version} +mariadb-java-client=${mariadb_driver_version} +mysql-connector-j=${mysql_driver_version} +hikari-cp=${hikari_version} +commons-pool=${commons_pool_version} +bstats-base=${bstats_version} +geantyref=${geantyref_version} +gson=${gson_version} +caffeine=${caffeine_version} +jedis=${jedis_version} \ No newline at end of file diff --git a/common/src/main/resources/translations/en.yml b/common/src/main/resources/translations/en.yml new file mode 100644 index 00000000..7319af91 --- /dev/null +++ b/common/src/main/resources/translations/en.yml @@ -0,0 +1,55 @@ +# +# Don't change this +# +config-version: "${config_version}" + +# +# Text format: https://docs.advntr.dev/minimessage/format +# +# You can disable the message by setting the value to "" (empty) for example +# commands.player.anvil.success: "" +# +# Methods for multiple lines: +# 1. "First lineSecond line" +# 2. key: +# - First line +# - Second line +# +exception.invalid_syntax: "Invalid syntax. Correct syntax: " +exception.invalid_argument: "Invalid argument. Reason: " +exception.invalid_sender: " is not allowed to execute that command. Must be of type " +exception.unexpected: "An internal error occurred while attempting to perform this command" +exception.no_permission: "I'm sorry, but you do not have permission to perform this command" +exception.no_such_command: "Unknown command." +argument.entity.notfound.player: "" +argument.entity.notfound.entity: "" +argument.parse.failure.time: "'' is not a valid time format" +argument.parse.failure.material: "'' is not a valid material name" +argument.parse.failure.enchantment: "'' is not a valid enchantment" +argument.parse.failure.offlineplayer: "No player found for input ''" +argument.parse.failure.player: "No player found for input ''" +argument.parse.failure.world: "'' is not a valid Minecraft world" +argument.parse.failure.location.invalid_format: "'' is not a valid location. Required format is ' " +argument.parse.failure.location.mixed_local_absolute: "Cannot mix local and absolute coordinates. (either all coordinates use '^' or none do)" +argument.parse.failure.namespacedkey.namespace: "Invalid namespace ''. Must be [a-z0-9._-]" +argument.parse.failure.namespacedkey.key: "Invalid key ''. Must be [a-z0-9/._-]" +argument.parse.failure.namespacedkey.need_namespace: "Invalid input '', requires an explicit namespace" +argument.parse.failure.boolean: "Could not parse boolean from ''" +argument.parse.failure.number: "'' is not a valid number in the range to " +argument.parse.failure.char: "'' is not a valid character" +argument.parse.failure.string: "'' is not a valid string of type " +argument.parse.failure.uuid: "'' is not a valid UUID" +argument.parse.failure.enum: "'' is not one of the following: " +argument.parse.failure.regex: "'' does not match ''" +argument.parse.failure.flag.unknown: "Unknown flag ''" +argument.parse.failure.flag.duplicate_flag: "Duplicate flag ''" +argument.parse.failure.flag.no_flag_started: "No flag started. Don't know what to do with ''" +argument.parse.failure.flag.missing_argument: "Missing argument for ''" +argument.parse.failure.flag.no_permission: "You don't have permission to use ''" +argument.parse.failure.color: "'' is not a valid color" +argument.parse.failure.duration: "'' is not a duration format" +argument.parse.failure.aggregate.missing: "Missing component ''" +argument.parse.failure.aggregate.failure: "Invalid component '': " +argument.parse.failure.either: "Could not resolve or from ''" +argument.parse.failure.url: "'' is not a valid URL" +argument.parse.failure.namedtextcolor: "'' is not a named text color" \ No newline at end of file diff --git a/compatibility/build.gradle.kts b/compatibility/build.gradle.kts new file mode 100644 index 00000000..bfb8bac9 --- /dev/null +++ b/compatibility/build.gradle.kts @@ -0,0 +1,18 @@ +dependencies { + compileOnly(project(":common")) + compileOnly(project(":api")) +} + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +tasks.withType { + options.encoding = "UTF-8" + options.release.set(17) + dependsOn(tasks.clean) +} \ No newline at end of file diff --git a/plugin/.gitignore b/core/.gitignore similarity index 100% rename from plugin/.gitignore rename to core/.gitignore diff --git a/plugin/build.gradle.kts b/core/build.gradle.kts similarity index 53% rename from plugin/build.gradle.kts rename to core/build.gradle.kts index 93a55d56..23e78aa8 100644 --- a/plugin/build.gradle.kts +++ b/core/build.gradle.kts @@ -1,56 +1,42 @@ +plugins { + id("io.github.goooler.shadow") version "8.1.7" +} + dependencies { + implementation(project(":common")) + implementation(project(":api")) + // adventure + implementation("net.kyori:adventure-api:4.17.0") + implementation("net.kyori:adventure-text-minimessage:4.17.0") + implementation("net.kyori:adventure-text-serializer-gson:4.17.0") { + exclude("com.google.code.gson", "gson") + } + implementation("net.kyori:adventure-platform-bukkit:4.3.2") + // GUI + implementation("xyz.xenondevs.invui:invui:1.30") { + exclude("org.jetbrains", "annotations") + } + // NBT + implementation("com.saicone.rtag:rtag:1.5.3") + implementation("com.saicone.rtag:rtag-item:1.5.3") + // sparrow heart + implementation("com.github.Xiao-MoMi:Sparrow-Heart:0.16") // server compileOnly("dev.folia:folia-api:1.20.4-R0.1-SNAPSHOT") - - // packet - compileOnly("com.comphenix.protocol:ProtocolLib:5.1.0") - - // command - compileOnly("dev.jorel:commandapi-bukkit-core:9.4.1") - // bStats compileOnly("org.bstats:bstats-bukkit:3.0.2") - // papi compileOnly("me.clip:placeholderapi:2.11.5") - // config compileOnly("dev.dejvokep:boosted-yaml:1.3.4") - - // mythic - compileOnly("io.lumine:Mythic-Dist:5.3.5") - compileOnly("net.Indyuce:MMOItems-API:6.9.2-SNAPSHOT") - compileOnly("io.lumine:MythicLib-dist:1.6-SNAPSHOT") - compileOnly("net.Indyuce:MMOCore-API:1.12-SNAPSHOT") - // Gson compileOnly("com.google.code.gson:gson:2.10.1") - - // eco - compileOnly("com.willfp:eco:6.67.2") - compileOnly("com.willfp:EcoJobs:3.47.1") - compileOnly("com.willfp:EcoSkills:3.21.0") - compileOnly("com.willfp:libreforge:4.48.1") - // database compileOnly("org.xerial:sqlite-jdbc:3.45.3.0") compileOnly("com.h2database:h2:2.2.224") compileOnly("org.mongodb:mongodb-driver-sync:5.0.1") compileOnly("com.zaxxer:HikariCP:5.0.1") compileOnly("redis.clients:jedis:5.1.2") - - // others - compileOnly("com.github.LoneDev6:api-itemsadder:3.5.0c-r5") - compileOnly("io.th0rgal:oraxen:1.165.0") - compileOnly("pers.neige.neigeitems:NeigeItems:1.16.24") - compileOnly("com.github.Zrips:Jobs:4.17.2") - compileOnly("com.github.Archy-X:AureliumSkills:Beta1.3.21") - compileOnly("dev.aurelium:auraskills-api-bukkit:2.0.0-SNAPSHOT") - compileOnly("com.github.MilkBowl:VaultAPI:1.7") - compileOnly("org.betonquest:betonquest:2.0.0") - compileOnly("com.github.Xiao-MoMi:Custom-Crops:3.4.4.1") - compileOnly("org.apache.commons:commons-lang3:3.14.0") - // local jars compileOnly(files("libs/AdvancedEnchantments-api.jar")) compileOnly(files("libs/BattlePass-4.0.6-api.jar")) @@ -59,52 +45,39 @@ dependencies { compileOnly(files("libs/ClueScrolls-4.8.7-api.jar")) compileOnly(files("libs/notquests-5.17.1.jar")) compileOnly(files("libs/zaphkiel-2.0.24.jar")) - - // GUI - implementation("xyz.xenondevs.invui:invui:1.30") { - exclude("org.jetbrains", "annotations") - } - - // nbt - implementation("de.tr7zw:item-nbt-api:2.12.4") - - // api module - implementation(project(":api")) - - // sparrow heart - implementation("com.github.Xiao-MoMi:Sparrow-Heart:0.16") - - // adventure - implementation("net.kyori:adventure-api:4.17.0") - implementation("net.kyori:adventure-text-minimessage:4.17.0") - implementation("net.kyori:adventure-text-serializer-gson:4.17.0") { - exclude("com.google.code.gson", "gson") - } - implementation("net.kyori:adventure-platform-bukkit:4.3.2") } tasks { shadowJar { - exclude("org.jetbrains:annotations:*") + relocate("net.kyori", "net.momirealms.customfishing.libraries") + relocate("org.incendo", "net.momirealms.customfishing.libraries") + relocate("dev.dejvokep", "net.momirealms.customfishing.libraries") + relocate("net.bytebuddy", "net.momirealms.customfishing.libraries.bytebuddy") relocate ("org.apache.commons.pool2", "net.momirealms.customfishing.libraries.commonspool2") - relocate ("org.apache.commons.lang3", "net.momirealms.customfishing.libraries.lang3") relocate ("com.mysql", "net.momirealms.customfishing.libraries.mysql") relocate ("org.mariadb", "net.momirealms.customfishing.libraries.mariadb") relocate ("com.zaxxer.hikari", "net.momirealms.customfishing.libraries.hikari") - relocate ("redis.clients.jedis", "net.momirealms.customfishing.libraries.jedis") relocate ("com.mongodb", "net.momirealms.customfishing.libraries.mongodb") relocate ("org.bson", "net.momirealms.customfishing.libraries.bson") - relocate ("net.objecthunter.exp4j", "net.momirealms.customfishing.libraries.exp4j") - relocate ("de.tr7zw.changeme", "net.momirealms.customfishing.libraries.changeme") - relocate ("net.kyori", "net.momirealms.customfishing.libraries") - relocate ("dev.jorel.commandapi", "net.momirealms.customfishing.libraries.commandapi") - relocate ("dev.dejvokep.boostedyaml", "net.momirealms.customfishing.libraries.boostedyaml") relocate ("org.bstats", "net.momirealms.customfishing.libraries.bstats") - relocate ("net.momirealms.sparrow.heart", "net.momirealms.customfishing.libraries.heart") - relocate ("xyz.xenondevs", "net.momirealms.customfishing.libraries") + relocate ("io.lettuce", "net.momirealms.customfishing.libraries.lettuce") + relocate ("io.leangen.geantyref", "net.momirealms.customfishing.libraries.geantyref") + relocate ("com.github.benmanes.caffeine", "net.momirealms.customfishing.libraries.caffeine") + relocate ("net.momirealms.sparrow.heart", "net.momirealms.customfishing.bukkit.nms") + relocate ("com.saicone.rtag", "net.momirealms.customfishing.libraries.rtag") + } +} + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + toolchain { + languageVersion = JavaLanguageVersion.of(17) } } tasks.withType { options.encoding = "UTF-8" + options.release.set(17) + dependsOn(tasks.clean) } \ No newline at end of file diff --git a/plugin/libs/AdvancedEnchantments-api.jar b/core/libs/AdvancedEnchantments-api.jar similarity index 100% rename from plugin/libs/AdvancedEnchantments-api.jar rename to core/libs/AdvancedEnchantments-api.jar diff --git a/plugin/libs/BattlePass-4.0.6-api.jar b/core/libs/BattlePass-4.0.6-api.jar similarity index 100% rename from plugin/libs/BattlePass-4.0.6-api.jar rename to core/libs/BattlePass-4.0.6-api.jar diff --git a/plugin/libs/ClueScrolls-4.8.7-api.jar b/core/libs/ClueScrolls-4.8.7-api.jar similarity index 100% rename from plugin/libs/ClueScrolls-4.8.7-api.jar rename to core/libs/ClueScrolls-4.8.7-api.jar diff --git a/plugin/libs/RealisticSeasons-api.jar b/core/libs/RealisticSeasons-api.jar similarity index 100% rename from plugin/libs/RealisticSeasons-api.jar rename to core/libs/RealisticSeasons-api.jar diff --git a/plugin/libs/mcMMO-api.jar b/core/libs/mcMMO-api.jar similarity index 100% rename from plugin/libs/mcMMO-api.jar rename to core/libs/mcMMO-api.jar diff --git a/plugin/libs/notquests-5.17.1.jar b/core/libs/notquests-5.17.1.jar similarity index 100% rename from plugin/libs/notquests-5.17.1.jar rename to core/libs/notquests-5.17.1.jar diff --git a/plugin/libs/zaphkiel-2.0.24.jar b/core/libs/zaphkiel-2.0.24.jar similarity index 100% rename from plugin/libs/zaphkiel-2.0.24.jar rename to core/libs/zaphkiel-2.0.24.jar diff --git a/plugin/src/main/java/net/momirealms/customfishing/CustomFishingPluginImpl.java b/core/src/main/java/net/momirealms/customfishing/BukkitCustomFishingPluginImpl.java similarity index 91% rename from plugin/src/main/java/net/momirealms/customfishing/CustomFishingPluginImpl.java rename to core/src/main/java/net/momirealms/customfishing/BukkitCustomFishingPluginImpl.java index 5cb7bb1e..33dff496 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/CustomFishingPluginImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/BukkitCustomFishingPluginImpl.java @@ -17,22 +17,10 @@ package net.momirealms.customfishing; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.ProtocolManager; -import com.comphenix.protocol.events.PacketContainer; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.event.CustomFishingReloadEvent; -import net.momirealms.customfishing.api.util.LogUtils; -import net.momirealms.customfishing.api.util.ReflectionUtils; -import net.momirealms.customfishing.command.CommandManagerImpl; -import net.momirealms.customfishing.compatibility.IntegrationManagerImpl; -import net.momirealms.customfishing.compatibility.papi.PlaceholderManagerImpl; -import net.momirealms.customfishing.libraries.classpath.ReflectionClassPathAppender; -import net.momirealms.customfishing.libraries.dependencies.Dependency; -import net.momirealms.customfishing.libraries.dependencies.DependencyManager; -import net.momirealms.customfishing.libraries.dependencies.DependencyManagerImpl; +import net.momirealms.customfishing.bukkit.compatibility.IntegrationManagerImpl; +import net.momirealms.customfishing.bukkit.compatibility.papi.PlaceholderManagerImpl; import net.momirealms.customfishing.mechanic.action.ActionManagerImpl; import net.momirealms.customfishing.mechanic.bag.BagManagerImpl; import net.momirealms.customfishing.mechanic.block.BlockManagerImpl; @@ -50,11 +38,9 @@ import net.momirealms.customfishing.mechanic.misc.CoolDownManager; import net.momirealms.customfishing.mechanic.requirement.RequirementManagerImpl; import net.momirealms.customfishing.mechanic.statistic.StatisticsManagerImpl; import net.momirealms.customfishing.mechanic.totem.TotemManagerImpl; -import net.momirealms.customfishing.scheduler.SchedulerImpl; import net.momirealms.customfishing.setting.CFConfig; import net.momirealms.customfishing.setting.CFLocale; import net.momirealms.customfishing.storage.StorageManagerImpl; -import net.momirealms.customfishing.util.NBTUtils; import net.momirealms.customfishing.version.VersionManagerImpl; import org.bstats.bukkit.Metrics; import org.bukkit.Bukkit; @@ -68,14 +54,14 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -public class CustomFishingPluginImpl extends CustomFishingPlugin { +public class BukkitCustomFishingPluginImpl extends BukkitCustomFishingPlugin { private static ProtocolManager protocolManager; private CoolDownManager coolDownManager; private ChatCatcherManager chatCatcherManager; private DependencyManager dependencyManager; - public CustomFishingPluginImpl() { + public BukkitCustomFishingPluginImpl() { super(); } diff --git a/plugin/src/main/java/net/momirealms/customfishing/adventure/component/Languages.java b/core/src/main/java/net/momirealms/customfishing/bukkit/adventure/Languages.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/adventure/component/Languages.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/adventure/Languages.java index ed3399d5..346c4879 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/adventure/component/Languages.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/adventure/Languages.java @@ -4,7 +4,7 @@ * Copyright (c) 2021 NichtStudioCode */ -package net.momirealms.customfishing.adventure.component; +package net.momirealms.customfishing.bukkit.adventure; import com.google.gson.stream.JsonReader; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/momirealms/customfishing/adventure/component/ShadedAdventureComponentUtils.java b/core/src/main/java/net/momirealms/customfishing/bukkit/adventure/ShadedAdventureComponentUtils.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/adventure/component/ShadedAdventureComponentUtils.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/adventure/ShadedAdventureComponentUtils.java index 9709b287..233c8b4e 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/adventure/component/ShadedAdventureComponentUtils.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/adventure/ShadedAdventureComponentUtils.java @@ -4,7 +4,7 @@ * Copyright (c) 2021 NichtStudioCode */ -package net.momirealms.customfishing.adventure.component; +package net.momirealms.customfishing.bukkit.adventure; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; diff --git a/plugin/src/main/java/net/momirealms/customfishing/adventure/component/ShadedAdventureComponentWrapper.java b/core/src/main/java/net/momirealms/customfishing/bukkit/adventure/ShadedAdventureComponentWrapper.java similarity index 96% rename from plugin/src/main/java/net/momirealms/customfishing/adventure/component/ShadedAdventureComponentWrapper.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/adventure/ShadedAdventureComponentWrapper.java index 46e56122..75832f79 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/adventure/component/ShadedAdventureComponentWrapper.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/adventure/ShadedAdventureComponentWrapper.java @@ -4,7 +4,7 @@ * Copyright (c) 2021 NichtStudioCode */ -package net.momirealms.customfishing.adventure.component; +package net.momirealms.customfishing.bukkit.adventure; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; diff --git a/plugin/src/main/java/net/momirealms/customfishing/adventure/component/ShadedAdventureShadedComponentLocalizer.java b/core/src/main/java/net/momirealms/customfishing/bukkit/adventure/ShadedAdventureShadedComponentLocalizer.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/adventure/component/ShadedAdventureShadedComponentLocalizer.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/adventure/ShadedAdventureShadedComponentLocalizer.java index 5fcebf65..89c242ef 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/adventure/component/ShadedAdventureShadedComponentLocalizer.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/adventure/ShadedAdventureShadedComponentLocalizer.java @@ -4,7 +4,7 @@ * Copyright (c) 2021 NichtStudioCode */ -package net.momirealms.customfishing.adventure.component; +package net.momirealms.customfishing.bukkit.adventure; import net.kyori.adventure.text.*; diff --git a/plugin/src/main/java/net/momirealms/customfishing/adventure/component/ShadedComponentLocalizer.java b/core/src/main/java/net/momirealms/customfishing/bukkit/adventure/ShadedComponentLocalizer.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/adventure/component/ShadedComponentLocalizer.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/adventure/ShadedComponentLocalizer.java index 418c7d94..7e125fba 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/adventure/component/ShadedComponentLocalizer.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/adventure/ShadedComponentLocalizer.java @@ -4,7 +4,7 @@ * Copyright (c) 2021 NichtStudioCode */ -package net.momirealms.customfishing.adventure.component; +package net.momirealms.customfishing.bukkit.adventure; import java.util.ArrayList; import java.util.List; diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/IntegrationManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/IntegrationManagerImpl.java similarity index 73% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/IntegrationManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/IntegrationManagerImpl.java index 1879c881..663144dc 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/IntegrationManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/IntegrationManagerImpl.java @@ -15,26 +15,27 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility; +package net.momirealms.customfishing.bukkit.compatibility; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.integration.EnchantmentInterface; -import net.momirealms.customfishing.api.integration.LevelInterface; -import net.momirealms.customfishing.api.integration.SeasonInterface; -import net.momirealms.customfishing.api.manager.IntegrationManager; -import net.momirealms.customfishing.api.util.LogUtils; -import net.momirealms.customfishing.compatibility.block.ItemsAdderBlockImpl; -import net.momirealms.customfishing.compatibility.enchant.AdvancedEnchantmentsImpl; -import net.momirealms.customfishing.compatibility.enchant.VanillaEnchantmentsImpl; -import net.momirealms.customfishing.compatibility.entity.ItemsAdderEntityImpl; -import net.momirealms.customfishing.compatibility.entity.MythicEntityImpl; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; +import net.momirealms.customfishing.api.integration.EnchantmentProvider; +import net.momirealms.customfishing.api.integration.LevelerProvider; +import net.momirealms.customfishing.api.integration.SeasonProvider; +import net.momirealms.customfishing.api.integration.IntegrationManager; +import net.momirealms.customfishing.bukkit.compatibility.block.ItemsAdderBlockImpl; +import net.momirealms.customfishing.bukkit.compatibility.enchant.AdvancedEnchantmentsImpl; +import net.momirealms.customfishing.bukkit.compatibility.enchant.VanillaEnchantmentsImpl; +import net.momirealms.customfishing.bukkit.compatibility.entity.ItemsAdderEntityImpl; +import net.momirealms.customfishing.bukkit.compatibility.entity.MythicEntityImpl; +import net.momirealms.customfishing.bukkit.compatibility.item.*; +import net.momirealms.customfishing.bukkit.compatibility.level.*; +import net.momirealms.customfishing.bukkit.compatibility.quest.BattlePassHook; +import net.momirealms.customfishing.bukkit.compatibility.quest.BetonQuestHook; +import net.momirealms.customfishing.bukkit.compatibility.quest.ClueScrollsHook; +import net.momirealms.customfishing.bukkit.compatibility.season.CustomCropsSeasonImpl; +import net.momirealms.customfishing.bukkit.compatibility.season.RealisticSeasonsImpl; import net.momirealms.customfishing.compatibility.item.*; import net.momirealms.customfishing.compatibility.level.*; -import net.momirealms.customfishing.compatibility.quest.BattlePassHook; -import net.momirealms.customfishing.compatibility.quest.BetonQuestHook; -import net.momirealms.customfishing.compatibility.quest.ClueScrollsHook; -import net.momirealms.customfishing.compatibility.season.CustomCropsSeasonImpl; -import net.momirealms.customfishing.compatibility.season.RealisticSeasonsImpl; import org.bukkit.Bukkit; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.Nullable; @@ -45,12 +46,12 @@ import java.util.List; public class IntegrationManagerImpl implements IntegrationManager { - private final CustomFishingPlugin plugin; - private final HashMap levelPluginMap; - private final HashMap enchantmentPluginMap; - private SeasonInterface seasonInterface; + private final BukkitCustomFishingPlugin plugin; + private final HashMap levelPluginMap; + private final HashMap enchantmentPluginMap; + private SeasonProvider seasonProvider; - public IntegrationManagerImpl(CustomFishingPlugin plugin) { + public IntegrationManagerImpl(BukkitCustomFishingPlugin plugin) { this.plugin = plugin; this.levelPluginMap = new HashMap<>(); this.enchantmentPluginMap = new HashMap<>(); @@ -66,7 +67,7 @@ public class IntegrationManagerImpl implements IntegrationManager { if (Bukkit.getPluginManager().getPlugin("ItemsAdder") != null) { plugin.getItemManager().registerItemLibrary(new ItemsAdderItemImpl()); plugin.getBlockManager().registerBlockLibrary(new ItemsAdderBlockImpl()); - plugin.getEntityManager().registerEntityLibrary(new ItemsAdderEntityImpl()); + plugin.getEntityManager().registerEntityProvider(new ItemsAdderEntityImpl()); hookMessage("ItemsAdder"); } if (Bukkit.getPluginManager().getPlugin("MMOItems") != null) { @@ -87,23 +88,23 @@ public class IntegrationManagerImpl implements IntegrationManager { } if (Bukkit.getPluginManager().getPlugin("MythicMobs") != null) { plugin.getItemManager().registerItemLibrary(new MythicMobsItemImpl()); - plugin.getEntityManager().registerEntityLibrary(new MythicEntityImpl()); + plugin.getEntityManager().registerEntityProvider(new MythicEntityImpl()); hookMessage("MythicMobs"); } if (plugin.isHookedPluginEnabled("EcoJobs")) { - registerLevelPlugin("EcoJobs", new EcoJobsImpl()); + registerLevelerProvider("EcoJobs", new EcoJobsImpl()); hookMessage("EcoJobs"); } if (plugin.isHookedPluginEnabled("EcoSkills")) { - registerLevelPlugin("EcoSkills", new EcoSkillsImpl()); + registerLevelerProvider("EcoSkills", new EcoSkillsImpl()); hookMessage("EcoSkills"); } if (Bukkit.getPluginManager().getPlugin("Jobs") != null) { - registerLevelPlugin("JobsReborn", new JobsRebornImpl()); + registerLevelerProvider("JobsReborn", new JobsRebornImpl()); hookMessage("JobsReborn"); } if (plugin.isHookedPluginEnabled("MMOCore")) { - registerLevelPlugin("MMOCore", new MMOCoreImpl()); + registerLevelerProvider("MMOCore", new MMOCoreImpl()); hookMessage("MMOCore"); } if (plugin.isHookedPluginEnabled("mcMMO")) { @@ -112,15 +113,15 @@ public class IntegrationManagerImpl implements IntegrationManager { } catch (ClassNotFoundException | NoSuchMethodException e) { LogUtils.warn("Failed to initialize mcMMO Treasure"); } - registerLevelPlugin("mcMMO", new McMMOImpl()); + registerLevelerProvider("mcMMO", new McMMOImpl()); hookMessage("mcMMO"); } if (plugin.isHookedPluginEnabled("AureliumSkills")) { - registerLevelPlugin("AureliumSkills", new AureliumSkillsImpl()); + registerLevelerProvider("AureliumSkills", new AureliumSkillsImpl()); hookMessage("AureliumSkills"); } if (plugin.isHookedPluginEnabled("AuraSkills")) { - registerLevelPlugin("AuraSkills", new AuraSkillsImpl()); + registerLevelerProvider("AuraSkills", new AuraSkillsImpl()); hookMessage("AuraSkills"); } if (plugin.isHookedPluginEnabled("EcoEnchants")) { @@ -134,9 +135,9 @@ public class IntegrationManagerImpl implements IntegrationManager { hookMessage("AdvancedEnchantments"); } if (plugin.isHookedPluginEnabled("RealisticSeasons")) { - this.seasonInterface = new RealisticSeasonsImpl(); + this.seasonProvider = new RealisticSeasonsImpl(); } else if (plugin.isHookedPluginEnabled("CustomCrops")) { - this.seasonInterface = new CustomCropsSeasonImpl(); + this.seasonProvider = new CustomCropsSeasonImpl(); } if (plugin.isHookedPluginEnabled("Vault")) { VaultHook.initialize(); @@ -170,7 +171,7 @@ public class IntegrationManagerImpl implements IntegrationManager { * @return true if the registration was successful, false if the plugin name is already registered. */ @Override - public boolean registerLevelPlugin(String plugin, LevelInterface level) { + public boolean registerLevelerProvider(String plugin, LevelerProvider level) { if (levelPluginMap.containsKey(plugin)) return false; levelPluginMap.put(plugin, level); return true; @@ -183,7 +184,7 @@ public class IntegrationManagerImpl implements IntegrationManager { * @return true if the unregistration was successful, false if the plugin name is not found. */ @Override - public boolean unregisterLevelPlugin(String plugin) { + public boolean unregisterLevelerProvider(String plugin) { return levelPluginMap.remove(plugin) != null; } @@ -195,7 +196,7 @@ public class IntegrationManagerImpl implements IntegrationManager { * @return true if the registration was successful, false if the enchantment name is already in use. */ @Override - public boolean registerEnchantment(String plugin, EnchantmentInterface enchantment) { + public boolean registerEnchantment(String plugin, EnchantmentProvider enchantment) { if (enchantmentPluginMap.containsKey(plugin)) return false; enchantmentPluginMap.put(plugin, enchantment); return true; @@ -224,7 +225,7 @@ public class IntegrationManagerImpl implements IntegrationManager { */ @Override @Nullable - public LevelInterface getLevelPlugin(String plugin) { + public LevelerProvider getLevelPlugin(String plugin) { return levelPluginMap.get(plugin); } @@ -236,7 +237,7 @@ public class IntegrationManagerImpl implements IntegrationManager { */ @Override @Nullable - public EnchantmentInterface getEnchantmentPlugin(String plugin) { + public EnchantmentProvider getEnchantmentPlugin(String plugin) { return enchantmentPluginMap.get(plugin); } @@ -249,8 +250,8 @@ public class IntegrationManagerImpl implements IntegrationManager { @Override public List getEnchantments(ItemStack itemStack) { ArrayList list = new ArrayList<>(); - for (EnchantmentInterface enchantmentInterface : enchantmentPluginMap.values()) { - list.addAll(enchantmentInterface.getEnchants(itemStack)); + for (EnchantmentProvider enchantmentProvider : enchantmentPluginMap.values()) { + list.addAll(enchantmentProvider.getEnchants(itemStack)); } return list; } @@ -261,8 +262,8 @@ public class IntegrationManagerImpl implements IntegrationManager { * @return The current season interface, or null if not available. */ @Nullable - public SeasonInterface getSeasonInterface() { - return seasonInterface; + public SeasonProvider getSeasonInterface() { + return seasonProvider; } /** @@ -271,7 +272,7 @@ public class IntegrationManagerImpl implements IntegrationManager { * @param season The season interface to set. */ @Override - public void setSeasonInterface(SeasonInterface season) { - this.seasonInterface = season; + public void setSeasonInterface(SeasonProvider season) { + this.seasonProvider = season; } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/VaultHook.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/VaultHook.java similarity index 79% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/VaultHook.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/VaultHook.java index 14c2e391..2ff27c93 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/VaultHook.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/VaultHook.java @@ -15,10 +15,10 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility; +package net.momirealms.customfishing.bukkit.compatibility; import net.milkbowl.vault.economy.Economy; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import org.bukkit.plugin.RegisteredServiceProvider; public class VaultHook { @@ -26,7 +26,7 @@ public class VaultHook { private static Economy economy; public static boolean initialize() { - RegisteredServiceProvider rsp = CustomFishingPlugin.getInstance().getServer().getServicesManager().getRegistration(Economy.class); + RegisteredServiceProvider rsp = BukkitCustomFishingPlugin.getInstance().getServer().getServicesManager().getRegistration(Economy.class); if (rsp == null) { return false; } diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/block/ItemsAdderBlockImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/block/ItemsAdderBlockImpl.java similarity index 96% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/block/ItemsAdderBlockImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/block/ItemsAdderBlockImpl.java index 43da1177..deb19afb 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/block/ItemsAdderBlockImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/block/ItemsAdderBlockImpl.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.block; +package net.momirealms.customfishing.bukkit.compatibility.block; import dev.lone.itemsadder.api.CustomBlock; import net.momirealms.customfishing.api.mechanic.block.BlockDataModifier; diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/block/VanillaBlockImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/block/VanillaBlockImpl.java similarity index 96% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/block/VanillaBlockImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/block/VanillaBlockImpl.java index 5709759e..30b0418f 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/block/VanillaBlockImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/block/VanillaBlockImpl.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.block; +package net.momirealms.customfishing.bukkit.compatibility.block; import net.momirealms.customfishing.api.mechanic.block.BlockDataModifier; import net.momirealms.customfishing.api.mechanic.block.BlockLibrary; diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/enchant/AdvancedEnchantmentsImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/enchant/AdvancedEnchantmentsImpl.java similarity index 84% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/enchant/AdvancedEnchantmentsImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/enchant/AdvancedEnchantmentsImpl.java index fd5cd1cc..0365c355 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/enchant/AdvancedEnchantmentsImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/enchant/AdvancedEnchantmentsImpl.java @@ -15,17 +15,17 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.enchant; +package net.momirealms.customfishing.bukkit.compatibility.enchant; import net.advancedplugins.ae.api.AEAPI; -import net.momirealms.customfishing.api.integration.EnchantmentInterface; +import net.momirealms.customfishing.api.integration.EnchantmentProvider; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.List; import java.util.Map; -public class AdvancedEnchantmentsImpl implements EnchantmentInterface { +public class AdvancedEnchantmentsImpl implements EnchantmentProvider { @Override public List getEnchants(ItemStack itemStack) { diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/enchant/VanillaEnchantmentsImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/enchant/VanillaEnchantmentsImpl.java similarity index 85% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/enchant/VanillaEnchantmentsImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/enchant/VanillaEnchantmentsImpl.java index 55ad72c8..74318d67 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/enchant/VanillaEnchantmentsImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/enchant/VanillaEnchantmentsImpl.java @@ -15,9 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.enchant; +package net.momirealms.customfishing.bukkit.compatibility.enchant; -import net.momirealms.customfishing.api.integration.EnchantmentInterface; +import net.momirealms.customfishing.api.integration.EnchantmentProvider; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; @@ -25,7 +25,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -public class VanillaEnchantmentsImpl implements EnchantmentInterface { +public class VanillaEnchantmentsImpl implements EnchantmentProvider { @Override public List getEnchants(ItemStack itemStack) { diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/entity/ItemsAdderEntityImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/entity/ItemsAdderEntityImpl.java similarity index 75% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/entity/ItemsAdderEntityImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/entity/ItemsAdderEntityImpl.java index 09f5223c..709a1c9f 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/entity/ItemsAdderEntityImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/entity/ItemsAdderEntityImpl.java @@ -15,24 +15,26 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.entity; +package net.momirealms.customfishing.bukkit.compatibility.entity; import dev.lone.itemsadder.api.CustomEntity; -import net.momirealms.customfishing.api.mechanic.entity.EntityLibrary; +import net.momirealms.customfishing.api.integration.EntityProvider; import org.bukkit.Location; import org.bukkit.entity.Entity; +import org.jetbrains.annotations.NotNull; import java.util.Map; -public class ItemsAdderEntityImpl implements EntityLibrary { +public class ItemsAdderEntityImpl implements EntityProvider { @Override - public String identification() { + public String identifier() { return "vanilla"; } + @NotNull @Override - public Entity spawn(Location location, String id, Map propertyMap) { + public Entity spawn(@NotNull Location location, @NotNull String id, @NotNull Map propertyMap) { CustomEntity customEntity = CustomEntity.spawn( id, location, diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/entity/MythicEntityImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/entity/MythicEntityImpl.java similarity index 83% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/entity/MythicEntityImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/entity/MythicEntityImpl.java index 464864ae..c41da355 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/entity/MythicEntityImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/entity/MythicEntityImpl.java @@ -15,22 +15,23 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.entity; +package net.momirealms.customfishing.bukkit.compatibility.entity; import io.lumine.mythic.api.adapters.AbstractLocation; import io.lumine.mythic.api.mobs.MythicMob; import io.lumine.mythic.bukkit.MythicBukkit; import io.lumine.mythic.bukkit.utils.serialize.Position; import io.lumine.mythic.core.mobs.ActiveMob; -import net.momirealms.customfishing.api.mechanic.entity.EntityLibrary; +import net.momirealms.customfishing.api.integration.EntityProvider; import net.momirealms.customfishing.util.ConfigUtils; import org.bukkit.Location; import org.bukkit.entity.Entity; +import org.jetbrains.annotations.NotNull; import java.util.Map; import java.util.Optional; -public class MythicEntityImpl implements EntityLibrary { +public class MythicEntityImpl implements EntityProvider { private MythicBukkit mythicBukkit; @@ -39,12 +40,13 @@ public class MythicEntityImpl implements EntityLibrary { } @Override - public String identification() { + public String identifier() { return "MythicMobs"; } + @NotNull @Override - public Entity spawn(Location location, String id, Map propertyMap) { + public Entity spawn(@NotNull Location location, @NotNull String id, @NotNull Map propertyMap) { if (this.mythicBukkit == null || mythicBukkit.isClosed()) { this.mythicBukkit = MythicBukkit.inst(); } diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/entity/VanillaEntityImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/entity/VanillaEntityImpl.java similarity index 71% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/entity/VanillaEntityImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/entity/VanillaEntityImpl.java index da5e9139..64886cfc 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/entity/VanillaEntityImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/entity/VanillaEntityImpl.java @@ -15,25 +15,27 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.entity; +package net.momirealms.customfishing.bukkit.compatibility.entity; -import net.momirealms.customfishing.api.mechanic.entity.EntityLibrary; +import net.momirealms.customfishing.api.integration.EntityProvider; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; +import org.jetbrains.annotations.NotNull; import java.util.Locale; import java.util.Map; -public class VanillaEntityImpl implements EntityLibrary { +public class VanillaEntityImpl implements EntityProvider { @Override - public String identification() { + public String identifier() { return "vanilla"; } + @NotNull @Override - public Entity spawn(Location location, String id, Map propertyMap) { + public Entity spawn(@NotNull Location location, @NotNull String id, @NotNull Map propertyMap) { return location.getWorld().spawnEntity(location, EntityType.valueOf(id.toUpperCase(Locale.ENGLISH))); } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/CustomFishingItemImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/CustomFishingItemImpl.java similarity index 64% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/item/CustomFishingItemImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/CustomFishingItemImpl.java index a754e006..c27817b1 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/CustomFishingItemImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/CustomFishingItemImpl.java @@ -15,28 +15,30 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.item; +package net.momirealms.customfishing.bukkit.compatibility.item; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.mechanic.item.ItemLibrary; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; +import net.momirealms.customfishing.api.integration.ItemProvider; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -public class CustomFishingItemImpl implements ItemLibrary { +public class CustomFishingItemImpl implements ItemProvider { @Override public String identification() { return "CustomFishing"; } + @NotNull @Override public ItemStack buildItem(Player player, String id) { String[] split = id.split(":", 2); - return CustomFishingPlugin.get().getItemManager().build(player, split[0], split[1]); + return BukkitCustomFishingPlugin.get().getItemManager().build(player, split[0], split[1]); } @Override - public String getItemID(ItemStack itemStack) { - return CustomFishingPlugin.get().getItemManager().getCustomFishingItemID(itemStack); + public String itemID(ItemStack itemStack) { + return BukkitCustomFishingPlugin.get().getItemManager().getCustomFishingItemID(itemStack); } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/ItemsAdderItemImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/ItemsAdderItemImpl.java similarity index 82% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/item/ItemsAdderItemImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/ItemsAdderItemImpl.java index 773910ea..1e1e7a7d 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/ItemsAdderItemImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/ItemsAdderItemImpl.java @@ -15,21 +15,22 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.item; +package net.momirealms.customfishing.bukkit.compatibility.item; import dev.lone.itemsadder.api.CustomStack; -import net.momirealms.customfishing.api.mechanic.item.ItemLibrary; -import net.momirealms.customfishing.api.util.LogUtils; +import net.momirealms.customfishing.api.integration.ItemProvider; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -public class ItemsAdderItemImpl implements ItemLibrary { +public class ItemsAdderItemImpl implements ItemProvider { @Override public String identification() { return "ItemsAdder"; } + @NotNull @Override public ItemStack buildItem(Player player, String id) { CustomStack stack = CustomStack.getInstance(id); @@ -41,7 +42,7 @@ public class ItemsAdderItemImpl implements ItemLibrary { } @Override - public String getItemID(ItemStack itemStack) { + public String itemID(ItemStack itemStack) { CustomStack customStack = CustomStack.byItemStack(itemStack); if (customStack == null) return null; return customStack.getNamespacedID(); diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/MMOItemsItemImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/MMOItemsItemImpl.java similarity index 79% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/item/MMOItemsItemImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/MMOItemsItemImpl.java index 1cf8409a..22021dc9 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/MMOItemsItemImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/MMOItemsItemImpl.java @@ -15,26 +15,28 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.item; +package net.momirealms.customfishing.bukkit.compatibility.item; -import de.tr7zw.changeme.nbtapi.NBTItem; +import io.lumine.mythic.lib.api.item.NBTItem; import net.Indyuce.mmoitems.MMOItems; import net.Indyuce.mmoitems.api.Type; import net.Indyuce.mmoitems.api.item.mmoitem.MMOItem; -import net.momirealms.customfishing.api.mechanic.item.ItemLibrary; +import net.momirealms.customfishing.api.integration.ItemProvider; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; import java.util.Locale; -public class MMOItemsItemImpl implements ItemLibrary { +public class MMOItemsItemImpl implements ItemProvider { @Override public String identification() { return "MMOItems"; } + @NotNull @Override public ItemStack buildItem(Player player, String id) { String[] split = id.split(":"); @@ -43,8 +45,8 @@ public class MMOItemsItemImpl implements ItemLibrary { } @Override - public String getItemID(ItemStack itemStack) { - NBTItem nbtItem = new NBTItem(itemStack); + public String itemID(ItemStack itemStack) { + NBTItem nbtItem = NBTItem.get(itemStack); if (!nbtItem.hasTag("MMOITEMS_ITEM_ID")) return null; return nbtItem.getString("MMOITEMS_ITEM_ID"); } diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/McMMOTreasureImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/McMMOTreasureImpl.java similarity index 91% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/item/McMMOTreasureImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/McMMOTreasureImpl.java index 6ca323b7..7d875b8c 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/McMMOTreasureImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/McMMOTreasureImpl.java @@ -15,17 +15,18 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.item; +package net.momirealms.customfishing.bukkit.compatibility.item; -import net.momirealms.customfishing.api.mechanic.item.ItemLibrary; +import net.momirealms.customfishing.api.integration.ItemProvider; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -public class McMMOTreasureImpl implements ItemLibrary { +public class McMMOTreasureImpl implements ItemProvider { private final Method getMcMMOPlayerMethod; private final Method getFishingManagerMethod; @@ -49,6 +50,7 @@ public class McMMOTreasureImpl implements ItemLibrary { return "mcMMO"; } + @NotNull @Override public ItemStack buildItem(Player player, String id) { if (!id.equals("treasure")) return new ItemStack(Material.AIR); @@ -72,7 +74,7 @@ public class McMMOTreasureImpl implements ItemLibrary { } @Override - public String getItemID(ItemStack itemStack) { + public String itemID(ItemStack itemStack) { return null; } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/MythicMobsItemImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/MythicMobsItemImpl.java similarity index 72% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/item/MythicMobsItemImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/MythicMobsItemImpl.java index 28a45b51..60432136 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/MythicMobsItemImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/MythicMobsItemImpl.java @@ -15,15 +15,15 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.item; +package net.momirealms.customfishing.bukkit.compatibility.item; -import de.tr7zw.changeme.nbtapi.NBTItem; import io.lumine.mythic.bukkit.MythicBukkit; -import net.momirealms.customfishing.api.mechanic.item.ItemLibrary; +import net.momirealms.customfishing.api.integration.ItemProvider; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -public class MythicMobsItemImpl implements ItemLibrary { +public class MythicMobsItemImpl implements ItemProvider { private MythicBukkit mythicBukkit; @@ -36,6 +36,7 @@ public class MythicMobsItemImpl implements ItemLibrary { return "MythicMobs"; } + @NotNull @Override public ItemStack buildItem(Player player, String id) { if (mythicBukkit == null || mythicBukkit.isClosed()) { @@ -45,8 +46,10 @@ public class MythicMobsItemImpl implements ItemLibrary { } @Override - public String getItemID(ItemStack itemStack) { - NBTItem nbtItem = new NBTItem(itemStack); - return nbtItem.hasTag("MYTHIC_TYPE") ? nbtItem.getString("MYTHIC_TYPE") : null; + public String itemID(ItemStack itemStack) { + if (mythicBukkit == null || mythicBukkit.isClosed()) { + this.mythicBukkit = MythicBukkit.inst(); + } + return mythicBukkit.getItemManager().getMythicTypeFromItem(itemStack); } } \ No newline at end of file diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/NeigeItemsItemImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/NeigeItemsItemImpl.java similarity index 81% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/item/NeigeItemsItemImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/NeigeItemsItemImpl.java index 43047613..b6914e90 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/NeigeItemsItemImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/NeigeItemsItemImpl.java @@ -15,29 +15,31 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.item; +package net.momirealms.customfishing.bukkit.compatibility.item; -import net.momirealms.customfishing.api.mechanic.item.ItemLibrary; +import net.momirealms.customfishing.api.integration.ItemProvider; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; import pers.neige.neigeitems.item.ItemInfo; import pers.neige.neigeitems.manager.ItemManager; import pers.neige.neigeitems.utils.ItemUtils; -public class NeigeItemsItemImpl implements ItemLibrary { +public class NeigeItemsItemImpl implements ItemProvider { @Override public String identification() { return "NeigeItems"; } + @NotNull @Override public ItemStack buildItem(Player player, String id) { return ItemManager.INSTANCE.getItemStack(id, player); } @Override - public String getItemID(ItemStack itemStack) { + public String itemID(ItemStack itemStack) { ItemInfo itemInfo = ItemUtils.isNiItem(itemStack); if (itemInfo != null) { return itemInfo.getId(); diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/OraxenItemImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/OraxenItemImpl.java similarity index 81% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/item/OraxenItemImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/OraxenItemImpl.java index 85dd40b5..d42bc7ab 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/OraxenItemImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/OraxenItemImpl.java @@ -15,22 +15,24 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.item; +package net.momirealms.customfishing.bukkit.compatibility.item; import io.th0rgal.oraxen.api.OraxenItems; import io.th0rgal.oraxen.items.ItemBuilder; -import net.momirealms.customfishing.api.mechanic.item.ItemLibrary; +import net.momirealms.customfishing.api.integration.ItemProvider; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -public class OraxenItemImpl implements ItemLibrary { +public class OraxenItemImpl implements ItemProvider { @Override public String identification() { return "Oraxen"; } + @NotNull @Override public ItemStack buildItem(Player player, String id) { ItemBuilder itemBuilder = OraxenItems.getItemById(id); @@ -38,7 +40,7 @@ public class OraxenItemImpl implements ItemLibrary { } @Override - public String getItemID(ItemStack itemStack) { + public String itemID(ItemStack itemStack) { return OraxenItems.getIdByItem(itemStack); } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/VanillaItemImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/VanillaItemImpl.java similarity index 79% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/item/VanillaItemImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/VanillaItemImpl.java index d502b47a..1e23136e 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/VanillaItemImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/VanillaItemImpl.java @@ -15,29 +15,31 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.item; +package net.momirealms.customfishing.bukkit.compatibility.item; -import net.momirealms.customfishing.api.mechanic.item.ItemLibrary; +import net.momirealms.customfishing.api.integration.ItemProvider; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; import java.util.Locale; -public class VanillaItemImpl implements ItemLibrary { +public class VanillaItemImpl implements ItemProvider { @Override public String identification() { return "vanilla"; } + @NotNull @Override public ItemStack buildItem(Player player, String id) { return new ItemStack(Material.valueOf(id.toUpperCase(Locale.ENGLISH))); } @Override - public String getItemID(ItemStack itemStack) { + public String itemID(ItemStack itemStack) { return itemStack.getType().name(); } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/ZaphkielItemImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/ZaphkielItemImpl.java similarity index 82% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/item/ZaphkielItemImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/ZaphkielItemImpl.java index d1dc0129..932ae641 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/item/ZaphkielItemImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/item/ZaphkielItemImpl.java @@ -15,16 +15,17 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.item; +package net.momirealms.customfishing.bukkit.compatibility.item; import ink.ptms.zaphkiel.ZapAPI; import ink.ptms.zaphkiel.Zaphkiel; -import net.momirealms.customfishing.api.mechanic.item.ItemLibrary; +import net.momirealms.customfishing.api.integration.ItemProvider; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -public class ZaphkielItemImpl implements ItemLibrary { +public class ZaphkielItemImpl implements ItemProvider { private final ZapAPI zapAPI; @@ -37,13 +38,14 @@ public class ZaphkielItemImpl implements ItemLibrary { return "Zaphkiel"; } + @NotNull @Override public ItemStack buildItem(Player player, String id) { return zapAPI.getItemManager().generateItemStack(id, player); } @Override - public String getItemID(ItemStack itemStack) { + public String itemID(ItemStack itemStack) { if (itemStack == null || itemStack.getType() == Material.AIR) return null; return zapAPI.getItemHandler().getItemId(itemStack); } diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/level/AuraSkillsImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/AuraSkillsImpl.java similarity index 87% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/level/AuraSkillsImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/AuraSkillsImpl.java index 70847a40..f6eedbc0 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/level/AuraSkillsImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/AuraSkillsImpl.java @@ -15,14 +15,14 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.level; +package net.momirealms.customfishing.bukkit.compatibility.level; import dev.aurelium.auraskills.api.AuraSkillsApi; import dev.aurelium.auraskills.api.registry.NamespacedId; -import net.momirealms.customfishing.api.integration.LevelInterface; +import net.momirealms.customfishing.api.integration.LevelerProvider; import org.bukkit.entity.Player; -public class AuraSkillsImpl implements LevelInterface { +public class AuraSkillsImpl implements LevelerProvider { @Override public void addXp(Player player, String target, double amount) { diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/level/AureliumSkillsImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/AureliumSkillsImpl.java similarity index 87% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/level/AureliumSkillsImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/AureliumSkillsImpl.java index cb25cee6..c846d29c 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/level/AureliumSkillsImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/AureliumSkillsImpl.java @@ -15,14 +15,14 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.level; +package net.momirealms.customfishing.bukkit.compatibility.level; import com.archyx.aureliumskills.api.AureliumAPI; import com.archyx.aureliumskills.leveler.Leveler; -import net.momirealms.customfishing.api.integration.LevelInterface; +import net.momirealms.customfishing.api.integration.LevelerProvider; import org.bukkit.entity.Player; -public class AureliumSkillsImpl implements LevelInterface { +public class AureliumSkillsImpl implements LevelerProvider { private final Leveler leveler; diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/level/EcoJobsImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/EcoJobsImpl.java similarity index 87% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/level/EcoJobsImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/EcoJobsImpl.java index fb0f8308..bbf203cd 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/level/EcoJobsImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/EcoJobsImpl.java @@ -15,15 +15,15 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.level; +package net.momirealms.customfishing.bukkit.compatibility.level; import com.willfp.ecojobs.api.EcoJobsAPI; import com.willfp.ecojobs.jobs.Job; import com.willfp.ecojobs.jobs.Jobs; -import net.momirealms.customfishing.api.integration.LevelInterface; +import net.momirealms.customfishing.api.integration.LevelerProvider; import org.bukkit.entity.Player; -public class EcoJobsImpl implements LevelInterface { +public class EcoJobsImpl implements LevelerProvider { @Override public void addXp(Player player, String target, double amount) { diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/level/EcoSkillsImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/EcoSkillsImpl.java similarity index 86% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/level/EcoSkillsImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/EcoSkillsImpl.java index 01dc15f7..9fffce2d 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/level/EcoSkillsImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/EcoSkillsImpl.java @@ -15,16 +15,16 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.level; +package net.momirealms.customfishing.bukkit.compatibility.level; import com.willfp.ecoskills.api.EcoSkillsAPI; import com.willfp.ecoskills.skills.Skills; -import net.momirealms.customfishing.api.integration.LevelInterface; +import net.momirealms.customfishing.api.integration.LevelerProvider; import org.bukkit.entity.Player; import java.util.Objects; -public class EcoSkillsImpl implements LevelInterface { +public class EcoSkillsImpl implements LevelerProvider { @Override public void addXp(Player player, String target, double amount) { diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/level/JobsRebornImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/JobsRebornImpl.java similarity index 90% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/level/JobsRebornImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/JobsRebornImpl.java index 0302b1a5..c6362346 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/level/JobsRebornImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/JobsRebornImpl.java @@ -15,18 +15,18 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.level; +package net.momirealms.customfishing.bukkit.compatibility.level; import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.container.Job; import com.gamingmesh.jobs.container.JobProgression; import com.gamingmesh.jobs.container.JobsPlayer; -import net.momirealms.customfishing.api.integration.LevelInterface; +import net.momirealms.customfishing.api.integration.LevelerProvider; import org.bukkit.entity.Player; import java.util.List; -public class JobsRebornImpl implements LevelInterface { +public class JobsRebornImpl implements LevelerProvider { @Override public void addXp(Player player, String target, double amount) { diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/level/MMOCoreImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/MMOCoreImpl.java similarity index 87% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/level/MMOCoreImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/MMOCoreImpl.java index 2c0691c5..30d904c8 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/level/MMOCoreImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/MMOCoreImpl.java @@ -15,15 +15,15 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.level; +package net.momirealms.customfishing.bukkit.compatibility.level; import net.Indyuce.mmocore.MMOCore; import net.Indyuce.mmocore.api.player.PlayerData; import net.Indyuce.mmocore.experience.EXPSource; -import net.momirealms.customfishing.api.integration.LevelInterface; +import net.momirealms.customfishing.api.integration.LevelerProvider; import org.bukkit.entity.Player; -public class MMOCoreImpl implements LevelInterface { +public class MMOCoreImpl implements LevelerProvider { @Override public void addXp(Player player, String target, double amount) { diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/level/McMMOImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/McMMOImpl.java similarity index 86% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/level/McMMOImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/McMMOImpl.java index 41ec39f0..d095ce7f 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/level/McMMOImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/level/McMMOImpl.java @@ -15,14 +15,14 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.level; +package net.momirealms.customfishing.bukkit.compatibility.level; import com.gmail.nossr50.api.ExperienceAPI; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; -import net.momirealms.customfishing.api.integration.LevelInterface; +import net.momirealms.customfishing.api.integration.LevelerProvider; import org.bukkit.entity.Player; -public class McMMOImpl implements LevelInterface { +public class McMMOImpl implements LevelerProvider { @Override public void addXp(Player player, String target, double amount) { diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/papi/CFPapi.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/papi/CFPapi.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/papi/CFPapi.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/papi/CFPapi.java index d57d56e6..5e204bf8 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/papi/CFPapi.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/papi/CFPapi.java @@ -15,10 +15,10 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.papi; +package net.momirealms.customfishing.bukkit.compatibility.papi; import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.user.OnlineUser; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; @@ -28,9 +28,9 @@ import org.jetbrains.annotations.Nullable; public class CFPapi extends PlaceholderExpansion { - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; - public CFPapi(CustomFishingPlugin plugin) { + public CFPapi(BukkitCustomFishingPlugin plugin) { this.plugin = plugin; } diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/papi/CompetitionPapi.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/papi/CompetitionPapi.java similarity index 95% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/papi/CompetitionPapi.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/papi/CompetitionPapi.java index c68b2492..4a90fd9d 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/papi/CompetitionPapi.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/papi/CompetitionPapi.java @@ -15,10 +15,10 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.papi; +package net.momirealms.customfishing.bukkit.compatibility.papi; import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.mechanic.competition.FishingCompetition; import net.momirealms.customfishing.setting.CFLocale; import org.bukkit.OfflinePlayer; @@ -29,9 +29,9 @@ import java.util.Optional; public class CompetitionPapi extends PlaceholderExpansion { - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; - public CompetitionPapi(CustomFishingPlugin plugin) { + public CompetitionPapi(BukkitCustomFishingPlugin plugin) { this.plugin = plugin; } diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/papi/ParseUtils.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/papi/ParseUtils.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/papi/ParseUtils.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/papi/ParseUtils.java index 3791dab0..b71dc732 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/papi/ParseUtils.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/papi/ParseUtils.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.papi; +package net.momirealms.customfishing.bukkit.compatibility.papi; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.OfflinePlayer; diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/papi/PlaceholderManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/papi/PlaceholderManagerImpl.java similarity index 96% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/papi/PlaceholderManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/papi/PlaceholderManagerImpl.java index 79f5ef63..eb4553e6 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/papi/PlaceholderManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/papi/PlaceholderManagerImpl.java @@ -15,9 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.papi; +package net.momirealms.customfishing.bukkit.compatibility.papi; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.manager.PlaceholderManager; import net.momirealms.customfishing.util.ConfigUtils; import net.objecthunter.exp4j.ExpressionBuilder; @@ -39,7 +39,7 @@ import java.util.stream.Collectors; public class PlaceholderManagerImpl implements PlaceholderManager { private static PlaceholderManagerImpl instance; - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; private final boolean hasPapi; private final Pattern pattern; private final HashMap customPlaceholderMap; @@ -47,7 +47,7 @@ public class PlaceholderManagerImpl implements PlaceholderManager { private StatisticsPapi statisticsPapi; private CFPapi cfPapi; - public PlaceholderManagerImpl(CustomFishingPlugin plugin) { + public PlaceholderManagerImpl(BukkitCustomFishingPlugin plugin) { instance = this; this.plugin = plugin; this.hasPapi = Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI"); diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/papi/StatisticsPapi.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/papi/StatisticsPapi.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/papi/StatisticsPapi.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/papi/StatisticsPapi.java index f313ad0e..a8803583 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/papi/StatisticsPapi.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/papi/StatisticsPapi.java @@ -15,10 +15,10 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.papi; +package net.momirealms.customfishing.bukkit.compatibility.papi; import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.user.OnlineUser; import net.momirealms.customfishing.api.mechanic.statistic.Statistics; import org.bukkit.OfflinePlayer; @@ -29,9 +29,9 @@ import java.util.List; public class StatisticsPapi extends PlaceholderExpansion { - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; - public StatisticsPapi(CustomFishingPlugin plugin) { + public StatisticsPapi(BukkitCustomFishingPlugin plugin) { this.plugin = plugin; } diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/quest/BattlePassHook.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/quest/BattlePassHook.java similarity index 92% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/quest/BattlePassHook.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/quest/BattlePassHook.java index 2983460d..80a8821f 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/quest/BattlePassHook.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/quest/BattlePassHook.java @@ -15,13 +15,13 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.quest; +package net.momirealms.customfishing.bukkit.compatibility.quest; import io.github.battlepass.BattlePlugin; import io.github.battlepass.api.events.server.PluginReloadEvent; import net.advancedplugins.bp.impl.actions.ActionRegistry; import net.advancedplugins.bp.impl.actions.external.executor.ActionQuestExecutor; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.event.FishingResultEvent; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -32,7 +32,7 @@ import org.bukkit.plugin.java.JavaPlugin; public class BattlePassHook implements Listener { public BattlePassHook() { - Bukkit.getPluginManager().registerEvents(this, CustomFishingPlugin.get()); + Bukkit.getPluginManager().registerEvents(this, BukkitCustomFishingPlugin.get()); } public void register() { diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/quest/BetonQuestHook.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/quest/BetonQuestHook.java similarity index 98% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/quest/BetonQuestHook.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/quest/BetonQuestHook.java index 15fc7859..8f1f5af5 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/quest/BetonQuestHook.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/quest/BetonQuestHook.java @@ -15,10 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.quest; +package net.momirealms.customfishing.bukkit.compatibility.quest; import net.momirealms.customfishing.api.event.FishingResultEvent; -import net.momirealms.customfishing.api.util.LogUtils; import org.betonquest.betonquest.BetonQuest; import org.betonquest.betonquest.Instruction; import org.betonquest.betonquest.VariableNumber; diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/quest/ClueScrollsHook.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/quest/ClueScrollsHook.java similarity index 84% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/quest/ClueScrollsHook.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/quest/ClueScrollsHook.java index eb328635..a8d97aff 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/quest/ClueScrollsHook.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/quest/ClueScrollsHook.java @@ -15,10 +15,10 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.quest; +package net.momirealms.customfishing.bukkit.compatibility.quest; import com.electro2560.dev.cluescrolls.api.*; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.event.FishingResultEvent; import net.momirealms.customfishing.api.mechanic.loot.Loot; import org.bukkit.Bukkit; @@ -32,12 +32,12 @@ public class ClueScrollsHook implements Listener { private final CustomClue groupClue; public ClueScrollsHook() { - idClue = ClueScrollsAPI.getInstance().registerCustomClue(CustomFishingPlugin.getInstance(), "loot", new ClueConfigData("id", DataType.STRING)); - groupClue = ClueScrollsAPI.getInstance().registerCustomClue(CustomFishingPlugin.getInstance(), "group", new ClueConfigData("group", DataType.STRING)); + idClue = ClueScrollsAPI.getInstance().registerCustomClue(BukkitCustomFishingPlugin.getInstance(), "loot", new ClueConfigData("id", DataType.STRING)); + groupClue = ClueScrollsAPI.getInstance().registerCustomClue(BukkitCustomFishingPlugin.getInstance(), "group", new ClueConfigData("group", DataType.STRING)); } public void register() { - Bukkit.getPluginManager().registerEvents(this, CustomFishingPlugin.get()); + Bukkit.getPluginManager().registerEvents(this, BukkitCustomFishingPlugin.get()); } @EventHandler diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/quest/NotQuestHook.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/quest/NotQuestHook.java similarity index 96% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/quest/NotQuestHook.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/quest/NotQuestHook.java index aec0f0c1..14d1734d 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/quest/NotQuestHook.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/quest/NotQuestHook.java @@ -15,9 +15,9 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.quest; +package net.momirealms.customfishing.bukkit.compatibility.quest; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.event.FishingResultEvent; import net.momirealms.customfishing.api.mechanic.loot.Loot; import org.bukkit.Bukkit; @@ -79,7 +79,7 @@ public class NotQuestHook implements Listener { } public void register() { - Bukkit.getPluginManager().registerEvents(this, CustomFishingPlugin.get()); + Bukkit.getPluginManager().registerEvents(this, BukkitCustomFishingPlugin.get()); notQuestsInstance.getObjectiveManager().registerObjective("CustomFishingGroup", GroupObjective.class); notQuestsInstance.getObjectiveManager().registerObjective("CustomFishingGroup", GroupObjective.class); } diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/season/CustomCropsSeasonImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/season/CustomCropsSeasonImpl.java similarity index 85% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/season/CustomCropsSeasonImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/season/CustomCropsSeasonImpl.java index 837db4d7..a799e273 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/season/CustomCropsSeasonImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/season/CustomCropsSeasonImpl.java @@ -15,17 +15,17 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.season; +package net.momirealms.customfishing.bukkit.compatibility.season; import net.momirealms.customcrops.api.CustomCropsPlugin; import net.momirealms.customcrops.api.mechanic.world.season.Season; -import net.momirealms.customfishing.api.integration.SeasonInterface; +import net.momirealms.customfishing.api.integration.SeasonProvider; import org.bukkit.World; import org.jetbrains.annotations.NotNull; import java.util.Locale; -public class CustomCropsSeasonImpl implements SeasonInterface { +public class CustomCropsSeasonImpl implements SeasonProvider { @NotNull @Override diff --git a/plugin/src/main/java/net/momirealms/customfishing/compatibility/season/RealisticSeasonsImpl.java b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/season/RealisticSeasonsImpl.java similarity index 85% rename from plugin/src/main/java/net/momirealms/customfishing/compatibility/season/RealisticSeasonsImpl.java rename to core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/season/RealisticSeasonsImpl.java index f0999f1f..620e9795 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/compatibility/season/RealisticSeasonsImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/compatibility/season/RealisticSeasonsImpl.java @@ -15,14 +15,14 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.compatibility.season; +package net.momirealms.customfishing.bukkit.compatibility.season; import me.casperge.realisticseasons.api.SeasonsAPI; -import net.momirealms.customfishing.api.integration.SeasonInterface; +import net.momirealms.customfishing.api.integration.SeasonProvider; import org.bukkit.World; import org.jetbrains.annotations.NotNull; -public class RealisticSeasonsImpl implements SeasonInterface { +public class RealisticSeasonsImpl implements SeasonProvider { @NotNull @Override diff --git a/core/src/main/java/net/momirealms/customfishing/bukkit/item/BukkitItemFactory.java b/core/src/main/java/net/momirealms/customfishing/bukkit/item/BukkitItemFactory.java new file mode 100644 index 00000000..e8a3877a --- /dev/null +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/item/BukkitItemFactory.java @@ -0,0 +1,70 @@ +package net.momirealms.customfishing.bukkit.item; + +import com.saicone.rtag.RtagItem; +import net.momirealms.customfishing.bukkit.item.impl.ComponentItemFactory; +import net.momirealms.customfishing.bukkit.item.impl.UniversalItemFactory; +import net.momirealms.customfishing.common.item.Item; +import net.momirealms.customfishing.common.item.ItemFactory; +import net.momirealms.customfishing.common.plugin.CustomFishingPlugin; +import org.bukkit.inventory.ItemStack; + +import java.util.Objects; +import java.util.Optional; + +public abstract class BukkitItemFactory extends ItemFactory { + + protected BukkitItemFactory(CustomFishingPlugin plugin) { + super(plugin); + } + + public static BukkitItemFactory create(CustomFishingPlugin plugin) { + Objects.requireNonNull(plugin, "plugin"); + switch (plugin.getServerVersion()) { + case "1.17", "1.17.1", + "1.18", "1.18.1", "1.18.2", + "1.19", "1.19.1", "1.19.2", "1.19.3", "1.19.4", + "1.20", "1.20.1", "1.20.2", "1.20.3", "1.20.4" -> { + return new UniversalItemFactory(plugin); + } + case "1.20.5", "1.20.6" -> { + return new ComponentItemFactory(plugin); + } + default -> throw new IllegalStateException("Unsupported server version: " + plugin.getServerVersion()); + } + } + + public Item wrap(ItemStack item) { + Objects.requireNonNull(item, "item"); + return wrap(new RtagItem(item)); + } + + @Override + protected void setTag(RtagItem item, Object value, Object... path) { + item.set(value, path); + } + + @Override + protected Optional getTag(RtagItem item, Object... path) { + return Optional.ofNullable(item.get(path)); + } + + @Override + protected void update(RtagItem item) { + item.update(); + } + + @Override + protected ItemStack load(RtagItem item) { + return item.load(); + } + + @Override + protected ItemStack getItem(RtagItem item) { + return item.getItem(); + } + + @Override + protected ItemStack loadCopy(RtagItem item) { + return item.loadCopy(); + } +} diff --git a/core/src/main/java/net/momirealms/customfishing/bukkit/item/BukkitItemManager.java b/core/src/main/java/net/momirealms/customfishing/bukkit/item/BukkitItemManager.java new file mode 100644 index 00000000..9dbae893 --- /dev/null +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/item/BukkitItemManager.java @@ -0,0 +1,89 @@ +package net.momirealms.customfishing.bukkit.item; + +import dev.dejvokep.boostedyaml.block.implementation.Section; +import net.kyori.adventure.key.Key; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; +import net.momirealms.customfishing.api.integration.ItemProvider; +import net.momirealms.customfishing.api.mechanic.context.Context; +import net.momirealms.customfishing.api.mechanic.item.CustomFishingItem; +import net.momirealms.customfishing.api.mechanic.item.ItemManager; +import net.momirealms.customfishing.api.mechanic.misc.function.FormatFunction; +import net.momirealms.customfishing.api.mechanic.misc.function.ItemPropertyFunction; +import net.momirealms.customfishing.api.mechanic.misc.value.MathValue; +import net.momirealms.customfishing.api.mechanic.misc.value.TextValue; +import net.momirealms.customfishing.common.config.node.Node; +import net.momirealms.customfishing.common.item.Item; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.function.Function; + +import static java.util.Objects.requireNonNull; + +public class BukkitItemManager implements ItemManager { + + private final BukkitCustomFishingPlugin plugin; + private final HashMap itemProviders = new HashMap<>(); + private final HashMap itemMap = new HashMap<>(); + private final BukkitItemFactory factory; + + public BukkitItemManager(BukkitCustomFishingPlugin plugin) { + this.plugin = plugin; + this.factory = BukkitItemFactory.create(plugin); + this.registerVanilla(); + } + + private void registerVanilla() { + this.itemProviders.put("vanilla", new ItemProvider() { + @NotNull + @Override + public ItemStack buildItem(Player player, String id) { + return new ItemStack(Material.valueOf(id.toUpperCase(Locale.ENGLISH))); + } + @NotNull + @Override + public String itemID(ItemStack itemStack) { + return itemStack.getType().name(); + } + @Override + public String identifier() { + return "vanilla"; + } + }); + } + + @Nullable + @Override + public ItemStack build(Context context, Key key) { + CustomFishingItem item = requireNonNull(itemMap.get(key), () -> "No item found for " + key); + ItemStack itemStack = getOriginalStack(context.getHolder(), item.material()); + Item wrappedItemStack = factory.wrap(itemStack); + for (BiConsumer, Context> consumer : item.tagConsumers()) { + consumer.accept(wrappedItemStack, context); + } + return wrappedItemStack.getItem(); + } + + private ItemStack getOriginalStack(Player player, String material) { + if (material.contains(":")) { + try { + return new ItemStack(Material.valueOf(material.toUpperCase(Locale.ENGLISH))); + } catch (IllegalArgumentException e) { + plugin.getPluginLogger().severe("material " + material + " not exists", e); + return new ItemStack(Material.PAPER); + } + } else { + String[] split = material.split(":", 2); + ItemProvider provider = requireNonNull(itemProviders.get(split[0]), "item provider " + split[0] + " not found"); + return requireNonNull(provider.buildItem(player, split[0]), "item " + split[0] + " not found"); + } + } +} diff --git a/core/src/main/java/net/momirealms/customfishing/bukkit/item/impl/ComponentItemFactory.java b/core/src/main/java/net/momirealms/customfishing/bukkit/item/impl/ComponentItemFactory.java new file mode 100644 index 00000000..52da5113 --- /dev/null +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/item/impl/ComponentItemFactory.java @@ -0,0 +1,113 @@ +package net.momirealms.customfishing.bukkit.item.impl; + +import com.saicone.rtag.RtagItem; +import com.saicone.rtag.data.ComponentType; +import net.momirealms.customfishing.bukkit.item.BukkitItemFactory; +import net.momirealms.customfishing.common.item.ComponentKeys; +import net.momirealms.customfishing.common.plugin.CustomFishingPlugin; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@SuppressWarnings("UnstableApiUsage") +public class ComponentItemFactory extends BukkitItemFactory { + + public ComponentItemFactory(CustomFishingPlugin plugin) { + super(plugin); + } + + @Override + protected void customModelData(RtagItem item, Integer data) { + if (data == null) { + item.removeComponent(ComponentKeys.CUSTOM_MODEL_DATA); + } else { + item.setComponent(ComponentKeys.CUSTOM_MODEL_DATA, data); + } + } + + @Override + protected Optional customModelData(RtagItem item) { + if (!item.hasComponent(ComponentKeys.CUSTOM_MODEL_DATA)) return Optional.empty(); + return Optional.ofNullable( + (Integer) ComponentType.encodeJava( + ComponentKeys.CUSTOM_MODEL_DATA, + item.getComponent(ComponentKeys.CUSTOM_MODEL_DATA) + ).orElse(null) + ); + } + + @Override + protected void displayName(RtagItem item, String json) { + if (json == null) { + item.removeComponent(ComponentKeys.CUSTOM_NAME); + } else { + item.setComponent(ComponentKeys.CUSTOM_NAME, json); + } + } + + @Override + protected Optional displayName(RtagItem item) { + if (item.getComponent(ComponentKeys.CUSTOM_NAME) == null) return Optional.empty(); + return Optional.ofNullable( + (String) ComponentType.encodeJava( + ComponentKeys.CUSTOM_NAME, + item.getComponent(ComponentKeys.CUSTOM_NAME) + ).orElse(null) + ); + } + + @Override + protected void skull(RtagItem item, String skullData) { + final Map profile = Map.of( + "properties", List.of( + Map.of( + "name", "textures", + "value", skullData + ) + ) + ); + item.setComponent("minecraft:profile", profile); + } + + @SuppressWarnings("unchecked") + @Override + protected Optional> lore(RtagItem item) { + if (item.getComponent(ComponentKeys.LORE) == null) return Optional.empty(); + return Optional.ofNullable( + (List) ComponentType.encodeJava( + ComponentKeys.LORE, + item.getComponent(ComponentKeys.LORE) + ).orElse(null) + ); + } + + @Override + protected void lore(RtagItem item, List lore) { + if (lore == null || lore.isEmpty()) { + item.removeComponent(ComponentKeys.LORE); + } else { + item.setComponent(ComponentKeys.LORE, lore); + } + } + + @Override + protected boolean unbreakable(RtagItem item) { + return false; + } + + @Override + protected void unbreakable(RtagItem item, boolean unbreakable) { + + } + + @Override + protected Optional glint(RtagItem item) { + return Optional.empty(); + } + + @Override + protected void glint(RtagItem item, Boolean glint) { + + } +} \ No newline at end of file diff --git a/core/src/main/java/net/momirealms/customfishing/bukkit/item/impl/UniversalItemFactory.java b/core/src/main/java/net/momirealms/customfishing/bukkit/item/impl/UniversalItemFactory.java new file mode 100644 index 00000000..9a45e95e --- /dev/null +++ b/core/src/main/java/net/momirealms/customfishing/bukkit/item/impl/UniversalItemFactory.java @@ -0,0 +1,90 @@ +package net.momirealms.customfishing.bukkit.item.impl; + +import com.saicone.rtag.RtagItem; +import net.momirealms.customfishing.bukkit.item.BukkitItemFactory; +import net.momirealms.customfishing.common.plugin.CustomFishingPlugin; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +public class UniversalItemFactory extends BukkitItemFactory { + + public UniversalItemFactory(CustomFishingPlugin plugin) { + super(plugin); + } + + @Override + protected void displayName(RtagItem item, String json) { + if (json != null) { + item.set(json, "display", "Name"); + } else { + item.remove("display", "Name"); + } + } + + @Override + protected Optional displayName(RtagItem item) { + if (!item.hasTag("display", "Name")) return Optional.empty(); + return Optional.of(item.get("display", "Name")); + } + + @Override + protected void customModelData(RtagItem item, Integer data) { + if (data == null) { + item.remove("CustomModelData"); + } else { + item.set(data, "CustomModelData"); + } + } + + @Override + protected Optional customModelData(RtagItem item) { + if (!item.hasTag("CustomModelData")) return Optional.empty(); + return Optional.of(item.get("CustomModelData")); + } + + @Override + protected void skull(RtagItem item, String skullData) { + if (skullData == null) { + item.remove("SkullOwner"); + } else { + item.set(List.of(Map.of("Value", skullData)), "SkullOwner", "Properties", "textures"); + } + } + + @Override + protected Optional> lore(RtagItem item) { + if (!item.hasTag("display", "Lore")) return Optional.empty(); + return Optional.of(item.get("display", "Lore")); + } + + @Override + protected void lore(RtagItem item, List lore) { + if (lore == null || lore.isEmpty()) { + item.remove("display", "Lore"); + } else { + item.set(lore, "display", "Lore"); + } + } + + @Override + protected boolean unbreakable(RtagItem item) { + return false; + } + + @Override + protected void unbreakable(RtagItem item, boolean unbreakable) { + + } + + @Override + protected Optional glint(RtagItem item) { + return Optional.empty(); + } + + @Override + protected void glint(RtagItem item, Boolean glint) { + + } +} diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/Icon.java b/core/src/main/java/net/momirealms/customfishing/gui/Icon.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/gui/Icon.java rename to core/src/main/java/net/momirealms/customfishing/gui/Icon.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/ParentPage.java b/core/src/main/java/net/momirealms/customfishing/gui/ParentPage.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/gui/ParentPage.java rename to core/src/main/java/net/momirealms/customfishing/gui/ParentPage.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/SectionPage.java b/core/src/main/java/net/momirealms/customfishing/gui/SectionPage.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/gui/SectionPage.java rename to core/src/main/java/net/momirealms/customfishing/gui/SectionPage.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/YamlPage.java b/core/src/main/java/net/momirealms/customfishing/gui/YamlPage.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/gui/YamlPage.java rename to core/src/main/java/net/momirealms/customfishing/gui/YamlPage.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/BackGroundItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/BackGroundItem.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/BackGroundItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/BackGroundItem.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/BackToFolderItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/BackToFolderItem.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/BackToFolderItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/BackToFolderItem.java index 5b348c4b..236b579e 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/BackToFolderItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/BackToFolderItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.Icon; import net.momirealms.customfishing.gui.page.file.FileSelector; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/BackToPageItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/BackToPageItem.java similarity index 92% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/BackToPageItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/BackToPageItem.java index f5fb2cca..4fc69874 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/BackToPageItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/BackToPageItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.ParentPage; import net.momirealms.customfishing.setting.CFLocale; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/NextPageItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/NextPageItem.java similarity index 93% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/NextPageItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/NextPageItem.java index 6da7372d..261381bc 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/NextPageItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/NextPageItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.Icon; import net.momirealms.customfishing.setting.CFLocale; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/PreviousPageItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/PreviousPageItem.java similarity index 93% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/PreviousPageItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/PreviousPageItem.java index 8ea9fc89..2923b49a 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/PreviousPageItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/PreviousPageItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.Icon; import net.momirealms.customfishing.setting.CFLocale; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/ScrollDownItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/ScrollDownItem.java similarity index 92% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/ScrollDownItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/ScrollDownItem.java index 0426248c..31a5388f 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/ScrollDownItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/ScrollDownItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.Icon; import net.momirealms.customfishing.setting.CFLocale; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/ScrollUpItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/ScrollUpItem.java similarity index 92% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/ScrollUpItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/ScrollUpItem.java index c040c611..e08e120f 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/ScrollUpItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/ScrollUpItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.Icon; import net.momirealms.customfishing.setting.CFLocale; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/AmountItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/AmountItem.java similarity index 93% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/AmountItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/AmountItem.java index f47c40da..858d72fa 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/AmountItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/AmountItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.page.property.AmountEditor; import net.momirealms.customfishing.setting.CFLocale; @@ -42,7 +41,7 @@ public class AmountItem extends AbstractItem { @Override public ItemProvider getItemProvider() { ItemBuilder itemBuilder = new ItemBuilder(Material.IRON_NUGGET) - .setDisplayName(new ShadedAdventureComponentWrapper(AdventureHelper.getInstance().getComponentFromMiniMessage( + .setDisplayName(new ShadedAdventureComponentWrapper(AdventureHelper.getComponentFromMiniMessage( CFLocale.GUI_ITEM_AMOUNT ))) .setAmount(itemPage.getSection().getInt("amount", 1)); diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/CMDItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/CMDItem.java similarity index 95% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/CMDItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/CMDItem.java index ae3cec8b..5a15f33e 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/CMDItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/CMDItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.page.property.CustomModelDataEditor; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/DisplayNameItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/DisplayNameItem.java similarity index 95% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/DisplayNameItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/DisplayNameItem.java index 3fe0e95b..5f5caa5b 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/DisplayNameItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/DisplayNameItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.page.property.DisplayNameEditor; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/DurabilityItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/DurabilityItem.java similarity index 95% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/DurabilityItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/DurabilityItem.java index 7341393d..9795241a 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/DurabilityItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/DurabilityItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.page.property.DurabilityEditor; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/EnchantmentItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/EnchantmentItem.java similarity index 96% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/EnchantmentItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/EnchantmentItem.java index fe73a540..e430c351 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/EnchantmentItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/EnchantmentItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.page.property.EnchantmentEditor; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/Head64Item.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/Head64Item.java similarity index 90% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/Head64Item.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/Head64Item.java index ca213160..12b2036c 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/Head64Item.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/Head64Item.java @@ -17,10 +17,9 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.CustomFishingPluginImpl; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.BukkitCustomFishingPluginImpl; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.setting.CFLocale; import org.bukkit.Material; @@ -84,7 +83,7 @@ public class Head64Item extends AbstractItem { if (clickType.isLeftClick()) { player.closeInventory(); AdventureHelper.getInstance().sendMessageWithPrefix(player, "Input the head64 value in chat"); - ((CustomFishingPluginImpl) CustomFishingPlugin.get()).getChatCatcherManager().catchMessage(player, "head64", itemPage); + ((BukkitCustomFishingPluginImpl) BukkitCustomFishingPlugin.get()).getChatCatcherManager().catchMessage(player, "head64", itemPage); } else if (clickType.isRightClick()) { itemPage.getSection().set("head64", null); itemPage.save(); diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/ItemFlagItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/ItemFlagItem.java similarity index 95% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/ItemFlagItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/ItemFlagItem.java index 90f70925..6f6e89d6 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/ItemFlagItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/ItemFlagItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.page.property.ItemFlagEditor; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/LoreItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/LoreItem.java similarity index 95% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/LoreItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/LoreItem.java index f5525a7d..db65aa65 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/LoreItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/LoreItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.page.property.LoreEditor; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/MaterialItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/MaterialItem.java similarity index 95% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/MaterialItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/MaterialItem.java index ac638535..207d7f7c 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/MaterialItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/MaterialItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.page.property.MaterialEditor; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/NBTItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/NBTItem.java similarity index 95% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/NBTItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/NBTItem.java index df3b1ece..af21a788 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/NBTItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/NBTItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.page.property.NBTEditor; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/PreventGrabItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/PreventGrabItem.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/PreventGrabItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/PreventGrabItem.java index 436e2031..83be5005 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/PreventGrabItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/PreventGrabItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.setting.CFLocale; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/PriceItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/PriceItem.java similarity index 95% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/PriceItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/PriceItem.java index bfcd5080..ce7d320a 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/PriceItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/PriceItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.page.property.PriceEditor; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/RandomDurabilityItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/RandomDurabilityItem.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/RandomDurabilityItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/RandomDurabilityItem.java index e94841c6..c069b995 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/RandomDurabilityItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/RandomDurabilityItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.setting.CFLocale; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/SizeItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/SizeItem.java similarity index 95% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/SizeItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/SizeItem.java index 36a461a2..cb2282f3 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/SizeItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/SizeItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.page.property.SizeEditor; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/StackableItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/StackableItem.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/StackableItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/StackableItem.java index b5f3c504..526ee8aa 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/StackableItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/StackableItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.setting.CFLocale; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/StoredEnchantmentItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/StoredEnchantmentItem.java similarity index 96% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/StoredEnchantmentItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/StoredEnchantmentItem.java index c55c5900..9cfa7bf2 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/StoredEnchantmentItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/StoredEnchantmentItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.page.property.EnchantmentEditor; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/TagItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/TagItem.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/TagItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/TagItem.java index 694870d0..5786e165 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/TagItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/TagItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.setting.CFLocale; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/UnbreakableItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/UnbreakableItem.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/UnbreakableItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/UnbreakableItem.java index 30e3ee31..1b91a7a3 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/item/UnbreakableItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/item/UnbreakableItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.setting.CFLocale; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/DisableGameItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/DisableGameItem.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/DisableGameItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/DisableGameItem.java index d314f5da..18c0ed19 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/DisableGameItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/DisableGameItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.loot; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.setting.CFLocale; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/DisableStatsItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/DisableStatsItem.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/DisableStatsItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/DisableStatsItem.java index 5527128b..2be67535 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/DisableStatsItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/DisableStatsItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.loot; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.setting.CFLocale; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/InstantGameItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/InstantGameItem.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/InstantGameItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/InstantGameItem.java index 5109dd1e..e53d108c 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/InstantGameItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/InstantGameItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.loot; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.setting.CFLocale; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/NickItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/NickItem.java similarity index 95% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/NickItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/NickItem.java index f208f219..cbc7c1fb 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/NickItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/NickItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.loot; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.page.property.NickEditor; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/ScoreItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/ScoreItem.java similarity index 95% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/ScoreItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/ScoreItem.java index c953d39c..f47e2282 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/ScoreItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/ScoreItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.loot; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.page.property.ScoreEditor; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/ShowInFinderItem.java b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/ShowInFinderItem.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/ShowInFinderItem.java rename to core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/ShowInFinderItem.java index 9154e529..6f5a1bf3 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/ShowInFinderItem.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/icon/property/loot/ShowInFinderItem.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.icon.property.loot; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.setting.CFLocale; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/file/FileSelector.java b/core/src/main/java/net/momirealms/customfishing/gui/page/file/FileSelector.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/file/FileSelector.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/file/FileSelector.java index 31953891..8be1cff4 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/page/file/FileSelector.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/page/file/FileSelector.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.page.file; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.icon.BackGroundItem; import net.momirealms.customfishing.gui.icon.BackToFolderItem; import net.momirealms.customfishing.gui.icon.ScrollDownItem; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/item/AbstractSectionEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/item/AbstractSectionEditor.java similarity index 92% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/item/AbstractSectionEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/item/AbstractSectionEditor.java index 3121eff8..e077084a 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/page/item/AbstractSectionEditor.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/page/item/AbstractSectionEditor.java @@ -17,9 +17,8 @@ package net.momirealms.customfishing.gui.page.item; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.icon.BackGroundItem; import net.momirealms.customfishing.gui.icon.BackToPageItem; @@ -111,7 +110,7 @@ public abstract class AbstractSectionEditor implements SectionPage { @Override public ItemProvider getItemProvider() { - return new ItemBuilder(CustomFishingPlugin.get().getItemManager().getItemBuilder(section, "bait", key).build(player)); + return new ItemBuilder(BukkitCustomFishingPlugin.get().getItemManager().getItemBuilder(section, "bait", key).build(player)); } @Override diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/item/BaitEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/item/BaitEditor.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/item/BaitEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/item/BaitEditor.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/item/HookEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/item/HookEditor.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/item/HookEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/item/HookEditor.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/item/ItemSelector.java b/core/src/main/java/net/momirealms/customfishing/gui/page/item/ItemSelector.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/item/ItemSelector.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/item/ItemSelector.java index 4500c195..f8955e40 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/page/item/ItemSelector.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/page/item/ItemSelector.java @@ -17,11 +17,9 @@ package net.momirealms.customfishing.gui.page.item; -import de.tr7zw.changeme.nbtapi.NBTItem; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.util.LogUtils; +import com.saicone.rtag.RtagItem; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.gui.YamlPage; import net.momirealms.customfishing.gui.icon.BackGroundItem; import net.momirealms.customfishing.gui.icon.BackToFolderItem; @@ -175,10 +173,14 @@ public class ItemSelector implements YamlPage { if (!prefix.equals(SEARCH) && !entry.getKey().startsWith(prefix)) continue; String material = section.getString("material"); if (material != null) { - ItemStack build = CustomFishingPlugin.get().getItemManager().getItemBuilder(section, type, key).build(player); - NBTItem nbtItem = new NBTItem(build); - nbtItem.removeKey("display"); - ItemBuilder itemBuilder = new ItemBuilder(nbtItem.getItem()); + ItemStack build = BukkitCustomFishingPlugin.get().getItemManager().getItemBuilder(section, type, key).build(player); + RtagItem rtagItem = new RtagItem(build); + if (BukkitCustomFishingPlugin.get().getVersionManager().isNewerThan1_20_5()) { + rtagItem.getComponent(""); + } else { + rtagItem.remove("display"); + } + ItemBuilder itemBuilder = new ItemBuilder(rtagItem.getItem()); itemList.add(new ItemInList(key, itemBuilder, this)); continue; } diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/item/RodEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/item/RodEditor.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/item/RodEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/item/RodEditor.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/item/SectionEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/item/SectionEditor.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/item/SectionEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/item/SectionEditor.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/AmountEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/property/AmountEditor.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/property/AmountEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/property/AmountEditor.java index 6eca4aa1..91c44c1e 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/AmountEditor.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/page/property/AmountEditor.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.page.property; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.icon.BackGroundItem; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/CustomModelDataEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/property/CustomModelDataEditor.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/property/CustomModelDataEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/property/CustomModelDataEditor.java index fcefd2e2..0d1c0694 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/CustomModelDataEditor.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/page/property/CustomModelDataEditor.java @@ -17,9 +17,8 @@ package net.momirealms.customfishing.gui.page.property; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.icon.BackGroundItem; import net.momirealms.customfishing.setting.CFLocale; @@ -59,7 +58,7 @@ public class CustomModelDataEditor { .setStructure( "a # b" ) - .addIngredient('a', new ItemBuilder(CustomFishingPlugin.get() + .addIngredient('a', new ItemBuilder(BukkitCustomFishingPlugin.get() .getItemManager() .getItemStackAppearance(player, material) ) @@ -110,7 +109,7 @@ public class CustomModelDataEditor { int value = Integer.parseInt(cmd); if (value >= 0) { return new ItemBuilder( - CustomFishingPlugin.get() + BukkitCustomFishingPlugin.get() .getItemManager() .getItemStackAppearance(player, material) ) diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/DisplayNameEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/property/DisplayNameEditor.java similarity index 96% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/property/DisplayNameEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/property/DisplayNameEditor.java index 5b8ce025..dc479679 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/DisplayNameEditor.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/page/property/DisplayNameEditor.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.page.property; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.icon.BackGroundItem; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/DurabilityEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/property/DurabilityEditor.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/property/DurabilityEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/property/DurabilityEditor.java index 99ebfbc0..e50abf28 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/DurabilityEditor.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/page/property/DurabilityEditor.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.page.property; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.icon.BackGroundItem; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/EnchantmentEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/property/EnchantmentEditor.java similarity index 98% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/property/EnchantmentEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/property/EnchantmentEditor.java index cc954eac..3df4e12c 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/EnchantmentEditor.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/page/property/EnchantmentEditor.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.page.property; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.icon.BackGroundItem; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/ItemFlagEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/property/ItemFlagEditor.java similarity index 93% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/property/ItemFlagEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/property/ItemFlagEditor.java index 5f6d1e7d..b6910cbf 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/ItemFlagEditor.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/page/property/ItemFlagEditor.java @@ -17,9 +17,8 @@ package net.momirealms.customfishing.gui.page.property; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.icon.BackGroundItem; import net.momirealms.customfishing.setting.CFLocale; @@ -63,7 +62,7 @@ public class ItemFlagEditor { .setStructure( "# a #" ) - .addIngredient('a', new ItemBuilder(CustomFishingPlugin.get().getItemManager().getItemBuilder(section, "item", "id").build(player))) + .addIngredient('a', new ItemBuilder(BukkitCustomFishingPlugin.get().getItemManager().getItemBuilder(section, "item", "id").build(player))) .addIngredient('#', new SimpleItem(new ItemBuilder(Material.AIR))) .build(); diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/LoreEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/property/LoreEditor.java similarity index 98% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/property/LoreEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/property/LoreEditor.java index dd9aa32f..cfd53b6e 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/LoreEditor.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/page/property/LoreEditor.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.page.property; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.icon.BackGroundItem; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/MaterialEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/property/MaterialEditor.java similarity index 91% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/property/MaterialEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/property/MaterialEditor.java index f5dfdf87..c3969e03 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/MaterialEditor.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/page/property/MaterialEditor.java @@ -17,9 +17,8 @@ package net.momirealms.customfishing.gui.page.property; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.icon.BackGroundItem; import net.momirealms.customfishing.mechanic.item.ItemManagerImpl; @@ -58,7 +57,7 @@ public class MaterialEditor { Item border = new SimpleItem(new ItemBuilder(Material.AIR)); var confirm = new ConfirmIcon(); - var itemBuilder = new ItemBuilder(CustomFishingPlugin.get() + var itemBuilder = new ItemBuilder(BukkitCustomFishingPlugin.get() .getItemManager() .getItemStackAppearance(player, material) ) @@ -105,7 +104,7 @@ public class MaterialEditor { public List getCompatibilityItemList() { ArrayList items = new ArrayList<>(); - for (String lib : ((ItemManagerImpl) CustomFishingPlugin.get().getItemManager()).getItemLibraries()) { + for (String lib : ((ItemManagerImpl) BukkitCustomFishingPlugin.get().getItemManager()).getItemLibraries()) { switch (lib) { case "MMOItems" -> items.add(new SimpleItem(new ItemBuilder(Material.BELL).setDisplayName(lib + ":TYPE:ID"))); case "ItemsAdder" -> items.add(new SimpleItem(new ItemBuilder(Material.BELL).setDisplayName(lib + ":namespace:id"))); @@ -126,7 +125,7 @@ public class MaterialEditor { ))); } else { var builder = new ItemBuilder( - CustomFishingPlugin.get() + BukkitCustomFishingPlugin.get() .getItemManager() .getItemStackAppearance(player, material) ).setDisplayName(CFLocale.GUI_NEW_VALUE + material) @@ -143,7 +142,7 @@ public class MaterialEditor { public void handleClick(@NotNull ClickType clickType, @NotNull Player player, @NotNull InventoryClickEvent event) { if (material == null || material.isEmpty()) { section.set("material", null); - } else if (CustomFishingPlugin.get().getItemManager().getItemStackAppearance(player, material).getType() == Material.BARRIER) { + } else if (BukkitCustomFishingPlugin.get().getItemManager().getItemStackAppearance(player, material).getType() == Material.BARRIER) { return; } else { section.set("material", material); diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/NBTEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/property/NBTEditor.java similarity index 99% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/property/NBTEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/property/NBTEditor.java index 9f044ca5..7d151268 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/NBTEditor.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/page/property/NBTEditor.java @@ -17,13 +17,11 @@ package net.momirealms.customfishing.gui.page.property; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.icon.BackGroundItem; import net.momirealms.customfishing.setting.CFLocale; import net.momirealms.customfishing.util.ConfigUtils; -import net.momirealms.customfishing.util.NBTUtils; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/NickEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/property/NickEditor.java similarity index 96% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/property/NickEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/property/NickEditor.java index 77ece67f..7f6dffc2 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/NickEditor.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/page/property/NickEditor.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.page.property; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.icon.BackGroundItem; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/PriceEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/property/PriceEditor.java similarity index 98% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/property/PriceEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/property/PriceEditor.java index aa866830..62c33e35 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/PriceEditor.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/page/property/PriceEditor.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.page.property; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.icon.BackGroundItem; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/ScoreEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/property/ScoreEditor.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/property/ScoreEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/property/ScoreEditor.java index c524d29f..be2030de 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/ScoreEditor.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/page/property/ScoreEditor.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.page.property; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.icon.BackGroundItem; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/SizeEditor.java b/core/src/main/java/net/momirealms/customfishing/gui/page/property/SizeEditor.java similarity index 98% rename from plugin/src/main/java/net/momirealms/customfishing/gui/page/property/SizeEditor.java rename to core/src/main/java/net/momirealms/customfishing/gui/page/property/SizeEditor.java index 8ee058b8..9ab6ca24 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/gui/page/property/SizeEditor.java +++ b/core/src/main/java/net/momirealms/customfishing/gui/page/property/SizeEditor.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.gui.page.property; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.adventure.component.ShadedAdventureComponentWrapper; +import net.momirealms.customfishing.bukkit.adventure.ShadedAdventureComponentWrapper; import net.momirealms.customfishing.gui.SectionPage; import net.momirealms.customfishing.gui.icon.BackGroundItem; import net.momirealms.customfishing.setting.CFLocale; diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/action/ActionManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/action/ActionManagerImpl.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/action/ActionManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/action/ActionManagerImpl.java index 84082f06..e44fa875 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/action/ActionManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/action/ActionManagerImpl.java @@ -19,11 +19,10 @@ package net.momirealms.customfishing.mechanic.action; import net.kyori.adventure.key.Key; import net.kyori.adventure.sound.Sound; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.common.Pair; -import net.momirealms.customfishing.api.manager.ActionManager; -import net.momirealms.customfishing.api.manager.LootManager; +import net.momirealms.customfishing.api.mechanic.action.ActionManager; +import net.momirealms.customfishing.api.mechanic.loot.LootManager; import net.momirealms.customfishing.api.mechanic.GlobalSettings; import net.momirealms.customfishing.api.mechanic.action.Action; import net.momirealms.customfishing.api.mechanic.action.ActionExpansion; @@ -32,9 +31,9 @@ import net.momirealms.customfishing.api.mechanic.action.ActionTrigger; import net.momirealms.customfishing.api.mechanic.loot.Loot; import net.momirealms.customfishing.api.mechanic.requirement.Requirement; import net.momirealms.customfishing.api.scheduler.CancellableTask; -import net.momirealms.customfishing.api.util.LogUtils; -import net.momirealms.customfishing.compatibility.VaultHook; -import net.momirealms.customfishing.compatibility.papi.PlaceholderManagerImpl; +import net.momirealms.customfishing.bukkit.compatibility.VaultHook; +import net.momirealms.customfishing.bukkit.compatibility.papi.PlaceholderManagerImpl; +import net.momirealms.customfishing.common.util.ClassUtils; import net.momirealms.customfishing.setting.CFLocale; import net.momirealms.customfishing.util.*; import org.bukkit.Bukkit; @@ -60,11 +59,11 @@ import java.util.concurrent.TimeUnit; public class ActionManagerImpl implements ActionManager { - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; private final HashMap actionFactoryMap; private final String EXPANSION_FOLDER = "expansions/action"; - public ActionManagerImpl(CustomFishingPlugin plugin) { + public ActionManagerImpl(BukkitCustomFishingPlugin plugin) { this.plugin = plugin; this.actionFactoryMap = new HashMap<>(); this.registerInbuiltActions(); @@ -237,7 +236,7 @@ public class ActionManagerImpl implements ActionManager { */ @Nullable @Override - public ActionFactory getActionFactory(String type) { + public ActionFactory getActionFactory(@NotNull String type) { return actionFactoryMap.get(type); } @@ -258,7 +257,7 @@ public class ActionManagerImpl implements ActionManager { for (File expansionJar : expansionJars) { if (expansionJar.getName().endsWith(".jar")) { try { - Class expansionClass = ClassUtils.findClass(expansionJar, ActionExpansion.class); + Class> expansionClass = (Class>) ClassUtils.findClass(expansionJar, ActionExpansion.class); classes.add(expansionClass); } catch (IOException | ClassNotFoundException e) { LogUtils.warn("Failed to load expansion: " + expansionJar.getName(), e); @@ -437,11 +436,7 @@ public class ActionManagerImpl implements ActionManager { private void registerActionBarAction() { registerAction("actionbar", (args, chance) -> { - String text = (String) args; - return condition -> { - if (Math.random() > chance) return; - String parsed = PlaceholderManagerImpl.getInstance().parse(condition.getPlayer(), text, condition.getArgs()); - AdventureHelper.getInstance().sendActionbar(condition.getPlayer(), parsed); + return context -> { }; }); registerAction("random-actionbar", (args, chance) -> { @@ -489,7 +484,7 @@ public class ActionManagerImpl implements ActionManager { var value = ConfigUtils.getValue(args); return condition -> { if (Math.random() > chance) return; - if (CustomFishingPlugin.get().getVersionManager().isSpigot()) { + if (BukkitCustomFishingPlugin.get().getVersionManager().isSpigot()) { condition.getPlayer().getLocation().getWorld().spawn(condition.getPlayer().getLocation(), ExperienceOrb.class, e -> e.setExperience((int) value.get(condition.getPlayer(), condition.getArgs()))); } else { condition.getPlayer().giveExp((int) value.get(condition.getPlayer(), condition.getArgs()), true); @@ -626,7 +621,7 @@ public class ActionManagerImpl implements ActionManager { return condition -> { if (Math.random() > chance) return; Player player = condition.getPlayer(); - ItemUtils.giveItem(player, Objects.requireNonNull(CustomFishingPlugin.get().getItemManager().buildAnyPluginItemByID(player, id)), amount); + ItemUtils.giveItem(player, Objects.requireNonNull(BukkitCustomFishingPlugin.get().getItemManager().buildAnyPluginItemByID(player, id)), amount); }; } else { LogUtils.warn("Illegal value format found at action: give-item"); @@ -965,7 +960,7 @@ public class ActionManagerImpl implements ActionManager { if (Math.random() > chance) return; if (requirements != null) for (Requirement requirement : requirements) { - if (!requirement.isConditionMet(condition)) { + if (!requirement.check(condition)) { return; } } @@ -997,7 +992,7 @@ public class ActionManagerImpl implements ActionManager { for (Pair pair : conditionActionPairList) { if (pair.left() != null) for (Requirement requirement : pair.left()) { - if (!requirement.isConditionMet(condition)) { + if (!requirement.check(condition)) { continue outer; } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/action/EmptyAction.java b/core/src/main/java/net/momirealms/customfishing/mechanic/action/EmptyAction.java similarity index 77% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/action/EmptyAction.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/action/EmptyAction.java index 27011f2b..e2cb14d9 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/action/EmptyAction.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/action/EmptyAction.java @@ -1,7 +1,6 @@ package net.momirealms.customfishing.mechanic.action; import net.momirealms.customfishing.api.mechanic.action.Action; -import net.momirealms.customfishing.api.mechanic.condition.Condition; /** * An implementation of the Action interface that represents an empty action with no behavior. @@ -12,6 +11,6 @@ public class EmptyAction implements Action { public static EmptyAction instance = new EmptyAction(); @Override - public void trigger(Condition condition) { + public void trigger(PlayerContext playerContext) { } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/bag/BagManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/bag/BagManagerImpl.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/bag/BagManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/bag/BagManagerImpl.java index ad782914..17beb876 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/bag/BagManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/bag/BagManagerImpl.java @@ -17,17 +17,16 @@ package net.momirealms.customfishing.mechanic.bag; -import net.momirealms.customfishing.CustomFishingPluginImpl; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.BukkitCustomFishingPluginImpl; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.user.OfflineUser; -import net.momirealms.customfishing.api.manager.BagManager; -import net.momirealms.customfishing.api.manager.EffectManager; +import net.momirealms.customfishing.api.mechanic.bag.BagManager; +import net.momirealms.customfishing.api.mechanic.effect.EffectManager; import net.momirealms.customfishing.api.mechanic.action.Action; import net.momirealms.customfishing.api.mechanic.bag.FishingBagHolder; import net.momirealms.customfishing.api.mechanic.requirement.Requirement; import net.momirealms.customfishing.api.util.InventoryUtils; -import net.momirealms.customfishing.compatibility.papi.PlaceholderManagerImpl; +import net.momirealms.customfishing.bukkit.compatibility.papi.PlaceholderManagerImpl; import net.momirealms.customfishing.setting.CFConfig; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -48,7 +47,7 @@ import java.util.*; public class BagManagerImpl implements BagManager, Listener { - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; private final HashMap tempEditMap; private Action[] collectLootActions; private Action[] bagFullActions; @@ -57,7 +56,7 @@ public class BagManagerImpl implements BagManager, Listener { private List bagWhiteListItems; private Requirement[] collectRequirements; - public BagManagerImpl(CustomFishingPluginImpl plugin) { + public BagManagerImpl(BukkitCustomFishingPluginImpl plugin) { this.plugin = plugin; this.tempEditMap = new HashMap<>(); } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/block/BlockManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/block/BlockManagerImpl.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/block/BlockManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/block/BlockManagerImpl.java index 874b5fab..18b4bf4f 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/block/BlockManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/block/BlockManagerImpl.java @@ -17,15 +17,14 @@ package net.momirealms.customfishing.mechanic.block; -import net.momirealms.customfishing.CustomFishingPluginImpl; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.BukkitCustomFishingPluginImpl; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.common.Pair; import net.momirealms.customfishing.api.common.Tuple; -import net.momirealms.customfishing.api.manager.BlockManager; +import net.momirealms.customfishing.api.mechanic.block.BlockManager; import net.momirealms.customfishing.api.mechanic.block.*; import net.momirealms.customfishing.api.mechanic.loot.Loot; -import net.momirealms.customfishing.api.util.LogUtils; -import net.momirealms.customfishing.compatibility.block.VanillaBlockImpl; +import net.momirealms.customfishing.bukkit.compatibility.block.VanillaBlockImpl; import net.momirealms.customfishing.setting.CFConfig; import net.momirealms.customfishing.util.ConfigUtils; import org.bukkit.*; @@ -59,14 +58,14 @@ import java.util.concurrent.TimeUnit; public class BlockManagerImpl implements BlockManager, Listener { - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; private final HashMap blockLibraryMap; private BlockLibrary[] blockDetectionArray; private final HashMap blockConfigMap; private final HashMap dataBuilderMap; private final HashMap stateBuilderMap; - public BlockManagerImpl(CustomFishingPluginImpl plugin) { + public BlockManagerImpl(BukkitCustomFishingPluginImpl plugin) { this.plugin = plugin; this.blockLibraryMap = new HashMap<>(); this.blockConfigMap = new HashMap<>(); @@ -119,7 +118,7 @@ public class BlockManagerImpl implements BlockManager, Listener { // Retrieve a custom string value stored in the entity's persistent data container. String temp = event.getEntity().getPersistentDataContainer().get( - Objects.requireNonNull(NamespacedKey.fromString("block", CustomFishingPlugin.get())), + Objects.requireNonNull(NamespacedKey.fromString("block", BukkitCustomFishingPlugin.get())), PersistentDataType.STRING ); @@ -350,7 +349,7 @@ public class BlockManagerImpl implements BlockManager, Listener { } FallingBlock fallingBlock = hookLocation.getWorld().spawnFallingBlock(hookLocation, blockData); fallingBlock.getPersistentDataContainer().set( - Objects.requireNonNull(NamespacedKey.fromString("block", CustomFishingPlugin.get())), + Objects.requireNonNull(NamespacedKey.fromString("block", BukkitCustomFishingPlugin.get())), PersistentDataType.STRING, loot.getID() + ";" + player.getName() ); diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/Competition.java b/core/src/main/java/net/momirealms/customfishing/mechanic/competition/Competition.java similarity index 93% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/Competition.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/competition/Competition.java index 17ac9644..29be675f 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/Competition.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/competition/Competition.java @@ -17,7 +17,7 @@ package net.momirealms.customfishing.mechanic.competition; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.common.Pair; import net.momirealms.customfishing.api.event.CompetitionEvent; import net.momirealms.customfishing.api.mechanic.action.Action; @@ -25,7 +25,6 @@ import net.momirealms.customfishing.api.mechanic.competition.CompetitionConfig; import net.momirealms.customfishing.api.mechanic.competition.CompetitionGoal; import net.momirealms.customfishing.api.mechanic.competition.FishingCompetition; import net.momirealms.customfishing.api.mechanic.competition.Ranking; -import net.momirealms.customfishing.api.mechanic.condition.Condition; import net.momirealms.customfishing.api.scheduler.CancellableTask; import net.momirealms.customfishing.mechanic.competition.actionbar.ActionBarManager; import net.momirealms.customfishing.mechanic.competition.bossbar.BossBarManager; @@ -65,7 +64,7 @@ public class Competition implements FishingCompetition { if (CFConfig.redisRanking) this.ranking = new RedisRankingImpl(); else this.ranking = new LocalRankingImpl(); this.publicPlaceholders = new ConcurrentHashMap<>(); - this.publicPlaceholders.put("{goal}", CustomFishingPlugin.get().getCompetitionManager().getCompetitionGoalLocale(goal)); + this.publicPlaceholders.put("{goal}", BukkitCustomFishingPlugin.get().getCompetitionManager().getCompetitionGoalLocale(goal)); } /** @@ -92,9 +91,9 @@ public class Competition implements FishingCompetition { Action[] actions = config.getStartActions(); if (actions != null) { - Condition condition = new Condition(null, null, this.publicPlaceholders); + PlayerContext playerContext = new PlayerContext(null, null, this.publicPlaceholders); for (Action action : actions) { - action.trigger(condition); + action.trigger(playerContext); } } @@ -111,7 +110,7 @@ public class Competition implements FishingCompetition { * If the remaining time reaches zero, the competition is ended. */ private void arrangeTimerTask() { - this.competitionTimerTask = CustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(() -> { + this.competitionTimerTask = BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(() -> { if (decreaseTime()) { end(true); return; @@ -190,14 +189,14 @@ public class Competition implements FishingCompetition { Player player = Bukkit.getPlayer(competitionPlayer.left()); if (player != null) for (Action action : rewardsMap.get(String.valueOf(i))) - action.trigger(new Condition(player, this.publicPlaceholders)); + action.trigger(new PlayerContext(player, this.publicPlaceholders)); } else { Action[] actions = rewardsMap.get("participation"); if (actions != null) { Player player = Bukkit.getPlayer(competitionPlayer.left()); { if (player != null) for (Action action : actions) - action.trigger(new Condition(player, this.publicPlaceholders)); + action.trigger(new PlayerContext(player, this.publicPlaceholders)); } } } @@ -208,9 +207,9 @@ public class Competition implements FishingCompetition { // do end actions Action[] actions = config.getEndActions(); if (actions != null) { - Condition condition = new Condition(null, null, new HashMap<>(publicPlaceholders)); + PlayerContext playerContext = new PlayerContext(null, null, new HashMap<>(publicPlaceholders)); for (Action action : actions) { - action.trigger(condition); + action.trigger(playerContext); } } @@ -221,7 +220,7 @@ public class Competition implements FishingCompetition { } // 1 seconds delay for other servers to read the redis data - CustomFishingPlugin.get().getScheduler().runTaskAsyncLater(this.ranking::clear, 1, TimeUnit.SECONDS); + BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncLater(this.ranking::clear, 1, TimeUnit.SECONDS); } /** @@ -260,9 +259,9 @@ public class Competition implements FishingCompetition { if (!hasPlayerJoined(player)) { Action[] actions = config.getJoinActions(); if (actions != null) { - Condition condition = new Condition(player); + PlayerContext playerContext = new PlayerContext(player); for (Action action : actions) { - action.trigger(condition); + action.trigger(playerContext); } } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/CompetitionManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/competition/CompetitionManagerImpl.java similarity index 93% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/CompetitionManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/competition/CompetitionManagerImpl.java index 6493ce22..3b33fff4 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/CompetitionManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/competition/CompetitionManagerImpl.java @@ -17,14 +17,14 @@ package net.momirealms.customfishing.mechanic.competition; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.common.Pair; -import net.momirealms.customfishing.api.manager.CompetitionManager; +import net.momirealms.customfishing.api.mechanic.competition.CompetitionManager; import net.momirealms.customfishing.api.mechanic.action.Action; import net.momirealms.customfishing.api.mechanic.competition.*; -import net.momirealms.customfishing.api.mechanic.condition.Condition; +import net.momirealms.customfishing.api.mechanic.competition.info.ActionBarConfigImpl; +import net.momirealms.customfishing.api.mechanic.competition.info.BossBarConfigImpl; import net.momirealms.customfishing.api.scheduler.CancellableTask; -import net.momirealms.customfishing.api.util.LogUtils; import net.momirealms.customfishing.setting.CFLocale; import net.momirealms.customfishing.storage.method.database.nosql.RedisManager; import net.momirealms.customfishing.util.ConfigUtils; @@ -42,14 +42,14 @@ import java.util.concurrent.TimeUnit; public class CompetitionManagerImpl implements CompetitionManager { - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; private final HashMap timeConfigMap; private final HashMap commandConfigMap; private Competition currentCompetition; private CancellableTask timerCheckTask; private int nextCompetitionSeconds; - public CompetitionManagerImpl(CustomFishingPlugin plugin) { + public CompetitionManagerImpl(BukkitCustomFishingPlugin plugin) { this.plugin = plugin; this.timeConfigMap = new HashMap<>(); this.commandConfigMap = new HashMap<>(); @@ -137,9 +137,9 @@ public class CompetitionManagerImpl implements CompetitionManager { .skipActions(plugin.getActionManager().getActions(section.getConfigurationSection("skip-actions"))); if (section.getBoolean("bossbar.enable", false)) { - builder.bossbar(new BossBarConfig.Builder() + builder.bossbar(new BossBarConfigImpl.BuilderImpl() .color(BarColor.valueOf(section.getString("bossbar.color", "WHITE").toUpperCase(Locale.ENGLISH))) - .overlay(BossBarConfig.Overlay.valueOf(section.getString("bossbar.overlay", "PROGRESS").toUpperCase(Locale.ENGLISH))) + .overlay(BossBarConfigImpl.Overlay.valueOf(section.getString("bossbar.overlay", "PROGRESS").toUpperCase(Locale.ENGLISH))) .refreshRate(section.getInt("bossbar.refresh-rate", 20)) .switchInterval(section.getInt("bossbar.switch-interval", 200)) .showToAll(!section.getBoolean("bossbar.only-show-to-participants", true)) @@ -148,7 +148,7 @@ public class CompetitionManagerImpl implements CompetitionManager { } if (section.getBoolean("actionbar.enable", false)) { - builder.actionbar(new ActionBarConfig.Builder() + builder.actionbar(new ActionBarConfigImpl.BuilderImpl() .refreshRate(section.getInt("actionbar.refresh-rate", 5)) .switchInterval(section.getInt("actionbar.switch-interval", 200)) .showToAll(!section.getBoolean("actionbar.only-show-to-participants", true)) @@ -269,9 +269,9 @@ public class CompetitionManagerImpl implements CompetitionManager { if (players < config.getMinPlayersToStart()) { var actions = config.getSkipActions(); if (actions != null) { - Condition condition = new Condition(null, null, new HashMap<>()); + PlayerContext playerContext = new PlayerContext(null, null, new HashMap<>()); for (Action action : actions) { - action.trigger(condition); + action.trigger(playerContext); } } return false; diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/CompetitionSchedule.java b/core/src/main/java/net/momirealms/customfishing/mechanic/competition/CompetitionSchedule.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/CompetitionSchedule.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/competition/CompetitionSchedule.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/actionbar/ActionBarManager.java b/core/src/main/java/net/momirealms/customfishing/mechanic/competition/actionbar/ActionBarManager.java similarity index 83% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/actionbar/ActionBarManager.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/competition/actionbar/ActionBarManager.java index 1bb6b546..8d88372d 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/actionbar/ActionBarManager.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/competition/actionbar/ActionBarManager.java @@ -17,8 +17,8 @@ package net.momirealms.customfishing.mechanic.competition.actionbar; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.mechanic.competition.ActionBarConfig; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; +import net.momirealms.customfishing.api.mechanic.competition.info.ActionBarConfigImpl; import net.momirealms.customfishing.mechanic.competition.Competition; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -35,11 +35,11 @@ import java.util.concurrent.TimeUnit; public class ActionBarManager implements Listener { private static final ConcurrentHashMap senderMap = new ConcurrentHashMap<>(); - private final ActionBarConfig actionBarConfig; + private final ActionBarConfigImpl actionBarConfigImpl; private final Competition competition; - public ActionBarManager(ActionBarConfig actionBarConfig, Competition competition) { - this.actionBarConfig = actionBarConfig; + public ActionBarManager(ActionBarConfigImpl actionBarConfigImpl, Competition competition) { + this.actionBarConfigImpl = actionBarConfigImpl; this.competition = competition; } @@ -47,10 +47,10 @@ public class ActionBarManager implements Listener { * Loads the ActionBar manager, registering events and showing ActionBar messages to online players. */ public void load() { - Bukkit.getPluginManager().registerEvents(this, CustomFishingPlugin.getInstance()); - if (actionBarConfig.isShowToAll()) { + Bukkit.getPluginManager().registerEvents(this, BukkitCustomFishingPlugin.getInstance()); + if (actionBarConfigImpl.showToAll()) { for (Player player : Bukkit.getOnlinePlayers()) { - ActionBarSender sender = new ActionBarSender(player, actionBarConfig, competition); + ActionBarSender sender = new ActionBarSender(player, actionBarConfigImpl, competition); if (!sender.isVisible()) { sender.show(); } @@ -93,11 +93,11 @@ public class ActionBarManager implements Listener { @EventHandler public void onJoin(PlayerJoinEvent event) { final Player player = event.getPlayer(); - CustomFishingPlugin.getInstance().getScheduler().runTaskAsyncLater(() -> { + BukkitCustomFishingPlugin.getInstance().getScheduler().runTaskAsyncLater(() -> { boolean hasJoined = competition.hasPlayerJoined(player); - if ((hasJoined || actionBarConfig.isShowToAll()) + if ((hasJoined || actionBarConfigImpl.showToAll()) && !senderMap.containsKey(player.getUniqueId())) { - ActionBarSender sender = new ActionBarSender(player, actionBarConfig, competition); + ActionBarSender sender = new ActionBarSender(player, actionBarConfigImpl, competition); if (!sender.isVisible()) { sender.show(); } @@ -114,7 +114,7 @@ public class ActionBarManager implements Listener { public void showActionBarTo(Player player) { ActionBarSender sender = senderMap.get(player.getUniqueId()); if (sender == null) { - sender = new ActionBarSender(player, actionBarConfig, competition); + sender = new ActionBarSender(player, actionBarConfigImpl, competition); senderMap.put(player.getUniqueId(), sender); } if (!sender.isVisible()) { diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/actionbar/ActionBarSender.java b/core/src/main/java/net/momirealms/customfishing/mechanic/competition/actionbar/ActionBarSender.java similarity index 87% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/actionbar/ActionBarSender.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/competition/actionbar/ActionBarSender.java index 84124c45..ac98f579 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/actionbar/ActionBarSender.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/competition/actionbar/ActionBarSender.java @@ -17,9 +17,8 @@ package net.momirealms.customfishing.mechanic.competition.actionbar; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.mechanic.competition.ActionBarConfig; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; +import net.momirealms.customfishing.api.mechanic.competition.info.ActionBarConfigImpl; import net.momirealms.customfishing.api.scheduler.CancellableTask; import net.momirealms.customfishing.mechanic.competition.Competition; import net.momirealms.customfishing.mechanic.misc.DynamicText; @@ -40,7 +39,7 @@ public class ActionBarSender { private int counter; private final DynamicText[] texts; private CancellableTask senderTask; - private final ActionBarConfig config; + private final ActionBarConfigImpl config; private boolean isShown; private final Competition competition; private final HashMap privatePlaceholders; @@ -52,7 +51,7 @@ public class ActionBarSender { * @param config The configuration for ActionBar messages. * @param competition The competition associated with this ActionBarSender. */ - public ActionBarSender(Player player, ActionBarConfig config, Competition competition) { + public ActionBarSender(Player player, ActionBarConfigImpl config, Competition competition) { this.player = player; this.config = config; this.isShown = false; @@ -61,7 +60,7 @@ public class ActionBarSender { this.privatePlaceholders.put("{player}", player.getName()); this.updatePrivatePlaceholders(); - String[] str = config.getTexts(); + String[] str = config.texts(); texts = new DynamicText[str.length]; for (int i = 0; i < str.length; i++) { texts[i] = new DynamicText(player, str[i]); @@ -85,13 +84,13 @@ public class ActionBarSender { */ public void show() { this.isShown = true; - senderTask = CustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(() -> { + senderTask = BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(() -> { switchTimer++; - if (switchTimer > config.getSwitchInterval()) { + if (switchTimer > config.switchInterval()) { switchTimer = 0; counter++; } - if (refreshTimer < config.getRefreshRate()){ + if (refreshTimer < config.refreshRate()){ refreshTimer++; } else { refreshTimer = 0; @@ -129,7 +128,7 @@ public class ActionBarSender { * * @return The ActionBar configuration. */ - public ActionBarConfig getConfig() { + public ActionBarConfigImpl getConfig() { return config; } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/bossbar/BossBarManager.java b/core/src/main/java/net/momirealms/customfishing/mechanic/competition/bossbar/BossBarManager.java similarity index 82% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/bossbar/BossBarManager.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/competition/bossbar/BossBarManager.java index 1dccd3d5..6eea2af5 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/bossbar/BossBarManager.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/competition/bossbar/BossBarManager.java @@ -17,8 +17,8 @@ package net.momirealms.customfishing.mechanic.competition.bossbar; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.mechanic.competition.BossBarConfig; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; +import net.momirealms.customfishing.api.mechanic.competition.info.BossBarConfigImpl; import net.momirealms.customfishing.mechanic.competition.Competition; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -35,11 +35,11 @@ import java.util.concurrent.TimeUnit; public class BossBarManager implements Listener { private static final ConcurrentHashMap senderMap = new ConcurrentHashMap<>(); - private final BossBarConfig bossBarConfig; + private final BossBarConfigImpl bossBarConfigImpl; private final Competition competition; - public BossBarManager(BossBarConfig bossBarConfig, Competition competition) { - this.bossBarConfig = bossBarConfig; + public BossBarManager(BossBarConfigImpl bossBarConfigImpl, Competition competition) { + this.bossBarConfigImpl = bossBarConfigImpl; this.competition = competition; } @@ -47,10 +47,10 @@ public class BossBarManager implements Listener { * Loads the boss bar manager, registering events and showing boss bars to online players. */ public void load() { - Bukkit.getPluginManager().registerEvents(this, CustomFishingPlugin.getInstance()); - if (bossBarConfig.isShowToAll()) { + Bukkit.getPluginManager().registerEvents(this, BukkitCustomFishingPlugin.getInstance()); + if (bossBarConfigImpl.showToAll()) { for (Player player : Bukkit.getOnlinePlayers()) { - BossBarSender sender = new BossBarSender(player, bossBarConfig, competition); + BossBarSender sender = new BossBarSender(player, bossBarConfigImpl, competition); if (!sender.isVisible()) { sender.show(); } @@ -93,11 +93,11 @@ public class BossBarManager implements Listener { @EventHandler public void onJoin(PlayerJoinEvent event) { final Player player = event.getPlayer(); - CustomFishingPlugin.getInstance().getScheduler().runTaskAsyncLater(() -> { + BukkitCustomFishingPlugin.getInstance().getScheduler().runTaskAsyncLater(() -> { boolean hasJoined = competition.hasPlayerJoined(player); - if ((hasJoined || bossBarConfig.isShowToAll()) + if ((hasJoined || bossBarConfigImpl.showToAll()) && !senderMap.containsKey(player.getUniqueId())) { - BossBarSender sender = new BossBarSender(player, bossBarConfig, competition); + BossBarSender sender = new BossBarSender(player, bossBarConfigImpl, competition); if (!sender.isVisible()) { sender.show(); } @@ -114,7 +114,7 @@ public class BossBarManager implements Listener { public void showBossBarTo(Player player) { BossBarSender sender = senderMap.get(player.getUniqueId()); if (sender == null) { - sender = new BossBarSender(player, bossBarConfig, competition); + sender = new BossBarSender(player, bossBarConfigImpl, competition); senderMap.put(player.getUniqueId(), sender); } if (!sender.isVisible()) { diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/bossbar/BossBarSender.java b/core/src/main/java/net/momirealms/customfishing/mechanic/competition/bossbar/BossBarSender.java similarity index 85% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/bossbar/BossBarSender.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/competition/bossbar/BossBarSender.java index 262ceda3..fb733831 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/bossbar/BossBarSender.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/competition/bossbar/BossBarSender.java @@ -23,10 +23,9 @@ import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.wrappers.WrappedChatComponent; import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; -import net.momirealms.customfishing.CustomFishingPluginImpl; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.mechanic.competition.BossBarConfig; +import net.momirealms.customfishing.BukkitCustomFishingPluginImpl; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; +import net.momirealms.customfishing.api.mechanic.competition.info.BossBarConfigImpl; import net.momirealms.customfishing.api.scheduler.CancellableTask; import net.momirealms.customfishing.api.util.ReflectionUtils; import net.momirealms.customfishing.mechanic.competition.Competition; @@ -52,7 +51,7 @@ public class BossBarSender { private final DynamicText[] texts; private CancellableTask senderTask; private final UUID uuid; - private final BossBarConfig config; + private final BossBarConfigImpl config; private boolean isShown; private final Competition competition; private final HashMap privatePlaceholders; @@ -64,7 +63,7 @@ public class BossBarSender { * @param config The configuration for the boss bar. * @param competition The competition associated with this boss bar. */ - public BossBarSender(Player player, BossBarConfig config, Competition competition) { + public BossBarSender(Player player, BossBarConfigImpl config, Competition competition) { this.player = player; this.uuid = UUID.randomUUID(); this.config = config; @@ -74,7 +73,7 @@ public class BossBarSender { this.privatePlaceholders.put("{player}", player.getName()); this.updatePrivatePlaceholders(); - String[] str = config.getTexts(); + String[] str = config.texts(); texts = new DynamicText[str.length]; for (int i = 0; i < str.length; i++) { texts[i] = new DynamicText(player, str[i]); @@ -98,23 +97,23 @@ public class BossBarSender { */ public void show() { this.isShown = true; - CustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, getCreatePacket()); - senderTask = CustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(() -> { + BukkitCustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, getCreatePacket()); + senderTask = BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(() -> { switchTimer++; - if (switchTimer > config.getSwitchInterval()) { + if (switchTimer > config.switchInterval()) { switchTimer = 0; counter++; } - if (refreshTimer < config.getRefreshRate()){ + if (refreshTimer < config.refreshRate()){ refreshTimer++; } else { refreshTimer = 0; DynamicText text = texts[counter % (texts.length)]; updatePrivatePlaceholders(); if (text.update(privatePlaceholders)) { - CustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, getUpdatePacket(text)); + BukkitCustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, getUpdatePacket(text)); } - CustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, getProgressPacket()); + BukkitCustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, getProgressPacket()); } }, 50, 50, TimeUnit.MILLISECONDS); } @@ -133,7 +132,7 @@ public class BossBarSender { * * @return The boss bar configuration. */ - public BossBarConfig getConfig() { + public BossBarConfigImpl getConfig() { return config; } @@ -141,7 +140,7 @@ public class BossBarSender { * Hides the boss bar from the player. */ public void hide() { - CustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, getRemovePacket()); + BukkitCustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, getRemovePacket()); if (senderTask != null && !senderTask.isCancelled()) senderTask.cancel(); this.isShown = false; } @@ -182,7 +181,7 @@ public class BossBarSender { internalStructure.getChatComponents().write(0, WrappedChatComponent.fromJson(GsonComponentSerializer.gson().serialize(MiniMessage.miniMessage().deserialize(texts[0].getLatestValue())))); internalStructure.getFloat().write(0, competition.getProgress()); internalStructure.getEnumModifier(BarColor.class, 2).write(0, config.getColor()); - internalStructure.getEnumModifier(BossBarConfig.Overlay.class, 3).write(0, config.getOverlay()); + internalStructure.getEnumModifier(BossBarConfigImpl.Overlay.class, 3).write(0, config.getOverlay()); internalStructure.getModifier().write(4, false); internalStructure.getModifier().write(5, false); internalStructure.getModifier().write(6, false); diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/ranking/LocalRankingImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/competition/ranking/LocalRankingImpl.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/ranking/LocalRankingImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/competition/ranking/LocalRankingImpl.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/ranking/RedisRankingImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/competition/ranking/RedisRankingImpl.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/competition/ranking/RedisRankingImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/competition/ranking/RedisRankingImpl.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/effect/EffectManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/effect/EffectManagerImpl.java similarity index 84% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/effect/EffectManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/effect/EffectManagerImpl.java index fc0f978b..e66aa8b7 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/effect/EffectManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/effect/EffectManagerImpl.java @@ -17,20 +17,18 @@ package net.momirealms.customfishing.mechanic.effect; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.common.Key; import net.momirealms.customfishing.api.common.Pair; -import net.momirealms.customfishing.api.manager.EffectManager; +import net.momirealms.customfishing.api.mechanic.effect.EffectManager; import net.momirealms.customfishing.api.mechanic.GlobalSettings; import net.momirealms.customfishing.api.mechanic.effect.BaseEffect; import net.momirealms.customfishing.api.mechanic.effect.EffectCarrier; import net.momirealms.customfishing.api.mechanic.effect.EffectModifier; import net.momirealms.customfishing.api.mechanic.effect.FishingEffect; -import net.momirealms.customfishing.api.mechanic.misc.Value; -import net.momirealms.customfishing.api.mechanic.misc.WeightModifier; +import net.momirealms.customfishing.api.mechanic.misc.value.MathValue; import net.momirealms.customfishing.api.mechanic.requirement.Requirement; -import net.momirealms.customfishing.api.util.LogUtils; -import net.momirealms.customfishing.mechanic.misc.value.PlainValue; +import net.momirealms.customfishing.mechanic.misc.value.PlainMathValue; import net.momirealms.customfishing.util.ConfigUtils; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; @@ -42,11 +40,11 @@ import java.util.*; public class EffectManagerImpl implements EffectManager { - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; private final HashMap effectMap; - public EffectManagerImpl(CustomFishingPlugin plugin) { + public EffectManagerImpl(BukkitCustomFishingPlugin plugin) { this.plugin = plugin; this.effectMap = new HashMap<>(); } @@ -246,16 +244,16 @@ public class EffectManagerImpl implements EffectManager { @Override public BaseEffect getBaseEffect(ConfigurationSection section) { if (section == null) return new BaseEffect( - new PlainValue(0), new PlainValue(1d), - new PlainValue(0), new PlainValue(1d), - new PlainValue(0), new PlainValue(1d) + new PlainMathValue(0), new PlainMathValue(1d), + new PlainMathValue(0), new PlainMathValue(1d), + new PlainMathValue(0), new PlainMathValue(1d) ); - Value waitTime = section.contains("wait-time") ? ConfigUtils.getValue(section.get("wait-time")) : new PlainValue(0); - Value difficulty = section.contains("difficulty") ? ConfigUtils.getValue(section.get("difficulty")) : new PlainValue(0); - Value gameTime = section.contains("game-time") ? ConfigUtils.getValue(section.get("game-time")) : new PlainValue(0); - Value waitTimeMultiplier = section.contains("wait-time-multiplier") ? ConfigUtils.getValue(section.get("wait-time-multiplier")) : new PlainValue(1); - Value difficultyMultiplier = section.contains("difficulty-multiplier") ? ConfigUtils.getValue(section.get("difficulty-multiplier")) : new PlainValue(1); - Value gameTimeMultiplier = section.contains("game-time-multiplier") ? ConfigUtils.getValue(section.get("game-time-multiplier")) : new PlainValue(1); + MathValue waitTime = section.contains("wait-time") ? ConfigUtils.getValue(section.get("wait-time")) : new PlainMathValue(0); + MathValue difficulty = section.contains("difficulty") ? ConfigUtils.getValue(section.get("difficulty")) : new PlainMathValue(0); + MathValue gameTime = section.contains("game-time") ? ConfigUtils.getValue(section.get("game-time")) : new PlainMathValue(0); + MathValue waitTimeMultiplier = section.contains("wait-time-multiplier") ? ConfigUtils.getValue(section.get("wait-time-multiplier")) : new PlainMathValue(1); + MathValue difficultyMultiplier = section.contains("difficulty-multiplier") ? ConfigUtils.getValue(section.get("difficulty-multiplier")) : new PlainMathValue(1); + MathValue gameTimeMultiplier = section.contains("game-time-multiplier") ? ConfigUtils.getValue(section.get("game-time-multiplier")) : new PlainMathValue(1); return new BaseEffect( waitTime, waitTimeMultiplier, difficulty, difficultyMultiplier, @@ -308,7 +306,7 @@ public class EffectManagerImpl implements EffectManager { case "wait-time" -> { var value = ConfigUtils.getValue(section.get("value")); return ((effect, condition) -> { - effect.setWaitTime(effect.getWaitTime() + value.get(condition.getPlayer(), condition.getArgs())); + effect.setWaitTime(effect.waitTimeAdder() + value.get(condition.getPlayer(), condition.getArgs())); }); } case "hook-time", "wait-time-multiplier" -> { @@ -320,55 +318,55 @@ public class EffectManagerImpl implements EffectManager { case "difficulty" -> { var value = ConfigUtils.getValue(section.get("value")); return ((effect, condition) -> { - effect.setDifficulty(effect.getDifficulty() + value.get(condition.getPlayer(), condition.getArgs())); + effect.setDifficulty(effect.difficultyAdder() + value.get(condition.getPlayer(), condition.getArgs())); }); } case "difficulty-multiplier", "difficulty-bonus" -> { var value = ConfigUtils.getValue(section.get("value")); return ((effect, condition) -> { - effect.setDifficultyMultiplier(effect.getDifficultyMultiplier() + value.get(condition.getPlayer(), condition.getArgs()) - 1); + effect.setDifficultyMultiplier(effect.difficultyMultiplier() + value.get(condition.getPlayer(), condition.getArgs()) - 1); }); } case "multiple-loot" -> { var value = ConfigUtils.getValue(section.get("value")); return ((effect, condition) -> { - effect.setMultipleLootChance(effect.getMultipleLootChance() + value.get(condition.getPlayer(), condition.getArgs())); + effect.setMultipleLootChance(effect.multipleLootChance() + value.get(condition.getPlayer(), condition.getArgs())); }); } case "score" -> { var value = ConfigUtils.getValue(section.get("value")); return ((effect, condition) -> { - effect.setScore(effect.getScore() + value.get(condition.getPlayer(), condition.getArgs())); + effect.setScore(effect.scoreAdder() + value.get(condition.getPlayer(), condition.getArgs())); }); } case "score-bonus", "score-multiplier" -> { var value = ConfigUtils.getValue(section.get("value")); return ((effect, condition) -> { - effect.setScoreMultiplier(effect.getScoreMultiplier() + value.get(condition.getPlayer(), condition.getArgs()) - 1); + effect.setScoreMultiplier(effect.scoreMultiplier() + value.get(condition.getPlayer(), condition.getArgs()) - 1); }); } case "size" -> { var value = ConfigUtils.getValue(section.get("value")); return ((effect, condition) -> { - effect.setSize(effect.getSize() + value.get(condition.getPlayer(), condition.getArgs())); + effect.setSize(effect.sizeAdder() + value.get(condition.getPlayer(), condition.getArgs())); }); } case "size-bonus", "size-multiplier" -> { var value = ConfigUtils.getValue(section.get("value")); return ((effect, condition) -> { - effect.setSizeMultiplier(effect.getSizeMultiplier() + value.get(condition.getPlayer(), condition.getArgs()) - 1); + effect.setSizeMultiplier(effect.sizeMultiplier() + value.get(condition.getPlayer(), condition.getArgs()) - 1); }); } case "game-time" -> { var value = ConfigUtils.getValue(section.get("value")); return ((effect, condition) -> { - effect.setGameTime(effect.getGameTime() + value.get(condition.getPlayer(), condition.getArgs())); + effect.setGameTime(effect.gameTimeAdder() + value.get(condition.getPlayer(), condition.getArgs())); }); } case "game-time-bonus", "game-time-multiplier" -> { var value = ConfigUtils.getValue(section.get("value")); return ((effect, condition) -> { - effect.setGameTimeMultiplier(effect.getGameTimeMultiplier() + value.get(condition.getPlayer(), condition.getArgs()) - 1); + effect.setGameTimeMultiplier(effect.gameTimeMultiplier() + value.get(condition.getPlayer(), condition.getArgs()) - 1); }); } case "lava-fishing" -> { @@ -379,7 +377,7 @@ public class EffectManagerImpl implements EffectManager { EffectModifier[] modifiers = getEffectModifiers(section.getConfigurationSection("effects")); return ((effect, condition) -> { for (Requirement requirement : requirements) - if (!requirement.isConditionMet(condition)) + if (!requirement.check(condition)) return; for (EffectModifier modifier : modifiers) { modifier.modify(effect, condition); diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/entity/EntityManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/entity/EntityManagerImpl.java similarity index 81% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/entity/EntityManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/entity/EntityManagerImpl.java index d1c7f108..dedaa4ed 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/entity/EntityManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/entity/EntityManagerImpl.java @@ -17,13 +17,12 @@ package net.momirealms.customfishing.mechanic.entity; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.manager.EntityManager; -import net.momirealms.customfishing.api.mechanic.entity.EntityConfig; -import net.momirealms.customfishing.api.mechanic.entity.EntityLibrary; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; +import net.momirealms.customfishing.api.mechanic.entity.EntityManager; +import net.momirealms.customfishing.api.mechanic.entity.EntityConfigImpl; +import net.momirealms.customfishing.api.integration.EntityProvider; import net.momirealms.customfishing.api.mechanic.loot.Loot; -import net.momirealms.customfishing.api.util.LogUtils; -import net.momirealms.customfishing.compatibility.entity.VanillaEntityImpl; +import net.momirealms.customfishing.bukkit.compatibility.entity.VanillaEntityImpl; import org.bukkit.Location; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; @@ -35,15 +34,15 @@ import java.util.*; public class EntityManagerImpl implements EntityManager { - private final CustomFishingPlugin plugin; - private final HashMap entityLibraryMap; - private final HashMap entityConfigMap; + private final BukkitCustomFishingPlugin plugin; + private final HashMap entityLibraryMap; + private final HashMap entityConfigMap; - public EntityManagerImpl(CustomFishingPlugin plugin) { + public EntityManagerImpl(BukkitCustomFishingPlugin plugin) { this.plugin = plugin; this.entityLibraryMap = new HashMap<>(); this.entityConfigMap = new HashMap<>(); - this.registerEntityLibrary(new VanillaEntityImpl()); + this.registerEntityProvider(new VanillaEntityImpl()); } public void load() { @@ -51,9 +50,9 @@ public class EntityManagerImpl implements EntityManager { } public void unload() { - HashMap tempMap = new HashMap<>(this.entityConfigMap); + HashMap tempMap = new HashMap<>(this.entityConfigMap); this.entityConfigMap.clear(); - for (Map.Entry entry : tempMap.entrySet()) { + for (Map.Entry entry : tempMap.entrySet()) { if (entry.getValue().isPersist()) { tempMap.put(entry.getKey(), entry.getValue()); } @@ -63,13 +62,13 @@ public class EntityManagerImpl implements EntityManager { /** * Registers an entity library for use in the plugin. * - * @param entityLibrary The entity library to register. + * @param entityProvider The entity library to register. * @return {@code true} if the entity library was successfully registered, {@code false} if it already exists. */ @Override - public boolean registerEntityLibrary(EntityLibrary entityLibrary) { - if (entityLibraryMap.containsKey(entityLibrary.identification())) return false; - else entityLibraryMap.put(entityLibrary.identification(), entityLibrary); + public boolean registerEntityProvider(EntityProvider entityProvider) { + if (entityLibraryMap.containsKey(entityProvider.identifier())) return false; + else entityLibraryMap.put(entityProvider.identifier(), entityProvider); return true; } @@ -80,7 +79,7 @@ public class EntityManagerImpl implements EntityManager { * @return {@code true} if the entity library was successfully unregistered, {@code false} if it does not exist. */ @Override - public boolean unregisterEntityLibrary(String identification) { + public boolean unregisterEntityProvider(String identification) { return entityLibraryMap.remove(identification) != null; } @@ -131,14 +130,14 @@ public class EntityManagerImpl implements EntityManager { if (property != null) { propertyMap.putAll(property.getValues(false)); } - EntityConfig entityConfig = new EntityConfig.Builder() + EntityConfigImpl entityConfigImpl = new EntityConfigImpl.BuilderImpl() .entityID(entityID) .persist(false) .horizontalVector(section.getDouble("velocity.horizontal", 1.1)) .verticalVector(section.getDouble("velocity.vertical", 1.2)) .propertyMap(propertyMap) .build(); - entityConfigMap.put(entry.getKey(), entityConfig); + entityConfigMap.put(entry.getKey(), entityConfigImpl); } } } @@ -158,7 +157,7 @@ public class EntityManagerImpl implements EntityManager { */ @Override public void summonEntity(Location hookLocation, Location playerLocation, Loot loot) { - EntityConfig config = entityConfigMap.get(loot.getID()); + EntityConfigImpl config = entityConfigMap.get(loot.getID()); if (config == null) { LogUtils.warn("Entity: " + loot.getID() + " doesn't exist."); return; @@ -169,7 +168,7 @@ public class EntityManagerImpl implements EntityManager { String[] split = entityID.split(":", 2); String identification = split[0]; String id = split[1]; - EntityLibrary library = entityLibraryMap.get(identification); + EntityProvider library = entityLibraryMap.get(identification); entity = library.spawn(hookLocation, id, config.getPropertyMap()); } else { entity = entityLibraryMap.get("vanilla").spawn(hookLocation, entityID, config.getPropertyMap()); diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/fishing/BaitAnimationTask.java b/core/src/main/java/net/momirealms/customfishing/mechanic/fishing/BaitAnimationTask.java similarity index 66% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/fishing/BaitAnimationTask.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/fishing/BaitAnimationTask.java index 8e7e6381..339861ba 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/fishing/BaitAnimationTask.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/fishing/BaitAnimationTask.java @@ -17,8 +17,8 @@ package net.momirealms.customfishing.mechanic.fishing; -import net.momirealms.customfishing.CustomFishingPluginImpl; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.BukkitCustomFishingPluginImpl; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.scheduler.CancellableTask; import net.momirealms.customfishing.util.FakeItemUtils; import org.bukkit.entity.FishHook; @@ -46,15 +46,15 @@ public class BaitAnimationTask implements Runnable { * @param fishHook The FishHook entity. * @param baitItem The bait ItemStack. */ - public BaitAnimationTask(CustomFishingPlugin plugin, Player player, FishHook fishHook, ItemStack baitItem) { + public BaitAnimationTask(BukkitCustomFishingPlugin plugin, Player player, FishHook fishHook, ItemStack baitItem) { this.player = player; this.fishHook = fishHook; entityID = ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); - if (plugin.getVersionManager().isVersionNewerThan1_19_R3()) { - CustomFishingPluginImpl.sendPackets(player, FakeItemUtils.getSpawnPacket(entityID, fishHook.getLocation()), FakeItemUtils.getMetaPacket(entityID, baitItem)); + if (plugin.getVersionManager().isVersionNewerThan1_19_4()) { + BukkitCustomFishingPluginImpl.sendPackets(player, FakeItemUtils.getSpawnPacket(entityID, fishHook.getLocation()), FakeItemUtils.getMetaPacket(entityID, baitItem)); } else { - CustomFishingPluginImpl.sendPacket(player, FakeItemUtils.getSpawnPacket(entityID, fishHook.getLocation())); - CustomFishingPluginImpl.sendPacket(player, FakeItemUtils.getMetaPacket(entityID, baitItem)); + BukkitCustomFishingPluginImpl.sendPacket(player, FakeItemUtils.getSpawnPacket(entityID, fishHook.getLocation())); + BukkitCustomFishingPluginImpl.sendPacket(player, FakeItemUtils.getMetaPacket(entityID, baitItem)); } this.cancellableTask = plugin.getScheduler().runTaskAsyncTimer(this, 50, 50, TimeUnit.MILLISECONDS); } @@ -69,8 +69,8 @@ public class BaitAnimationTask implements Runnable { ) { cancelAnimation(); } else { - CustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, FakeItemUtils.getVelocityPacket(entityID, fishHook.getVelocity())); - CustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, FakeItemUtils.getTpPacket(entityID, fishHook.getLocation())); + BukkitCustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, FakeItemUtils.getVelocityPacket(entityID, fishHook.getVelocity())); + BukkitCustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, FakeItemUtils.getTpPacket(entityID, fishHook.getLocation())); } } @@ -79,6 +79,6 @@ public class BaitAnimationTask implements Runnable { */ private void cancelAnimation() { cancellableTask.cancel(); - CustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, FakeItemUtils.getDestroyPacket(entityID)); + BukkitCustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, FakeItemUtils.getDestroyPacket(entityID)); } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/fishing/FishingManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/fishing/FishingManagerImpl.java similarity index 96% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/fishing/FishingManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/fishing/FishingManagerImpl.java index a760a84c..62341e8d 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/fishing/FishingManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/fishing/FishingManagerImpl.java @@ -22,20 +22,17 @@ import de.tr7zw.changeme.nbtapi.NBTCompound; import de.tr7zw.changeme.nbtapi.NBTItem; import net.kyori.adventure.key.Key; import net.kyori.adventure.sound.Sound; -import net.momirealms.customfishing.CustomFishingPluginImpl; -import net.momirealms.customfishing.adventure.AdventureHelper; +import net.momirealms.customfishing.BukkitCustomFishingPluginImpl; import net.momirealms.customfishing.api.common.Pair; import net.momirealms.customfishing.api.event.FishingResultEvent; import net.momirealms.customfishing.api.event.LavaFishingEvent; import net.momirealms.customfishing.api.event.RodCastEvent; -import net.momirealms.customfishing.api.manager.FishingManager; -import net.momirealms.customfishing.api.manager.RequirementManager; +import net.momirealms.customfishing.api.mechanic.fishing.FishingManager; +import net.momirealms.customfishing.api.mechanic.requirement.RequirementManager; import net.momirealms.customfishing.api.mechanic.GlobalSettings; import net.momirealms.customfishing.api.mechanic.TempFishingState; import net.momirealms.customfishing.api.mechanic.action.ActionTrigger; import net.momirealms.customfishing.api.mechanic.competition.FishingCompetition; -import net.momirealms.customfishing.api.mechanic.condition.Condition; -import net.momirealms.customfishing.api.mechanic.condition.FishingPreparation; import net.momirealms.customfishing.api.mechanic.effect.Effect; import net.momirealms.customfishing.api.mechanic.effect.EffectCarrier; import net.momirealms.customfishing.api.mechanic.effect.EffectModifier; @@ -46,7 +43,6 @@ import net.momirealms.customfishing.api.mechanic.game.GameSettings; import net.momirealms.customfishing.api.mechanic.game.GamingPlayer; import net.momirealms.customfishing.api.mechanic.loot.Loot; import net.momirealms.customfishing.api.mechanic.loot.LootType; -import net.momirealms.customfishing.api.util.LogUtils; import net.momirealms.customfishing.api.util.WeightUtils; import net.momirealms.customfishing.mechanic.requirement.RequirementManagerImpl; import net.momirealms.customfishing.setting.CFConfig; @@ -72,14 +68,14 @@ import java.util.concurrent.ConcurrentHashMap; public class FishingManagerImpl implements Listener, FishingManager { - private final CustomFishingPluginImpl plugin; + private final BukkitCustomFishingPluginImpl plugin; private final ConcurrentHashMap hookCacheMap; private final ConcurrentHashMap hookCheckMap; private final ConcurrentHashMap tempFishingStateMap; private final ConcurrentHashMap gamingPlayerMap; private final ConcurrentHashMap> vanillaLootMap; - public FishingManagerImpl(CustomFishingPluginImpl plugin) { + public FishingManagerImpl(BukkitCustomFishingPluginImpl plugin) { this.plugin = plugin; this.hookCacheMap = new ConcurrentHashMap<>(); this.tempFishingStateMap = new ConcurrentHashMap<>(); @@ -635,12 +631,12 @@ public class FishingManagerImpl implements Listener, FishingManager { var effect = state.getEffect(); var fishingPreparation = state.getPreparation(); var player = fishingPreparation.getPlayer(); - fishingPreparation.insertArg("{size-multiplier}", String.valueOf(effect.getSizeMultiplier())); - fishingPreparation.insertArg("{size-fixed}", String.valueOf(effect.getSize())); + fishingPreparation.insertArg("{size-multiplier}", String.valueOf(effect.sizeMultiplier())); + fishingPreparation.insertArg("{size-fixed}", String.valueOf(effect.sizeAdder())); int amount; if (loot.getType() == LootType.ITEM) { - amount = (int) effect.getMultipleLootChance(); - amount += Math.random() < (effect.getMultipleLootChance() - amount) ? 2 : 1; + amount = (int) effect.multipleLootChance(); + amount += Math.random() < (effect.multipleLootChance() - amount) ? 2 : 1; } else { amount = 1; } @@ -741,7 +737,7 @@ public class FishingManagerImpl implements Listener, FishingManager { case TOTAL_SCORE -> { score = loot.getScore(); if (score > 0) { - score = score * effect.getScoreMultiplier() + effect.getScore(); + score = score * effect.scoreMultiplier() + effect.scoreAdder(); competition.refreshData(player, score); } else { score = 0; @@ -772,7 +768,7 @@ public class FishingManagerImpl implements Listener, FishingManager { it.addLootAmount(loot, fishingPreparation, 1); String size = fishingPreparation.getArg("{SIZE}"); if (size != null) - if (it.setSizeIfHigher(loot.getStatisticKey().getSizeKey(), Float.parseFloat(size))) { + if (it.setSizeIfHigher(loot.getStatisticKey().sizeKey(), Float.parseFloat(size))) { if (!loot.disableGlobalAction()) GlobalSettings.triggerLootActions(ActionTrigger.NEW_SIZE_RECORD, fishingPreparation); loot.triggerActions(ActionTrigger.NEW_SIZE_RECORD, fishingPreparation); @@ -784,16 +780,16 @@ public class FishingManagerImpl implements Listener, FishingManager { * Starts a fishing game for the specified player with the given condition and effect. * * @param player The player starting the fishing game. - * @param condition The condition used to determine the game. + * @param playerContext The condition used to determine the game. * @param effect The effect applied to the game. */ @Override - public boolean startFishingGame(Player player, Condition condition, Effect effect) { - Map gameWithWeight = plugin.getGameManager().getGameWithWeight(condition); + public boolean startFishingGame(Player player, PlayerContext playerContext, Effect effect) { + Map gameWithWeight = plugin.getGameManager().getGameWithWeight(playerContext); String random = WeightUtils.getRandom(gameWithWeight); Pair gamePair = plugin.getGameManager().getGameInstance(random); if (random == null) { - LogUtils.warn("No game is available for player:" + player.getName() + " location:" + condition.getLocation()); + LogUtils.warn("No game is available for player:" + player.getName() + " location:" + playerContext.getLocation()); return false; } if (gamePair == null) { diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/fishing/FishingPreparationImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/fishing/FishingPreparationImpl.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/fishing/FishingPreparationImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/fishing/FishingPreparationImpl.java index 76a54c58..96c54d19 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/fishing/FishingPreparationImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/fishing/FishingPreparationImpl.java @@ -19,11 +19,10 @@ package net.momirealms.customfishing.mechanic.fishing; import de.tr7zw.changeme.nbtapi.NBTCompound; import de.tr7zw.changeme.nbtapi.NBTItem; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.mechanic.GlobalSettings; import net.momirealms.customfishing.api.mechanic.action.Action; import net.momirealms.customfishing.api.mechanic.action.ActionTrigger; -import net.momirealms.customfishing.api.mechanic.condition.FishingPreparation; import net.momirealms.customfishing.api.mechanic.effect.EffectCarrier; import net.momirealms.customfishing.api.mechanic.effect.EffectModifier; import net.momirealms.customfishing.api.mechanic.effect.FishingEffect; @@ -48,7 +47,7 @@ public class FishingPreparationImpl extends FishingPreparation { private final List effects; private boolean canFish = true; - public FishingPreparationImpl(Player player, CustomFishingPlugin plugin) { + public FishingPreparationImpl(Player player, BukkitCustomFishingPlugin plugin) { super(player); PlayerInventory playerInventory = player.getInventory(); diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/fishing/HookCheckTimerTask.java b/core/src/main/java/net/momirealms/customfishing/mechanic/fishing/HookCheckTimerTask.java similarity index 91% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/fishing/HookCheckTimerTask.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/fishing/HookCheckTimerTask.java index a0eafee1..e4cdd1e1 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/fishing/HookCheckTimerTask.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/fishing/HookCheckTimerTask.java @@ -19,13 +19,11 @@ package net.momirealms.customfishing.mechanic.fishing; import net.kyori.adventure.key.Key; import net.kyori.adventure.sound.Sound; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.event.FishHookLandEvent; import net.momirealms.customfishing.api.event.LavaFishingEvent; import net.momirealms.customfishing.api.mechanic.TempFishingState; import net.momirealms.customfishing.api.mechanic.action.ActionTrigger; -import net.momirealms.customfishing.api.mechanic.condition.FishingPreparation; import net.momirealms.customfishing.api.mechanic.effect.Effect; import net.momirealms.customfishing.api.mechanic.effect.FishingEffect; import net.momirealms.customfishing.api.mechanic.loot.Loot; @@ -86,7 +84,7 @@ public class HookCheckTimerTask implements Runnable { this.fishHook = fishHook; this.initialEffect = initialEffect; this.fishingPreparation = fishingPreparation; - this.hookMovementTask = CustomFishingPlugin.get().getScheduler().runTaskSyncTimer(this, fishHook.getLocation(), 1, 1); + this.hookMovementTask = BukkitCustomFishingPlugin.get().getScheduler().runTaskSyncTimer(this, fishHook.getLocation(), 1, 1); this.lureLevel = fishingPreparation.getRodItemStack().getEnchantmentLevel(Enchantment.LURE); this.firstTime = true; this.tempEffect = new FishingEffect(); @@ -114,7 +112,7 @@ public class HookCheckTimerTask implements Runnable { this.fishingPreparation.setLocation(this.fishHook.getLocation()); this.fishingPreparation.mergeEffect(this.initialEffect); - if (!initialEffect.canLavaFishing()) { + if (!initialEffect.allowLavaFishing()) { this.destroy(); return; } @@ -156,7 +154,7 @@ public class HookCheckTimerTask implements Runnable { this.tempEffect = new FishingEffect(); this.tempEffect.merge(this.initialEffect); this.manager.removeTempFishingState(fishingPreparation.getPlayer()); - CustomFishingPlugin.get().debug("No loot available for " + fishingPreparation.getPlayer().getName() + " at " + fishingPreparation.getLocation()); + BukkitCustomFishingPlugin.get().debug("No loot available for " + fishingPreparation.getPlayer().getName() + " at " + fishingPreparation.getLocation()); } this.makeHookStatic(this.fishHook.getLocation()); @@ -191,7 +189,7 @@ public class HookCheckTimerTask implements Runnable { this.tempEffect = new FishingEffect(); this.tempEffect.merge(this.initialEffect); this.manager.removeTempFishingState(fishingPreparation.getPlayer()); - CustomFishingPlugin.get().debug("No loot available for " + fishingPreparation.getPlayer().getName() + " at " + fishingPreparation.getLocation()); + BukkitCustomFishingPlugin.get().debug("No loot available for " + fishingPreparation.getPlayer().getName() + " at " + fishingPreparation.getLocation()); } else { this.tempEffect = this.loot.getBaseEffect().build(fishingPreparation.getPlayer(), fishingPreparation.getArgs()); this.tempEffect.merge(this.initialEffect); @@ -224,7 +222,7 @@ public class HookCheckTimerTask implements Runnable { } private void setNextLoot() { - Loot nextLoot = CustomFishingPlugin.get().getLootManager().getNextLoot(initialEffect, fishingPreparation); + Loot nextLoot = BukkitCustomFishingPlugin.get().getLootManager().getNextLoot(initialEffect, fishingPreparation); if (nextLoot == null) { this.loot = null; return; @@ -239,8 +237,8 @@ public class HookCheckTimerTask implements Runnable { fishingPreparation.insertArg("{nick}", loot.getNick()); fishingPreparation.insertArg("{loot}", loot.getID()); if (!loot.disableStats()) { - fishingPreparation.insertArg("{statistics_size}", loot.getStatisticKey().getSizeKey()); - fishingPreparation.insertArg("{statistics_amount}", loot.getStatisticKey().getAmountKey()); + fishingPreparation.insertArg("{statistics_size}", loot.getStatisticKey().sizeKey()); + fishingPreparation.insertArg("{statistics_amount}", loot.getStatisticKey().amountKey()); } manager.setTempFishingState(fishingPreparation.getPlayer(), new TempFishingState( tempEffect, @@ -266,14 +264,14 @@ public class HookCheckTimerTask implements Runnable { if (CFConfig.overrideVanilla) { random = ThreadLocalRandom.current().nextInt(CFConfig.lavaMinTime, CFConfig.lavaMaxTime); random *= tempEffect.getWaitTimeMultiplier(); - random += tempEffect.getWaitTime(); + random += tempEffect.waitTimeAdder(); random = Math.max(1, random); } else { random = ThreadLocalRandom.current().nextInt(CFConfig.lavaMinTime, CFConfig.lavaMaxTime); random -= lureLevel * 100; random = Math.max(CFConfig.lavaMinTime, random); random *= tempEffect.getWaitTimeMultiplier(); - random += tempEffect.getWaitTime(); + random += tempEffect.waitTimeAdder(); random = Math.max(1, random); } @@ -310,7 +308,7 @@ public class HookCheckTimerTask implements Runnable { 1 ); - CustomFishingPlugin.get().getScheduler().runTaskAsyncLater(() -> { + BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncLater(() -> { fishHooked = false; reserve = false; }, (2 * 20) * 50L, TimeUnit.MILLISECONDS); @@ -329,7 +327,7 @@ public class HookCheckTimerTask implements Runnable { a.setSmall(true); a.setGravity(false); a.getPersistentDataContainer().set( - Objects.requireNonNull(NamespacedKey.fromString("lavafishing", CustomFishingPlugin.get())), + Objects.requireNonNull(NamespacedKey.fromString("lavafishing", BukkitCustomFishingPlugin.get())), PersistentDataType.STRING, "temp" ); @@ -349,10 +347,10 @@ public class HookCheckTimerTask implements Runnable { private void setWaitTime() { if (CFConfig.overrideVanilla) { double initialTime = ThreadLocalRandom.current().nextInt(CFConfig.waterMaxTime - CFConfig.waterMinTime + 1) + CFConfig.waterMinTime; - fishHook.setWaitTime(Math.max(1, (int) (initialTime * tempEffect.getWaitTimeMultiplier() + tempEffect.getWaitTime()))); + fishHook.setWaitTime(Math.max(1, (int) (initialTime * tempEffect.getWaitTimeMultiplier() + tempEffect.waitTimeAdder()))); } else { - fishHook.setMinWaitTime(Math.max(1, (int) (fishHook.getMinWaitTime() * tempEffect.getWaitTimeMultiplier() + tempEffect.getWaitTime()))); - fishHook.setMaxWaitTime(Math.max(2, (int) (fishHook.getMaxWaitTime() * tempEffect.getWaitTimeMultiplier() + tempEffect.getWaitTime()))); + fishHook.setMinWaitTime(Math.max(1, (int) (fishHook.getMinWaitTime() * tempEffect.getWaitTimeMultiplier() + tempEffect.waitTimeAdder()))); + fishHook.setMaxWaitTime(Math.max(2, (int) (fishHook.getMaxWaitTime() * tempEffect.getWaitTimeMultiplier() + tempEffect.waitTimeAdder()))); } } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/fishing/LavaEffectTask.java b/core/src/main/java/net/momirealms/customfishing/mechanic/fishing/LavaEffectTask.java similarity index 90% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/fishing/LavaEffectTask.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/fishing/LavaEffectTask.java index 22a06065..c80de8a3 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/fishing/LavaEffectTask.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/fishing/LavaEffectTask.java @@ -17,7 +17,7 @@ package net.momirealms.customfishing.mechanic.fishing; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.scheduler.CancellableTask; import org.bukkit.Location; import org.bukkit.Particle; @@ -53,7 +53,7 @@ public class LavaEffectTask implements Runnable { startLoc.getY(), (startLoc.getZ() + endLoc.getZ())/2 + Math.random() * 12 - 6 ); - this.lavaTask = CustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(this, delay * 50L, 50, TimeUnit.MILLISECONDS); + this.lavaTask = BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(this, delay * 50L, 50, TimeUnit.MILLISECONDS); } @Override @@ -61,7 +61,7 @@ public class LavaEffectTask implements Runnable { timer++; if (timer > 60) { lavaTask.cancel(); - CustomFishingPlugin.get().getScheduler().runTaskSync(hookCheckTimerTask::getHooked, startLoc); + BukkitCustomFishingPlugin.get().getScheduler().runTaskSync(hookCheckTimerTask::getHooked, startLoc); } else { double t = (double) timer / 60; Location particleLoc = endLoc.clone().multiply(Math.pow((1 - t), 2)).add(controlLoc.clone().multiply(2 * t * (1 - t))).add(startLoc.clone().multiply(Math.pow(t, 2))); diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/game/GameManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/game/GameManagerImpl.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/game/GameManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/game/GameManagerImpl.java index 50037e9d..9f408f9b 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/game/GameManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/game/GameManagerImpl.java @@ -19,14 +19,10 @@ package net.momirealms.customfishing.mechanic.game; import net.kyori.adventure.key.Key; import net.kyori.adventure.sound.Sound; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.common.Pair; -import net.momirealms.customfishing.api.manager.GameManager; -import net.momirealms.customfishing.api.mechanic.condition.Condition; +import net.momirealms.customfishing.api.mechanic.game.GameManager; import net.momirealms.customfishing.api.mechanic.game.*; -import net.momirealms.customfishing.api.util.FontUtils; -import net.momirealms.customfishing.api.util.LogUtils; import net.momirealms.customfishing.api.util.OffsetUtils; import net.momirealms.customfishing.mechanic.requirement.RequirementManagerImpl; import net.momirealms.customfishing.util.ClassUtils; @@ -45,12 +41,12 @@ import java.util.concurrent.TimeUnit; @SuppressWarnings("DuplicatedCode") public class GameManagerImpl implements GameManager { - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; private final HashMap gameCreatorMap; private final HashMap> gameInstanceMap; private final String EXPANSION_FOLDER = "expansions/minigame"; - public GameManagerImpl(CustomFishingPlugin plugin) { + public GameManagerImpl(BukkitCustomFishingPlugin plugin) { this.plugin = plugin; this.gameCreatorMap = new HashMap<>(); this.gameInstanceMap = new HashMap<>(); @@ -136,12 +132,12 @@ public class GameManagerImpl implements GameManager { /** * Retrieves a map of game names and their associated weights based on the specified conditions. * - * @param condition The condition to evaluate game weights. + * @param playerContext The condition to evaluate game weights. * @return A {@code HashMap} containing game names as keys and their associated weights as values. */ @Override - public HashMap getGameWithWeight(Condition condition) { - return ((RequirementManagerImpl) plugin.getRequirementManager()).getGameWithWeight(condition); + public HashMap getGameWithWeight(PlayerContext playerContext) { + return ((RequirementManagerImpl) plugin.getRequirementManager()).getGameWithWeight(playerContext); } /** @@ -231,7 +227,7 @@ public class GameManagerImpl implements GameManager { @Override public void arrangeTask() { var period = ((double) 10*(200-settings.getDifficulty()))/((double) (1+4*settings.getDifficulty())); - this.task = CustomFishingPlugin.get().getScheduler().runTaskAsyncTimer( + this.task = BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncTimer( this, 50, (long) period, @@ -305,7 +301,7 @@ public class GameManagerImpl implements GameManager { @Override public void arrangeTask() { this.judgement_position = (double) (barEffectiveWidth - judgementAreaWidth) / 2; - this.task = CustomFishingPlugin.get().getScheduler().runTaskAsyncTimer( + this.task = BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncTimer( this, 50, 33, @@ -440,7 +436,7 @@ public class GameManagerImpl implements GameManager { @Override public void arrangeTask() { - this.task = CustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(this, 50, 40, TimeUnit.MILLISECONDS); + this.task = BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(this, 50, 40, TimeUnit.MILLISECONDS); } @Override @@ -547,7 +543,7 @@ public class GameManagerImpl implements GameManager { for (int i = 0; i < requiredTimes; i++) { order[i] = ThreadLocalRandom.current().nextInt(0, easy ? 2 : 4); } - this.task = CustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(this, 50, 50, TimeUnit.MILLISECONDS); + this.task = BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(this, 50, 50, TimeUnit.MILLISECONDS); } @Override @@ -800,7 +796,7 @@ public class GameManagerImpl implements GameManager { @Override public void arrangeTask() { - this.task = CustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(this, 50, 50, TimeUnit.MILLISECONDS); + this.task = BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(this, 50, 50, TimeUnit.MILLISECONDS); } @Override @@ -879,7 +875,7 @@ public class GameManagerImpl implements GameManager { @Override public void arrangeTask() { - this.task = CustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(this, 50, 50, TimeUnit.MILLISECONDS); + this.task = BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(this, 50, 50, TimeUnit.MILLISECONDS); } @Override @@ -963,7 +959,7 @@ public class GameManagerImpl implements GameManager { @Override public void arrangeTask() { var period = ((double) 10*(200-settings.getDifficulty()))/((double) (1+4*settings.getDifficulty())); - this.task = CustomFishingPlugin.get().getScheduler().runTaskAsyncTimer( + this.task = BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncTimer( this, 50, (long) period, @@ -1050,7 +1046,7 @@ public class GameManagerImpl implements GameManager { @Override public void arrangeTask() { this.judgement_position = (double) (barEffectiveWidth - judgementAreaWidth) / 2; - this.task = CustomFishingPlugin.get().getScheduler().runTaskAsyncTimer( + this.task = BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncTimer( this, 50, 33, diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/hook/HookManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/hook/HookManagerImpl.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/hook/HookManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/hook/HookManagerImpl.java index d4956270..60753c2f 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/hook/HookManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/hook/HookManagerImpl.java @@ -19,13 +19,11 @@ package net.momirealms.customfishing.mechanic.hook; import de.tr7zw.changeme.nbtapi.NBTCompound; import de.tr7zw.changeme.nbtapi.NBTItem; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.manager.HookManager; -import net.momirealms.customfishing.api.manager.RequirementManager; -import net.momirealms.customfishing.api.mechanic.condition.Condition; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; +import net.momirealms.customfishing.api.mechanic.hook.HookManager; +import net.momirealms.customfishing.api.mechanic.requirement.RequirementManager; import net.momirealms.customfishing.api.mechanic.effect.EffectCarrier; import net.momirealms.customfishing.api.mechanic.hook.HookSetting; -import net.momirealms.customfishing.api.util.LogUtils; import net.momirealms.customfishing.mechanic.item.ItemManagerImpl; import net.momirealms.customfishing.util.ItemUtils; import org.bukkit.Bukkit; @@ -47,10 +45,10 @@ import java.util.*; public class HookManagerImpl implements Listener, HookManager { - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; private final HashMap hookSettingMap; - public HookManagerImpl(CustomFishingPlugin plugin) { + public HookManagerImpl(BukkitCustomFishingPlugin plugin) { this.plugin = plugin; this.hookSettingMap = new HashMap<>(); } @@ -296,11 +294,11 @@ public class HookManagerImpl implements Listener, HookManager { } } - Condition condition = new Condition(player, new HashMap<>()); - condition.insertArg("{rod}", plugin.getItemManager().getAnyPluginItemID(clicked)); + PlayerContext playerContext = new PlayerContext(player, new HashMap<>()); + playerContext.insertArg("{rod}", plugin.getItemManager().getAnyPluginItemID(clicked)); EffectCarrier effectCarrier = plugin.getEffectManager().getEffectCarrier("hook", hookID); if (effectCarrier != null) { - if (!RequirementManager.isRequirementMet(condition, effectCarrier.getRequirements())) { + if (!RequirementManager.isRequirementMet(playerContext, effectCarrier.getRequirements())) { return; } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/item/ItemManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/item/ItemManagerImpl.java similarity index 78% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/item/ItemManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/item/ItemManagerImpl.java index 696e3a6f..719971b9 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/item/ItemManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/item/ItemManagerImpl.java @@ -17,38 +17,34 @@ package net.momirealms.customfishing.mechanic.item; +import com.saicone.rtag.RtagItem; +import com.saicone.rtag.tag.TagCompound; +import com.saicone.rtag.tag.TagList; import de.tr7zw.changeme.nbtapi.*; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.common.Key; import net.momirealms.customfishing.api.common.Pair; import net.momirealms.customfishing.api.common.Tuple; import net.momirealms.customfishing.api.event.FishingBagPreCollectEvent; import net.momirealms.customfishing.api.event.FishingLootPreSpawnEvent; import net.momirealms.customfishing.api.event.FishingLootSpawnEvent; -import net.momirealms.customfishing.api.manager.ActionManager; -import net.momirealms.customfishing.api.manager.ItemManager; -import net.momirealms.customfishing.api.manager.RequirementManager; +import net.momirealms.customfishing.api.mechanic.action.ActionManager; +import net.momirealms.customfishing.api.mechanic.item.ItemManager; +import net.momirealms.customfishing.api.mechanic.requirement.RequirementManager; import net.momirealms.customfishing.api.mechanic.GlobalSettings; import net.momirealms.customfishing.api.mechanic.action.Action; import net.momirealms.customfishing.api.mechanic.action.ActionTrigger; -import net.momirealms.customfishing.api.mechanic.condition.Condition; import net.momirealms.customfishing.api.mechanic.effect.EffectCarrier; -import net.momirealms.customfishing.api.mechanic.item.BuildableItem; -import net.momirealms.customfishing.api.mechanic.item.ItemBuilder; -import net.momirealms.customfishing.api.mechanic.item.ItemLibrary; +import net.momirealms.customfishing.api.integration.ItemProvider; import net.momirealms.customfishing.api.mechanic.loot.Loot; -import net.momirealms.customfishing.api.mechanic.misc.Value; -import net.momirealms.customfishing.api.util.LogUtils; -import net.momirealms.customfishing.api.util.WeightUtils; -import net.momirealms.customfishing.compatibility.item.CustomFishingItemImpl; -import net.momirealms.customfishing.compatibility.item.VanillaItemImpl; -import net.momirealms.customfishing.compatibility.papi.PlaceholderManagerImpl; +import net.momirealms.customfishing.api.mechanic.misc.value.MathValue; +import net.momirealms.customfishing.bukkit.compatibility.item.CustomFishingItemImpl; +import net.momirealms.customfishing.bukkit.compatibility.item.VanillaItemImpl; +import net.momirealms.customfishing.bukkit.compatibility.papi.PlaceholderManagerImpl; import net.momirealms.customfishing.setting.CFConfig; import net.momirealms.customfishing.util.ConfigUtils; import net.momirealms.customfishing.util.ItemUtils; import net.momirealms.customfishing.util.LocationUtils; -import net.momirealms.customfishing.util.NBTUtils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; @@ -57,7 +53,6 @@ import org.bukkit.block.Block; import org.bukkit.block.Skull; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.Event; @@ -75,7 +70,7 @@ import org.bukkit.event.player.PlayerItemMendEvent; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataContainer; import org.bukkit.persistence.PersistentDataType; import org.bukkit.util.Vector; @@ -90,13 +85,13 @@ import java.util.concurrent.TimeUnit; public class ItemManagerImpl implements ItemManager, Listener { private static ItemManager instance; - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; private final HashMap buildableItemMap; - private final HashMap itemLibraryMap; - private ItemLibrary[] itemDetectionArray; + private final HashMap itemLibraryMap; + private ItemProvider[] itemDetectionArray; private NamespacedKey blockKey; - public ItemManagerImpl(CustomFishingPlugin plugin) { + public ItemManagerImpl(BukkitCustomFishingPlugin plugin) { instance = this; this.plugin = plugin; this.itemLibraryMap = new LinkedHashMap<>(); @@ -124,14 +119,14 @@ public class ItemManagerImpl implements ItemManager, Listener { } private void resetItemDetectionOrder() { - ArrayList list = new ArrayList<>(); + ArrayList list = new ArrayList<>(); for (String plugin : CFConfig.itemDetectOrder) { - ItemLibrary library = itemLibraryMap.get(plugin); + ItemProvider library = itemLibraryMap.get(plugin); if (library != null) { list.add(library); } } - this.itemDetectionArray = list.toArray(new ItemLibrary[0]); + this.itemDetectionArray = list.toArray(new ItemProvider[0]); } public Collection getItemLibraries() { @@ -212,10 +207,7 @@ public class ItemManagerImpl implements ItemManager, Listener { * @param value The value of the item. * @return The constructed ItemStack. */ - @Override - public ItemStack build(Player player, String namespace, String value) { - return build(player, namespace, value, new HashMap<>()); - } + /** * Build an ItemStack with a specified namespace and value, replacing placeholders, @@ -272,8 +264,8 @@ public class ItemManagerImpl implements ItemManager, Listener { public String getAnyPluginItemID(ItemStack itemStack) { if (itemStack == null || itemStack.getType() == Material.AIR) return "AIR"; - for (ItemLibrary library : itemDetectionArray) { - String id = library.getItemID(itemStack); + for (ItemProvider library : itemDetectionArray) { + String id = library.itemID(itemStack); if (id != null) { return id; } @@ -400,11 +392,12 @@ public class ItemManagerImpl implements ItemManager, Listener { } int amount = builder.getAmount(); temp.setAmount(amount); - NBTItem nbtItem = new NBTItem(temp); + RtagItem nbtItem = new RtagItem(temp); for (ItemBuilder.ItemPropertyEditor editor : builder.getEditors()) { editor.edit(player, nbtItem, placeholders); } - ItemUtils.updateNBTItemLore(nbtItem); + // TODO FIX + //ItemUtils.updateNBTItemLore(nbtItem); return nbtItem.getItem(); } @@ -413,9 +406,13 @@ public class ItemManagerImpl implements ItemManager, Listener { if (material != null) { ItemStack itemStack = buildAnyPluginItemByID(player, material); if (itemStack != null) { - NBTItem nbtItem = new NBTItem(itemStack); - nbtItem.removeKey("display"); - return nbtItem.getItem(); + ItemStack cloned = new ItemStack(itemStack.getType()); + ItemMeta meta = cloned.getItemMeta(); + if (itemStack.getItemMeta().hasCustomModelData()) { + meta.setCustomModelData(itemStack.getItemMeta().getCustomModelData()); + } + cloned.setItemMeta(meta); + return cloned; } else { return new ItemStack(Material.BARRIER); } @@ -427,13 +424,13 @@ public class ItemManagerImpl implements ItemManager, Listener { /** * Register an item library. * - * @param itemLibrary The item library to register. + * @param itemProvider The item library to register. * @return True if the item library was successfully registered, false if it already exists. */ @Override - public boolean registerItemLibrary(ItemLibrary itemLibrary) { - if (itemLibraryMap.containsKey(itemLibrary.identification())) return false; - itemLibraryMap.put(itemLibrary.identification(), itemLibrary); + public boolean registerItemLibrary(ItemProvider itemProvider) { + if (itemLibraryMap.containsKey(itemProvider.identification())) return false; + itemLibraryMap.put(itemProvider.identification(), itemProvider); this.resetItemDetectionOrder(); return true; } @@ -453,12 +450,12 @@ public class ItemManagerImpl implements ItemManager, Listener { } @Override - public void dropItem(Player player, Location hookLocation, Location playerLocation, ItemStack item, Condition condition) { + public void dropItem(Player player, Location hookLocation, Location playerLocation, ItemStack item, PlayerContext playerContext) { if (item.getType() == Material.AIR) { return; } - if (CFConfig.enableFishingBag && plugin.getBagManager().doesBagStoreLoots() && RequirementManager.isRequirementMet(condition, plugin.getBagManager().getCollectRequirements())) { + if (CFConfig.enableFishingBag && plugin.getBagManager().doesBagStoreLoots() && RequirementManager.isRequirementMet(playerContext, plugin.getBagManager().getCollectRequirements())) { var bag = plugin.getBagManager().getOnlineBagInventory(player.getUniqueId()); FishingBagPreCollectEvent preCollectEvent = new FishingBagPreCollectEvent(player, item, bag); @@ -470,7 +467,7 @@ public class ItemManagerImpl implements ItemManager, Listener { int cannotPut = ItemUtils.putLootsToBag(bag, item, item.getAmount()); // some are put into bag if (cannotPut != item.getAmount()) { - ActionManager.triggerActions(condition, plugin.getBagManager().getCollectLootActions()); + ActionManager.triggerActions(playerContext, plugin.getBagManager().getCollectLootActions()); } // all are put if (cannotPut == 0) { @@ -478,7 +475,7 @@ public class ItemManagerImpl implements ItemManager, Listener { } // bag is full item.setAmount(cannotPut); - ActionManager.triggerActions(condition, plugin.getBagManager().getBagFullActions()); + ActionManager.triggerActions(playerContext, plugin.getBagManager().getBagFullActions()); } FishingLootPreSpawnEvent preSpawnEvent = new FishingLootPreSpawnEvent(player, hookLocation, item); @@ -576,7 +573,7 @@ public class ItemManagerImpl implements ItemManager, Listener { @Override public ItemBuilder customModelData(int value) { if (value == 0) return this; - editors.put("custom-model-data", (player, nbtItem, placeholders) -> nbtItem.setInteger("CustomModelData", value)); + editors.put("custom-model-data", (player, nbtItem, placeholders) -> nbtItem.set(value, "CustomModelData")); return this; } @@ -584,12 +581,11 @@ public class ItemManagerImpl implements ItemManager, Listener { public ItemBuilder name(String name) { if (name == null) return this; editors.put("name", (player, nbtItem, placeholders) -> { - NBTCompound displayCompound = nbtItem.getOrCreateCompound("display"); - displayCompound.setString("Name", AdventureHelper.getInstance().componentToJson( + nbtItem.set(AdventureHelper.getInstance().componentToJson( AdventureHelper.getInstance().getComponentFromMiniMessage( "" + PlaceholderManagerImpl.getInstance().parse(player, name, placeholders) ) - )); + ), "display", "Name"); }); return this; } @@ -612,9 +608,8 @@ public class ItemManagerImpl implements ItemManager, Listener { public ItemBuilder tag(boolean tag, String type, String id) { editors.put("tag", (player, nbtItem, placeholders) -> { if (!tag) return; - NBTCompound cfCompound = nbtItem.getOrCreateCompound("CustomFishing"); - cfCompound.setString("type", type); - cfCompound.setString("id", id); + nbtItem.set(type, "CustomFishing", "type"); + nbtItem.set(id, "CustomFishing", "id"); }); return this; } @@ -623,7 +618,7 @@ public class ItemManagerImpl implements ItemManager, Listener { public ItemBuilder unbreakable(boolean unbreakable) { editors.put("unbreakable", (player, nbtItem, placeholders) -> { if (!unbreakable) return; - nbtItem.setByte("Unbreakable", (byte) 1); + nbtItem.setUnbreakable(true); }); return this; } @@ -632,31 +627,28 @@ public class ItemManagerImpl implements ItemManager, Listener { public ItemBuilder placeable(boolean placeable) { editors.put("placeable", (player, nbtItem, placeholders) -> { if (!placeable) return; - NBTCompound cfCompound = nbtItem.getOrCreateCompound("CustomFishing"); - cfCompound.setByte("placeable", (byte) 1); + nbtItem.set((byte) 1, "CustomFishing", "placeable"); }); return this; } @Override public ItemBuilder lore(List lore) { - if (lore.size() == 0) return this; + if (lore.isEmpty()) return this; editors.put("lore", (player, nbtItem, placeholders) -> { - NBTCompound displayCompound = nbtItem.getOrCreateCompound("display"); - NBTList list = displayCompound.getStringList("Lore"); - list.clear(); - list.addAll(lore.stream().map(s -> AdventureHelper.getInstance().componentToJson( + List list = new ArrayList<>(lore.stream().map(s -> AdventureHelper.getInstance().componentToJson( AdventureHelper.getInstance().getComponentFromMiniMessage( "" + PlaceholderManagerImpl.getInstance().parse(player, s, placeholders) ) )).toList()); + nbtItem.set(list, "display", "Lore"); }); return this; } @Override public ItemBuilder nbt(Map nbt) { - if (nbt.size() == 0) return this; + if (nbt.isEmpty()) return this; editors.put("nbt", (player, nbtItem, placeholders) -> NBTUtils.setTagsFromBukkitYAML(player, placeholders, nbtItem, nbt)); return this; } @@ -670,91 +662,93 @@ public class ItemManagerImpl implements ItemManager, Listener { @Override public ItemBuilder itemFlag(List itemFlags) { - if (itemFlags.size() == 0) return this; + if (itemFlags.isEmpty()) return this; editors.put("item-flag", (player, nbtItem, placeholders) -> { int flag = 0; for (ItemFlag itemFlag : itemFlags) { flag = flag | 1 << itemFlag.ordinal(); } - nbtItem.setInteger("HideFlags", flag); + nbtItem.set(flag, "HideFlags"); }); return this; } @Override public ItemBuilder enchantment(List> enchantments, boolean store) { - if (enchantments.size() == 0) return this; + if (enchantments.isEmpty()) return this; editors.put("enchantment", (player, nbtItem, placeholders) -> { - NBTCompoundList list = nbtItem.getCompoundList(store ? "StoredEnchantments" : "Enchantments"); + Object nbtList = TagList.newTag(); for (Pair pair : enchantments) { - NBTCompound nbtCompound = list.addCompound(); - nbtCompound.setString("id", pair.left()); - nbtCompound.setShort("lvl", pair.right()); + Object nbtCompound = TagCompound.newTag(); + TagCompound.set(nbtCompound, "id", pair.left()); + TagCompound.set(nbtCompound, "lvl", pair.right()); + TagList.add(nbtList, nbtCompound); } + nbtItem.set(nbtList, store ? "StoredEnchantments" : "Enchantments"); }); return this; } @Override public ItemBuilder randomEnchantments(List> enchantments, boolean store) { - if (enchantments.size() == 0) return this; + if (enchantments.isEmpty()) return this; editors.put("random-enchantment", (player, nbtItem, placeholders) -> { - NBTCompoundList list = nbtItem.getCompoundList(store ? "StoredEnchantments" : "Enchantments"); - HashSet ids = new HashSet<>(); - for (Tuple pair : enchantments) { - if (Math.random() < pair.getLeft() && !ids.contains(pair.getMid())) { - NBTCompound nbtCompound = list.addCompound(); - nbtCompound.setString("id", pair.getMid()); - nbtCompound.setShort("lvl", pair.getRight()); - ids.add(pair.getMid()); - } - } +// NBTCompoundList list = nbtItem.getCompoundList(store ? "StoredEnchantments" : "Enchantments"); +// HashSet ids = new HashSet<>(); +// for (Tuple pair : enchantments) { +// if (Math.random() < pair.getLeft() && !ids.contains(pair.getMid())) { +// NBTCompound nbtCompound = list.addCompound(); +// nbtCompound.setString("id", pair.getMid()); +// nbtCompound.setShort("lvl", pair.getRight()); +// ids.add(pair.getMid()); +// } +// } }); return this; } @Override - public ItemBuilder enchantmentPool(List> amountPairs, List, Value>> enchantments, boolean store) { + public ItemBuilder enchantmentPool(List> amountPairs, List, MathValue>> enchantments, boolean store) { if (enchantments.size() == 0 || amountPairs.size() == 0) return this; editors.put("enchantment-pool", (player, nbtItem, placeholders) -> { - List> parsedAmountPair = new ArrayList<>(amountPairs.size()); - Map map = new HashMap<>(); - for (Pair rawValue : amountPairs) { - parsedAmountPair.add(Pair.of(rawValue.left(), rawValue.right().get(player, map))); - } - - int amount = WeightUtils.getRandom(parsedAmountPair); - if (amount <= 0) return; - NBTCompoundList list = nbtItem.getCompoundList(store ? "StoredEnchantments" : "Enchantments"); - - HashSet addedEnchantments = new HashSet<>(); - - List, Double>> cloned = new ArrayList<>(enchantments.size()); - for (Pair, Value> rawValue : enchantments) { - cloned.add(Pair.of(rawValue.left(), rawValue.right().get(player, map))); - } - - int i = 0; - outer: - while (i < amount && cloned.size() != 0) { - Pair enchantPair = WeightUtils.getRandom(cloned); - Enchantment enchantment = Enchantment.getByKey(NamespacedKey.fromString(enchantPair.left())); - if (enchantment == null) { - throw new NullPointerException("Enchantment: " + enchantPair.left() + " doesn't exist on your server."); - } - for (Enchantment added : addedEnchantments) { - if (enchantment.conflictsWith(added)) { - cloned.removeIf(pair -> pair.left().left().equals(enchantPair.left())); - continue outer; - } - } - NBTCompound nbtCompound = list.addCompound(); - nbtCompound.setString("id", enchantPair.left()); - nbtCompound.setShort("lvl", enchantPair.right()); - addedEnchantments.add(enchantment); - cloned.removeIf(pair -> pair.left().left().equals(enchantPair.left())); - i++; - } +// List> parsedAmountPair = new ArrayList<>(amountPairs.size()); +// Map map = new HashMap<>(); +// for (Pair rawValue : amountPairs) { +// parsedAmountPair.add(Pair.of(rawValue.left(), rawValue.right().get(player, map))); +// } +// +// int amount = WeightUtils.getRandom(parsedAmountPair); +// if (amount <= 0) return; +// NBTCompoundList list = nbtItem.getCompoundList(store ? "StoredEnchantments" : "Enchantments"); +// +// HashSet addedEnchantments = new HashSet<>(); +// +// List, Double>> cloned = new ArrayList<>(enchantments.size()); +// for (Pair, Value> rawValue : enchantments) { +// cloned.add(Pair.of(rawValue.left(), rawValue.right().get(player, map))); +// } +// +// int i = 0; +// outer: +// while (i < amount && cloned.size() != 0) { +// Pair enchantPair = WeightUtils.getRandom(cloned); +// Enchantment enchantment = Enchantment.getByKey(NamespacedKey.fromString(enchantPair.left())); +// if (enchantment == null) { +// throw new NullPointerException("Enchantment: " + enchantPair.left() + " doesn't exist on your server."); +// } +// for (Enchantment added : addedEnchantments) { +// if (enchantment.conflictsWith(added)) { +// cloned.removeIf(pair -> pair.left().left().equals(enchantPair.left())); +// continue outer; +// } +// } +// NBTCompound nbtCompound = list.addCompound(); +// nbtCompound.setString("id", enchantPair.left()); +// nbtCompound.setShort("lvl", enchantPair.right()); +// addedEnchantments.add(enchantment); +// cloned.removeIf(pair -> pair.left().left().equals(enchantPair.left())); +// i++; +// } }); return this; } @@ -763,9 +757,8 @@ public class ItemManagerImpl implements ItemManager, Listener { public ItemBuilder maxDurability(int max) { if (max == 0) return this; editors.put("durability", (player, nbtItem, placeholders) -> { - NBTCompound cfCompound = nbtItem.getOrCreateCompound("CustomFishing"); - cfCompound.setInteger("max_dur", max); - cfCompound.setInteger("cur_dur", max); + nbtItem.set(max, "CustomFishing", "max_dur"); + nbtItem.set(max, "CustomFishing", "cur_dur"); }); return this; } @@ -779,11 +772,11 @@ public class ItemManagerImpl implements ItemManager, Listener { placeholders.put("{bonus}", String.format("%.2f", bonus)); placeholders.put("{BONUS}", String.valueOf(bonus)); double price; - price = CustomFishingPlugin.get().getMarketManager().getFishPrice( + price = BukkitCustomFishingPlugin.get().getMarketManager().getFishPrice( player, placeholders ); - nbtItem.setDouble("Price", price); + nbtItem.set(price, "Price"); placeholders.put("{price}", String.format("%.2f", price)); placeholders.put("{PRICE}", String.valueOf(price)); }); @@ -794,7 +787,6 @@ public class ItemManagerImpl implements ItemManager, Listener { public ItemBuilder size(Pair size) { if (size == null) return this; editors.put("size", (player, nbtItem, placeholders) -> { - NBTCompound cfCompound = nbtItem.getOrCreateCompound("CustomFishing"); float random = size.left() + (size.left() >= size.right() ? 0 : ThreadLocalRandom.current().nextFloat(size.right() - size.left())); float bonus = Float.parseFloat(placeholders.getOrDefault("{size-multiplier}", "1.0")); double fixed = Double.parseDouble(placeholders.getOrDefault("{size-fixed}", "0.0")); @@ -807,7 +799,7 @@ public class ItemManagerImpl implements ItemManager, Listener { random = size.left(); } } - cfCompound.setFloat("size", random); + nbtItem.set(random, "CustomFishing", "size"); placeholders.put("{size}", String.format("%.2f", random)); placeholders.put("{SIZE}", String.valueOf(random)); placeholders.put("{min_size}", String.valueOf(size.left())); @@ -820,8 +812,7 @@ public class ItemManagerImpl implements ItemManager, Listener { public ItemBuilder stackable(boolean stackable) { if (stackable) return this; editors.put("stackable", (player, nbtItem, placeholders) -> { - NBTCompound cfCompound = nbtItem.getOrCreateCompound("CustomFishing"); - cfCompound.setUUID("uuid", UUID.randomUUID()); + nbtItem.set(UUID.randomUUID(), "CustomFishing", "stackable"); }); return this; } @@ -830,7 +821,7 @@ public class ItemManagerImpl implements ItemManager, Listener { public ItemBuilder preventGrabbing(boolean prevent) { if (!prevent) return this; editors.put("grabbing", (player, nbtItem, placeholders) -> { - nbtItem.setString("owner", placeholders.get("player")); + nbtItem.set(placeholders.get("player"), "owner"); }); return this; } @@ -839,8 +830,8 @@ public class ItemManagerImpl implements ItemManager, Listener { public ItemBuilder head(String base64) { if (base64 == null) return this; editors.put("head", (player, nbtItem, placeholders) -> { - NBTCompound nbtCompound = nbtItem.addCompound("SkullOwner"); - nbtCompound.setUUID("Id", UUID.nameUUIDFromBytes(id.getBytes())); + nbtItem.set(UUID.nameUUIDFromBytes(id.getBytes()), "SkullOwner", "Id"); + NBTListCompound texture = nbtCompound.addCompound("Properties").getCompoundList("textures").addCompound(); texture.setString("Value", base64); }); @@ -851,18 +842,17 @@ public class ItemManagerImpl implements ItemManager, Listener { public ItemBuilder randomDamage(boolean damage) { if (!damage) return this; editors.put("damage", (player, nbtItem, placeholders) -> { - NBTCompound cfCompound = nbtItem.getCompound("CustomFishing"); - if (cfCompound != null) { - int i = cfCompound.getInteger("max_dur"); + if (nbtItem.hasTag("CustomFishing")) { + int i = nbtItem.get("CustomFishing", "max_dur"); if (i != 0) { int dur = ThreadLocalRandom.current().nextInt(i); - cfCompound.setInteger("cur_dur", dur); - nbtItem.setInteger("Damage", (int) (nbtItem.getItem().getType().getMaxDurability() * ((double) dur / i))); + nbtItem.set(dur, "CustomFishing", "max_dur"); + nbtItem.set((int) (nbtItem.getItem().getType().getMaxDurability() * ((double) dur / i)), "Damage"); } else { - nbtItem.setInteger("Damage", ThreadLocalRandom.current().nextInt(nbtItem.getItem().getType().getMaxDurability())); + nbtItem.set(ThreadLocalRandom.current().nextInt(nbtItem.getItem().getType().getMaxDurability()), "Damage"); } } else { - nbtItem.setInteger("Damage", ThreadLocalRandom.current().nextInt(nbtItem.getItem().getType().getMaxDurability())); + nbtItem.set(ThreadLocalRandom.current().nextInt(nbtItem.getItem().getType().getMaxDurability()), "Damage"); } }); return this; @@ -909,13 +899,14 @@ public class ItemManagerImpl implements ItemManager, Listener { @EventHandler (ignoreCancelled = true) public void onPickUp(PlayerAttemptPickupItemEvent event) { ItemStack itemStack = event.getItem().getItemStack(); - NBTItem nbtItem = new NBTItem(itemStack); + RtagItem nbtItem = new RtagItem(itemStack); if (!nbtItem.hasTag("owner")) return; - if (!Objects.equals(nbtItem.getString("owner"), event.getPlayer().getName())) { + if (!Objects.equals(nbtItem.get("owner"), event.getPlayer().getName())) { event.setCancelled(true); } else { - nbtItem.removeKey("owner"); - itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); + nbtItem.remove("owner"); + nbtItem.load(); +// itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); } } @@ -927,10 +918,11 @@ public class ItemManagerImpl implements ItemManager, Listener { @EventHandler (ignoreCancelled = true) public void onInvPickItem(InventoryPickupItemEvent event) { ItemStack itemStack = event.getItem().getItemStack(); - NBTItem nbtItem = new NBTItem(itemStack); + RtagItem nbtItem = new RtagItem(itemStack); if (!nbtItem.hasTag("owner")) return; - nbtItem.removeKey("owner"); - itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); + nbtItem.remove("owner"); + nbtItem.load(); +// itemStack.setItemMeta(nbtItem.getItem().getItemMeta()); } /** @@ -944,10 +936,10 @@ public class ItemManagerImpl implements ItemManager, Listener { String id = getAnyPluginItemID(itemStack); Loot loot = plugin.getLootManager().getLoot(id); if (loot != null) { - Condition condition = new Condition(event.getPlayer()); + PlayerContext playerContext = new PlayerContext(event.getPlayer()); if (!loot.disableGlobalAction()) - GlobalSettings.triggerLootActions(ActionTrigger.CONSUME, condition); - loot.triggerActions(ActionTrigger.CONSUME, condition); + GlobalSettings.triggerLootActions(ActionTrigger.CONSUME, playerContext); + loot.triggerActions(ActionTrigger.CONSUME, playerContext); } } @@ -958,17 +950,17 @@ public class ItemManagerImpl implements ItemManager, Listener { */ @EventHandler (ignoreCancelled = true) public void onRepairItem(PrepareAnvilEvent event) { - ItemStack result = event.getInventory().getResult(); - if (result == null || result.getType() == Material.AIR) return; - NBTItem nbtItem = new NBTItem(result); - NBTCompound compound = nbtItem.getCompound("CustomFishing"); - if (compound == null || !compound.hasTag("max_dur")) return; - if (!(result.getItemMeta() instanceof Damageable damageable)) { - return; - } - int max_dur = compound.getInteger("max_dur"); - compound.setInteger("cur_dur", (int) (max_dur * (1 - (double) damageable.getDamage() / result.getType().getMaxDurability()))); - event.setResult(nbtItem.getItem()); +// ItemStack result = event.getInventory().getResult(); +// if (result == null || result.getType() == Material.AIR) return; +// NBTItem nbtItem = new NBTItem(result); +// NBTCompound compound = nbtItem.getCompound("CustomFishing"); +// if (compound == null || !compound.hasTag("max_dur")) return; +// if (!(result.getItemMeta() instanceof Damageable damageable)) { +// return; +// } +// int max_dur = compound.getInteger("max_dur"); +// compound.setInteger("cur_dur", (int) (max_dur * (1 - (double) damageable.getDamage() / result.getType().getMaxDurability()))); +// event.setResult(nbtItem.getItem()); } /** @@ -979,9 +971,8 @@ public class ItemManagerImpl implements ItemManager, Listener { @EventHandler (ignoreCancelled = true) public void onMending(PlayerItemMendEvent event) { ItemStack itemStack = event.getItem(); - NBTItem nbtItem = new NBTItem(itemStack); - NBTCompound compound = nbtItem.getCompound("CustomFishing"); - if (compound == null) return; + RtagItem nbtItem = new RtagItem(itemStack); + if (!nbtItem.hasTag("CustomFishing")) return; event.setCancelled(true); ItemUtils.increaseDurability(itemStack, event.getRepairAmount(), true); } @@ -1003,11 +994,11 @@ public class ItemManagerImpl implements ItemManager, Listener { if (event.getAction() != org.bukkit.event.block.Action.RIGHT_CLICK_AIR && event.getAction() != org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK) return; String id = getAnyPluginItemID(itemStack); - Condition condition = new Condition(event.getPlayer()); + PlayerContext playerContext = new PlayerContext(event.getPlayer()); Loot loot = plugin.getLootManager().getLoot(id); if (loot != null) { - loot.triggerActions(ActionTrigger.INTERACT, condition); + loot.triggerActions(ActionTrigger.INTERACT, playerContext); return; } @@ -1018,7 +1009,7 @@ public class ItemManagerImpl implements ItemManager, Listener { Action[] actions = carrier.getActions(ActionTrigger.INTERACT); if (actions != null) for (Action action : actions) { - action.trigger(condition); + action.trigger(playerContext); } break; } @@ -1032,11 +1023,10 @@ public class ItemManagerImpl implements ItemManager, Listener { return; } - NBTItem nbtItem = new NBTItem(itemStack); - NBTCompound compound = nbtItem.getCompound("CustomFishing"); - if (compound != null) { + RtagItem nbtItem = new RtagItem(itemStack); + if (nbtItem.hasTag("CustomFishing")) { - if (!compound.hasTag("placeable") || compound.getByte("placeable") != 1) { + if (!nbtItem.hasTag("CustomFishing", "placeable") || (byte) nbtItem.get("CustomFishing", "placeable") != 1) { event.setCancelled(true); return; } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/loot/LootManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/loot/LootManagerImpl.java similarity index 87% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/loot/LootManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/loot/LootManagerImpl.java index d2f0dd86..bc06dcdd 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/loot/LootManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/loot/LootManagerImpl.java @@ -17,17 +17,13 @@ package net.momirealms.customfishing.mechanic.loot; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.common.Pair; -import net.momirealms.customfishing.api.manager.LootManager; -import net.momirealms.customfishing.api.mechanic.condition.Condition; +import net.momirealms.customfishing.api.mechanic.loot.LootManager; import net.momirealms.customfishing.api.mechanic.effect.Effect; -import net.momirealms.customfishing.api.mechanic.loot.CFLoot; import net.momirealms.customfishing.api.mechanic.loot.Loot; import net.momirealms.customfishing.api.mechanic.loot.LootType; -import net.momirealms.customfishing.api.mechanic.misc.WeightModifier; -import net.momirealms.customfishing.api.mechanic.statistic.StatisticsKey; -import net.momirealms.customfishing.api.util.LogUtils; +import net.momirealms.customfishing.api.mechanic.statistic.StatisticsKeys; import net.momirealms.customfishing.api.util.WeightUtils; import net.momirealms.customfishing.mechanic.requirement.RequirementManagerImpl; import net.momirealms.customfishing.setting.CFConfig; @@ -43,13 +39,13 @@ import java.util.*; public class LootManagerImpl implements LootManager { - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; // A map that associates loot IDs with their respective loot configurations. private final HashMap lootMap; // A map that associates loot group IDs with lists of loot IDs. private final HashMap> lootGroupMap; - public LootManagerImpl(CustomFishingPlugin plugin) { + public LootManagerImpl(BukkitCustomFishingPlugin plugin) { this.plugin = plugin; this.lootMap = new HashMap<>(); this.lootGroupMap = new HashMap<>(); @@ -146,43 +142,43 @@ public class LootManagerImpl implements LootManager { /** * Retrieves loot configurations with weights based on a given condition. * - * @param condition The condition used to filter loot configurations. + * @param playerContext The condition used to filter loot configurations. * @return A mapping of loot configuration keys to their associated weights. */ @Override - public HashMap getLootWithWeight(Condition condition) { - return ((RequirementManagerImpl) plugin.getRequirementManager()).getLootWithWeight(condition); + public HashMap getLootWithWeight(PlayerContext playerContext) { + return ((RequirementManagerImpl) plugin.getRequirementManager()).getLootWithWeight(playerContext); } /** * Get a collection of possible loot keys based on a given condition. * - * @param condition The condition to determine possible loot. + * @param playerContext The condition to determine possible loot. * @return A collection of loot keys. */ @Override - public Collection getPossibleLootKeys(Condition condition) { - return ((RequirementManagerImpl) plugin.getRequirementManager()).getLootWithWeight(condition).keySet(); + public Collection getPossibleLootKeys(PlayerContext playerContext) { + return ((RequirementManagerImpl) plugin.getRequirementManager()).getLootWithWeight(playerContext).keySet(); } /** * Get a map of possible loot keys with their corresponding weights, considering fishing effect and condition. * * @param effect The effect to apply weight modifiers. - * @param condition The condition to determine possible loot. + * @param playerContext The condition to determine possible loot. * @return A map of loot keys and their weights. */ @NotNull @Override - public Map getPossibleLootKeysWithWeight(Effect effect, Condition condition) { - Map lootWithWeight = ((RequirementManagerImpl) plugin.getRequirementManager()).getLootWithWeight(condition); - Player player = condition.getPlayer(); - for (Pair pair : effect.getWeightModifier()) { + public Map getPossibleLootKeysWithWeight(Effect effect, PlayerContext playerContext) { + Map lootWithWeight = ((RequirementManagerImpl) plugin.getRequirementManager()).getLootWithWeight(playerContext); + Player player = playerContext.getPlayer(); + for (Pair pair : effect.weightModifier()) { Double previous = lootWithWeight.get(pair.left()); if (previous != null) lootWithWeight.put(pair.left(), pair.right().modify(player, previous)); } - for (Pair pair : effect.getWeightModifierIgnored()) { + for (Pair pair : effect.weightModifierIgnored()) { double previous = lootWithWeight.getOrDefault(pair.left(), 0d); lootWithWeight.put(pair.left(), pair.right().modify(player, previous)); } @@ -193,13 +189,13 @@ public class LootManagerImpl implements LootManager { * Get the next loot item based on fishing effect and condition. * * @param effect The effect to apply weight modifiers. - * @param condition The condition to determine possible loot. + * @param playerContext The condition to determine possible loot. * @return The next loot item, or null if it doesn't exist. */ @Override @Nullable - public Loot getNextLoot(Effect effect, Condition condition) { - String key = WeightUtils.getRandom(getPossibleLootKeysWithWeight(effect, condition)); + public Loot getNextLoot(Effect effect, PlayerContext playerContext) { + String key = WeightUtils.getRandom(getPossibleLootKeysWithWeight(effect, playerContext)); if (key == null) { return null; } @@ -275,7 +271,7 @@ public class LootManagerImpl implements LootManager { .nick(section.getString("nick", section.getString("display.name", key))) .addActions(plugin.getActionManager().getActionMap(section.getConfigurationSection("events"))) .addTimesActions(plugin.getActionManager().getTimesActionMap(section.getConfigurationSection("events.success-times"))) - .statsKey(new StatisticsKey(section.getString("statistics.amount", key), section.getString("statistics.size", key))) + .statsKey(new StatisticsKeys(section.getString("statistics.amount", key), section.getString("statistics.size", key))) .build(); } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/market/MarketDynamicGUIElement.java b/core/src/main/java/net/momirealms/customfishing/mechanic/market/MarketDynamicGUIElement.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/market/MarketDynamicGUIElement.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/market/MarketDynamicGUIElement.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/market/MarketGUI.java b/core/src/main/java/net/momirealms/customfishing/mechanic/market/MarketGUI.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/market/MarketGUI.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/market/MarketGUI.java index 17b75777..57811287 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/market/MarketGUI.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/market/MarketGUI.java @@ -17,12 +17,10 @@ package net.momirealms.customfishing.mechanic.market; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.EarningData; import net.momirealms.customfishing.api.mechanic.market.MarketGUIHolder; import net.momirealms.customfishing.api.util.InventoryUtils; -import net.momirealms.customfishing.api.util.LogUtils; import net.momirealms.customfishing.util.ItemUtils; import net.momirealms.customfishing.util.NumberUtils; import org.bukkit.Material; @@ -196,8 +194,8 @@ public class MarketGUI { if (sellAllElement != null && sellAllElement.getSlots().size() > 0) { double totalWorth = manager.getInventoryTotalWorth(owner.getInventory()); int sellAmount = manager.getInventorySellAmount(owner.getInventory()); - if (manager.sellFishingBag() && CustomFishingPlugin.get().getBagManager().isEnabled()) { - Inventory bag = CustomFishingPlugin.get().getBagManager().getOnlineBagInventory(owner.getUniqueId()); + if (manager.sellFishingBag() && BukkitCustomFishingPlugin.get().getBagManager().isEnabled()) { + Inventory bag = BukkitCustomFishingPlugin.get().getBagManager().getOnlineBagInventory(owner.getUniqueId()); if (bag != null) { totalWorth += manager.getInventoryTotalWorth(bag); sellAmount += manager.getInventorySellAmount(bag); diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/market/MarketGUIElement.java b/core/src/main/java/net/momirealms/customfishing/mechanic/market/MarketGUIElement.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/market/MarketGUIElement.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/market/MarketGUIElement.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/market/MarketManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/market/MarketManagerImpl.java similarity index 92% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/market/MarketManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/market/MarketManagerImpl.java index cad0fdac..c5c417e3 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/market/MarketManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/market/MarketManagerImpl.java @@ -18,17 +18,14 @@ package net.momirealms.customfishing.mechanic.market; import de.tr7zw.changeme.nbtapi.NBTItem; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.EarningData; import net.momirealms.customfishing.api.data.user.OnlineUser; -import net.momirealms.customfishing.api.manager.MarketManager; +import net.momirealms.customfishing.api.mechanic.market.MarketManager; import net.momirealms.customfishing.api.mechanic.action.Action; -import net.momirealms.customfishing.api.mechanic.condition.Condition; -import net.momirealms.customfishing.api.mechanic.item.BuildableItem; import net.momirealms.customfishing.api.mechanic.market.MarketGUIHolder; import net.momirealms.customfishing.api.scheduler.CancellableTask; -import net.momirealms.customfishing.api.util.LogUtils; -import net.momirealms.customfishing.compatibility.papi.PlaceholderManagerImpl; +import net.momirealms.customfishing.bukkit.compatibility.papi.PlaceholderManagerImpl; import net.momirealms.customfishing.util.ConfigUtils; import net.momirealms.customfishing.util.NumberUtils; import net.objecthunter.exp4j.ExpressionBuilder; @@ -54,7 +51,7 @@ import java.util.concurrent.TimeUnit; public class MarketManagerImpl implements MarketManager, Listener { - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; private final HashMap priceMap; private String[] layout; private String title; @@ -83,12 +80,12 @@ public class MarketManagerImpl implements MarketManager, Listener { private CancellableTask resetEarningsTask; private int date; - public MarketManagerImpl(CustomFishingPlugin plugin) { + public MarketManagerImpl(BukkitCustomFishingPlugin plugin) { this.plugin = plugin; this.priceMap = new HashMap<>(); this.decorativeIcons = new HashMap<>(); this.marketGUIMap = new ConcurrentHashMap<>(); - this.date = getDate(); + this.date = getRealTimeDate(); } public void load() { @@ -96,7 +93,7 @@ public class MarketManagerImpl implements MarketManager, Listener { Bukkit.getPluginManager().registerEvents(this, plugin); if (!enable) return; this.resetEarningsTask = plugin.getScheduler().runTaskAsyncTimer(() -> { - int now = getDate(); + int now = getRealTimeDate(); if (this.date != now) { this.date = now; for (OnlineUser onlineUser : plugin.getStorageManager().getOnlineUsers()) { @@ -327,7 +324,7 @@ public class MarketManagerImpl implements MarketManager, Listener { double worth = gui.getTotalWorthInMarketGUI(); int amount = gui.getSoldAmount(); double earningLimit = getEarningLimit(player); - Condition condition = new Condition(player, new HashMap<>(Map.of( + PlayerContext playerContext = new PlayerContext(player, new HashMap<>(Map.of( "{money}", NumberUtils.money(worth), "{rest}", NumberUtils.money(earningLimit - data.earnings), "{money_formatted}", String.format("%.2f", worth) @@ -339,18 +336,18 @@ public class MarketManagerImpl implements MarketManager, Listener { // Can't earn more money if (getSellLimitActions() != null) { for (Action action : getSellLimitActions()) { - action.trigger(condition); + action.trigger(playerContext); } } } else { // Clear items and update earnings gui.clearWorthyItems(); data.earnings += worth; - condition.insertArg("{rest}", NumberUtils.money(earningLimit - data.earnings)); - condition.insertArg("{rest_formatted}", String.format("%.2f", (earningLimit - data.earnings))); + playerContext.insertArg("{rest}", NumberUtils.money(earningLimit - data.earnings)); + playerContext.insertArg("{rest_formatted}", String.format("%.2f", (earningLimit - data.earnings))); if (getSellAllowActions() != null) { for (Action action : getSellAllowActions()) { - action.trigger(condition); + action.trigger(playerContext); } } } @@ -358,7 +355,7 @@ public class MarketManagerImpl implements MarketManager, Listener { // Nothing to sell if (getSellDenyActions() != null) { for (Action action : getSellDenyActions()) { - action.trigger(condition); + action.trigger(playerContext); } } } @@ -366,14 +363,14 @@ public class MarketManagerImpl implements MarketManager, Listener { double worth = getInventoryTotalWorth(player.getInventory()); int amount = getInventorySellAmount(player.getInventory()); double earningLimit = getEarningLimit(player); - if (sellFishingBag() && CustomFishingPlugin.get().getBagManager().isEnabled()) { - Inventory bag = CustomFishingPlugin.get().getBagManager().getOnlineBagInventory(player.getUniqueId()); + if (sellFishingBag() && BukkitCustomFishingPlugin.get().getBagManager().isEnabled()) { + Inventory bag = BukkitCustomFishingPlugin.get().getBagManager().getOnlineBagInventory(player.getUniqueId()); if (bag != null) { worth += getInventoryTotalWorth(bag); amount += getInventorySellAmount(bag); } } - Condition condition = new Condition(player, new HashMap<>(Map.of( + PlayerContext playerContext = new PlayerContext(player, new HashMap<>(Map.of( "{money}", NumberUtils.money(worth), "{rest}", NumberUtils.money(earningLimit - data.earnings), "{money_formatted}", String.format("%.2f", worth) @@ -385,24 +382,24 @@ public class MarketManagerImpl implements MarketManager, Listener { // Can't earn more money if (getSellAllLimitActions() != null) { for (Action action : getSellAllLimitActions()) { - action.trigger(condition); + action.trigger(playerContext); } } } else { // Clear items and update earnings clearWorthyItems(player.getInventory()); - if (sellFishingBag() && CustomFishingPlugin.get().getBagManager().isEnabled()) { - Inventory bag = CustomFishingPlugin.get().getBagManager().getOnlineBagInventory(player.getUniqueId()); + if (sellFishingBag() && BukkitCustomFishingPlugin.get().getBagManager().isEnabled()) { + Inventory bag = BukkitCustomFishingPlugin.get().getBagManager().getOnlineBagInventory(player.getUniqueId()); if (bag != null) { clearWorthyItems(bag); } } data.earnings += worth; - condition.insertArg("{rest}", NumberUtils.money(earningLimit - data.earnings)); - condition.insertArg("{rest_formatted}", String.format("%.2f", (earningLimit - data.earnings))); + playerContext.insertArg("{rest}", NumberUtils.money(earningLimit - data.earnings)); + playerContext.insertArg("{rest_formatted}", String.format("%.2f", (earningLimit - data.earnings))); if (getSellAllAllowActions() != null) { for (Action action : getSellAllAllowActions()) { - action.trigger(condition); + action.trigger(playerContext); } } } @@ -410,7 +407,7 @@ public class MarketManagerImpl implements MarketManager, Listener { // Nothing to sell if (getSellAllDenyActions() != null) { for (Action action : getSellAllDenyActions()) { - action.trigger(condition); + action.trigger(playerContext); } } } @@ -467,7 +464,7 @@ public class MarketManagerImpl implements MarketManager, Listener { } @Override - public int getDate() { + public int getRealTimeDate() { Calendar calendar = Calendar.getInstance(); return (calendar.get(Calendar.MONTH) +1) * 100 + calendar.get(Calendar.DATE); } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/misc/ChatCatcherManager.java b/core/src/main/java/net/momirealms/customfishing/mechanic/misc/ChatCatcherManager.java similarity index 92% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/misc/ChatCatcherManager.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/misc/ChatCatcherManager.java index 2dcb9177..e1c08073 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/misc/ChatCatcherManager.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/misc/ChatCatcherManager.java @@ -17,7 +17,7 @@ package net.momirealms.customfishing.mechanic.misc; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.common.Pair; import net.momirealms.customfishing.gui.SectionPage; import org.bukkit.Bukkit; @@ -33,10 +33,10 @@ import java.util.concurrent.ConcurrentHashMap; public class ChatCatcherManager implements Listener { - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; private final ConcurrentHashMap> pageMap; - public ChatCatcherManager(CustomFishingPlugin plugin) { + public ChatCatcherManager(BukkitCustomFishingPlugin plugin) { this.pageMap = new ConcurrentHashMap<>(); this.plugin = plugin; } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/misc/CoolDownManager.java b/core/src/main/java/net/momirealms/customfishing/mechanic/misc/CoolDownManager.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/misc/CoolDownManager.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/misc/CoolDownManager.java index acfffad8..a9034c14 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/misc/CoolDownManager.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/misc/CoolDownManager.java @@ -17,7 +17,7 @@ package net.momirealms.customfishing.mechanic.misc; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; @@ -35,9 +35,9 @@ import java.util.concurrent.ConcurrentHashMap; public class CoolDownManager implements Listener { private final ConcurrentHashMap dataMap; - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; - public CoolDownManager(CustomFishingPlugin plugin) { + public CoolDownManager(BukkitCustomFishingPlugin plugin) { this.dataMap = new ConcurrentHashMap<>(); this.plugin = plugin; } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/misc/DynamicText.java b/core/src/main/java/net/momirealms/customfishing/mechanic/misc/DynamicText.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/misc/DynamicText.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/misc/DynamicText.java index 4e72eac2..8f76869f 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/misc/DynamicText.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/misc/DynamicText.java @@ -17,7 +17,7 @@ package net.momirealms.customfishing.mechanic.misc; -import net.momirealms.customfishing.compatibility.papi.PlaceholderManagerImpl; +import net.momirealms.customfishing.bukkit.compatibility.papi.PlaceholderManagerImpl; import org.bukkit.entity.Player; import java.util.ArrayList; diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/misc/value/ExpressionValue.java b/core/src/main/java/net/momirealms/customfishing/mechanic/misc/value/ExpressionMathValue.java similarity index 86% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/misc/value/ExpressionValue.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/misc/value/ExpressionMathValue.java index f0daf218..0a330a91 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/misc/value/ExpressionValue.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/misc/value/ExpressionMathValue.java @@ -17,17 +17,17 @@ package net.momirealms.customfishing.mechanic.misc.value; -import net.momirealms.customfishing.api.mechanic.misc.Value; +import net.momirealms.customfishing.api.mechanic.misc.value.MathValue; import net.momirealms.customfishing.util.ConfigUtils; import org.bukkit.entity.Player; import java.util.Map; -public class ExpressionValue implements Value { +public class ExpressionMathValue implements MathValue { private final String expression; - public ExpressionValue(String expression) { + public ExpressionMathValue(String expression) { this.expression = expression; } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/misc/value/PlainValue.java b/core/src/main/java/net/momirealms/customfishing/mechanic/misc/value/PlainMathValue.java similarity index 85% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/misc/value/PlainValue.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/misc/value/PlainMathValue.java index 8c22a4c5..586e2b7c 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/misc/value/PlainValue.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/misc/value/PlainMathValue.java @@ -17,16 +17,16 @@ package net.momirealms.customfishing.mechanic.misc.value; -import net.momirealms.customfishing.api.mechanic.misc.Value; +import net.momirealms.customfishing.api.mechanic.misc.value.MathValue; import org.bukkit.entity.Player; import java.util.Map; -public class PlainValue implements Value { +public class PlainMathValue implements MathValue { private final double value; - public PlainValue(double value) { + public PlainMathValue(double value) { this.value = value; } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/requirement/ConditionalElement.java b/core/src/main/java/net/momirealms/customfishing/mechanic/requirement/ConditionalElement.java similarity index 96% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/requirement/ConditionalElement.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/requirement/ConditionalElement.java index 0f60dfd3..e7bb9d08 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/requirement/ConditionalElement.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/requirement/ConditionalElement.java @@ -18,7 +18,6 @@ package net.momirealms.customfishing.mechanic.requirement; import net.momirealms.customfishing.api.common.Pair; -import net.momirealms.customfishing.api.mechanic.misc.WeightModifier; import net.momirealms.customfishing.api.mechanic.requirement.Requirement; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/requirement/EmptyRequirement.java b/core/src/main/java/net/momirealms/customfishing/mechanic/requirement/EmptyRequirement.java similarity index 89% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/requirement/EmptyRequirement.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/requirement/EmptyRequirement.java index f01645be..1c2d5251 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/requirement/EmptyRequirement.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/requirement/EmptyRequirement.java @@ -17,7 +17,6 @@ package net.momirealms.customfishing.mechanic.requirement; -import net.momirealms.customfishing.api.mechanic.condition.Condition; import net.momirealms.customfishing.api.mechanic.requirement.Requirement; /** @@ -28,7 +27,7 @@ public class EmptyRequirement implements Requirement { public static EmptyRequirement instance = new EmptyRequirement(); @Override - public boolean isConditionMet(Condition condition) { + public boolean isConditionMet(PlayerContext playerContext) { return true; } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/requirement/RequirementManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/requirement/RequirementManagerImpl.java similarity index 96% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/requirement/RequirementManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/requirement/RequirementManagerImpl.java index a278a44a..f23c8ade 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/requirement/RequirementManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/requirement/RequirementManagerImpl.java @@ -17,21 +17,20 @@ package net.momirealms.customfishing.mechanic.requirement; -import net.momirealms.customfishing.CustomFishingPluginImpl; +import net.momirealms.customfishing.BukkitCustomFishingPluginImpl; import net.momirealms.customfishing.api.common.Pair; -import net.momirealms.customfishing.api.integration.LevelInterface; -import net.momirealms.customfishing.api.integration.SeasonInterface; -import net.momirealms.customfishing.api.manager.RequirementManager; +import net.momirealms.customfishing.api.integration.LevelerProvider; +import net.momirealms.customfishing.api.integration.SeasonProvider; +import net.momirealms.customfishing.api.mechanic.requirement.RequirementManager; import net.momirealms.customfishing.api.mechanic.action.Action; import net.momirealms.customfishing.api.mechanic.competition.FishingCompetition; -import net.momirealms.customfishing.api.mechanic.condition.Condition; import net.momirealms.customfishing.api.mechanic.loot.Loot; import net.momirealms.customfishing.api.mechanic.requirement.Requirement; import net.momirealms.customfishing.api.mechanic.requirement.RequirementExpansion; import net.momirealms.customfishing.api.mechanic.requirement.RequirementFactory; -import net.momirealms.customfishing.api.util.LogUtils; -import net.momirealms.customfishing.compatibility.VaultHook; -import net.momirealms.customfishing.compatibility.papi.ParseUtils; +import net.momirealms.customfishing.bukkit.compatibility.VaultHook; +import net.momirealms.customfishing.bukkit.compatibility.papi.ParseUtils; +import net.momirealms.customfishing.common.util.ClassUtils; import net.momirealms.customfishing.util.ClassUtils; import net.momirealms.customfishing.util.ConfigUtils; import net.momirealms.customfishing.util.MoonPhase; @@ -58,13 +57,13 @@ import java.util.*; public class RequirementManagerImpl implements RequirementManager { public static Requirement[] mechanicRequirements; - private final CustomFishingPluginImpl plugin; + private final BukkitCustomFishingPluginImpl plugin; private final HashMap requirementFactoryMap; private final LinkedHashMap conditionalLootsMap; private final LinkedHashMap conditionalGamesMap; private final String EXPANSION_FOLDER = "expansions/requirement"; - public RequirementManagerImpl(CustomFishingPluginImpl plugin) { + public RequirementManagerImpl(BukkitCustomFishingPluginImpl plugin) { this.plugin = plugin; this.requirementFactoryMap = new HashMap<>(); this.conditionalLootsMap = new LinkedHashMap<>(); @@ -129,7 +128,7 @@ public class RequirementManagerImpl implements RequirementManager { * @return True if registration was successful, false if the type is already registered. */ @Override - public boolean registerRequirement(String type, RequirementFactory requirementFactory) { + public boolean registerRequirement(@NotNull String type, @NotNull RequirementFactory requirementFactory) { if (this.requirementFactoryMap.containsKey(type)) return false; this.requirementFactoryMap.put(type, requirementFactory); return true; @@ -142,7 +141,7 @@ public class RequirementManagerImpl implements RequirementManager { * @return True if unregistration was successful, false if the type is not registered. */ @Override - public boolean unregisterRequirement(String type) { + public boolean unregisterRequirement(@NotNull String type) { return this.requirementFactoryMap.remove(type) != null; } @@ -220,31 +219,31 @@ public class RequirementManagerImpl implements RequirementManager { this.registerInListRequirement(); } - public HashMap getLootWithWeight(Condition condition) { - return getString2DoubleMap(condition, conditionalLootsMap); + public HashMap getLootWithWeight(PlayerContext playerContext) { + return getString2DoubleMap(playerContext, conditionalLootsMap); } - public HashMap getGameWithWeight(Condition condition) { - return getString2DoubleMap(condition, conditionalGamesMap); + public HashMap getGameWithWeight(PlayerContext playerContext) { + return getString2DoubleMap(playerContext, conditionalGamesMap); } /** * Retrieves a mapping of strings to doubles based on conditional elements and a player's condition. * - * @param condition The player's condition. + * @param playerContext The player's condition. * @param conditionalGamesMap The map of conditional elements representing loots/games. * @return A HashMap with strings as keys and doubles as values representing loot/game weights. */ @NotNull - private HashMap getString2DoubleMap(Condition condition, LinkedHashMap conditionalGamesMap) { + private HashMap getString2DoubleMap(PlayerContext playerContext, LinkedHashMap conditionalGamesMap) { HashMap lootWeightMap = new HashMap<>(); Queue> lootQueue = new LinkedList<>(); lootQueue.add(conditionalGamesMap); - Player player = condition.getPlayer(); + Player player = playerContext.getPlayer(); while (!lootQueue.isEmpty()) { HashMap currentLootMap = lootQueue.poll(); for (ConditionalElement loots : currentLootMap.values()) { - if (RequirementManager.isRequirementMet(condition, loots.getRequirements())) { + if (RequirementManager.isRequirementMet(playerContext, loots.getRequirements())) { loots.combine(player, lootWeightMap); if (loots.getSubElements() != null) { lootQueue.add(loots.getSubElements()); @@ -281,7 +280,7 @@ public class RequirementManagerImpl implements RequirementManager { } @Override - public boolean hasRequirement(String type) { + public boolean hasRequirement(@NotNull String type) { return requirementFactoryMap.containsKey(type); } @@ -332,7 +331,7 @@ public class RequirementManagerImpl implements RequirementManager { */ @Override @NotNull - public Requirement getRequirement(String type, Object value) { + public Requirement getRequirement(@NotNull String type, @NotNull Object value) { RequirementFactory factory = getRequirementFactory(type); if (factory == null) { LogUtils.warn("Requirement type: " + type + " doesn't exist."); @@ -349,7 +348,7 @@ public class RequirementManagerImpl implements RequirementManager { */ @Override @Nullable - public RequirementFactory getRequirementFactory(String type) { + public RequirementFactory getRequirementFactory(@NotNull String type) { return requirementFactoryMap.get(type); } @@ -449,7 +448,7 @@ public class RequirementManagerImpl implements RequirementManager { Requirement[] requirements = getRequirements(section, advanced); return condition -> { for (Requirement requirement : requirements) { - if (requirement.isConditionMet(condition)) { + if (requirement.check(condition)) { return true; } } @@ -470,7 +469,7 @@ public class RequirementManagerImpl implements RequirementManager { return condition -> { outer: { for (Requirement requirement : requirements) { - if (!requirement.isConditionMet(condition)) { + if (!requirement.check(condition)) { break outer; } } @@ -723,9 +722,9 @@ public class RequirementManagerImpl implements RequirementManager { registerRequirement("season", (args, actions, advanced) -> { List seasons = ConfigUtils.stringListArgs(args); return condition -> { - SeasonInterface seasonInterface = plugin.getIntegrationManager().getSeasonInterface(); - if (seasonInterface == null) return true; - String season = seasonInterface.getSeason(condition.getLocation().getWorld()); + SeasonProvider seasonProvider = plugin.getIntegrationManager().getSeasonInterface(); + if (seasonProvider == null) return true; + String season = seasonProvider.getSeason(condition.getLocation().getWorld()); if (seasons.contains(season)) return true; if (advanced) triggerActions(actions, condition); return false; @@ -1278,12 +1277,12 @@ public class RequirementManagerImpl implements RequirementManager { int level = section.getInt("level"); String target = section.getString("target"); return condition -> { - LevelInterface levelInterface = plugin.getIntegrationManager().getLevelPlugin(pluginName); - if (levelInterface == null) { + LevelerProvider levelerProvider = plugin.getIntegrationManager().getLevelPlugin(pluginName); + if (levelerProvider == null) { LogUtils.warn("Plugin (" + pluginName + "'s) level is not compatible. Please double check if it's a problem caused by pronunciation."); return true; } - if (levelInterface.getLevel(condition.getPlayer(), target) >= level) + if (levelerProvider.getLevel(condition.getPlayer(), target) >= level) return true; if (advanced) triggerActions(actions, condition); return false; @@ -1348,12 +1347,12 @@ public class RequirementManagerImpl implements RequirementManager { * If the list of actions is not null, each action in the list is triggered. * * @param actions The list of actions to trigger. - * @param condition The condition associated with the actions. + * @param playerContext The condition associated with the actions. */ - private void triggerActions(List actions, Condition condition) { + private void triggerActions(List actions, PlayerContext playerContext) { if (actions != null) for (Action action : actions) - action.trigger(condition); + action.trigger(playerContext); } /** diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/statistic/StatisticsManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/statistic/StatisticsManagerImpl.java similarity index 93% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/statistic/StatisticsManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/statistic/StatisticsManagerImpl.java index 732dd3bf..7258ede5 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/statistic/StatisticsManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/statistic/StatisticsManagerImpl.java @@ -17,9 +17,9 @@ package net.momirealms.customfishing.mechanic.statistic; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.user.OnlineUser; -import net.momirealms.customfishing.api.manager.StatisticsManager; +import net.momirealms.customfishing.api.mechanic.statistic.StatisticsManager; import net.momirealms.customfishing.api.mechanic.statistic.Statistics; import org.bukkit.configuration.file.YamlConfiguration; import org.jetbrains.annotations.Nullable; @@ -29,10 +29,10 @@ import java.util.*; public class StatisticsManagerImpl implements StatisticsManager { - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; private final HashMap> categoryMap; - public StatisticsManagerImpl(CustomFishingPlugin plugin) { + public StatisticsManagerImpl(BukkitCustomFishingPlugin plugin) { this.plugin = plugin; this.categoryMap = new HashMap<>(); } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/totem/ActivatedTotem.java b/core/src/main/java/net/momirealms/customfishing/mechanic/totem/ActivatedTotem.java similarity index 88% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/totem/ActivatedTotem.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/totem/ActivatedTotem.java index 35f70ee6..c3e3354c 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/totem/ActivatedTotem.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/totem/ActivatedTotem.java @@ -17,10 +17,9 @@ package net.momirealms.customfishing.mechanic.totem; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.mechanic.action.Action; import net.momirealms.customfishing.api.mechanic.action.ActionTrigger; -import net.momirealms.customfishing.api.mechanic.condition.Condition; import net.momirealms.customfishing.api.mechanic.effect.EffectCarrier; import net.momirealms.customfishing.api.mechanic.totem.TotemConfig; import net.momirealms.customfishing.api.mechanic.totem.TotemParticle; @@ -44,7 +43,7 @@ public class ActivatedTotem { this.expireTime = System.currentTimeMillis() + config.getDuration() * 1000L; this.coreLocation = coreLocation.clone().add(0.5,0,0.5); this.totemConfig = config; - this.effectCarrier = CustomFishingPlugin.get().getEffectManager().getEffectCarrier("totem", config.getKey()); + this.effectCarrier = BukkitCustomFishingPlugin.get().getEffectManager().getEffectCarrier("totem", config.getKey()); for (TotemParticle particleSetting : config.getParticleSettings()) { this.subTasks.add(particleSetting.start(coreLocation, config.getRadius())); } @@ -71,12 +70,12 @@ public class ActivatedTotem { public void doTimerAction() { HashMap args = new HashMap<>(); args.put("{time_left}", String.valueOf((expireTime - System.currentTimeMillis())/1000)); - Condition condition = new Condition(coreLocation, null, args); + PlayerContext playerContext = new PlayerContext(coreLocation, null, args); if (effectCarrier != null) { Action[] actions = effectCarrier.getActions(ActionTrigger.TIMER); if (actions != null) { for (Action action : actions) { - action.trigger(condition); + action.trigger(playerContext); } } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/totem/TotemManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/mechanic/totem/TotemManagerImpl.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/totem/TotemManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/totem/TotemManagerImpl.java index a835d8cf..bf26393c 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/totem/TotemManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/totem/TotemManagerImpl.java @@ -17,14 +17,13 @@ package net.momirealms.customfishing.mechanic.totem; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.common.Pair; import net.momirealms.customfishing.api.common.SimpleLocation; import net.momirealms.customfishing.api.event.TotemActivateEvent; -import net.momirealms.customfishing.api.manager.TotemManager; +import net.momirealms.customfishing.api.mechanic.totem.TotemManager; import net.momirealms.customfishing.api.mechanic.action.Action; import net.momirealms.customfishing.api.mechanic.action.ActionTrigger; -import net.momirealms.customfishing.api.mechanic.condition.Condition; import net.momirealms.customfishing.api.mechanic.effect.EffectCarrier; import net.momirealms.customfishing.api.mechanic.totem.TotemConfig; import net.momirealms.customfishing.api.mechanic.totem.TotemModel; @@ -60,13 +59,13 @@ import java.util.concurrent.TimeUnit; public class TotemManagerImpl implements TotemManager, Listener { - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; private final HashMap> totemConfigMap; private final List allMaterials; private final ConcurrentHashMap activatedTotems; private CancellableTask timerCheckTask; - public TotemManagerImpl(CustomFishingPlugin plugin) { + public TotemManagerImpl(BukkitCustomFishingPlugin plugin) { this.plugin = plugin; this.totemConfigMap = new HashMap<>(); this.allMaterials = Arrays.stream(Material.values()).map(Enum::name).toList(); @@ -165,8 +164,8 @@ public class TotemManagerImpl implements TotemManager, Listener { EffectCarrier carrier = plugin.getEffectManager().getEffectCarrier("totem", totemKey); if (carrier == null) return; - Condition condition = new Condition(block.getLocation(), event.getPlayer(), new HashMap<>()); - if (!carrier.isConditionMet(condition)) + PlayerContext playerContext = new PlayerContext(block.getLocation(), event.getPlayer(), new HashMap<>()); + if (!carrier.isConditionMet(playerContext)) return; TotemActivateEvent totemActivateEvent = new TotemActivateEvent(event.getPlayer(), block.getLocation(), config); @@ -178,7 +177,7 @@ public class TotemManagerImpl implements TotemManager, Listener { Action[] actions = carrier.getActionMap().get(ActionTrigger.ACTIVATE); if (actions != null) for (Action action : actions) { - action.trigger(condition); + action.trigger(playerContext); } Location location = block.getLocation(); ActivatedTotem activatedTotem = new ActivatedTotem(location, config); diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/totem/particle/DustParticleSetting.java b/core/src/main/java/net/momirealms/customfishing/mechanic/totem/particle/DustParticleSetting.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/totem/particle/DustParticleSetting.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/totem/particle/DustParticleSetting.java index ebc34e5b..e7ef06fb 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/totem/particle/DustParticleSetting.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/totem/particle/DustParticleSetting.java @@ -17,7 +17,7 @@ package net.momirealms.customfishing.mechanic.totem.particle; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.common.Pair; import net.momirealms.customfishing.api.scheduler.CancellableTask; import org.bukkit.Location; @@ -48,7 +48,7 @@ public class DustParticleSetting extends ParticleSetting { @SuppressWarnings("DuplicatedCode") public CancellableTask start(Location location, double radius) { World world = location.getWorld(); - return CustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(() -> { + return BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(() -> { for (Pair range : ranges) { for (double theta = range.left(); theta <= range.right(); theta += interval) { double r = expressionHorizontal.setVariable("theta", theta).setVariable("radius", radius).evaluate(); diff --git a/plugin/src/main/java/net/momirealms/customfishing/mechanic/totem/particle/ParticleSetting.java b/core/src/main/java/net/momirealms/customfishing/mechanic/totem/particle/ParticleSetting.java similarity index 95% rename from plugin/src/main/java/net/momirealms/customfishing/mechanic/totem/particle/ParticleSetting.java rename to core/src/main/java/net/momirealms/customfishing/mechanic/totem/particle/ParticleSetting.java index 0ec64ac1..9d324c24 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/mechanic/totem/particle/ParticleSetting.java +++ b/core/src/main/java/net/momirealms/customfishing/mechanic/totem/particle/ParticleSetting.java @@ -17,7 +17,7 @@ package net.momirealms.customfishing.mechanic.totem.particle; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.common.Pair; import net.momirealms.customfishing.api.mechanic.totem.TotemParticle; import net.momirealms.customfishing.api.scheduler.CancellableTask; @@ -65,7 +65,7 @@ public class ParticleSetting implements TotemParticle { @SuppressWarnings("DuplicatedCode") public CancellableTask start(Location location, double radius) { World world = location.getWorld(); - return CustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(() -> { + return BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncTimer(() -> { for (Pair range : ranges) { for (double theta = range.left(); theta <= range.right(); theta += interval) { double r = expressionHorizontal.setVariable("theta", theta).setVariable("radius", radius).evaluate(); diff --git a/plugin/src/main/java/net/momirealms/customfishing/setting/CFConfig.java b/core/src/main/java/net/momirealms/customfishing/setting/CFConfig.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/setting/CFConfig.java rename to core/src/main/java/net/momirealms/customfishing/setting/CFConfig.java index 8fa8282f..db82e9d2 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/setting/CFConfig.java +++ b/core/src/main/java/net/momirealms/customfishing/setting/CFConfig.java @@ -23,8 +23,7 @@ import dev.dejvokep.boostedyaml.settings.dumper.DumperSettings; import dev.dejvokep.boostedyaml.settings.general.GeneralSettings; import dev.dejvokep.boostedyaml.settings.loader.LoaderSettings; import dev.dejvokep.boostedyaml.settings.updater.UpdaterSettings; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.util.LogUtils; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.util.OffsetUtils; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.event.EventPriority; @@ -102,8 +101,8 @@ public class CFConfig { public static void load() { try { YamlDocument.create( - new File(CustomFishingPlugin.getInstance().getDataFolder(), "config.yml"), - Objects.requireNonNull(CustomFishingPlugin.getInstance().getResource("config.yml")), + new File(BukkitCustomFishingPlugin.getInstance().getDataFolder(), "config.yml"), + Objects.requireNonNull(BukkitCustomFishingPlugin.getInstance().getResource("config.yml")), GeneralSettings.DEFAULT, LoaderSettings .builder() @@ -121,7 +120,7 @@ public class CFConfig { .addIgnoredRoute(configVersion, "other-settings.placeholder-register", '.') .build() ); - loadSettings(CustomFishingPlugin.getInstance().getConfig("config.yml")); + loadSettings(BukkitCustomFishingPlugin.getInstance().getConfig("config.yml")); } catch (IOException e) { LogUtils.warn(e.getMessage()); } diff --git a/plugin/src/main/java/net/momirealms/customfishing/setting/CFLocale.java b/core/src/main/java/net/momirealms/customfishing/setting/CFLocale.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/setting/CFLocale.java rename to core/src/main/java/net/momirealms/customfishing/setting/CFLocale.java index 0eb42ca7..20bbb5cd 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/setting/CFLocale.java +++ b/core/src/main/java/net/momirealms/customfishing/setting/CFLocale.java @@ -23,8 +23,7 @@ import dev.dejvokep.boostedyaml.settings.dumper.DumperSettings; import dev.dejvokep.boostedyaml.settings.general.GeneralSettings; import dev.dejvokep.boostedyaml.settings.loader.LoaderSettings; import dev.dejvokep.boostedyaml.settings.updater.UpdaterSettings; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.util.LogUtils; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; @@ -154,11 +153,11 @@ public class CFLocale { public static String GUI_EDIT_KEY; public static void load() { - InputStream inputStream = CustomFishingPlugin.getInstance().getResource("messages/" + CFConfig.language + ".yml"); + InputStream inputStream = BukkitCustomFishingPlugin.getInstance().getResource("messages/" + CFConfig.language + ".yml"); if (inputStream != null) { try { YamlDocument.create( - new File(CustomFishingPlugin.getInstance().getDataFolder(), "messages/" + CFConfig.language + ".yml"), + new File(BukkitCustomFishingPlugin.getInstance().getDataFolder(), "messages/" + CFConfig.language + ".yml"), inputStream, GeneralSettings.DEFAULT, LoaderSettings @@ -176,7 +175,7 @@ public class CFLocale { LogUtils.warn(e.getMessage()); } } - loadSettings(CustomFishingPlugin.get().getConfig("messages/" + CFConfig.language + ".yml")); + loadSettings(BukkitCustomFishingPlugin.get().getConfig("messages/" + CFConfig.language + ".yml")); } private static void loadSettings(YamlConfiguration locale) { diff --git a/plugin/src/main/java/net/momirealms/customfishing/storage/StorageManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/storage/StorageManagerImpl.java similarity index 98% rename from plugin/src/main/java/net/momirealms/customfishing/storage/StorageManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/storage/StorageManagerImpl.java index d9fbbd6d..85b79fd1 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/storage/StorageManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/storage/StorageManagerImpl.java @@ -20,8 +20,8 @@ package net.momirealms.customfishing.storage; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; -import net.momirealms.customfishing.CustomFishingPluginImpl; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.BukkitCustomFishingPluginImpl; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.DataStorageInterface; import net.momirealms.customfishing.api.data.PlayerData; import net.momirealms.customfishing.api.data.StorageType; @@ -29,7 +29,6 @@ import net.momirealms.customfishing.api.data.user.OfflineUser; import net.momirealms.customfishing.api.data.user.OnlineUser; import net.momirealms.customfishing.api.manager.StorageManager; import net.momirealms.customfishing.api.scheduler.CancellableTask; -import net.momirealms.customfishing.api.util.LogUtils; import net.momirealms.customfishing.setting.CFConfig; import net.momirealms.customfishing.storage.method.database.nosql.MongoDBImpl; import net.momirealms.customfishing.storage.method.database.nosql.RedisManager; @@ -67,7 +66,7 @@ import java.util.concurrent.TimeUnit; */ public class StorageManagerImpl implements StorageManager, Listener { - private final CustomFishingPlugin plugin; + private final BukkitCustomFishingPlugin plugin; private DataStorageInterface dataSource; private StorageType previousType; private final ConcurrentHashMap onlineUserMap; @@ -78,7 +77,7 @@ public class StorageManagerImpl implements StorageManager, Listener { private CancellableTask timerSaveTask; private final Gson gson; - public StorageManagerImpl(CustomFishingPluginImpl plugin) { + public StorageManagerImpl(BukkitCustomFishingPluginImpl plugin) { this.plugin = plugin; this.locked = new HashSet<>(); this.onlineUserMap = new ConcurrentHashMap<>(); diff --git a/plugin/src/main/java/net/momirealms/customfishing/storage/method/AbstractStorage.java b/core/src/main/java/net/momirealms/customfishing/storage/method/AbstractStorage.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/storage/method/AbstractStorage.java rename to core/src/main/java/net/momirealms/customfishing/storage/method/AbstractStorage.java index d9306d06..44c6ac8a 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/storage/method/AbstractStorage.java +++ b/core/src/main/java/net/momirealms/customfishing/storage/method/AbstractStorage.java @@ -17,7 +17,7 @@ package net.momirealms.customfishing.storage.method; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.DataStorageInterface; import net.momirealms.customfishing.api.data.PlayerData; import net.momirealms.customfishing.api.data.user.OfflineUser; @@ -32,9 +32,9 @@ import java.util.concurrent.CompletableFuture; */ public abstract class AbstractStorage implements DataStorageInterface { - protected CustomFishingPlugin plugin; + protected BukkitCustomFishingPlugin plugin; - public AbstractStorage(CustomFishingPlugin plugin) { + public AbstractStorage(BukkitCustomFishingPlugin plugin) { this.plugin = plugin; } diff --git a/plugin/src/main/java/net/momirealms/customfishing/storage/method/database/nosql/MongoDBImpl.java b/core/src/main/java/net/momirealms/customfishing/storage/method/database/nosql/MongoDBImpl.java similarity index 98% rename from plugin/src/main/java/net/momirealms/customfishing/storage/method/database/nosql/MongoDBImpl.java rename to core/src/main/java/net/momirealms/customfishing/storage/method/database/nosql/MongoDBImpl.java index 1bfd7562..7a9c04c9 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/storage/method/database/nosql/MongoDBImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/storage/method/database/nosql/MongoDBImpl.java @@ -21,11 +21,10 @@ import com.mongodb.*; import com.mongodb.client.*; import com.mongodb.client.model.*; import com.mongodb.client.result.UpdateResult; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.PlayerData; import net.momirealms.customfishing.api.data.StorageType; import net.momirealms.customfishing.api.data.user.OfflineUser; -import net.momirealms.customfishing.api.util.LogUtils; import net.momirealms.customfishing.setting.CFConfig; import net.momirealms.customfishing.storage.method.AbstractStorage; import org.bson.Document; @@ -48,7 +47,7 @@ public class MongoDBImpl extends AbstractStorage { private MongoDatabase database; private String collectionPrefix; - public MongoDBImpl(CustomFishingPlugin plugin) { + public MongoDBImpl(BukkitCustomFishingPlugin plugin) { super(plugin); } diff --git a/plugin/src/main/java/net/momirealms/customfishing/storage/method/database/nosql/RedisManager.java b/core/src/main/java/net/momirealms/customfishing/storage/method/database/nosql/RedisManager.java similarity index 94% rename from plugin/src/main/java/net/momirealms/customfishing/storage/method/database/nosql/RedisManager.java rename to core/src/main/java/net/momirealms/customfishing/storage/method/database/nosql/RedisManager.java index 3fb89303..3a48e2eb 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/storage/method/database/nosql/RedisManager.java +++ b/core/src/main/java/net/momirealms/customfishing/storage/method/database/nosql/RedisManager.java @@ -17,10 +17,9 @@ package net.momirealms.customfishing.storage.method.database.nosql; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.PlayerData; import net.momirealms.customfishing.api.data.StorageType; -import net.momirealms.customfishing.api.util.LogUtils; import net.momirealms.customfishing.setting.CFConfig; import net.momirealms.customfishing.storage.method.AbstractStorage; import org.bukkit.configuration.ConfigurationSection; @@ -51,7 +50,7 @@ public class RedisManager extends AbstractStorage { private BlockingThreadTask threadTask; private boolean isNewerThan5; - public RedisManager(CustomFishingPlugin plugin) { + public RedisManager(BukkitCustomFishingPlugin plugin) { super(plugin); instance = this; } @@ -190,26 +189,26 @@ public class RedisManager extends AbstractStorage { } private static void handleMessage(String message) { - CustomFishingPlugin.get().debug("Received Redis message: " + message); + BukkitCustomFishingPlugin.get().debug("Received Redis message: " + message); String[] split = message.split(";"); String server = split[0]; if (!CFConfig.serverGroup.contains(server)) { return; } String action = split[1]; - CustomFishingPlugin.get().getScheduler().runTaskAsync(() -> { + BukkitCustomFishingPlugin.get().getScheduler().runTaskAsync(() -> { switch (action) { case "start" -> { // start competition for all the servers that connected to redis - CustomFishingPlugin.get().getCompetitionManager().startCompetition(split[2], true, null); + BukkitCustomFishingPlugin.get().getCompetitionManager().startCompetition(split[2], true, null); } case "end" -> { - if (CustomFishingPlugin.get().getCompetitionManager().getOnGoingCompetition() != null) - CustomFishingPlugin.get().getCompetitionManager().getOnGoingCompetition().end(true); + if (BukkitCustomFishingPlugin.get().getCompetitionManager().getOnGoingCompetition() != null) + BukkitCustomFishingPlugin.get().getCompetitionManager().getOnGoingCompetition().end(true); } case "stop" -> { - if (CustomFishingPlugin.get().getCompetitionManager().getOnGoingCompetition() != null) - CustomFishingPlugin.get().getCompetitionManager().getOnGoingCompetition().stop(true); + if (BukkitCustomFishingPlugin.get().getCompetitionManager().getOnGoingCompetition() != null) + BukkitCustomFishingPlugin.get().getCompetitionManager().getOnGoingCompetition().stop(true); } } }); diff --git a/plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/AbstractHikariDatabase.java b/core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/AbstractHikariDatabase.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/AbstractHikariDatabase.java rename to core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/AbstractHikariDatabase.java index 29f242b2..bb29fdc5 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/AbstractHikariDatabase.java +++ b/core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/AbstractHikariDatabase.java @@ -19,9 +19,8 @@ package net.momirealms.customfishing.storage.method.database.sql; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.*; -import net.momirealms.customfishing.api.util.LogUtils; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; @@ -42,7 +41,7 @@ public abstract class AbstractHikariDatabase extends AbstractSQLDatabase impleme private final String driverClass; private final String sqlBrand; - public AbstractHikariDatabase(CustomFishingPlugin plugin) { + public AbstractHikariDatabase(BukkitCustomFishingPlugin plugin) { super(plugin); this.driverClass = getStorageType() == StorageType.MariaDB ? "org.mariadb.jdbc.Driver" : "com.mysql.cj.jdbc.Driver"; this.sqlBrand = getStorageType() == StorageType.MariaDB ? "MariaDB" : "MySQL"; diff --git a/plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/AbstractSQLDatabase.java b/core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/AbstractSQLDatabase.java similarity index 98% rename from plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/AbstractSQLDatabase.java rename to core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/AbstractSQLDatabase.java index ca8bfee9..2100cb59 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/AbstractSQLDatabase.java +++ b/core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/AbstractSQLDatabase.java @@ -17,10 +17,9 @@ package net.momirealms.customfishing.storage.method.database.sql; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.PlayerData; import net.momirealms.customfishing.api.data.user.OfflineUser; -import net.momirealms.customfishing.api.util.LogUtils; import net.momirealms.customfishing.setting.CFConfig; import net.momirealms.customfishing.storage.method.AbstractStorage; import org.bukkit.Bukkit; @@ -40,7 +39,7 @@ public abstract class AbstractSQLDatabase extends AbstractStorage { protected String tablePrefix; - public AbstractSQLDatabase(CustomFishingPlugin plugin) { + public AbstractSQLDatabase(BukkitCustomFishingPlugin plugin) { super(plugin); } diff --git a/plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/H2Impl.java b/core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/H2Impl.java similarity index 90% rename from plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/H2Impl.java rename to core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/H2Impl.java index f28e029c..9884ce2e 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/H2Impl.java +++ b/core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/H2Impl.java @@ -17,8 +17,8 @@ package net.momirealms.customfishing.storage.method.database.sql; -import net.momirealms.customfishing.CustomFishingPluginImpl; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.BukkitCustomFishingPluginImpl; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.StorageType; import net.momirealms.customfishing.libraries.dependencies.Dependency; import org.bukkit.configuration.file.YamlConfiguration; @@ -37,7 +37,7 @@ public class H2Impl extends AbstractSQLDatabase { private Method disposeMethod; private Method getConnectionMethod; - public H2Impl(CustomFishingPlugin plugin) { + public H2Impl(BukkitCustomFishingPlugin plugin) { super(plugin); } @@ -51,7 +51,7 @@ public class H2Impl extends AbstractSQLDatabase { super.tablePrefix = config.getString("H2.table-prefix", "customfishing"); final String url = String.format("jdbc:h2:%s", databaseFile.getAbsolutePath()); - ClassLoader classLoader = ((CustomFishingPluginImpl) plugin).getDependencyManager().obtainClassLoaderWith(EnumSet.of(Dependency.H2_DRIVER)); + ClassLoader classLoader = ((BukkitCustomFishingPluginImpl) plugin).getDependencyManager().obtainClassLoaderWith(EnumSet.of(Dependency.H2_DRIVER)); try { Class connectionClass = classLoader.loadClass("org.h2.jdbcx.JdbcConnectionPool"); Method createPoolMethod = connectionClass.getMethod("create", String.class, String.class, String.class); diff --git a/plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/MariaDBImpl.java b/core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/MariaDBImpl.java similarity index 88% rename from plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/MariaDBImpl.java rename to core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/MariaDBImpl.java index b209b168..354673c7 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/MariaDBImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/MariaDBImpl.java @@ -17,12 +17,12 @@ package net.momirealms.customfishing.storage.method.database.sql; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.StorageType; public class MariaDBImpl extends AbstractHikariDatabase { - public MariaDBImpl(CustomFishingPlugin plugin) { + public MariaDBImpl(BukkitCustomFishingPlugin plugin) { super(plugin); } diff --git a/plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/MySQLImpl.java b/core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/MySQLImpl.java similarity index 88% rename from plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/MySQLImpl.java rename to core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/MySQLImpl.java index ff644f84..2c529fa1 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/MySQLImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/MySQLImpl.java @@ -17,12 +17,12 @@ package net.momirealms.customfishing.storage.method.database.sql; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.StorageType; public class MySQLImpl extends AbstractHikariDatabase { - public MySQLImpl(CustomFishingPlugin plugin) { + public MySQLImpl(BukkitCustomFishingPlugin plugin) { super(plugin); } diff --git a/plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/SQLiteImpl.java b/core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/SQLiteImpl.java similarity index 95% rename from plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/SQLiteImpl.java rename to core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/SQLiteImpl.java index 9e4ae73e..bed18e02 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/storage/method/database/sql/SQLiteImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/storage/method/database/sql/SQLiteImpl.java @@ -17,12 +17,11 @@ package net.momirealms.customfishing.storage.method.database.sql; -import net.momirealms.customfishing.CustomFishingPluginImpl; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.BukkitCustomFishingPluginImpl; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.PlayerData; import net.momirealms.customfishing.api.data.StorageType; import net.momirealms.customfishing.api.data.user.OfflineUser; -import net.momirealms.customfishing.api.util.LogUtils; import net.momirealms.customfishing.libraries.dependencies.Dependency; import net.momirealms.customfishing.setting.CFConfig; import org.bukkit.Bukkit; @@ -46,7 +45,7 @@ public class SQLiteImpl extends AbstractSQLDatabase { private File databaseFile; private Constructor connectionConstructor; - public SQLiteImpl(CustomFishingPlugin plugin) { + public SQLiteImpl(BukkitCustomFishingPlugin plugin) { super(plugin); } @@ -55,7 +54,7 @@ public class SQLiteImpl extends AbstractSQLDatabase { */ @Override public void initialize() { - ClassLoader classLoader = ((CustomFishingPluginImpl) plugin).getDependencyManager().obtainClassLoaderWith(EnumSet.of(Dependency.SQLITE_DRIVER, Dependency.SLF4J_SIMPLE, Dependency.SLF4J_API)); + ClassLoader classLoader = ((BukkitCustomFishingPluginImpl) plugin).getDependencyManager().obtainClassLoaderWith(EnumSet.of(Dependency.SQLITE_DRIVER, Dependency.SLF4J_SIMPLE, Dependency.SLF4J_API)); try { Class connectionClass = classLoader.loadClass("org.sqlite.jdbc4.JDBC4Connection"); connectionConstructor = connectionClass.getConstructor(String.class, String.class, Properties.class); diff --git a/plugin/src/main/java/net/momirealms/customfishing/storage/method/file/JsonImpl.java b/core/src/main/java/net/momirealms/customfishing/storage/method/file/JsonImpl.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/storage/method/file/JsonImpl.java rename to core/src/main/java/net/momirealms/customfishing/storage/method/file/JsonImpl.java index 9f4b2f7f..4a54cb74 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/storage/method/file/JsonImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/storage/method/file/JsonImpl.java @@ -18,7 +18,7 @@ package net.momirealms.customfishing.storage.method.file; import com.google.gson.Gson; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.PlayerData; import net.momirealms.customfishing.api.data.StorageType; import net.momirealms.customfishing.storage.method.AbstractStorage; @@ -41,7 +41,7 @@ import java.util.concurrent.CompletableFuture; public class JsonImpl extends AbstractStorage { @SuppressWarnings("ResultOfMethodCallIgnored") - public JsonImpl(CustomFishingPlugin plugin) { + public JsonImpl(BukkitCustomFishingPlugin plugin) { super(plugin); File folder = new File(plugin.getDataFolder(), "data"); if (!folder.exists()) folder.mkdirs(); diff --git a/plugin/src/main/java/net/momirealms/customfishing/storage/method/file/YAMLImpl.java b/core/src/main/java/net/momirealms/customfishing/storage/method/file/YAMLImpl.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/storage/method/file/YAMLImpl.java rename to core/src/main/java/net/momirealms/customfishing/storage/method/file/YAMLImpl.java index e3ac1db4..8df635c5 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/storage/method/file/YAMLImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/storage/method/file/YAMLImpl.java @@ -17,9 +17,8 @@ package net.momirealms.customfishing.storage.method.file; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.*; -import net.momirealms.customfishing.api.util.LogUtils; import net.momirealms.customfishing.storage.method.AbstractStorage; import net.momirealms.customfishing.util.ConfigUtils; import org.bukkit.Bukkit; @@ -37,7 +36,7 @@ import java.util.concurrent.CompletableFuture; public class YAMLImpl extends AbstractStorage implements LegacyDataStorageInterface { @SuppressWarnings("ResultOfMethodCallIgnored") - public YAMLImpl(CustomFishingPlugin plugin) { + public YAMLImpl(BukkitCustomFishingPlugin plugin) { super(plugin); File folder = new File(plugin.getDataFolder(), "data"); if (!folder.exists()) folder.mkdirs(); diff --git a/plugin/src/main/java/net/momirealms/customfishing/storage/user/OfflineUserImpl.java b/core/src/main/java/net/momirealms/customfishing/storage/user/OfflineUserImpl.java similarity index 92% rename from plugin/src/main/java/net/momirealms/customfishing/storage/user/OfflineUserImpl.java rename to core/src/main/java/net/momirealms/customfishing/storage/user/OfflineUserImpl.java index 066a2ef4..5ff08f57 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/storage/user/OfflineUserImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/storage/user/OfflineUserImpl.java @@ -17,8 +17,7 @@ package net.momirealms.customfishing.storage.user; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.data.EarningData; import net.momirealms.customfishing.api.data.InventoryData; import net.momirealms.customfishing.api.data.PlayerData; @@ -27,7 +26,7 @@ import net.momirealms.customfishing.api.data.user.OfflineUser; import net.momirealms.customfishing.api.mechanic.bag.FishingBagHolder; import net.momirealms.customfishing.api.mechanic.statistic.Statistics; import net.momirealms.customfishing.api.util.InventoryUtils; -import net.momirealms.customfishing.compatibility.papi.PlaceholderManagerImpl; +import net.momirealms.customfishing.bukkit.compatibility.papi.PlaceholderManagerImpl; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; @@ -65,13 +64,13 @@ public class OfflineUserImpl implements OfflineUser { AdventureHelper.getInstance().getComponentFromMiniMessage( PlaceholderManagerImpl.getInstance().parse( offlinePlayer, - CustomFishingPlugin.get().getBagManager().getBagTitle(), + BukkitCustomFishingPlugin.get().getBagManager().getBagTitle(), Map.of("{player}", Optional.ofNullable(offlinePlayer.getName()).orElse(String.valueOf(uuid))) ) ))); this.holder.setItems(InventoryUtils.getInventoryItems(playerData.getBagData().serialized)); this.earningData = playerData.getEarningData(); - int date = CustomFishingPlugin.get().getMarketManager().getDate(); + int date = BukkitCustomFishingPlugin.get().getMarketManager().getRealTimeDate(); if (earningData.date != date) { earningData.date = date; earningData.earnings = 0d; diff --git a/plugin/src/main/java/net/momirealms/customfishing/storage/user/OnlineUserImpl.java b/core/src/main/java/net/momirealms/customfishing/storage/user/OnlineUserImpl.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/storage/user/OnlineUserImpl.java rename to core/src/main/java/net/momirealms/customfishing/storage/user/OnlineUserImpl.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/util/ArmorStandUtils.java b/core/src/main/java/net/momirealms/customfishing/util/ArmorStandUtils.java similarity index 83% rename from plugin/src/main/java/net/momirealms/customfishing/util/ArmorStandUtils.java rename to core/src/main/java/net/momirealms/customfishing/util/ArmorStandUtils.java index df9d4ab0..38b84623 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/util/ArmorStandUtils.java +++ b/core/src/main/java/net/momirealms/customfishing/util/ArmorStandUtils.java @@ -23,8 +23,8 @@ import com.comphenix.protocol.wrappers.*; import com.google.common.collect.Lists; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; -import net.momirealms.customfishing.CustomFishingPluginImpl; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.BukkitCustomFishingPluginImpl; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import org.bukkit.Location; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; @@ -68,7 +68,7 @@ public class ArmorStandUtils { entityPacket.getDoubles().write(0, location.getX()); entityPacket.getDoubles().write(1, location.getY()); entityPacket.getDoubles().write(2, location.getZ()); - if (CustomFishingPlugin.get().getVersionManager().isVersionNewerThan1_19()) { + if (BukkitCustomFishingPlugin.get().getVersionManager().isVersionNewerThan1_19()) { entityPacket.getBytes().write(0, (byte) ((location.getYaw() % 360) * 128 / 180)); } else { entityPacket.getIntegers().write(5, (int) ((location.getYaw() % 360) * 128 / 180)); @@ -88,7 +88,7 @@ public class ArmorStandUtils { public static PacketContainer getMetaPacket(int id) { PacketContainer metaPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA); metaPacket.getIntegers().write(0, id); - if (CustomFishingPlugin.get().getVersionManager().isVersionNewerThan1_19_R2()) { + if (BukkitCustomFishingPlugin.get().getVersionManager().isVersionNewerThan1_19_3()) { WrappedDataWatcher wrappedDataWatcher = createDataWatcher(); setValueList(metaPacket, wrappedDataWatcher); } else { @@ -123,7 +123,7 @@ public class ArmorStandUtils { public static PacketContainer getMetaPacket(int id, Component component) { PacketContainer metaPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA); metaPacket.getIntegers().write(0, id); - if (CustomFishingPlugin.get().getVersionManager().isVersionNewerThan1_19_R2()) { + if (BukkitCustomFishingPlugin.get().getVersionManager().isVersionNewerThan1_19_3()) { WrappedDataWatcher wrappedDataWatcher = createDataWatcher(component); setValueList(metaPacket, wrappedDataWatcher); } else { @@ -191,14 +191,14 @@ public class ArmorStandUtils { */ public static void sendFakeItem(Player player, Location location, ItemStack itemStack, int seconds) { int id = new Random().nextInt(Integer.MAX_VALUE); - if (CustomFishingPlugin.get().getVersionManager().isVersionNewerThan1_19_R3()) { - CustomFishingPluginImpl.sendPackets(player, getSpawnPacket(id, location.clone().subtract(0,1,0)), getMetaPacket(id), getEquipPacket(id, itemStack)); + if (BukkitCustomFishingPlugin.get().getVersionManager().isVersionNewerThan1_19_4()) { + BukkitCustomFishingPluginImpl.sendPackets(player, getSpawnPacket(id, location.clone().subtract(0,1,0)), getMetaPacket(id), getEquipPacket(id, itemStack)); } else { - CustomFishingPluginImpl.sendPacket(player, getSpawnPacket(id, location.clone().subtract(0,1,0))); - CustomFishingPluginImpl.sendPacket(player, getMetaPacket(id)); - CustomFishingPluginImpl.sendPacket(player, getEquipPacket(id, itemStack)); + BukkitCustomFishingPluginImpl.sendPacket(player, getSpawnPacket(id, location.clone().subtract(0,1,0))); + BukkitCustomFishingPluginImpl.sendPacket(player, getMetaPacket(id)); + BukkitCustomFishingPluginImpl.sendPacket(player, getEquipPacket(id, itemStack)); } - CustomFishingPlugin.get().getScheduler().runTaskAsyncLater(() -> CustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, getDestroyPacket(id)), seconds * 50L, TimeUnit.MILLISECONDS); + BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncLater(() -> BukkitCustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, getDestroyPacket(id)), seconds * 50L, TimeUnit.MILLISECONDS); } /** @@ -211,12 +211,12 @@ public class ArmorStandUtils { */ public static void sendHologram(Player player, Location location, Component component, int seconds) { int id = new Random().nextInt(Integer.MAX_VALUE); - if (CustomFishingPlugin.get().getVersionManager().isVersionNewerThan1_19_R3()) { - CustomFishingPluginImpl.sendPackets(player, getSpawnPacket(id, location.clone().subtract(0,1,0)), getMetaPacket(id, component)); + if (BukkitCustomFishingPlugin.get().getVersionManager().isVersionNewerThan1_19_4()) { + BukkitCustomFishingPluginImpl.sendPackets(player, getSpawnPacket(id, location.clone().subtract(0,1,0)), getMetaPacket(id, component)); } else { - CustomFishingPluginImpl.sendPacket(player, getSpawnPacket(id, location.clone().subtract(0,1,0))); - CustomFishingPluginImpl.sendPacket(player, getMetaPacket(id, component)); + BukkitCustomFishingPluginImpl.sendPacket(player, getSpawnPacket(id, location.clone().subtract(0,1,0))); + BukkitCustomFishingPluginImpl.sendPacket(player, getMetaPacket(id, component)); } - CustomFishingPlugin.get().getScheduler().runTaskAsyncLater(() -> CustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, getDestroyPacket(id)), seconds * 50L, TimeUnit.MILLISECONDS); + BukkitCustomFishingPlugin.get().getScheduler().runTaskAsyncLater(() -> BukkitCustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, getDestroyPacket(id)), seconds * 50L, TimeUnit.MILLISECONDS); } } \ No newline at end of file diff --git a/plugin/src/main/java/net/momirealms/customfishing/util/CompletableFutures.java b/core/src/main/java/net/momirealms/customfishing/util/CompletableFutures.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/util/CompletableFutures.java rename to core/src/main/java/net/momirealms/customfishing/util/CompletableFutures.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/util/ConfigUtils.java b/core/src/main/java/net/momirealms/customfishing/util/ConfigUtils.java similarity index 89% rename from plugin/src/main/java/net/momirealms/customfishing/util/ConfigUtils.java rename to core/src/main/java/net/momirealms/customfishing/util/ConfigUtils.java index b3f4b513..35e09607 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/util/ConfigUtils.java +++ b/core/src/main/java/net/momirealms/customfishing/util/ConfigUtils.java @@ -19,12 +19,10 @@ package net.momirealms.customfishing.util; import net.momirealms.customfishing.api.common.Pair; import net.momirealms.customfishing.api.common.Tuple; -import net.momirealms.customfishing.api.mechanic.misc.Value; -import net.momirealms.customfishing.api.mechanic.misc.WeightModifier; -import net.momirealms.customfishing.api.util.LogUtils; -import net.momirealms.customfishing.compatibility.papi.PlaceholderManagerImpl; -import net.momirealms.customfishing.mechanic.misc.value.ExpressionValue; -import net.momirealms.customfishing.mechanic.misc.value.PlainValue; +import net.momirealms.customfishing.api.mechanic.misc.value.MathValue; +import net.momirealms.customfishing.bukkit.compatibility.papi.PlaceholderManagerImpl; +import net.momirealms.customfishing.mechanic.misc.value.ExpressionMathValue; +import net.momirealms.customfishing.mechanic.misc.value.PlainMathValue; import net.objecthunter.exp4j.ExpressionBuilder; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; @@ -128,13 +126,13 @@ public class ConfigUtils { * @param arg int / double / expression * @return Value */ - public static Value getValue(Object arg) { + public static MathValue getValue(Object arg) { if (arg instanceof Integer i) { - return new PlainValue(i); + return new PlainMathValue(i); } else if (arg instanceof Double d) { - return new PlainValue(d); + return new PlainMathValue(d); } else if (arg instanceof String s) { - return new ExpressionValue(s); + return new ExpressionMathValue(s); } throw new IllegalArgumentException("Illegal value type"); } @@ -209,8 +207,8 @@ public class ConfigUtils { return list; } - public static List> getEnchantAmountPair(ConfigurationSection section) { - List> list = new ArrayList<>(); + public static List> getEnchantAmountPair(ConfigurationSection section) { + List> list = new ArrayList<>(); if (section == null) return list; for (Map.Entry entry : section.getValues(false).entrySet()) { list.add(Pair.of(Integer.parseInt(entry.getKey()), getValue(entry.getValue()))); @@ -218,8 +216,8 @@ public class ConfigUtils { return list; } - public static List, Value>> getEnchantPoolPair(ConfigurationSection section) { - List, Value>> list = new ArrayList<>(); + public static List, MathValue>> getEnchantPoolPair(ConfigurationSection section) { + List, MathValue>> list = new ArrayList<>(); if (section == null) return list; for (Map.Entry entry : section.getValues(false).entrySet()) { list.add(Pair.of(getEnchantmentPair(entry.getKey()), getValue(entry.getValue()))); @@ -345,14 +343,7 @@ public class ConfigUtils { boolean first = true; for (Map.Entry entry : map.entrySet()) { Object nbt = entry.getValue(); - if (nbt instanceof String value) { - if (isMapList && first) { - first = false; - readableList.add(" ".repeat(loop_times - 1) + "- " + entry.getKey() + ": " + value); - } else { - readableList.add(" ".repeat(loop_times) + "" + entry.getKey() + ": " + value); - } - } else if (nbt instanceof List list) { + if (nbt instanceof List list) { if (isMapList && first) { first = false; readableList.add(" ".repeat(loop_times - 1) + "- " + entry.getKey() + ":"); @@ -366,14 +357,6 @@ public class ConfigUtils { readableList.add(" ".repeat(loop_times + 1) + "- " + value); } } - } else if (nbt instanceof ConfigurationSection section) { - if (isMapList && first) { - first = false; - readableList.add(" ".repeat(loop_times - 1) + "- " + entry.getKey() + ":"); - } else { - readableList.add(" ".repeat(loop_times) + "" + entry.getKey() + ":"); - } - mapToReadableStringList(section.getValues(false), readableList, loop_times + 1, false); } else if (nbt instanceof Map innerMap) { if (isMapList && first) { first = false; @@ -382,6 +365,13 @@ public class ConfigUtils { readableList.add(" ".repeat(loop_times) + "" + entry.getKey() + ":"); } mapToReadableStringList((Map) innerMap, readableList, loop_times + 1, false); + } else { + if (isMapList && first) { + first = false; + readableList.add(" ".repeat(loop_times - 1) + "- " + entry.getKey() + ": " + nbt.toString()); + } else { + readableList.add(" ".repeat(loop_times) + "" + entry.getKey() + ": " + nbt.toString()); + } } } } diff --git a/plugin/src/main/java/net/momirealms/customfishing/util/FakeItemUtils.java b/core/src/main/java/net/momirealms/customfishing/util/FakeItemUtils.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/util/FakeItemUtils.java rename to core/src/main/java/net/momirealms/customfishing/util/FakeItemUtils.java index d0ae3c8e..d8f47255 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/util/FakeItemUtils.java +++ b/core/src/main/java/net/momirealms/customfishing/util/FakeItemUtils.java @@ -22,7 +22,7 @@ import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.wrappers.WrappedDataValue; import com.comphenix.protocol.wrappers.WrappedDataWatcher; import com.google.common.collect.Lists; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import org.bukkit.Location; import org.bukkit.entity.EntityType; import org.bukkit.inventory.ItemStack; @@ -79,7 +79,7 @@ public class FakeItemUtils { public static PacketContainer getMetaPacket(int id, ItemStack itemStack) { PacketContainer metaPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA); metaPacket.getIntegers().write(0, id); - if (CustomFishingPlugin.getInstance().getVersionManager().isVersionNewerThan1_19_R2()) { + if (BukkitCustomFishingPlugin.getInstance().getVersionManager().isVersionNewerThan1_19_3()) { WrappedDataWatcher wrappedDataWatcher = createDataWatcher(itemStack); setValueList(metaPacket, wrappedDataWatcher); } else { diff --git a/plugin/src/main/java/net/momirealms/customfishing/util/ItemUtils.java b/core/src/main/java/net/momirealms/customfishing/util/ItemUtils.java similarity index 97% rename from plugin/src/main/java/net/momirealms/customfishing/util/ItemUtils.java rename to core/src/main/java/net/momirealms/customfishing/util/ItemUtils.java index a1aeea39..da8f3dd2 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/util/ItemUtils.java +++ b/core/src/main/java/net/momirealms/customfishing/util/ItemUtils.java @@ -23,11 +23,9 @@ import de.tr7zw.changeme.nbtapi.NBTList; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.ScoreComponent; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; +import net.momirealms.customfishing.api.BukkitCustomFishingPlugin; import net.momirealms.customfishing.api.common.Pair; import net.momirealms.customfishing.api.mechanic.hook.HookSetting; -import net.momirealms.customfishing.api.util.LogUtils; import net.momirealms.customfishing.setting.CFConfig; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -71,7 +69,7 @@ public class ItemUtils { if (cfCompound.hasTag("hook_id")) { String hookID = cfCompound.getString("hook_id"); - HookSetting setting = CustomFishingPlugin.get().getHookManager().getHookSetting(hookID); + HookSetting setting = BukkitCustomFishingPlugin.get().getHookManager().getHookSetting(hookID); if (setting == null) { cfCompound.removeKey("hook_id"); cfCompound.removeKey("hook_item"); @@ -159,7 +157,7 @@ public class ItemUtils { int hookDur = cfCompound.getInteger("hook_dur"); if (hookDur != -1) { String id = cfCompound.getString("hook_id"); - HookSetting setting = CustomFishingPlugin.get().getHookManager().getHookSetting(id); + HookSetting setting = BukkitCustomFishingPlugin.get().getHookManager().getHookSetting(id); if (setting == null) { cfCompound.removeKey("hook_id"); cfCompound.removeKey("hook_dur"); @@ -190,7 +188,7 @@ public class ItemUtils { int hookDur = cfCompound.getInteger("hook_dur"); if (hookDur != -1) { String id = cfCompound.getString("hook_id"); - HookSetting setting = CustomFishingPlugin.get().getHookManager().getHookSetting(id); + HookSetting setting = BukkitCustomFishingPlugin.get().getHookManager().getHookSetting(id); if (setting == null) { cfCompound.removeKey("hook_id"); cfCompound.removeKey("hook_dur"); diff --git a/plugin/src/main/java/net/momirealms/customfishing/util/LocationUtils.java b/core/src/main/java/net/momirealms/customfishing/util/LocationUtils.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/util/LocationUtils.java rename to core/src/main/java/net/momirealms/customfishing/util/LocationUtils.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/util/MoonPhase.java b/core/src/main/java/net/momirealms/customfishing/util/MoonPhase.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/util/MoonPhase.java rename to core/src/main/java/net/momirealms/customfishing/util/MoonPhase.java diff --git a/plugin/src/main/java/net/momirealms/customfishing/util/NumberUtils.java b/core/src/main/java/net/momirealms/customfishing/util/NumberUtils.java similarity index 100% rename from plugin/src/main/java/net/momirealms/customfishing/util/NumberUtils.java rename to core/src/main/java/net/momirealms/customfishing/util/NumberUtils.java diff --git a/api/src/main/java/net/momirealms/customfishing/api/common/SimpleLocation.java b/core/src/main/java/net/momirealms/customfishing/util/SimpleLocation.java similarity index 97% rename from api/src/main/java/net/momirealms/customfishing/api/common/SimpleLocation.java rename to core/src/main/java/net/momirealms/customfishing/util/SimpleLocation.java index b14bec65..867eb708 100644 --- a/api/src/main/java/net/momirealms/customfishing/api/common/SimpleLocation.java +++ b/core/src/main/java/net/momirealms/customfishing/util/SimpleLocation.java @@ -15,7 +15,7 @@ * along with this program. If not, see . */ -package net.momirealms.customfishing.api.common; +package net.momirealms.customfishing.util; import org.bukkit.Location; diff --git a/plugin/src/main/java/net/momirealms/customfishing/version/VersionManagerImpl.java b/core/src/main/java/net/momirealms/customfishing/version/VersionManagerImpl.java similarity index 86% rename from plugin/src/main/java/net/momirealms/customfishing/version/VersionManagerImpl.java rename to core/src/main/java/net/momirealms/customfishing/version/VersionManagerImpl.java index 0120864c..5a938992 100644 --- a/plugin/src/main/java/net/momirealms/customfishing/version/VersionManagerImpl.java +++ b/core/src/main/java/net/momirealms/customfishing/version/VersionManagerImpl.java @@ -17,9 +17,8 @@ package net.momirealms.customfishing.version; -import net.momirealms.customfishing.CustomFishingPluginImpl; +import net.momirealms.customfishing.BukkitCustomFishingPluginImpl; import net.momirealms.customfishing.api.manager.VersionManager; -import net.momirealms.customfishing.api.util.LogUtils; import org.bukkit.Bukkit; import java.io.BufferedReader; @@ -34,19 +33,20 @@ import java.util.concurrent.CompletableFuture; */ public class VersionManagerImpl implements VersionManager { - private final boolean isNewerThan1_19_R2; - private final boolean isNewerThan1_19_R3; + private final boolean isNewerThan1_19_3; + private final boolean isNewerThan1_19_4; private final boolean isNewerThan1_20; + private final boolean isNewerThan1_20_5; private final boolean isNewerThan1_19; private final String serverVersion; - private final CustomFishingPluginImpl plugin; + private final BukkitCustomFishingPluginImpl plugin; private final boolean isSpigot; private boolean hasRegionScheduler; private boolean isMojmap; private final String pluginVersion; @SuppressWarnings("deprecation") - public VersionManagerImpl(CustomFishingPluginImpl plugin) { + public VersionManagerImpl(BukkitCustomFishingPluginImpl plugin) { this.plugin = plugin; // Get the server version @@ -55,16 +55,17 @@ public class VersionManagerImpl implements VersionManager { int main_ver = Integer.parseInt(split[0]); // Determine if the server version is newer than 1_19_R2 and 1_20_R1 if (main_ver >= 20) { - isNewerThan1_19_R2 = isNewerThan1_19_R3 = true; + isNewerThan1_20_5 = Integer.parseInt(split[1]) >= 5; + isNewerThan1_19_3 = isNewerThan1_19_4 = true; isNewerThan1_20 = true; isNewerThan1_19 = true; } else if (main_ver == 19) { - isNewerThan1_20 = false; - isNewerThan1_19_R2 = Integer.parseInt(split[1]) >= 2; - isNewerThan1_19_R3 = Integer.parseInt(split[1]) >= 3; + isNewerThan1_20 = isNewerThan1_20_5 = false; + isNewerThan1_19_3 = Integer.parseInt(split[1]) >= 3; + isNewerThan1_19_4 = Integer.parseInt(split[1]) >= 4; isNewerThan1_19 = true; } else { - isNewerThan1_20 = isNewerThan1_19 = isNewerThan1_19_R2 = isNewerThan1_19_R3 = false; + isNewerThan1_20 = isNewerThan1_20_5 = isNewerThan1_19 = isNewerThan1_19_3 = isNewerThan1_19_4 = false; } // Check if the server is Spigot String server_name = plugin.getServer().getName(); @@ -96,14 +97,13 @@ public class VersionManagerImpl implements VersionManager { } @Override - public boolean isVersionNewerThan1_19_R3() { - return isNewerThan1_19_R3; + public boolean isVersionNewerThan1_19_4() { + return isNewerThan1_19_4; } - @Override - public boolean isVersionNewerThan1_19_R2() { - return isNewerThan1_19_R2; + public boolean isVersionNewerThan1_19_3() { + return isNewerThan1_19_3; } @Override @@ -111,6 +111,11 @@ public class VersionManagerImpl implements VersionManager { return isNewerThan1_20; } + @Override + public boolean isNewerThan1_20_5() { + return isNewerThan1_20_5; + } + @Override public boolean isSpigot() { return isSpigot; @@ -140,7 +145,7 @@ public class VersionManagerImpl implements VersionManager { @Override public CompletableFuture checkUpdate() { CompletableFuture updateFuture = new CompletableFuture<>(); - plugin.getScheduler().runTaskAsync(() -> { + plugin.getScheduler().async(() -> { try { URL url = new URL("https://api.polymart.org/v1/getResourceInfoSimple/?resource_id=2723&key=version"); URLConnection conn = url.openConnection(); diff --git a/plugin/src/main/resources/config.yml b/core/src/main/resources/config.yml similarity index 100% rename from plugin/src/main/resources/config.yml rename to core/src/main/resources/config.yml diff --git a/plugin/src/main/resources/contents/bait/default.yml b/core/src/main/resources/contents/bait/default.yml similarity index 100% rename from plugin/src/main/resources/contents/bait/default.yml rename to core/src/main/resources/contents/bait/default.yml diff --git a/plugin/src/main/resources/contents/block/default.yml b/core/src/main/resources/contents/block/default.yml similarity index 100% rename from plugin/src/main/resources/contents/block/default.yml rename to core/src/main/resources/contents/block/default.yml diff --git a/plugin/src/main/resources/contents/category/default.yml b/core/src/main/resources/contents/category/default.yml similarity index 100% rename from plugin/src/main/resources/contents/category/default.yml rename to core/src/main/resources/contents/category/default.yml diff --git a/plugin/src/main/resources/contents/competition/default.yml b/core/src/main/resources/contents/competition/default.yml similarity index 100% rename from plugin/src/main/resources/contents/competition/default.yml rename to core/src/main/resources/contents/competition/default.yml diff --git a/plugin/src/main/resources/contents/enchant/default.yml b/core/src/main/resources/contents/enchant/default.yml similarity index 100% rename from plugin/src/main/resources/contents/enchant/default.yml rename to core/src/main/resources/contents/enchant/default.yml diff --git a/plugin/src/main/resources/contents/entity/default.yml b/core/src/main/resources/contents/entity/default.yml similarity index 100% rename from plugin/src/main/resources/contents/entity/default.yml rename to core/src/main/resources/contents/entity/default.yml diff --git a/plugin/src/main/resources/contents/hook/default.yml b/core/src/main/resources/contents/hook/default.yml similarity index 100% rename from plugin/src/main/resources/contents/hook/default.yml rename to core/src/main/resources/contents/hook/default.yml diff --git a/plugin/src/main/resources/contents/item/default.yml b/core/src/main/resources/contents/item/default.yml similarity index 100% rename from plugin/src/main/resources/contents/item/default.yml rename to core/src/main/resources/contents/item/default.yml diff --git a/plugin/src/main/resources/contents/minigame/default.yml b/core/src/main/resources/contents/minigame/default.yml similarity index 100% rename from plugin/src/main/resources/contents/minigame/default.yml rename to core/src/main/resources/contents/minigame/default.yml diff --git a/plugin/src/main/resources/contents/rod/default.yml b/core/src/main/resources/contents/rod/default.yml similarity index 100% rename from plugin/src/main/resources/contents/rod/default.yml rename to core/src/main/resources/contents/rod/default.yml diff --git a/plugin/src/main/resources/contents/totem/default.yml b/core/src/main/resources/contents/totem/default.yml similarity index 100% rename from plugin/src/main/resources/contents/totem/default.yml rename to core/src/main/resources/contents/totem/default.yml diff --git a/plugin/src/main/resources/contents/util/default.yml b/core/src/main/resources/contents/util/default.yml similarity index 100% rename from plugin/src/main/resources/contents/util/default.yml rename to core/src/main/resources/contents/util/default.yml diff --git a/core/src/main/resources/database.yml b/core/src/main/resources/database.yml new file mode 100644 index 00000000..af8f3715 --- /dev/null +++ b/core/src/main/resources/database.yml @@ -0,0 +1,77 @@ +# file: +# JSON +# YAML +# +# local database +# SQLite +# H2 (preferred over SQLite) +# +# remote database +# MySQL +# MariaDB (preferred over MySQL) +# MongoDB +# +data-storage-method: H2 + +SQLite: + file: 'sqlite' + table-prefix: customfishing + +H2: + file: 'h2' + table-prefix: customfishing + +MySQL: + host: 'localhost' + port: '3306' + user: 'root' + password: 'password' + database: 'minecraft' + connection-parameters: '?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8' + Pool-Settings: + max-pool-size: 10 + min-idle: 10 + max-lifetime: 180000 + keep-alive-time: 60000 + time-out: 20000 + table-prefix: customfishing + +MariaDB: + host: 'localhost' + port: '3306' + user: 'root' + password: 'password' + database: 'minecraft' + connection-parameters: '?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8' + Pool-Settings: + max-pool-size: 10 + min-idle: 10 + max-lifetime: 180000 + keep-alive-time: 60000 + time-out: 20000 + table-prefix: customfishing + +MongoDB: + host: 'localhost' + port: '27017' + #user: 'root' + #password: 'password' + database: 'minecraft' + # If this section is not empty, it would override the configs above + # https://www.mongodb.com/docs/manual/reference/connection-string/ + connection-uri: '' + collection-prefix: customfishing + +# Redis is optional if you are using remote database +# If you do not know how to use Redis, please do not enable it +Redis: + enable: false + host: localhost + #password: "123456" + port: 6379 + use-ssl: false + MaxTotal: 10 + MaxIdle: 10 + MinIdle: 1 + MaxWaitMillis: 30000 + MinEvictableIdleTimeMillis: 1800000 \ No newline at end of file diff --git a/plugin/src/main/resources/game-conditions.yml b/core/src/main/resources/game-conditions.yml similarity index 100% rename from plugin/src/main/resources/game-conditions.yml rename to core/src/main/resources/game-conditions.yml diff --git a/plugin/src/main/resources/loot-conditions.yml b/core/src/main/resources/loot-conditions.yml similarity index 100% rename from plugin/src/main/resources/loot-conditions.yml rename to core/src/main/resources/loot-conditions.yml diff --git a/plugin/src/main/resources/market.yml b/core/src/main/resources/market.yml similarity index 100% rename from plugin/src/main/resources/market.yml rename to core/src/main/resources/market.yml diff --git a/plugin/src/main/resources/messages/en.yml b/core/src/main/resources/messages/en.yml similarity index 100% rename from plugin/src/main/resources/messages/en.yml rename to core/src/main/resources/messages/en.yml diff --git a/plugin/src/main/resources/messages/es.yml b/core/src/main/resources/messages/es.yml similarity index 100% rename from plugin/src/main/resources/messages/es.yml rename to core/src/main/resources/messages/es.yml diff --git a/plugin/src/main/resources/messages/fr.yml b/core/src/main/resources/messages/fr.yml similarity index 100% rename from plugin/src/main/resources/messages/fr.yml rename to core/src/main/resources/messages/fr.yml diff --git a/plugin/src/main/resources/messages/hu.yml b/core/src/main/resources/messages/hu.yml similarity index 100% rename from plugin/src/main/resources/messages/hu.yml rename to core/src/main/resources/messages/hu.yml diff --git a/plugin/src/main/resources/messages/zh_cn.yml b/core/src/main/resources/messages/zh_cn.yml similarity index 100% rename from plugin/src/main/resources/messages/zh_cn.yml rename to core/src/main/resources/messages/zh_cn.yml diff --git a/plugin/src/main/resources/plugin.yml b/core/src/main/resources/plugin.yml similarity index 100% rename from plugin/src/main/resources/plugin.yml rename to core/src/main/resources/plugin.yml diff --git a/plugin/src/main/resources/schema/h2.sql b/core/src/main/resources/schema/h2.sql similarity index 100% rename from plugin/src/main/resources/schema/h2.sql rename to core/src/main/resources/schema/h2.sql diff --git a/plugin/src/main/resources/schema/mariadb.sql b/core/src/main/resources/schema/mariadb.sql similarity index 100% rename from plugin/src/main/resources/schema/mariadb.sql rename to core/src/main/resources/schema/mariadb.sql diff --git a/plugin/src/main/resources/schema/mysql.sql b/core/src/main/resources/schema/mysql.sql similarity index 100% rename from plugin/src/main/resources/schema/mysql.sql rename to core/src/main/resources/schema/mysql.sql diff --git a/plugin/src/main/resources/schema/sqlite.sql b/core/src/main/resources/schema/sqlite.sql similarity index 100% rename from plugin/src/main/resources/schema/sqlite.sql rename to core/src/main/resources/schema/sqlite.sql diff --git a/gradle.properties b/gradle.properties index 7b26f395..d078c27d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,8 +1,47 @@ +# Project settings +# Rule: [major update].[feature update].[bug fix] +project_version=1.7.1 +config_version=2 +project_group=net.momirealms + +# Dependency settings +paper_version=1.20.4 +jetbrains_annotations_version=24.0.0 +slf4j_version=2.0.13 +log4j_version=2.23.1 +gson_version=2.10.1 +asm_version=9.7 +asm_commons_version=9.7 +jar_relocator_version=1.7 +h2_driver_version=2.2.224 +sqlite_driver_version=3.45.3.0 +adventure_bundle_version=4.16.0 +sparrow_heart_version=0.15 +cloud_core_version=2.0.0-rc.1 +cloud_brigadier_version=2.0.0-beta.7 +cloud_services_version=2.0.0-rc.1 +cloud_bukkit_version=2.0.0-beta.7 +cloud_paper_version=2.0.0-beta.7 +cloud_minecraft_extras_version=2.0.0-beta.7 +boosted_yaml_version=1.3.4 +byte_buddy_version=1.14.14 +mojang_brigadier_version=1.0.18 +adventure_platform_version=4.3.2 +mongodb_driver_version=5.1.0 +mariadb_driver_version=3.3.3 +mysql_driver_version=8.4.0 +hikari_version=5.1.0 +commons_pool_version=2.12.0 +bstats_version=3.0.2 +geantyref_version=1.3.15 +caffeine_version=3.1.8 +rtag_version=1.5.3 +jedis_version=5.1.2 + +# Proxy settings systemProp.socks.proxyHost=127.0.0.1 systemProp.socks.proxyPort=7890 - systemProp.http.proxyHost=127.0.0.1 systemProp.http.proxyPort=7890 - systemProp.https.proxyHost=127.0.0.1 systemProp.https.proxyPort=7890 \ No newline at end of file diff --git a/paper-loader/build.gradle.kts b/paper-loader/build.gradle.kts new file mode 100644 index 00000000..e69de29b diff --git a/paper-loader/src/main/java/net/momirealms/Main.java b/paper-loader/src/main/java/net/momirealms/Main.java new file mode 100644 index 00000000..40cdae49 --- /dev/null +++ b/paper-loader/src/main/java/net/momirealms/Main.java @@ -0,0 +1,5 @@ +package net.momirealms; + +public class Main { + +} \ No newline at end of file diff --git a/plugin/src/main/java/net/momirealms/customfishing/adventure/AdventureHelper.java b/plugin/src/main/java/net/momirealms/customfishing/adventure/AdventureHelper.java deleted file mode 100644 index 9a0279bf..00000000 --- a/plugin/src/main/java/net/momirealms/customfishing/adventure/AdventureHelper.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.adventure; - -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.PacketContainer; -import net.kyori.adventure.audience.Audience; -import net.kyori.adventure.key.Key; -import net.kyori.adventure.platform.bukkit.BukkitAudiences; -import net.kyori.adventure.sound.Sound; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.minimessage.MiniMessage; -import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import net.momirealms.customfishing.CustomFishingPluginImpl; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.manager.AdventureManager; -import net.momirealms.customfishing.api.util.LogUtils; -import net.momirealms.customfishing.api.util.ReflectionUtils; -import net.momirealms.customfishing.setting.CFConfig; -import net.momirealms.customfishing.setting.CFLocale; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.entity.Player; - -import java.lang.reflect.InvocationTargetException; - -public class AdventureHelper implements AdventureManager { - - private final BukkitAudiences adventure; - private static AdventureManager instance; - - public AdventureHelper(CustomFishingPlugin plugin) { - this.adventure = BukkitAudiences.create(plugin); - instance = this; - } - - public static AdventureManager getInstance() { - return instance; - } - - public void close() { - if (adventure != null) - adventure.close(); - } - - @Override - public Component getComponentFromMiniMessage(String text) { - if (text == null) { - return Component.empty(); - } - if (CFConfig.legacyColorSupport) { - return MiniMessage.miniMessage().deserialize(legacyToMiniMessage(text)); - } else { - return MiniMessage.miniMessage().deserialize(text); - } - } - - @Override - public void sendMessage(CommandSender sender, String s) { - if (s == null) return; - if (sender instanceof Player player) sendPlayerMessage(player, s); - else if (sender instanceof ConsoleCommandSender) sendConsoleMessage(s); - } - - @Override - public void sendMessageWithPrefix(CommandSender sender, String s) { - if (s == null) return; - if (sender instanceof Player player) sendPlayerMessage(player, CFLocale.MSG_Prefix + s); - else if (sender instanceof ConsoleCommandSender) sendConsoleMessage(CFLocale.MSG_Prefix + s); - } - - @Override - public void sendConsoleMessage(String s) { - if (s == null) return; - Audience au = adventure.sender(Bukkit.getConsoleSender()); - au.sendMessage(getComponentFromMiniMessage(s)); - } - - @Override - public void sendPlayerMessage(Player player, String s) { - if (s == null) return; - Audience au = adventure.player(player); - au.sendMessage(getComponentFromMiniMessage(s)); - } - - @Override - public void sendTitle(Player player, String title, String subtitle, int in, int duration, int out) { - sendTitle(player, getComponentFromMiniMessage(title), getComponentFromMiniMessage(subtitle), in, duration, out); - } - - @Override - public void sendTitle(Player player, Component title, Component subtitle, int in, int duration, int out) { - try { - PacketContainer titlePacket = new PacketContainer(PacketType.Play.Server.SET_TITLE_TEXT); - titlePacket.getModifier().write(0, getIChatComponent(componentToJson(title))); - PacketContainer subTitlePacket = new PacketContainer(PacketType.Play.Server.SET_SUBTITLE_TEXT); - subTitlePacket.getModifier().write(0, getIChatComponent(componentToJson(subtitle))); - PacketContainer timePacket = new PacketContainer(PacketType.Play.Server.SET_TITLES_ANIMATION); - timePacket.getIntegers().write(0, in); - timePacket.getIntegers().write(1, duration); - timePacket.getIntegers().write(2, out); - CustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, titlePacket); - CustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, subTitlePacket); - CustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, timePacket); - } catch (InvocationTargetException | IllegalAccessException e) { - LogUtils.warn("Error occurred when sending title"); - } - } - - @Override - public void sendActionbar(Player player, String s) { - try { - PacketContainer packet = new PacketContainer(PacketType.Play.Server.SET_ACTION_BAR_TEXT); - packet.getModifier().write(0, getIChatComponent(componentToJson(getComponentFromMiniMessage(s)))); - CustomFishingPluginImpl.getProtocolManager().sendServerPacket(player, packet); - } catch (InvocationTargetException | IllegalAccessException e) { - LogUtils.warn("Error occurred when sending actionbar"); - } - } - - @Override - public void sendSound(Player player, Sound.Source source, Key key, float volume, float pitch) { - Sound sound = Sound.sound(key, source, volume, pitch); - Audience au = adventure.player(player); - au.playSound(sound); - } - - @Override - public void sendSound(Player player, Sound sound) { - Audience au = adventure.player(player); - au.playSound(sound); - } - - @Override - public String legacyToMiniMessage(String legacy) { - StringBuilder stringBuilder = new StringBuilder(); - char[] chars = legacy.toCharArray(); - for (int i = 0; i < chars.length; i++) { - if (!isColorCode(chars[i])) { - stringBuilder.append(chars[i]); - continue; - } - if (i + 1 >= chars.length) { - stringBuilder.append(chars[i]); - continue; - } - switch (chars[i+1]) { - case '0' -> stringBuilder.append(""); - case '1' -> stringBuilder.append(""); - case '2' -> stringBuilder.append(""); - case '3' -> stringBuilder.append(""); - case '4' -> stringBuilder.append(""); - case '5' -> stringBuilder.append(""); - case '6' -> stringBuilder.append(""); - case '7' -> stringBuilder.append(""); - case '8' -> stringBuilder.append(""); - case '9' -> stringBuilder.append(""); - case 'a' -> stringBuilder.append(""); - case 'b' -> stringBuilder.append(""); - case 'c' -> stringBuilder.append(""); - case 'd' -> stringBuilder.append(""); - case 'e' -> stringBuilder.append(""); - case 'f' -> stringBuilder.append(""); - case 'r' -> stringBuilder.append(""); - case 'l' -> stringBuilder.append(""); - case 'm' -> stringBuilder.append(""); - case 'o' -> stringBuilder.append(""); - case 'n' -> stringBuilder.append(""); - case 'k' -> stringBuilder.append(""); - case 'x' -> { - if (i + 13 >= chars.length - || !isColorCode(chars[i+2]) - || !isColorCode(chars[i+4]) - || !isColorCode(chars[i+6]) - || !isColorCode(chars[i+8]) - || !isColorCode(chars[i+10]) - || !isColorCode(chars[i+12])) { - stringBuilder.append(chars[i]); - continue; - } - stringBuilder - .append("<#") - .append(chars[i+3]) - .append(chars[i+5]) - .append(chars[i+7]) - .append(chars[i+9]) - .append(chars[i+11]) - .append(chars[i+13]) - .append(">"); - i += 12; - } - default -> { - stringBuilder.append(chars[i]); - continue; - } - } - i++; - } - return stringBuilder.toString(); - } - - @Override - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean isColorCode(char c) { - return c == '§' || c == '&'; - } - - @Override - public String componentToLegacy(Component component) { - return LegacyComponentSerializer.legacySection().serialize(component); - } - - @Override - public String componentToJson(Component component) { - return GsonComponentSerializer.gson().serialize(component); - } - - @Override - public Object shadedComponentToOriginalComponent(Component component) { - Object cp; - try { - cp = ReflectionUtils.gsonDeserializeMethod.invoke(ReflectionUtils.gsonInstance, GsonComponentSerializer.gson().serialize(component)); - } catch (InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - return null; - } - return cp; - } - - public Object getIChatComponent(String json) throws InvocationTargetException, IllegalAccessException { - return ReflectionUtils.iChatComponentMethod.invoke(null, json); - } -} diff --git a/plugin/src/main/java/net/momirealms/customfishing/command/CommandManagerImpl.java b/plugin/src/main/java/net/momirealms/customfishing/command/CommandManagerImpl.java deleted file mode 100644 index 7bbe1497..00000000 --- a/plugin/src/main/java/net/momirealms/customfishing/command/CommandManagerImpl.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.command; - -import dev.jorel.commandapi.CommandAPI; -import dev.jorel.commandapi.CommandAPIBukkitConfig; -import dev.jorel.commandapi.CommandAPICommand; -import dev.jorel.commandapi.arguments.EntitySelectorArgument; -import dev.jorel.commandapi.arguments.StringArgument; -import dev.jorel.commandapi.arguments.UUIDArgument; -import net.momirealms.customfishing.CustomFishingPluginImpl; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.manager.CommandManager; -import net.momirealms.customfishing.api.util.LogUtils; -import net.momirealms.customfishing.command.sub.*; -import net.momirealms.customfishing.setting.CFLocale; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; - -import java.util.Collection; -import java.util.UUID; - -public class CommandManagerImpl implements CommandManager { - - private final CustomFishingPlugin plugin; - - public CommandManagerImpl(CustomFishingPluginImpl plugin) { - this.plugin = plugin; - } - - @Override - public void load() { - if (!CommandAPI.isLoaded()) - CommandAPI.onLoad(new CommandAPIBukkitConfig(plugin).silentLogs(true)); - new CommandAPICommand("customfishing") - .withAliases("cfishing") - .withPermission("customfishing.admin") - .withSubcommands( - getReloadCommand(), - getOpenCommand(), - getAboutCommand(), - GUIEditorCommand.INSTANCE.getEditorCommand(), - DataCommand.INSTANCE.getDataCommand(), - CompetitionCommand.INSTANCE.getCompetitionCommand(), - ItemCommand.INSTANCE.getItemCommand(), - DebugCommand.INSTANCE.getDebugCommand(), - StatisticsCommand.INSTANCE.getStatisticsCommand() - ) - .register(); - if (plugin.getMarketManager().isEnable()) { - new CommandAPICommand("sellfish") - .withPermission("customfishing.sellfish") - .executesPlayer((player, args) -> { - if (plugin.getMarketManager().isEnable()) - plugin.getMarketManager().openMarketGUI(player); - }) - .register(); - } - if (plugin.getBagManager().isEnabled()) { - FishingBagCommand.INSTANCE.getBagCommand().register(); - } - } - - @Override - public void unload() { - } - - private CommandAPICommand getReloadCommand() { - return new CommandAPICommand("reload") - .executes((sender, args) -> { - long time = System.currentTimeMillis(); - plugin.reload(); - AdventureHelper.getInstance().sendMessageWithPrefix(sender, CFLocale.MSG_Reload.replace("{time}", String.valueOf(System.currentTimeMillis()-time))); - }); - } - - @SuppressWarnings("unchecked") - private CommandAPICommand getOpenCommand() { - CommandAPICommand command = new CommandAPICommand("open"); - if (plugin.getMarketManager().isEnable()) { - command.withSubcommands( - new CommandAPICommand("market") - .withArguments(new EntitySelectorArgument.ManyPlayers("player")) - .withOptionalArguments(new StringArgument("-s")) - .executes((sender, args) -> { - Collection players = (Collection) args.get("player"); - assert players != null; - boolean silence = args.getOrDefault("-s","").equals("-s"); - for (Player player : players) { - plugin.getMarketManager().openMarketGUI(player); - if (!silence) AdventureHelper.getInstance().sendMessageWithPrefix(sender, CFLocale.MSG_Market_GUI_Open.replace("{player}", player.getName())); - } - }), - new CommandAPICommand("market-uuid") - .withArguments(new UUIDArgument("uuid")) - .withOptionalArguments(new StringArgument("-s")) - .executes((sender, args) -> { - UUID uuid = (UUID) args.get("uuid"); - Player player = Bukkit.getPlayer(uuid); - boolean silence = args.getOrDefault("-s","").equals("-s"); - if (player == null) return; - plugin.getMarketManager().openMarketGUI(player); - if (!silence) AdventureHelper.getInstance().sendMessageWithPrefix(sender, CFLocale.MSG_Market_GUI_Open.replace("{player}", player.getName())); - }) - ); - } - if (plugin.getBagManager().isEnabled()) { - command.withSubcommands( - new CommandAPICommand("bag") - .withArguments(new EntitySelectorArgument.ManyPlayers("player")) - .withOptionalArguments(new StringArgument("-s")) - .executes((sender, args) -> { - Collection players = (Collection) args.get("player"); - assert players != null; - boolean silence = args.getOrDefault("-s","").equals("-s"); - for (Player player : players) { - Inventory inventory = plugin.getBagManager().getOnlineBagInventory(player.getUniqueId()); - if (inventory != null) { - player.openInventory(inventory); - if (!silence) AdventureHelper.getInstance().sendMessageWithPrefix(sender, CFLocale.MSG_Fishing_Bag_Open.replace("{player}", player.getName())); - } else { - LogUtils.warn("Player " + player.getName() + "'s bag data has not been loaded."); - } - } - }), - new CommandAPICommand("bag-uuid") - .withArguments(new UUIDArgument("uuid")) - .withOptionalArguments(new StringArgument("-s")) - .executes((sender, args) -> { - UUID uuid = (UUID) args.get("uuid"); - Player player = Bukkit.getPlayer(uuid); - boolean silence = args.getOrDefault("-s","").equals("-s"); - if (player == null) return; - Inventory inventory = plugin.getBagManager().getOnlineBagInventory(uuid); - if (inventory != null) { - player.openInventory(inventory); - if (!silence) AdventureHelper.getInstance().sendMessageWithPrefix(sender, CFLocale.MSG_Fishing_Bag_Open.replace("{player}", player.getName())); - } else { - LogUtils.warn("Player " + player.getName() + "'s bag data has not been loaded."); - } - }) - ); - } - return command; - } - - private CommandAPICommand getAboutCommand() { - return new CommandAPICommand("about").executes((sender, args) -> { - AdventureHelper.getInstance().sendMessage(sender, "<#00BFFF>\uD83C\uDFA3 CustomFishing - <#87CEEB>" + CustomFishingPlugin.getInstance().getVersionManager().getPluginVersion()); - AdventureHelper.getInstance().sendMessage(sender, "<#B0C4DE>A fishing plugin that provides innovative mechanics and powerful loot system"); - AdventureHelper.getInstance().sendMessage(sender, "<#DA70D6>\uD83E\uDDEA Author: <#FFC0CB>XiaoMoMi"); - AdventureHelper.getInstance().sendMessage(sender, "<#FF7F50>\uD83D\uDD25 Contributors: <#FFA07A>0ft3n, <#FFA07A>Peng_Lx, <#FFA07A>Masaki, <#FFA07A>g2213swo"); - AdventureHelper.getInstance().sendMessage(sender, "<#FFD700>⭐ Document <#A9A9A9>| <#FAFAD2>⛏ Github <#A9A9A9>| <#48D1CC>\uD83D\uDD14 Polymart"); - }); - } -} diff --git a/plugin/src/main/java/net/momirealms/customfishing/command/sub/CompetitionCommand.java b/plugin/src/main/java/net/momirealms/customfishing/command/sub/CompetitionCommand.java deleted file mode 100644 index 38bb4fac..00000000 --- a/plugin/src/main/java/net/momirealms/customfishing/command/sub/CompetitionCommand.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.command.sub; - -import dev.jorel.commandapi.CommandAPICommand; -import dev.jorel.commandapi.arguments.ArgumentSuggestions; -import dev.jorel.commandapi.arguments.StringArgument; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.mechanic.competition.FishingCompetition; -import net.momirealms.customfishing.setting.CFConfig; -import net.momirealms.customfishing.setting.CFLocale; -import net.momirealms.customfishing.storage.method.database.nosql.RedisManager; - -import java.util.Set; - -public class CompetitionCommand { - - public static CompetitionCommand INSTANCE = new CompetitionCommand(); - - public CommandAPICommand getCompetitionCommand() { - return new CommandAPICommand("competition") - .withSubcommands( - getCompetitionStartCommand(), - getCompetitionEndCommand(), - getCompetitionStopCommand() - ); - } - - private CommandAPICommand getCompetitionStartCommand() { - Set allCompetitions = CustomFishingPlugin.get().getCompetitionManager().getAllCompetitionKeys(); - var command = new CommandAPICommand("start") - .withArguments( - new StringArgument("id") - .replaceSuggestions( - ArgumentSuggestions.strings(allCompetitions) - ) - ); - if (CFConfig.redisRanking) command.withOptionalArguments(new StringArgument("server-group")); - command.executes((sender, args) -> { - String id = (String) args.get(0); - assert id != null; - if (!allCompetitions.contains(id)) { - AdventureHelper.getInstance().sendMessageWithPrefix(sender, CFLocale.MSG_Competition_Not_Exist.replace("{id}", id)); - return; - } - Object server = args.get("server-group"); - if (server != null) { - CustomFishingPlugin.get().getCompetitionManager().startCompetition(id, true, (String) server); - } else { - CustomFishingPlugin.get().getCompetitionManager().startCompetition(id, true, null); - } - }); - return command; - } - - private CommandAPICommand getCompetitionEndCommand() { - var command = new CommandAPICommand("end"); - if (CFConfig.redisRanking) command.withOptionalArguments(new StringArgument("server-group")); - command.executes((sender, args) -> { - Object server = args.get("server-group"); - if (server != null) { - RedisManager.getInstance().publishRedisMessage((String) server, "end"); - } else { - FishingCompetition competition = CustomFishingPlugin.get().getCompetitionManager().getOnGoingCompetition(); - if (competition != null) { - CustomFishingPlugin.get().getScheduler().runTaskAsync(() -> competition.end(true)); - AdventureHelper.getInstance().sendMessageWithPrefix(sender, CFLocale.MSG_End_Competition); - } else { - AdventureHelper.getInstance().sendMessageWithPrefix(sender, CFLocale.MSG_No_Competition_Ongoing); - } - } - }); - return command; - } - - private CommandAPICommand getCompetitionStopCommand() { - var command = new CommandAPICommand("stop"); - if (CFConfig.redisRanking) command.withOptionalArguments(new StringArgument("server-group")); - command.executes((sender, args) -> { - Object server = args.get("server-group"); - if (server != null) { - RedisManager.getInstance().publishRedisMessage((String) server, "stop"); - } else { - FishingCompetition competition = CustomFishingPlugin.get().getCompetitionManager().getOnGoingCompetition(); - if (competition != null) { - CustomFishingPlugin.get().getScheduler().runTaskAsync(() -> { - competition.stop(true); - }); - AdventureHelper.getInstance().sendMessageWithPrefix(sender, CFLocale.MSG_Stop_Competition); - } else { - AdventureHelper.getInstance().sendMessageWithPrefix(sender, CFLocale.MSG_No_Competition_Ongoing); - } - } - }); - return command; - } -} diff --git a/plugin/src/main/java/net/momirealms/customfishing/command/sub/DataCommand.java b/plugin/src/main/java/net/momirealms/customfishing/command/sub/DataCommand.java deleted file mode 100644 index d2bfd6cc..00000000 --- a/plugin/src/main/java/net/momirealms/customfishing/command/sub/DataCommand.java +++ /dev/null @@ -1,284 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.command.sub; - -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import dev.jorel.commandapi.CommandAPICommand; -import dev.jorel.commandapi.arguments.ArgumentSuggestions; -import dev.jorel.commandapi.arguments.StringArgument; -import dev.jorel.commandapi.arguments.UUIDArgument; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.data.DataStorageInterface; -import net.momirealms.customfishing.api.data.LegacyDataStorageInterface; -import net.momirealms.customfishing.api.data.PlayerData; -import net.momirealms.customfishing.api.util.LogUtils; -import net.momirealms.customfishing.storage.method.database.sql.MariaDBImpl; -import net.momirealms.customfishing.storage.method.database.sql.MySQLImpl; -import net.momirealms.customfishing.storage.method.file.YAMLImpl; -import net.momirealms.customfishing.util.CompletableFutures; -import org.bukkit.Bukkit; - -import java.io.*; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - -public class DataCommand { - - public static DataCommand INSTANCE = new DataCommand(); - - public CommandAPICommand getDataCommand() { - return new CommandAPICommand("data") - .withSubcommands( - getExportLegacyCommand(), - getExportCommand(), - getImportCommand(), - getUnlockCommand() - ); - } - - private CommandAPICommand getUnlockCommand() { - return new CommandAPICommand("unlock") - .withArguments(new UUIDArgument("uuid")) - .executes((sender, args) -> { - UUID uuid = (UUID) args.get("uuid"); - CustomFishingPlugin.get().getStorageManager().getDataSource().lockOrUnlockPlayerData(uuid, false); - AdventureHelper.getInstance().sendMessageWithPrefix(sender, "Successfully unlocked."); - }); - } - - @SuppressWarnings("DuplicatedCode") - private CommandAPICommand getExportLegacyCommand() { - return new CommandAPICommand("export-legacy") - .withArguments(new StringArgument("method") - .replaceSuggestions(ArgumentSuggestions.strings("MySQL", "MariaDB", "YAML"))) - .executes((sender, args) -> { - String arg = (String) args.get("method"); - if (arg == null) return; - CustomFishingPlugin plugin = CustomFishingPlugin.get(); - plugin.getScheduler().runTaskAsync(() -> { - - AdventureHelper.getInstance().sendMessageWithPrefix(sender, "Starting export."); - - LegacyDataStorageInterface dataStorageInterface; - switch (arg) { - case "MySQL" -> dataStorageInterface = new MySQLImpl(plugin); - case "MariaDB" -> dataStorageInterface = new MariaDBImpl(plugin); - case "YAML" -> dataStorageInterface = new YAMLImpl(plugin); - default -> { - AdventureHelper.getInstance().sendMessageWithPrefix(sender, "No such legacy storage method."); - return; - } - } - - dataStorageInterface.initialize(); - Set uuids = dataStorageInterface.getUniqueUsers(true); - Set> futures = new HashSet<>(); - AtomicInteger userCount = new AtomicInteger(0); - Map out = Collections.synchronizedMap(new TreeMap<>()); - - for (UUID uuid : uuids) { - futures.add(dataStorageInterface.getLegacyPlayerData(uuid).thenAccept(it -> { - if (it.isPresent()) { - out.put(uuid, plugin.getStorageManager().toJson(it.get())); - userCount.incrementAndGet(); - } - })); - } - - CompletableFuture overallFuture = CompletableFutures.allOf(futures); - - while (true) { - try { - overallFuture.get(3, TimeUnit.SECONDS); - } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); - break; - } catch (TimeoutException e) { - LogUtils.info("Progress: " + userCount.get() + "/" + uuids.size()); - continue; - } - break; - } - - JsonObject outJson = new JsonObject(); - for (Map.Entry entry : out.entrySet()) { - outJson.addProperty(entry.getKey().toString(), entry.getValue()); - } - SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm"); - String formattedDate = formatter.format(new Date()); - File outFile = new File(plugin.getDataFolder(), "exported-" + formattedDate + ".json.gz"); - try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream(Files.newOutputStream(outFile.toPath())), StandardCharsets.UTF_8))) { - new GsonBuilder().disableHtmlEscaping().create().toJson(outJson, writer); - } catch (IOException e) { - e.printStackTrace(); - } - - dataStorageInterface.disable(); - - AdventureHelper.getInstance().sendMessageWithPrefix(sender, "Completed."); - }); - }); - } - - @SuppressWarnings("DuplicatedCode") - private CommandAPICommand getExportCommand() { - return new CommandAPICommand("export") - .executesConsole((sender, args) -> { - if (Bukkit.getOnlinePlayers().size() != 0) { - AdventureHelper.getInstance().sendMessageWithPrefix(sender, "Please kick all the players before exporting. Otherwise the cache will be inconsistent with data, resulting in the backup file not being up to date."); - return; - } - - CustomFishingPlugin plugin = CustomFishingPlugin.get(); - plugin.getScheduler().runTaskAsync(() -> { - - AdventureHelper.getInstance().sendMessageWithPrefix(sender, "Starting export."); - DataStorageInterface dataStorageInterface = plugin.getStorageManager().getDataSource(); - - Set uuids = dataStorageInterface.getUniqueUsers(false); - Set> futures = new HashSet<>(); - AtomicInteger userCount = new AtomicInteger(0); - Map out = Collections.synchronizedMap(new TreeMap<>()); - - int amount = uuids.size(); - for (UUID uuid : uuids) { - futures.add(dataStorageInterface.getPlayerData(uuid, false).thenAccept(it -> { - if (it.isPresent()) { - out.put(uuid, plugin.getStorageManager().toJson(it.get())); - userCount.incrementAndGet(); - } - })); - } - - CompletableFuture overallFuture = CompletableFutures.allOf(futures); - - while (true) { - try { - overallFuture.get(3, TimeUnit.SECONDS); - } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); - break; - } catch (TimeoutException e) { - LogUtils.info("Progress: " + userCount.get() + "/" + amount); - continue; - } - break; - } - - JsonObject outJson = new JsonObject(); - for (Map.Entry entry : out.entrySet()) { - outJson.addProperty(entry.getKey().toString(), entry.getValue()); - } - SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm"); - String formattedDate = formatter.format(new Date()); - File outFile = new File(plugin.getDataFolder(), "exported-" + formattedDate + ".json.gz"); - try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream(Files.newOutputStream(outFile.toPath())), StandardCharsets.UTF_8))) { - new GsonBuilder().disableHtmlEscaping().create().toJson(outJson, writer); - } catch (IOException e) { - e.printStackTrace(); - } - - AdventureHelper.getInstance().sendMessageWithPrefix(sender, "Completed."); - }); - }); - } - - @SuppressWarnings("DuplicatedCode") - private CommandAPICommand getImportCommand() { - return new CommandAPICommand("import") - .withArguments(new StringArgument("file")) - .executesConsole((sender, args) -> { - if (Bukkit.getOnlinePlayers().size() != 0) { - AdventureHelper.getInstance().sendMessageWithPrefix(sender, "Please kick all the players before importing. Otherwise the cache will be inconsistent with data."); - return; - } - - String fileName = (String) args.get("file"); - if (fileName == null) return; - CustomFishingPlugin plugin = CustomFishingPlugin.get(); - - File file = new File(plugin.getDataFolder(), fileName); - if (!file.exists()) { - AdventureHelper.getInstance().sendMessageWithPrefix(sender, "File not exists."); - return; - } - if (!file.getName().endsWith(".json.gz")) { - AdventureHelper.getInstance().sendMessageWithPrefix(sender, "Invalid file."); - return; - } - - plugin.getScheduler().runTaskAsync(() -> { - - AdventureHelper.getInstance().sendMessageWithPrefix(sender, "Starting import."); - - JsonObject data; - try (BufferedReader reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(Files.newInputStream(file.toPath())), StandardCharsets.UTF_8))) { - data = new GsonBuilder().disableHtmlEscaping().create().fromJson(reader, JsonObject.class); - } catch (IOException e) { - AdventureHelper.getInstance().sendMessageWithPrefix(sender, "Error occurred when reading the backup file."); - e.printStackTrace(); - return; - } - - DataStorageInterface dataStorageInterface = plugin.getStorageManager().getDataSource(); - var entrySet = data.entrySet(); - int amount = entrySet.size(); - AtomicInteger userCount = new AtomicInteger(0); - Set> futures = new HashSet<>(); - - for (Map.Entry entry : entrySet) { - UUID uuid = UUID.fromString(entry.getKey()); - if (entry.getValue() instanceof JsonPrimitive primitive) { - PlayerData playerData = plugin.getStorageManager().fromJson(primitive.getAsString()); - futures.add(dataStorageInterface.updateOrInsertPlayerData(uuid, playerData, true).thenAccept(it -> userCount.incrementAndGet())); - } - } - - CompletableFuture overallFuture = CompletableFutures.allOf(futures); - - while (true) { - try { - overallFuture.get(3, TimeUnit.SECONDS); - } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); - break; - } catch (TimeoutException e) { - LogUtils.info("Progress: " + userCount.get() + "/" + amount); - continue; - } - break; - } - - AdventureHelper.getInstance().sendMessageWithPrefix(sender, "Completed."); - }); - }); - } -} diff --git a/plugin/src/main/java/net/momirealms/customfishing/command/sub/DebugCommand.java b/plugin/src/main/java/net/momirealms/customfishing/command/sub/DebugCommand.java deleted file mode 100644 index 29782ad2..00000000 --- a/plugin/src/main/java/net/momirealms/customfishing/command/sub/DebugCommand.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.command.sub; - -import de.tr7zw.changeme.nbtapi.NBTItem; -import dev.jorel.commandapi.CommandAPICommand; -import dev.jorel.commandapi.IStringTooltip; -import dev.jorel.commandapi.StringTooltip; -import dev.jorel.commandapi.arguments.ArgumentSuggestions; -import dev.jorel.commandapi.arguments.BooleanArgument; -import dev.jorel.commandapi.arguments.StringArgument; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.integration.SeasonInterface; -import net.momirealms.customfishing.api.manager.AdventureManager; -import net.momirealms.customfishing.api.mechanic.condition.FishingPreparation; -import net.momirealms.customfishing.api.mechanic.effect.EffectCarrier; -import net.momirealms.customfishing.api.mechanic.effect.EffectModifier; -import net.momirealms.customfishing.api.mechanic.effect.FishingEffect; -import net.momirealms.customfishing.mechanic.fishing.FishingPreparationImpl; -import net.momirealms.customfishing.util.ConfigUtils; -import net.momirealms.customfishing.util.NBTUtils; -import net.momirealms.sparrow.heart.SparrowHeart; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.StringJoiner; - -public class DebugCommand { - - public static DebugCommand INSTANCE = new DebugCommand(); - - public CommandAPICommand getDebugCommand() { - return new CommandAPICommand("debug") - .withSubcommands( - getLootChanceCommand(), - getBiomeCommand(), - getSeasonCommand(), - getGroupCommand(), - getCategoryCommand(), - getNBTCommand(), - getLocationCommand() - ); - } - - public CommandAPICommand getBiomeCommand() { - return new CommandAPICommand("biome") - .executesPlayer((player, arg) -> { - AdventureHelper.getInstance().sendMessage(player, SparrowHeart.getInstance().getBiomeResourceLocation(player.getLocation())); - }); - } - - public CommandAPICommand getLocationCommand() { - return new CommandAPICommand("location") - .executesPlayer((player, arg) -> { - AdventureHelper.getInstance().sendMessage(player, player.getLocation().toString()); - }); - } - - public CommandAPICommand getNBTCommand() { - return new CommandAPICommand("nbt") - .executesPlayer((player, arg) -> { - ItemStack item = player.getInventory().getItemInMainHand(); - if (item.getType() == Material.AIR) - return; - ArrayList list = new ArrayList<>(); - ConfigUtils.mapToReadableStringList(NBTUtils.compoundToMap(new NBTItem(item)), list, 0, false); - for (String line : list) { - AdventureHelper.getInstance().sendMessage(player, line); - } - }); - } - - public CommandAPICommand getSeasonCommand() { - return new CommandAPICommand("season") - .executesPlayer((player, arg) -> { - SeasonInterface seasonInterface = CustomFishingPlugin.get().getIntegrationManager().getSeasonInterface(); - if (seasonInterface == null) { - AdventureHelper.getInstance().sendMessageWithPrefix(player, "NO SEASON PLUGIN"); - return; - } - AdventureHelper.getInstance().sendMessage(player, seasonInterface.getSeason(player.getLocation().getWorld())); - }); - } - - public CommandAPICommand getGroupCommand() { - return new CommandAPICommand("group") - .withArguments(new StringArgument("group")) - .executes((sender, arg) -> { - String group = (String) arg.get("group"); - StringJoiner stringJoiner = new StringJoiner(", "); - List groups = CustomFishingPlugin.get().getLootManager().getLootGroup(group); - if (groups != null) - for (String key : groups) { - stringJoiner.add(key); - } - AdventureHelper.getInstance().sendMessageWithPrefix(sender, "Group{" + group + "}[" + stringJoiner + "]"); - }); - } - - public CommandAPICommand getCategoryCommand() { - return new CommandAPICommand("category") - .withArguments(new StringArgument("category")) - .executes((sender, arg) -> { - String c = (String) arg.get("category"); - StringJoiner stringJoiner = new StringJoiner(", "); - List cs = CustomFishingPlugin.get().getStatisticsManager().getCategory(c); - if (cs != null) - for (String key : cs) { - stringJoiner.add(key); - } - AdventureHelper.getInstance().sendMessageWithPrefix(sender, "Category{" + c + "}[" + stringJoiner + "]"); - }); - } - - public CommandAPICommand getLootChanceCommand() { - return new CommandAPICommand("loot-chance") - .withArguments(new BooleanArgument("lava fishing").replaceSuggestions(ArgumentSuggestions.stringsWithTooltips(info -> - new IStringTooltip[] { - StringTooltip.ofString("true", "loots in lava"), - StringTooltip.ofString("false", "loots in water") - }))) - .executesPlayer((player, arg) -> { - if (player.getInventory().getItemInMainHand().getType() != Material.FISHING_ROD) { - AdventureHelper.getInstance().sendMessageWithPrefix(player, "Please hold a fishing rod before using this command."); - return; - } - FishingEffect initialEffect = CustomFishingPlugin.get().getEffectManager().getInitialEffect(); - FishingPreparation fishingPreparation = new FishingPreparationImpl(player, CustomFishingPlugin.get()); - boolean inLava = (boolean) arg.getOrDefault("lava fishing", false); - fishingPreparation.insertArg("{lava}", String.valueOf(inLava)); - fishingPreparation.mergeEffect(initialEffect); - EffectCarrier totemEffect = CustomFishingPlugin.get().getTotemManager().getTotemEffect(player.getLocation()); - if (totemEffect != null) - for (EffectModifier modifier : totemEffect.getEffectModifiers()) { - modifier.modify(initialEffect, fishingPreparation); - } - var map = CustomFishingPlugin.get().getLootManager().getPossibleLootKeysWithWeight(initialEffect, fishingPreparation); - List loots = new ArrayList<>(); - double sum = 0; - for (Map.Entry entry : map.entrySet()) { - double weight = entry.getValue(); - String loot = entry.getKey(); - if (weight <= 0) continue; - loots.add(new LootWithWeight(loot, weight)); - sum += weight; - } - LootWithWeight[] lootArray = loots.toArray(new LootWithWeight[0]); - quickSort(lootArray, 0,lootArray.length - 1); - AdventureManager adventureManager = AdventureHelper.getInstance(); - adventureManager.sendMessage(player, "---------- results ---------"); - for (LootWithWeight loot : lootArray) { - adventureManager.sendMessage(player, loot.key() + ": " + String.format("%.2f", loot.weight()*100/sum) + "% (" + String.format("%.2f", loot.weight()) + ")"); - } - adventureManager.sendMessage(player, "----------- end -----------"); - }); - } - - public record LootWithWeight(String key, double weight) { - } - - private static void quickSort(LootWithWeight[] loot, int low, int high) { - if (low < high) { - int pi = partition(loot, low, high); - quickSort(loot, low, pi - 1); - quickSort(loot, pi + 1, high); - } - } - - private static int partition(LootWithWeight[] loot, int low, int high) { - double pivot = loot[high].weight(); - int i = low - 1; - for (int j = low; j <= high - 1; j++) { - if (loot[j].weight() > pivot) { - i++; - swap(loot, i, j); - } - } - swap(loot, i + 1, high); - return i + 1; - } - - private static void swap(LootWithWeight[] loot, int i, int j) { - LootWithWeight temp = loot[i]; - loot[i] = loot[j]; - loot[j] = temp; - } -} diff --git a/plugin/src/main/java/net/momirealms/customfishing/command/sub/FishingBagCommand.java b/plugin/src/main/java/net/momirealms/customfishing/command/sub/FishingBagCommand.java deleted file mode 100644 index b147f3f5..00000000 --- a/plugin/src/main/java/net/momirealms/customfishing/command/sub/FishingBagCommand.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.command.sub; - -import dev.jorel.commandapi.CommandAPICommand; -import dev.jorel.commandapi.arguments.PlayerArgument; -import dev.jorel.commandapi.arguments.UUIDArgument; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.data.user.OfflineUser; -import net.momirealms.customfishing.setting.CFConfig; -import net.momirealms.customfishing.setting.CFLocale; -import net.momirealms.customfishing.storage.user.OfflineUserImpl; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; - -import java.util.UUID; - -public class FishingBagCommand { - - public static FishingBagCommand INSTANCE = new FishingBagCommand(); - - public CommandAPICommand getBagCommand() { - return new CommandAPICommand("fishingbag") - .withPermission("fishingbag.user") - .withSubcommands(getEditOnlineCommand(), getEditOfflineCommand()) - .executesPlayer(((player, args) -> { - if (CustomFishingPlugin.get().getBagManager().isEnabled()) { - var inv = CustomFishingPlugin.get().getBagManager().getOnlineBagInventory(player.getUniqueId()); - if (inv != null) { - player.openInventory(inv); - } else { - AdventureHelper.getInstance().sendMessageWithPrefix(player, CFLocale.MSG_Data_Not_Loaded); - } - } - })); - } - - private CommandAPICommand getEditOnlineCommand() { - return new CommandAPICommand("edit-online") - .withPermission("fishingbag.admin") - .withArguments(new PlayerArgument("player")) - .executesPlayer(((player, args) -> { - Player player1 = (Player) args.get("player"); - UUID uuid = player1.getUniqueId(); - Inventory onlineInv = CustomFishingPlugin.get().getBagManager().getOnlineBagInventory(uuid); - if (onlineInv != null) { - player.openInventory(onlineInv); - } - })); - } - - private CommandAPICommand getEditOfflineCommand() { - return new CommandAPICommand("edit-offline") - .withPermission("fishingbag.admin") - .withArguments(new UUIDArgument("UUID")) - .executesPlayer(((player, args) -> { - UUID uuid = (UUID) args.get("UUID"); - Player online = Bukkit.getPlayer(uuid); - if (online != null) { - Inventory onlineInv = CustomFishingPlugin.get().getBagManager().getOnlineBagInventory(uuid); - if (onlineInv != null) { - player.openInventory(onlineInv); - return; - } - } - CustomFishingPlugin.get().getStorageManager().getOfflineUser(uuid, CFConfig.lockData).thenAccept(optional -> { - if (optional.isEmpty()) { - AdventureHelper.getInstance().sendMessageWithPrefix(player, CFLocale.MSG_Never_Played); - return; - } - OfflineUser offlineUser = optional.get(); - if (offlineUser == OfflineUserImpl.LOCKED_USER) { - AdventureHelper.getInstance().sendMessageWithPrefix(player, CFLocale.MSG_Unsafe_Modification); - return; - } - CustomFishingPlugin.get().getScheduler().runTaskSync(() -> { - CustomFishingPlugin.get().getBagManager().editOfflinePlayerBag(player, offlineUser); - }, player.getLocation()); - }); - })); - } -} diff --git a/plugin/src/main/java/net/momirealms/customfishing/command/sub/GUIEditorCommand.java b/plugin/src/main/java/net/momirealms/customfishing/command/sub/GUIEditorCommand.java deleted file mode 100644 index 874d9b6d..00000000 --- a/plugin/src/main/java/net/momirealms/customfishing/command/sub/GUIEditorCommand.java +++ /dev/null @@ -1,19 +0,0 @@ -package net.momirealms.customfishing.command.sub; - -import dev.jorel.commandapi.CommandAPICommand; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.gui.page.file.FileSelector; - -import java.io.File; - -public class GUIEditorCommand { - - public static GUIEditorCommand INSTANCE = new GUIEditorCommand(); - - public CommandAPICommand getEditorCommand() { - return new CommandAPICommand("browser") - .executesPlayer((player, arg) -> { - new FileSelector(player, new File(CustomFishingPlugin.get().getDataFolder(), "contents")); - }); - } -} diff --git a/plugin/src/main/java/net/momirealms/customfishing/command/sub/ItemCommand.java b/plugin/src/main/java/net/momirealms/customfishing/command/sub/ItemCommand.java deleted file mode 100644 index 15eba24f..00000000 --- a/plugin/src/main/java/net/momirealms/customfishing/command/sub/ItemCommand.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.command.sub; - -import de.tr7zw.changeme.nbtapi.NBTItem; -import dev.jorel.commandapi.CommandAPICommand; -import dev.jorel.commandapi.arguments.ArgumentSuggestions; -import dev.jorel.commandapi.arguments.EntitySelectorArgument; -import dev.jorel.commandapi.arguments.IntegerArgument; -import dev.jorel.commandapi.arguments.StringArgument; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.common.Key; -import net.momirealms.customfishing.api.mechanic.condition.Condition; -import net.momirealms.customfishing.api.mechanic.item.BuildableItem; -import net.momirealms.customfishing.api.util.LogUtils; -import net.momirealms.customfishing.setting.CFLocale; -import net.momirealms.customfishing.util.ItemUtils; -import net.momirealms.customfishing.util.NBTUtils; -import org.bukkit.Material; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import java.io.File; -import java.io.IOException; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -public class ItemCommand { - - public static ItemCommand INSTANCE = new ItemCommand(); - - private final HashMap completionMap = new HashMap<>(); - - public CommandAPICommand getItemCommand() { - return new CommandAPICommand("items") - .withSubcommands( - getSubCommand("item"), - getSubCommand("util"), - getSubCommand("bait"), - getSubCommand("rod"), - getSubCommand("hook") - ); - } - - private CommandAPICommand getSubCommand(String namespace) { - completionMap.put(namespace, CustomFishingPlugin.get() - .getItemManager() - .getAllItemsKey() - .stream() - .filter(it -> it.namespace().equals(namespace)) - .map(Key::value) - .toList().toArray(new String[0])); - return new CommandAPICommand(namespace) - .withSubcommands( - getCommand(namespace), - giveCommand(namespace), - importCommand(namespace) - ); - } - - @SuppressWarnings("ResultOfMethodCallIgnored") - private CommandAPICommand importCommand(String namespace) { - return new CommandAPICommand("import") - .withArguments(new StringArgument("key")) - .withOptionalArguments(new StringArgument("file")) - .executesPlayer((player, args) -> { - String key = (String) args.get("key"); - String fileName = args.getOrDefault("file","import") + ".yml"; - ItemStack itemStack = player.getInventory().getItemInMainHand(); - if (itemStack.getType() == Material.AIR) - return; - File file = new File(CustomFishingPlugin.get().getDataFolder(), - "contents" + File.separator + namespace + File.separator + fileName); - try { - if (!file.exists()) { - file.createNewFile(); - } - YamlConfiguration config = YamlConfiguration.loadConfiguration(file); - config.set(key + ".material", itemStack.getType().toString()); - config.set(key + ".amount", itemStack.getAmount()); - Map nbtMap = NBTUtils.compoundToMap(new NBTItem(itemStack)); - if (nbtMap.size() != 0) { - config.createSection(key + ".nbt", nbtMap); - } - try { - config.save(file); - AdventureHelper.getInstance().sendMessageWithPrefix(player, "Imported! Saved to " + file.getAbsolutePath()); - } catch (IOException e) { - e.printStackTrace(); - } - } catch (IOException e) { - LogUtils.warn("Failed to create imported file.", e); - } - }); - } - - private CommandAPICommand getCommand(String namespace) { - return new CommandAPICommand("get") - .withArguments(new StringArgument("id") - .replaceSuggestions(ArgumentSuggestions.strings( - info -> completionMap.get(namespace) - ))) - .withOptionalArguments(new IntegerArgument("amount", 1)) - .executesPlayer((player, args) -> { - String id = (String) args.get("id"); - assert id != null; - int amount = (int) args.getOrDefault("amount", 1); - ItemStack item = CustomFishingPlugin.get().getItemManager().build(player, namespace, id, new Condition(player).getArgs()); - if (item != null) { - int actual = ItemUtils.giveItem(player, item, amount); - AdventureHelper.getInstance().sendMessageWithPrefix(player, CFLocale.MSG_Get_Item.replace("{item}", id).replace("{amount}", String.valueOf(actual))); - } else { - AdventureHelper.getInstance().sendMessageWithPrefix(player, CFLocale.MSG_Item_Not_Exists); - } - }); - } - - @SuppressWarnings("unchecked") - private CommandAPICommand giveCommand(String namespace) { - return new CommandAPICommand("give") - .withArguments(new EntitySelectorArgument.ManyPlayers("player")) - .withArguments(new StringArgument("id") - .replaceSuggestions(ArgumentSuggestions.strings( - info -> completionMap.get(namespace) - ))) - .withOptionalArguments(new IntegerArgument("amount", 1)) - .withOptionalArguments(new StringArgument("-s")) - .executes((sender, args) -> { - Collection players = (Collection) args.get("player"); - String id = (String) args.get("id"); - boolean silence = args.getOrDefault("-s", "").equals("-s"); - int amount = (int) args.getOrDefault("amount", 1); - BuildableItem buildableItem = CustomFishingPlugin.get().getItemManager().getBuildableItem(namespace, id); - if (buildableItem != null) { - assert players != null; - for (Player player : players) { - ItemStack item = CustomFishingPlugin.get().getItemManager().build(player, namespace, id, new Condition(player).getArgs()); - int actual = ItemUtils.giveItem(player, item, amount); - if (!silence) AdventureHelper.getInstance().sendMessageWithPrefix(sender, CFLocale.MSG_Give_Item.replace("{item}", id).replace("{amount}", String.valueOf(actual)).replace("{player}", player.getName())); - } - } else { - AdventureHelper.getInstance().sendMessageWithPrefix(sender, CFLocale.MSG_Item_Not_Exists); - } - }); - } -} diff --git a/plugin/src/main/java/net/momirealms/customfishing/command/sub/StatisticsCommand.java b/plugin/src/main/java/net/momirealms/customfishing/command/sub/StatisticsCommand.java deleted file mode 100644 index f8d78dfb..00000000 --- a/plugin/src/main/java/net/momirealms/customfishing/command/sub/StatisticsCommand.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.command.sub; - -import dev.jorel.commandapi.CommandAPICommand; -import dev.jorel.commandapi.arguments.*; -import net.momirealms.customfishing.adventure.AdventureHelper; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.mechanic.condition.Condition; -import net.momirealms.customfishing.api.mechanic.loot.Loot; -import net.momirealms.customfishing.api.mechanic.statistic.Statistics; -import net.momirealms.customfishing.api.util.LogUtils; -import org.bukkit.entity.Player; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Map; - -public class StatisticsCommand { - - public static StatisticsCommand INSTANCE = new StatisticsCommand(); - - private Collection loots = new HashSet<>(); - - public CommandAPICommand getStatisticsCommand() { - loots = CustomFishingPlugin.get().getLootManager().getAllLoots().stream().filter(it -> !it.disableStats()).map(Loot::getID).toList(); - return new CommandAPICommand("statistics") - .withSubcommands( - getSetCommand(), - getResetCommand(), - getQueryCommand(), - getAddCommand() - ); - } - - @SuppressWarnings("unchecked") - private CommandAPICommand getSetCommand() { - return new CommandAPICommand("set") - .withArguments(new EntitySelectorArgument.ManyPlayers("player")) - .withArguments(new StringArgument("id").replaceSuggestions(ArgumentSuggestions.strings(loots))) - .withArguments(new IntegerArgument("amount", 0)) - .executes((sender, args) -> { - Collection players = (Collection) args.get("player"); - String id = (String) args.get("id"); - int amount = (int) args.getOrDefault("amount", 0); - assert players != null; - Loot loot = CustomFishingPlugin.get().getLootManager().getLoot(id); - for (Player player : players) { - Statistics statistics = CustomFishingPlugin.get().getStatisticsManager().getStatistics(player.getUniqueId()); - if (statistics != null) { - if (loot != null) - statistics.setData(id, amount); - else - throw new RuntimeException("Loot " + id + " doesn't exist."); - } else { - LogUtils.warn("Player " + player.getName() + "'s statistics data has not been loaded."); - } - } - }); - } - - @SuppressWarnings("unchecked") - private CommandAPICommand getResetCommand() { - return new CommandAPICommand("reset") - .withArguments(new EntitySelectorArgument.ManyPlayers("player")) - .executes((sender, args) -> { - Collection players = (Collection) args.get("player"); - assert players != null; - for (Player player : players) { - Statistics statistics = CustomFishingPlugin.get().getStatisticsManager().getStatistics(player.getUniqueId()); - if (statistics != null) { - statistics.reset(); - } else { - LogUtils.warn("Player " + player.getName() + "'s statistics data has not been loaded."); - } - } - }); - } - - @SuppressWarnings("unchecked") - private CommandAPICommand getAddCommand() { - return new CommandAPICommand("add") - .withArguments(new EntitySelectorArgument.ManyPlayers("player")) - .withArguments(new StringArgument("id").replaceSuggestions(ArgumentSuggestions.strings(loots))) - .withArguments(new IntegerArgument("amount", 0)) - .executes((sender, args) -> { - Collection players = (Collection) args.get("player"); - String id = (String) args.get("id"); - int amount = (int) args.getOrDefault("amount", 0); - assert players != null; - Loot loot = CustomFishingPlugin.get().getLootManager().getLoot(id); - for (Player player : players) { - Statistics statistics = CustomFishingPlugin.get().getStatisticsManager().getStatistics(player.getUniqueId()); - if (statistics != null) { - if (loot != null) - statistics.addLootAmount(loot, new Condition(player), amount); - else - throw new RuntimeException("Loot " + id + " doesn't exist."); - } else { - LogUtils.warn("Player " + player.getName() + "'s statistics data has not been loaded."); - } - } - }); - } - - private CommandAPICommand getQueryCommand() { - return new CommandAPICommand("query") - .withArguments(new PlayerArgument("player")) - .executes((sender, args) -> { - Player player = (Player) args.get("player"); - assert player != null; - Statistics statistics = CustomFishingPlugin.get().getStatisticsManager().getStatistics(player.getUniqueId()); - if (statistics != null) { - var adventure = AdventureHelper.getInstance(); - for (Map.Entry entry : statistics.getStatisticMap().entrySet()) { - adventure.sendMessage(sender, entry.getKey() + ": " + entry.getValue()); - } - } else { - throw new RuntimeException("Player " + player.getName() + "'s statistics data has not been loaded."); - } - }); - } -} diff --git a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/Dependency.java b/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/Dependency.java deleted file mode 100644 index d8321eec..00000000 --- a/plugin/src/main/java/net/momirealms/customfishing/libraries/dependencies/Dependency.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * This file is part of LuckPerms, licensed under the MIT License. - * - * Copyright (c) lucko (Luck) - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package net.momirealms.customfishing.libraries.dependencies; - -import com.google.common.collect.ImmutableList; -import net.momirealms.customfishing.libraries.dependencies.relocation.Relocation; -import org.bukkit.Bukkit; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.List; -import java.util.Locale; - -/** - * The dependencies used by CustomFishing. - */ -public enum Dependency { - - ASM( - "org.ow2.asm", - "asm", - "9.7", - "asm" - ), - ASM_COMMONS( - "org.ow2.asm", - "asm-commons", - "9.7", - "asm-commons" - ), - JAR_RELOCATOR( - "me.lucko", - "jar-relocator", - "1.7", - "jar-relocator" - ), - COMMAND_API( - "dev{}jorel", - "commandapi-bukkit-shade", - "9.4.1", - "commandapi-bukkit", - Relocation.of("commandapi", "dev{}jorel{}commandapi") - ), - COMMAND_API_MOJMAP( - "dev{}jorel", - "commandapi-bukkit-shade-mojang-mapped", - "9.4.1", - "commandapi-bukkit-shade-mojang-mapped", - Relocation.of("commandapi", "dev{}jorel{}commandapi") - ), - MARIADB_DRIVER( - "org{}mariadb{}jdbc", - "mariadb-java-client", - "3.3.3", - "mariadb-java-client", - Relocation.of("mariadb", "org{}mariadb") - ), - BOOSTED_YAML( - "dev{}dejvokep", - "boosted-yaml", - "1.3.4", - "boosted-yaml", - Relocation.of("boostedyaml", "dev{}dejvokep{}boostedyaml") - ), - EXP4J( - "net{}objecthunter", - "exp4j", - "0.4.8", - "exp4j", - Relocation.of("exp4j", "net{}objecthunter{}exp4j") - ), - MYSQL_DRIVER( - "com{}mysql", - "mysql-connector-j", - "8.4.0", - "mysql-connector-j", - Relocation.of("mysql", "com{}mysql") - ), - H2_DRIVER( - "com.h2database", - "h2", - "2.2.224", - "h2database" - ), - SQLITE_DRIVER( - "org.xerial", - "sqlite-jdbc", - "3.45.3.0", - "sqlite-jdbc" - ), - HIKARI( - "com{}zaxxer", - "HikariCP", - "5.1.0", - "HikariCP", - Relocation.of("hikari", "com{}zaxxer{}hikari") - ), - SLF4J_SIMPLE( - "org.slf4j", - "slf4j-simple", - "2.0.12", - "slf4j-simple" - ), - SLF4J_API( - "org.slf4j", - "slf4j-api", - "2.0.12", - "slf4j-api" - ), - MONGODB_DRIVER_CORE( - "org{}mongodb", - "mongodb-driver-core", - "5.1.0", - "mongodb-driver-core", - Relocation.of("mongodb", "com{}mongodb"), - Relocation.of("bson", "org{}bson") - ), - MONGODB_DRIVER_SYNC( - "org{}mongodb", - "mongodb-driver-sync", - "5.1.0", - "mongodb-driver-sync", - Relocation.of("mongodb", "com{}mongodb"), - Relocation.of("bson", "org{}bson") - ), - MONGODB_DRIVER_BSON( - "org{}mongodb", - "bson", - "5.1.0", - "mongodb-bson", - Relocation.of("mongodb", "com{}mongodb"), - Relocation.of("bson", "org{}bson") - ), - JEDIS( - "redis{}clients", - "jedis", - "5.1.2", - "jedis", - Relocation.of("jedis", "redis{}clients{}jedis"), - Relocation.of("commonspool2", "org{}apache{}commons{}pool2") - ), - BSTATS_BASE( - "org{}bstats", - "bstats-base", - "3.0.2", - "bstats-base", - Relocation.of("bstats", "org{}bstats") - ), - BSTATS_BUKKIT( - "org{}bstats", - "bstats-bukkit", - "3.0.2", - "bstats-bukkit", - Relocation.of("bstats", "org{}bstats") - ), - COMMONS_POOL_2( - "org{}apache{}commons", - "commons-pool2", - "2.12.0", - "commons-pool2", - Relocation.of("commonspool2", "org{}apache{}commons{}pool2") - ), - GSON( - "com.google.code.gson", - "gson", - "2.10.1", - "gson" - ), - COMMONS_LANG_3( - "org{}apache{}commons", - "commons-lang3", - "3.14.0", - "commons-lang3", - Relocation.of("lang3", "org{}apache{}commons{}lang3") - ); - - private final String mavenRepoPath; - private final String version; - private final List relocations; - private final String artifact; - - private static final String MAVEN_FORMAT = "%s/%s/%s/%s-%s.jar"; - - Dependency(String groupId, String artifactId, String version, String artifact) { - this(groupId, artifactId, version, artifact, new Relocation[0]); - } - - Dependency(String groupId, String artifactId, String version, String artifact, Relocation... relocations) { - this.mavenRepoPath = String.format(MAVEN_FORMAT, - rewriteEscaping(groupId).replace(".", "/"), - rewriteEscaping(artifactId), - version, - rewriteEscaping(artifactId), - version - ); - this.version = version; - this.relocations = ImmutableList.copyOf(relocations); - this.artifact = artifact; - } - - private static String rewriteEscaping(String s) { - return s.replace("{}", "."); - } - - public String getFileName(String classifier) { - String name = artifact.toLowerCase(Locale.ROOT).replace('_', '-'); - String extra = classifier == null || classifier.isEmpty() - ? "" - : "-" + classifier; - - return name + "-" + this.version + extra + ".jar"; - } - - String getMavenRepoPath() { - return this.mavenRepoPath; - } - - public List getRelocations() { - return this.relocations; - } -} diff --git a/plugin/src/main/java/net/momirealms/customfishing/libraries/loader/JarInJarClassLoader.java b/plugin/src/main/java/net/momirealms/customfishing/libraries/loader/JarInJarClassLoader.java deleted file mode 100644 index e61b6c76..00000000 --- a/plugin/src/main/java/net/momirealms/customfishing/libraries/loader/JarInJarClassLoader.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * This file is part of LuckPerms, licensed under the MIT License. - * - * Copyright (c) lucko (Luck) - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package net.momirealms.customfishing.libraries.loader; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Constructor; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; - -/** - * Classloader that can load a jar from within another jar file. - * - *

The "loader" jar contains the loading code & public API classes, - * and is class-loaded by the platform.

- * - *

The inner "plugin" jar contains the plugin itself, and is class-loaded - * by the loading code & this classloader.

- */ -public class JarInJarClassLoader extends URLClassLoader { - static { - ClassLoader.registerAsParallelCapable(); - } - - /** - * Creates a new jar-in-jar class loader. - * - * @param loaderClassLoader the loader plugin's classloader (setup and created by the platform) - * @param jarResourcePath the path to the jar-in-jar resource within the loader jar - * @throws LoadingException if something unexpectedly bad happens - */ - public JarInJarClassLoader(ClassLoader loaderClassLoader, String jarResourcePath) throws LoadingException { - super(new URL[]{extractJar(loaderClassLoader, jarResourcePath)}, loaderClassLoader); - } - - public void addJarToClasspath(URL url) { - addURL(url); - } - - public void deleteJarResource() { - URL[] urls = getURLs(); - if (urls.length == 0) { - return; - } - - try { - Path path = Paths.get(urls[0].toURI()); - Files.deleteIfExists(path); - } catch (Exception e) { - // ignore - } - } - - /** - * Creates a new plugin instance. - * - * @param bootstrapClass the name of the bootstrap plugin class - * @param loaderPluginType the type of the loader plugin, the only parameter of the bootstrap - * plugin constructor - * @param loaderPlugin the loader plugin instance - * @param the type of the loader plugin - * @return the instantiated bootstrap plugin - */ - public LoaderBootstrap instantiatePlugin(String bootstrapClass, Class loaderPluginType, T loaderPlugin) throws LoadingException { - Class plugin; - try { - plugin = loadClass(bootstrapClass).asSubclass(LoaderBootstrap.class); - } catch (ReflectiveOperationException e) { - throw new LoadingException("Unable to load bootstrap class", e); - } - - Constructor constructor; - try { - constructor = plugin.getConstructor(loaderPluginType); - } catch (ReflectiveOperationException e) { - throw new LoadingException("Unable to get bootstrap constructor", e); - } - - try { - return constructor.newInstance(loaderPlugin); - } catch (ReflectiveOperationException e) { - throw new LoadingException("Unable to create bootstrap plugin instance", e); - } - } - - /** - * Extracts the "jar-in-jar" from the loader plugin into a temporary file, - * then returns a URL that can be used by the {@link JarInJarClassLoader}. - * - * @param loaderClassLoader the classloader for the "host" loader plugin - * @param jarResourcePath the inner jar resource path - * @return a URL to the extracted file - */ - private static URL extractJar(ClassLoader loaderClassLoader, String jarResourcePath) throws LoadingException { - // get the jar-in-jar resource - URL jarInJar = loaderClassLoader.getResource(jarResourcePath); - if (jarInJar == null) { - throw new LoadingException("Could not locate jar-in-jar"); - } - - // create a temporary file - // on posix systems by default this is only read/writable by the process owner - Path path; - try { - path = Files.createTempFile("customfishing-jarinjar", ".jar.tmp"); - } catch (IOException e) { - throw new LoadingException("Unable to create a temporary file", e); - } - - // mark that the file should be deleted on exit - path.toFile().deleteOnExit(); - - // copy the jar-in-jar to the temporary file path - try (InputStream in = jarInJar.openStream()) { - Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING); - } catch (IOException e) { - throw new LoadingException("Unable to copy jar-in-jar to temporary path", e); - } - - try { - return path.toUri().toURL(); - } catch (MalformedURLException e) { - throw new LoadingException("Unable to get URL from path", e); - } - } - -} diff --git a/plugin/src/main/java/net/momirealms/customfishing/scheduler/BukkitSchedulerImpl.java b/plugin/src/main/java/net/momirealms/customfishing/scheduler/BukkitSchedulerImpl.java deleted file mode 100644 index b3de4a61..00000000 --- a/plugin/src/main/java/net/momirealms/customfishing/scheduler/BukkitSchedulerImpl.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.scheduler; - -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.scheduler.CancellableTask; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.scheduler.BukkitTask; - -/** - * A scheduler implementation for synchronous tasks using Bukkit's Scheduler. - */ -public class BukkitSchedulerImpl implements SyncScheduler { - - private final CustomFishingPlugin plugin; - - public BukkitSchedulerImpl(CustomFishingPlugin plugin) { - this.plugin = plugin; - } - - /** - * Runs a synchronous task on the main server thread using Bukkit's Scheduler. - * If already on the main thread, the task is executed immediately. - * - * @param runnable The task to run. - * @param location The location associated with the task. - */ - @Override - public void runSyncTask(Runnable runnable, Location location) { - if (Bukkit.isPrimaryThread()) - runnable.run(); - else - Bukkit.getScheduler().runTask(plugin, runnable); - } - - /** - * Runs a synchronous task repeatedly with a specified delay and period using Bukkit's Scheduler. - * - * @param runnable The task to run. - * @param location The location associated with the task. - * @param delay The delay in ticks before the first execution. - * @param period The period between subsequent executions in ticks. - * @return A CancellableTask for managing the scheduled task. - */ - @Override - public CancellableTask runTaskSyncTimer(Runnable runnable, Location location, long delay, long period) { - return new BukkitCancellableTask(Bukkit.getScheduler().runTaskTimer(plugin, runnable, delay, period)); - } - - /** - * Runs a synchronous task with a specified delay using Bukkit's Scheduler. - * - * @param runnable The task to run. - * @param location The location associated with the task. - * @param delay The delay in ticks before the task execution. - * @return A CancellableTask for managing the scheduled task. - */ - @Override - public CancellableTask runTaskSyncLater(Runnable runnable, Location location, long delay) { - if (delay == 0) { - if (Bukkit.isPrimaryThread()) runnable.run(); - else Bukkit.getScheduler().runTask(plugin, runnable); - return new BukkitCancellableTask(null); - } - return new BukkitCancellableTask(Bukkit.getScheduler().runTaskLater(plugin, runnable, delay)); - } - - /** - * Represents a scheduled task using Bukkit's Scheduler that can be cancelled. - */ - public static class BukkitCancellableTask implements CancellableTask { - - private final BukkitTask bukkitTask; - - public BukkitCancellableTask(BukkitTask bukkitTask) { - this.bukkitTask = bukkitTask; - } - - @Override - public void cancel() { - if (this.bukkitTask != null) - this.bukkitTask.cancel(); - } - - @Override - public boolean isCancelled() { - if (this.bukkitTask == null) return true; - return this.bukkitTask.isCancelled(); - } - } -} diff --git a/plugin/src/main/java/net/momirealms/customfishing/scheduler/FoliaSchedulerImpl.java b/plugin/src/main/java/net/momirealms/customfishing/scheduler/FoliaSchedulerImpl.java deleted file mode 100644 index 838e5f28..00000000 --- a/plugin/src/main/java/net/momirealms/customfishing/scheduler/FoliaSchedulerImpl.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.scheduler; - -import io.papermc.paper.threadedregions.scheduler.ScheduledTask; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.scheduler.CancellableTask; -import org.bukkit.Bukkit; -import org.bukkit.Location; - -/** - * A scheduler implementation for "synchronous" tasks using Folia's RegionScheduler. - */ -public class FoliaSchedulerImpl implements SyncScheduler { - - private final CustomFishingPlugin plugin; - - public FoliaSchedulerImpl(CustomFishingPlugin plugin) { - this.plugin = plugin; - } - - /** - * Runs a "synchronous" task on the region thread using Folia's RegionScheduler. - * - * @param runnable The task to run. - * @param location The location associated with the task. - */ - @Override - public void runSyncTask(Runnable runnable, Location location) { - if (location == null) { - Bukkit.getGlobalRegionScheduler().execute(plugin, runnable); - } else { - Bukkit.getRegionScheduler().execute(plugin, location, runnable); - } - } - - /** - * Runs a "synchronous" task repeatedly with a specified delay and period using Folia's RegionScheduler. - * - * @param runnable The task to run. - * @param location The location associated with the task. - * @param delay The delay in ticks before the first execution. - * @param period The period between subsequent executions in ticks. - * @return A CancellableTask for managing the scheduled task. - */ - @Override - public CancellableTask runTaskSyncTimer(Runnable runnable, Location location, long delay, long period) { - if (location == null) { - return new FoliaCancellableTask(Bukkit.getGlobalRegionScheduler().runAtFixedRate(plugin, (scheduledTask -> runnable.run()), delay, period)); - } - return new FoliaCancellableTask(Bukkit.getRegionScheduler().runAtFixedRate(plugin, location, (scheduledTask -> runnable.run()), delay, period)); - } - - /** - * Runs a "synchronous" task with a specified delay using Folia's RegionScheduler. - * - * @param runnable The task to run. - * @param location The location associated with the task. - * @param delay The delay in ticks before the task execution. - * @return A CancellableTask for managing the scheduled task. - */ - @Override - public CancellableTask runTaskSyncLater(Runnable runnable, Location location, long delay) { - if (delay == 0) { - if (location == null) { - return new FoliaCancellableTask(Bukkit.getGlobalRegionScheduler().run(plugin, (scheduledTask -> runnable.run()))); - } - return new FoliaCancellableTask(Bukkit.getRegionScheduler().run(plugin, location, (scheduledTask -> runnable.run()))); - } - if (location == null) { - return new FoliaCancellableTask(Bukkit.getGlobalRegionScheduler().runDelayed(plugin, (scheduledTask -> runnable.run()), delay)); - } - return new FoliaCancellableTask(Bukkit.getRegionScheduler().runDelayed(plugin, location, (scheduledTask -> runnable.run()), delay)); - } - - /** - * Represents a scheduled task using Folia's RegionScheduler that can be cancelled. - */ - public static class FoliaCancellableTask implements CancellableTask { - - private final ScheduledTask scheduledTask; - - public FoliaCancellableTask(ScheduledTask scheduledTask) { - this.scheduledTask = scheduledTask; - } - - @Override - public void cancel() { - this.scheduledTask.cancel(); - } - - @Override - public boolean isCancelled() { - return this.scheduledTask.isCancelled(); - } - } -} diff --git a/plugin/src/main/java/net/momirealms/customfishing/scheduler/SchedulerImpl.java b/plugin/src/main/java/net/momirealms/customfishing/scheduler/SchedulerImpl.java deleted file mode 100644 index 267ec3bc..00000000 --- a/plugin/src/main/java/net/momirealms/customfishing/scheduler/SchedulerImpl.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.scheduler; - -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.api.scheduler.CancellableTask; -import net.momirealms.customfishing.api.scheduler.Scheduler; -import net.momirealms.customfishing.api.util.LogUtils; -import net.momirealms.customfishing.setting.CFConfig; -import org.bukkit.Location; - -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * A scheduler implementation responsible for scheduling and managing tasks in a multi-threaded environment. - */ -public class SchedulerImpl implements Scheduler { - - private final SyncScheduler syncScheduler; - private final ScheduledThreadPoolExecutor schedule; - private final CustomFishingPlugin plugin; - - public SchedulerImpl(CustomFishingPlugin plugin) { - this.plugin = plugin; - this.syncScheduler = plugin.getVersionManager().hasRegionScheduler() ? - new FoliaSchedulerImpl(plugin) : new BukkitSchedulerImpl(plugin); - this.schedule = new ScheduledThreadPoolExecutor(1); - this.schedule.setMaximumPoolSize(1); - this.schedule.setKeepAliveTime(30, TimeUnit.SECONDS); - this.schedule.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy()); - } - - /** - * Reloads the scheduler configuration based on CustomFishingPlugin settings. - */ - public void reload() { - try { - this.schedule.setMaximumPoolSize(CFConfig.maximumPoolSize); - this.schedule.setCorePoolSize(CFConfig.corePoolSize); - this.schedule.setKeepAliveTime(CFConfig.keepAliveTime, TimeUnit.SECONDS); - } catch (IllegalArgumentException e) { - LogUtils.warn("Failed to create thread pool. Please lower the corePoolSize in config.yml.", e); - } - } - - /** - * Shuts down the scheduler. - */ - public void shutdown() { - if (this.schedule != null && !this.schedule.isShutdown()) - this.schedule.shutdown(); - } - - /** - * Runs a task synchronously on the main server thread or region thread. - * - * @param runnable The task to run. - * @param location The location associated with the task. - */ - @Override - public void runTaskSync(Runnable runnable, Location location) { - this.syncScheduler.runSyncTask(runnable, location); - } - - /** - * Runs a task asynchronously. - * - * @param runnable The task to run. - */ - @Override - public void runTaskAsync(Runnable runnable) { - try { - this.schedule.execute(runnable); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Runs a task synchronously with a specified delay and period. - * - * @param runnable The task to run. - * @param location The location associated with the task. - * @param delayTicks The delay in ticks before the first execution. - * @param periodTicks The period between subsequent executions in ticks. - * @return A CancellableTask for managing the scheduled task. - */ - @Override - public CancellableTask runTaskSyncTimer(Runnable runnable, Location location, long delayTicks, long periodTicks) { - return this.syncScheduler.runTaskSyncTimer(runnable, location, delayTicks, periodTicks); - } - - /** - * Runs a task asynchronously with a specified delay. - * - * @param runnable The task to run. - * @param delay The delay before the task execution. - * @param timeUnit The time unit for the delay. - * @return A CancellableTask for managing the scheduled task. - */ - @Override - public CancellableTask runTaskAsyncLater(Runnable runnable, long delay, TimeUnit timeUnit) { - return new ScheduledTask(schedule.schedule(() -> { - try { - runnable.run(); - } catch (Exception e) { - e.printStackTrace(); - } - }, delay, timeUnit)); - } - - /** - * Runs a task synchronously with a specified delay. - * - * @param runnable The task to run. - * @param location The location associated with the task. - * @param delay The delay before the task execution. - * @param timeUnit The time unit for the delay. - * @return A CancellableTask for managing the scheduled task. - */ - @Override - public CancellableTask runTaskSyncLater(Runnable runnable, Location location, long delay, TimeUnit timeUnit) { - return new ScheduledTask(schedule.schedule(() -> { - runTaskSync(runnable, location); - }, delay, timeUnit)); - } - - /** - * Runs a task synchronously with a specified delay in ticks. - * - * @param runnable The task to run. - * @param location The location associated with the task. - * @param delayTicks The delay in ticks before the task execution. - * @return A CancellableTask for managing the scheduled task. - */ - @Override - public CancellableTask runTaskSyncLater(Runnable runnable, Location location, long delayTicks) { - return this.syncScheduler.runTaskSyncLater(runnable, location, delayTicks); - } - - /** - * Runs a task asynchronously with a specified delay and period. - * - * @param runnable The task to run. - * @param delay The delay before the first execution. - * @param period The period between subsequent executions. - * @param timeUnit The time unit for the delay and period. - * @return A CancellableTask for managing the scheduled task. - */ - @Override - public CancellableTask runTaskAsyncTimer(Runnable runnable, long delay, long period, TimeUnit timeUnit) { - return new ScheduledTask(schedule.scheduleAtFixedRate(() -> { - try { - runnable.run(); - } catch (Exception e) { - e.printStackTrace(); - } - }, delay, period, timeUnit)); - } - - /** - * Represents a thread-pool task that can be cancelled. - */ - public static class ScheduledTask implements CancellableTask { - - private final ScheduledFuture scheduledFuture; - - public ScheduledTask(ScheduledFuture scheduledFuture) { - this.scheduledFuture = scheduledFuture; - } - - @Override - public void cancel() { - this.scheduledFuture.cancel(false); - } - - @Override - public boolean isCancelled() { - return this.scheduledFuture.isCancelled(); - } - } -} diff --git a/plugin/src/main/java/net/momirealms/customfishing/scheduler/SyncScheduler.java b/plugin/src/main/java/net/momirealms/customfishing/scheduler/SyncScheduler.java deleted file mode 100644 index 9d706dc1..00000000 --- a/plugin/src/main/java/net/momirealms/customfishing/scheduler/SyncScheduler.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.scheduler; - -import net.momirealms.customfishing.api.scheduler.CancellableTask; -import org.bukkit.Location; - -public interface SyncScheduler { - - /** - * Runs a task synchronously on the main server thread or region thread. - * - * @param runnable The task to run. - * @param location The location associated with the task. - */ - void runSyncTask(Runnable runnable, Location location); - - /** - * Runs a task synchronously with a specified delay and period. - * - * @param runnable The task to run. - * @param location The location associated with the task. - * @param delayTicks The delay in ticks before the first execution. - * @param periodTicks The period between subsequent executions in ticks. - * @return A CancellableTask for managing the scheduled task. - */ - CancellableTask runTaskSyncTimer(Runnable runnable, Location location, long delayTicks, long periodTicks); - - /** - * Runs a task synchronously with a specified delay in ticks. - * - * @param runnable The task to run. - * @param location The location associated with the task. - * @param delayTicks The delay in ticks before the task execution. - * @return A CancellableTask for managing the scheduled task. - */ - CancellableTask runTaskSyncLater(Runnable runnable, Location location, long delayTicks); -} diff --git a/plugin/src/main/java/net/momirealms/customfishing/util/NBTUtils.java b/plugin/src/main/java/net/momirealms/customfishing/util/NBTUtils.java deleted file mode 100644 index 34b8c16b..00000000 --- a/plugin/src/main/java/net/momirealms/customfishing/util/NBTUtils.java +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Copyright (C) <2022> - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package net.momirealms.customfishing.util; - -import de.tr7zw.changeme.nbtapi.NBTCompound; -import de.tr7zw.changeme.nbtapi.NBTListCompound; -import de.tr7zw.changeme.nbtapi.iface.ReadWriteNBT; -import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion; -import de.tr7zw.changeme.nbtapi.utils.VersionChecker; -import net.momirealms.customfishing.api.CustomFishingPlugin; -import net.momirealms.customfishing.compatibility.papi.PlaceholderManagerImpl; -import org.bukkit.Bukkit; -import org.bukkit.configuration.MemorySection; -import org.bukkit.entity.Player; - -import java.lang.reflect.Field; -import java.util.*; - -/** - * Utility class for working with NBT (Named Binary Tag) data. - */ -public class NBTUtils { - - private NBTUtils() {} - - public static void disableNBTAPILogs() { - MinecraftVersion.disableBStats(); - MinecraftVersion.disableUpdateCheck(); - VersionChecker.hideOk = true; - try { - Field field = MinecraftVersion.class.getDeclaredField("version"); - field.setAccessible(true); - MinecraftVersion minecraftVersion; - try { - minecraftVersion = MinecraftVersion.valueOf(CustomFishingPlugin.get().getVersionManager().getServerVersion().replace("v", "MC")); - } catch (Exception ex) { - minecraftVersion = VERSION_TO_REVISION.getOrDefault(Bukkit.getServer().getBukkitVersion().split("-")[0], - MinecraftVersion.UNKNOWN); - } - field.set(MinecraftVersion.class, minecraftVersion); - } catch (NoSuchFieldException | IllegalAccessException e) { - throw new RuntimeException(e); - } - boolean hasGsonSupport; - try { - Class.forName("com.google.gson.Gson"); - hasGsonSupport = true; - } catch (Exception ex) { - hasGsonSupport = false; - } - try { - Field field= MinecraftVersion.class.getDeclaredField("hasGsonSupport"); - field.setAccessible(true); - field.set(Boolean.class, hasGsonSupport); - } catch (NoSuchFieldException | IllegalAccessException e) { - throw new RuntimeException(e); - } - } - - private static final Map VERSION_TO_REVISION = new HashMap<>() { - { - this.put("1.20", MinecraftVersion.MC1_20_R1); - this.put("1.20.1", MinecraftVersion.MC1_20_R1); - this.put("1.20.2", MinecraftVersion.MC1_20_R2); - this.put("1.20.3", MinecraftVersion.MC1_20_R3); - this.put("1.20.4", MinecraftVersion.MC1_20_R3); - this.put("1.20.5", MinecraftVersion.MC1_20_R4); - this.put("1.20.6", MinecraftVersion.MC1_20_R4); - } - }; - - - /** - * Inner class representing a stack element used during NBT data conversion. - */ - public static class StackElement { - final Map currentMap; - final NBTCompound currentNbtCompound; - - StackElement(Map map, NBTCompound nbtCompound) { - this.currentMap = map; - this.currentNbtCompound = nbtCompound; - } - } - - /** - * Converts data from a Bukkit YAML configuration to NBT tags. - * - * @param nbtCompound The target NBT compound - * @param map The source map from Bukkit YAML - */ - @SuppressWarnings("unchecked") - public static void setTagsFromBukkitYAML(Player player, Map placeholders, NBTCompound nbtCompound, Map map) { - - Deque stack = new ArrayDeque<>(); - stack.push(new StackElement(map, nbtCompound)); - - while (!stack.isEmpty()) { - StackElement currentElement = stack.pop(); - Map currentMap = currentElement.currentMap; - NBTCompound currentNbtCompound = currentElement.currentNbtCompound; - - for (Map.Entry entry : currentMap.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - - if (value instanceof MemorySection memorySection) { - stack.push(new StackElement(memorySection.getValues(false), currentNbtCompound.addCompound(key))); - } else if (value instanceof List list) { - for (Object o : list) { - if (o instanceof String stringValue) { - setListValue(player, placeholders, key, stringValue, currentNbtCompound); - } else if (o instanceof Map mapValue) { - NBTListCompound nbtListCompound = currentNbtCompound.getCompoundList(key).addCompound(); - stack.push(new StackElement((Map) mapValue, nbtListCompound)); - } - } - } else if (value instanceof String stringValue) { - setSingleValue(player, placeholders, key, stringValue, currentNbtCompound); - } - } - } - } - - // Private helper method - private static void setListValue(Player player, Map placeholders, String key, String value, NBTCompound nbtCompound) { - String[] parts = getTypeAndData(value); - String type = parts[0]; - String data = getParsedData(player, placeholders, parts[1]); - switch (type) { - case "String" -> nbtCompound.getStringList(key).add(data); - case "UUID" -> nbtCompound.getUUIDList(key).add(UUID.fromString(data)); - case "Double" -> nbtCompound.getDoubleList(key).add(Double.parseDouble(data)); - case "Long" -> nbtCompound.getLongList(key).add(Long.parseLong(data)); - case "Float" -> nbtCompound.getFloatList(key).add(Float.parseFloat(data)); - case "Int" -> nbtCompound.getIntegerList(key).add(Integer.parseInt(data)); - case "IntArray" -> { - String[] split = data.replace("[", "").replace("]", "").replaceAll("\\s", "").split(","); - int[] array = Arrays.stream(split).mapToInt(Integer::parseInt).toArray(); - nbtCompound.getIntArrayList(key).add(array); - } - default -> throw new IllegalArgumentException("Invalid value type: " + type); - } - } - - // Private helper method - private static void setSingleValue(Player player, Map placeholders, String key, String value, NBTCompound nbtCompound) { - String[] parts = getTypeAndData(value); - String type = parts[0]; - String data = getParsedData(player, placeholders, parts[1]); - switch (type) { - case "Int" -> nbtCompound.setInteger(key, Integer.parseInt(data)); - case "String" -> nbtCompound.setString(key, data); - case "Long" -> nbtCompound.setLong(key, Long.parseLong(data)); - case "Float" -> nbtCompound.setFloat(key, Float.parseFloat(data)); - case "Double" -> nbtCompound.setDouble(key, Double.parseDouble(data)); - case "Short" -> nbtCompound.setShort(key, Short.parseShort(data)); - case "Boolean" -> nbtCompound.setBoolean(key, Boolean.parseBoolean(data)); - case "UUID" -> nbtCompound.setUUID(key, UUID.nameUUIDFromBytes(data.getBytes())); - case "Byte" -> nbtCompound.setByte(key, Byte.parseByte(data)); - case "ByteArray" -> { - String[] split = splitValue(value); - byte[] bytes = new byte[split.length]; - for (int i = 0; i < split.length; i++){ - bytes[i] = Byte.parseByte(split[i]); - } - nbtCompound.setByteArray(key, bytes); - } - case "IntArray" -> { - String[] split = splitValue(value); - int[] array = Arrays.stream(split).mapToInt(Integer::parseInt).toArray(); - nbtCompound.setIntArray(key, array); - } - default -> throw new IllegalArgumentException("Invalid value type: " + type); - } - } - - public static String getParsedData(Player player, Map placeholders, String data) { - if (data.length() >= 3) - switch (data.substring(0,3)) { - case "-P:" -> data = PlaceholderManagerImpl.getInstance().parse(player, data.substring(3), placeholders); - case "-E:" -> { - double value = ConfigUtils.getExpressionValue(player, data.substring(3), placeholders); - if (value % 1 == 0) { - data = Long.toString((long) value); - } else { - data = Double.toString(value); - } - } - } - return data; - } - - /** - * Converts an NBT compound to a map of key-value pairs. - * - * @param nbtCompound The source NBT compound - * @return A map representing the NBT data - */ - public static Map compoundToMap(ReadWriteNBT nbtCompound){ - Map map = new HashMap<>(); - for (String key : nbtCompound.getKeys()) { - switch (nbtCompound.getType(key)){ - case NBTTagByte -> map.put(key, "(Byte) " + nbtCompound.getByte(key)); - case NBTTagInt -> map.put(key, "(Int) " + nbtCompound.getInteger(key)); - case NBTTagDouble -> map.put(key, "(Double) " + nbtCompound.getDouble(key)); - case NBTTagLong -> map.put(key, "(Long) " + nbtCompound.getLong(key)); - case NBTTagFloat -> map.put(key, "(Float) " + nbtCompound.getFloat(key)); - case NBTTagShort -> map.put(key, "(Short) " + nbtCompound.getShort(key)); - case NBTTagString -> map.put(key, "(String) " + nbtCompound.getString(key)); - case NBTTagByteArray -> map.put(key, "(ByteArray) " + Arrays.toString(nbtCompound.getByteArray(key))); - case NBTTagIntArray -> map.put(key, "(IntArray) " + Arrays.toString(nbtCompound.getIntArray(key))); - case NBTTagCompound -> { - Map map1 = compoundToMap(Objects.requireNonNull(nbtCompound.getCompound(key))); - if (!map1.isEmpty()) map.put(key, map1); - } - case NBTTagList -> { - List list = new ArrayList<>(); - switch (Objects.requireNonNull(nbtCompound.getListType(key))) { - case NBTTagCompound -> nbtCompound.getCompoundList(key).forEach(a -> list.add(compoundToMap(a))); - case NBTTagInt -> nbtCompound.getIntegerList(key).forEach(a -> list.add("(Int) " + a)); - case NBTTagDouble -> nbtCompound.getDoubleList(key).forEach(a -> list.add("(Double) " + a)); - case NBTTagString -> nbtCompound.getStringList(key).forEach(a -> list.add("(String) " + a)); - case NBTTagFloat -> nbtCompound.getFloatList(key).forEach(a -> list.add("(Float) " + a)); - case NBTTagLong -> nbtCompound.getLongList(key).forEach(a -> list.add("(Long) " + a)); - case NBTTagIntArray -> nbtCompound.getIntArrayList(key).forEach(a -> list.add("(IntArray) " + Arrays.toString(a))); - } - if (!list.isEmpty()) map.put(key, list); - } - } - } - return map; - } - - /** - * Splits a value into type and data components. - * - * @param str The input value string - * @return An array containing type and data strings - */ - public static String[] getTypeAndData(String str) { - String[] parts = str.split("\\s+", 2); - if (parts.length == 1) { - return new String[]{"String", str}; - } - if (parts.length != 2) { - throw new IllegalArgumentException("Invalid value format: " + str); - } - String type = parts[0].substring(1, parts[0].length() - 1); - String data = parts[1]; - return new String[]{type, data}; - } - - /** - * Splits a value containing arrays into individual elements. - * - * @param value The input value containing arrays - * @return An array of individual elements - */ - public static String[] splitValue(String value) { - return value.substring(value.indexOf('[') + 1, value.lastIndexOf(']')) - .replaceAll("\\s", "") - .split(","); - } -} \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts index d2bc3642..0029c53a 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,3 +1,7 @@ rootProject.name = "CustomFishing" include("api") -include("plugin") +include("common") +include("core") +include("compatibility") +include("paper-loader") +include("bukkit-loader")