From e448604f3b6e0b92513e368efe0d8210e00a13a7 Mon Sep 17 00:00:00 2001 From: GB6 Date: Fri, 11 Jan 2019 16:30:18 +0100 Subject: [PATCH] WIP: version independent --- .gitignore | 5 + .gitlab-ci.yml | 22 + EpicFurnaces-Parent.iml | 22 + EpicFurnaces.iml | 12 + LICENSE | 9 + README.MD | 5 + Read_this_before_your_first_use.txt | 20 + core/core.iml | 44 ++ core/pom.xml | 168 +++++ .../songoda/epicfurnaces/EpicFurnaces.java | 584 ++++++++++++++++++ .../java/com/songoda/epicfurnaces/Locale.java | 377 +++++++++++ .../com/songoda/epicfurnaces/References.java | 14 + .../songoda/epicfurnaces/boost/BoostData.java | 50 ++ .../epicfurnaces/boost/BoostManager.java | 36 ++ .../epicfurnaces/command/AbstractCommand.java | 38 ++ .../epicfurnaces/command/CommandManager.java | 79 +++ .../command/commands/CommandBoost.java | 87 +++ .../command/commands/CommandEpicFurnaces.java | 46 ++ .../command/commands/CommandGive.java | 69 +++ .../command/commands/CommandReload.java | 37 ++ .../command/commands/CommandRemote.java | 76 +++ .../command/commands/CommandSettings.java | 36 ++ .../epicfurnaces/furnace/FurnaceManager.java | 47 ++ .../epicfurnaces/furnace/FurnaceObject.java | 358 +++++++++++ .../songoda/epicfurnaces/furnace/Level.java | 88 +++ .../epicfurnaces/furnace/LevelManager.java | 46 ++ .../handlers/BlacklistHandler.java | 67 ++ .../listeners/BlockListeners.java | 115 ++++ .../listeners/FurnaceListeners.java | 66 ++ .../listeners/InteractListeners.java | 56 ++ .../listeners/InventoryListeners.java | 66 ++ .../epicfurnaces/menus/OverviewMenu.java | 216 +++++++ .../songoda/epicfurnaces/storage/Storage.java | 31 + .../epicfurnaces/storage/StorageItem.java | 64 ++ .../epicfurnaces/storage/StorageRow.java | 28 + .../storage/types/StorageMysql.java | 125 ++++ .../storage/types/StorageYaml.java | 103 +++ .../epicfurnaces/tasks/FurnaceTask.java | 166 +++++ .../epicfurnaces/tasks/HologramTask.java | 110 ++++ .../epicfurnaces/utils/BukkitEnums.java | 29 + .../songoda/epicfurnaces/utils/Debugger.java | 31 + .../songoda/epicfurnaces/utils/Methods.java | 81 +++ .../epicfurnaces/utils/MySQLDatabase.java | 49 ++ .../songoda/epicfurnaces/utils/NMSUtil.java | 100 +++ .../epicfurnaces/utils/SettingsManager.java | 256 ++++++++ .../utils/gui/AbstractAnvilGUI.java | 264 ++++++++ .../epicfurnaces/utils/gui/FastInv.java | 529 ++++++++++++++++ .../epicfurnaces/utils/gui/ItemBuilder.java | 294 +++++++++ .../epicfurnaces/utils/gui/OnClose.java | 10 + core/src/main/resources/Furnace Recipes.yml | 161 +++++ .../src/main/resources/SettingDefinitions.yml | 16 + core/src/main/resources/blacklist.yml | 0 core/src/main/resources/config.yml | 0 core/src/main/resources/en_US.lang | 55 ++ core/src/main/resources/plugin.yml | 13 + hooks/askyblock/askyblock.iml | 8 + hooks/askyblock/hook.askyblock.iml | 12 + hooks/askyblock/pom.xml | 35 ++ .../epicfurnaces/hooks/ASkyBlockHook.java | 60 ++ .../craftbukkit-1-8-r1/craftbukkit-1-8-r1.iml | 8 + hooks/craftbukkit-1-8-r1/pom.xml | 27 + .../epicfurnaces/hooks/CraftBukkit18R1.java | 16 + .../craftbukkit-1-8-r2/craftbukkit-1-8-r2.iml | 8 + hooks/craftbukkit-1-8-r2/pom.xml | 29 + .../epicfurnaces/hooks/CraftBukkit18R2.java | 15 + .../craftbukkit-1-8-r3/craftbukkit-1-8-r3.iml | 8 + hooks/craftbukkit-1-8-r3/pom.xml | 29 + .../epicfurnaces/hooks/CraftBukkit18R3.java | 15 + hooks/craftbukkit-1-9/craftbukkit-1-9.iml | 8 + hooks/craftbukkit-1-9/craftbukkit19.iml | 12 + hooks/craftbukkit-1-9/pom.xml | 27 + .../songoda/epicfurnaces/CraftBukkit19.java | 15 + hooks/factions/factions.iml | 8 + hooks/factions/hook.factions.iml | 12 + hooks/factions/pom.xml | 36 ++ .../epicfurnaces/hooks/FactionsHook.java | 41 ++ hooks/griefprevention/griefprevention.iml | 8 + hooks/griefprevention/pom.xml | 36 ++ .../hooks/GriefPreventionHook.java | 28 + hooks/hooks.iml | 8 + hooks/kingdoms/hook.kingdoms.iml | 12 + hooks/kingdoms/kingdoms.iml | 8 + hooks/kingdoms/pom.xml | 40 ++ .../epicfurnaces/hooks/KingdomsHook.java | 36 ++ hooks/manager/manager.iml | 8 + hooks/manager/pom.xml | 25 + .../hook/ClaimableProtectionPluginHook.java | 37 ++ .../epicfurnaces/hook/CraftBukkitHook.java | 8 + .../hook/ProtectionPluginHook.java | 45 ++ hooks/plotsquared/hook.plotsquared.iml | 12 + hooks/plotsquared/plotsquared.iml | 8 + hooks/plotsquared/pom.xml | 34 + .../epicfurnaces/hooks/PlotSquaredHook.java | 27 + hooks/pom.xml | 33 + hooks/redprotect/hook.redprotect.iml | 12 + hooks/redprotect/pom.xml | 36 ++ hooks/redprotect/redprotect.iml | 8 + .../epicfurnaces/hooks/RedProtectHook.java | 30 + hooks/towny/hook.towny.iml | 12 + hooks/towny/pom.xml | 36 ++ .../songoda/epicfurnaces/hooks/TownyHook.java | 55 ++ hooks/towny/towny.iml | 8 + hooks/uskyblock/hook.uskyblock.iml | 12 + hooks/uskyblock/pom.xml | 33 + .../songoda/epicfurnaces/USkyBlockHook.java | 34 + hooks/uskyblock/uskyblock.iml | 8 + hooks/worldguard6/pom.xml | 34 + .../epicfurnaces/hooks/WorldGuard6Hook.java | 23 + hooks/worldguard6/worldguard6.iml | 8 + hooks/worldguard7/hook.worldguard.iml | 26 + hooks/worldguard7/pom.xml | 40 ++ .../epicfurnaces/hooks/WorldGuard7Hook.java | 30 + hooks/worldguard7/worldguard7.iml | 8 + pom.xml | 44 ++ 114 files changed, 6815 insertions(+) create mode 100644 .gitignore create mode 100644 .gitlab-ci.yml create mode 100644 EpicFurnaces-Parent.iml create mode 100644 EpicFurnaces.iml create mode 100644 LICENSE create mode 100644 README.MD create mode 100644 Read_this_before_your_first_use.txt create mode 100644 core/core.iml create mode 100644 core/pom.xml create mode 100644 core/src/main/java/com/songoda/epicfurnaces/EpicFurnaces.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/Locale.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/References.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/boost/BoostData.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/boost/BoostManager.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/command/AbstractCommand.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/command/CommandManager.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandBoost.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandEpicFurnaces.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandGive.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandReload.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandRemote.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandSettings.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/furnace/FurnaceManager.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/furnace/FurnaceObject.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/furnace/Level.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/furnace/LevelManager.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/handlers/BlacklistHandler.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/listeners/BlockListeners.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/listeners/FurnaceListeners.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/listeners/InteractListeners.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/listeners/InventoryListeners.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/menus/OverviewMenu.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/storage/Storage.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/storage/StorageItem.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/storage/StorageRow.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/storage/types/StorageMysql.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/storage/types/StorageYaml.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/tasks/FurnaceTask.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/tasks/HologramTask.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/utils/BukkitEnums.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/utils/Debugger.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/utils/Methods.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/utils/MySQLDatabase.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/utils/NMSUtil.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/utils/SettingsManager.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/utils/gui/AbstractAnvilGUI.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/utils/gui/FastInv.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/utils/gui/ItemBuilder.java create mode 100644 core/src/main/java/com/songoda/epicfurnaces/utils/gui/OnClose.java create mode 100644 core/src/main/resources/Furnace Recipes.yml create mode 100644 core/src/main/resources/SettingDefinitions.yml create mode 100644 core/src/main/resources/blacklist.yml create mode 100644 core/src/main/resources/config.yml create mode 100644 core/src/main/resources/en_US.lang create mode 100644 core/src/main/resources/plugin.yml create mode 100644 hooks/askyblock/askyblock.iml create mode 100644 hooks/askyblock/hook.askyblock.iml create mode 100644 hooks/askyblock/pom.xml create mode 100644 hooks/askyblock/src/main/java/com/songoda/epicfurnaces/hooks/ASkyBlockHook.java create mode 100644 hooks/craftbukkit-1-8-r1/craftbukkit-1-8-r1.iml create mode 100644 hooks/craftbukkit-1-8-r1/pom.xml create mode 100644 hooks/craftbukkit-1-8-r1/src/main/java/com/songoda/epicfurnaces/hooks/CraftBukkit18R1.java create mode 100644 hooks/craftbukkit-1-8-r2/craftbukkit-1-8-r2.iml create mode 100644 hooks/craftbukkit-1-8-r2/pom.xml create mode 100644 hooks/craftbukkit-1-8-r2/src/main/java/com/songoda/epicfurnaces/hooks/CraftBukkit18R2.java create mode 100644 hooks/craftbukkit-1-8-r3/craftbukkit-1-8-r3.iml create mode 100644 hooks/craftbukkit-1-8-r3/pom.xml create mode 100644 hooks/craftbukkit-1-8-r3/src/main/java/com/songoda/epicfurnaces/hooks/CraftBukkit18R3.java create mode 100644 hooks/craftbukkit-1-9/craftbukkit-1-9.iml create mode 100644 hooks/craftbukkit-1-9/craftbukkit19.iml create mode 100644 hooks/craftbukkit-1-9/pom.xml create mode 100644 hooks/craftbukkit-1-9/src/main/java/com/songoda/epicfurnaces/CraftBukkit19.java create mode 100644 hooks/factions/factions.iml create mode 100644 hooks/factions/hook.factions.iml create mode 100644 hooks/factions/pom.xml create mode 100644 hooks/factions/src/main/java/com/songoda/epicfurnaces/hooks/FactionsHook.java create mode 100644 hooks/griefprevention/griefprevention.iml create mode 100644 hooks/griefprevention/pom.xml create mode 100644 hooks/griefprevention/src/main/java/com/songoda/epicfurnaces/hooks/GriefPreventionHook.java create mode 100644 hooks/hooks.iml create mode 100644 hooks/kingdoms/hook.kingdoms.iml create mode 100644 hooks/kingdoms/kingdoms.iml create mode 100644 hooks/kingdoms/pom.xml create mode 100644 hooks/kingdoms/src/main/java/com/songoda/epicfurnaces/hooks/KingdomsHook.java create mode 100644 hooks/manager/manager.iml create mode 100644 hooks/manager/pom.xml create mode 100644 hooks/manager/src/main/java/com/songoda/epicfurnaces/hook/ClaimableProtectionPluginHook.java create mode 100644 hooks/manager/src/main/java/com/songoda/epicfurnaces/hook/CraftBukkitHook.java create mode 100644 hooks/manager/src/main/java/com/songoda/epicfurnaces/hook/ProtectionPluginHook.java create mode 100644 hooks/plotsquared/hook.plotsquared.iml create mode 100644 hooks/plotsquared/plotsquared.iml create mode 100644 hooks/plotsquared/pom.xml create mode 100644 hooks/plotsquared/src/main/java/com/gb6/songoda/epicfurnaces/hooks/PlotSquaredHook.java create mode 100644 hooks/pom.xml create mode 100644 hooks/redprotect/hook.redprotect.iml create mode 100644 hooks/redprotect/pom.xml create mode 100644 hooks/redprotect/redprotect.iml create mode 100644 hooks/redprotect/src/main/java/com/songoda/epicfurnaces/hooks/RedProtectHook.java create mode 100644 hooks/towny/hook.towny.iml create mode 100644 hooks/towny/pom.xml create mode 100644 hooks/towny/src/main/java/com/songoda/epicfurnaces/hooks/TownyHook.java create mode 100644 hooks/towny/towny.iml create mode 100644 hooks/uskyblock/hook.uskyblock.iml create mode 100644 hooks/uskyblock/pom.xml create mode 100644 hooks/uskyblock/src/main/java/com/songoda/epicfurnaces/USkyBlockHook.java create mode 100644 hooks/uskyblock/uskyblock.iml create mode 100644 hooks/worldguard6/pom.xml create mode 100644 hooks/worldguard6/src/main/java/com/songoda/epicfurnaces/hooks/WorldGuard6Hook.java create mode 100644 hooks/worldguard6/worldguard6.iml create mode 100644 hooks/worldguard7/hook.worldguard.iml create mode 100644 hooks/worldguard7/pom.xml create mode 100644 hooks/worldguard7/src/main/java/com/songoda/epicfurnaces/hooks/WorldGuard7Hook.java create mode 100644 hooks/worldguard7/worldguard7.iml create mode 100644 pom.xml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6c17bc0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +out/ +.idea/ +*.iml/ +META-INF/ +target/ diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..6721e73 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,22 @@ +stages: +- build + +variables: + name: "EpicFurnaces" + path: "/builds/Songoda/$name" + version: "4.0.19" + +build: + stage: build + image: maven:3.5.3-jdk-8 + script: + - find $path/ -type f -name "*.xml" -print0 | xargs -0 sed -i -e s/maven-version-number/$version/g + - find $path/ -type f -name "*.yml" -print0 | xargs -0 sed -i -e s/maven-version-number/$version/g + - mvn clean package + - find $path/$name-Plugin/ -depth -path '*original*' -delete + - mv -v $path/$name-Plugin/target/*.jar $path + artifacts: + name: $name-$version + paths: + - "$path/*.jar" + - "$path/Read_this_before_your_first_use.txt" diff --git a/EpicFurnaces-Parent.iml b/EpicFurnaces-Parent.iml new file mode 100644 index 0000000..7bc53d3 --- /dev/null +++ b/EpicFurnaces-Parent.iml @@ -0,0 +1,22 @@ + + + + + + + SPIGOT + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/EpicFurnaces.iml b/EpicFurnaces.iml new file mode 100644 index 0000000..82e1f31 --- /dev/null +++ b/EpicFurnaces.iml @@ -0,0 +1,12 @@ + + + + + + + SPIGOT + + + + + \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2ddfa07 --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +Copyright (c) 2018 Brianna O’Keefe + +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 with minimal restriction, including the rights to use, copy, modify or merge while excluding the rights to publish, (re)distribute, sub-license, 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 same distribution rights and limitations above shall similarly apply to any and all source code, and other means that can be used to emulate this work. + +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. \ No newline at end of file diff --git a/README.MD b/README.MD new file mode 100644 index 0000000..3708135 --- /dev/null +++ b/README.MD @@ -0,0 +1,5 @@ +# EpicFurnaces + +EpicFurnaces allows you to upgrade basic Minecraft features to make the game way more entertaining. Currently, you can upgrade all furnaces to make it both faster and more rewarding. + +![N|Solid](https://i.imgur.com/jKtE7ZM.png) \ No newline at end of file diff --git a/Read_this_before_your_first_use.txt b/Read_this_before_your_first_use.txt new file mode 100644 index 0000000..181fc32 --- /dev/null +++ b/Read_this_before_your_first_use.txt @@ -0,0 +1,20 @@ +Hey loves, + +Thanks for downloading our plugin ^_^ In order to +run it you will need a plugin called arconix. It +basically takes a bunch of methods that we use all +over the place throughout our plugin lineup and +stores it in one place so we don't have to write +new code every time we need to get something simple +done. So make sure to stay up to date with the latest +updates for it. + +Link to download: +https://gitlab.com/Songoda/Arconix/-/jobs/artifacts/master/download?job=build + +If you need help you can always join our +discord in which is listed at the bottom of all of +our plugin pages. + +Enjoy <3 +Brianna & The Songoda Team. \ No newline at end of file diff --git a/core/core.iml b/core/core.iml new file mode 100644 index 0000000..49039f7 --- /dev/null +++ b/core/core.iml @@ -0,0 +1,44 @@ + + + + + + + SPIGOT + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/pom.xml b/core/pom.xml new file mode 100644 index 0000000..1dc0d27 --- /dev/null +++ b/core/pom.xml @@ -0,0 +1,168 @@ + + + 4.0.0 + + + EpicFurnaces-Parent + com.songoda + 4.0.19 + + + EpicFurnaces + jar + + EpicFurnaces + + + UTF-8 + + https://songoda.com/ + + + clean package + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-shade-plugin + 3.1.0 + + + package + + shade + + + false + true + + + + + + + + src/main/resources + true + + + + + + + maven.sainttx.com + http://maven.sainttx.com/nexus/content/groups/public/ + + + + + + org.spigotmc + spigot + 1.13.2 + provided + + + + net.milkbowl + vault + LATEST + provided + + + + com.songoda + arconix + LATEST + provided + + + com.songoda + manager + 4.0.19 + compile + + + com.songoda + craftbukkit-1-8-r1 + 4.0.19 + compile + + + com.songoda + craftbukkit-1-8-r3 + 4.0.19 + compile + + + com.songoda + craftbukkit-1-9 + 4.0.19 + compile + + + com.songoda + craftbukkit-1-8-r2 + 4.0.19 + compile + + + com.songoda + askyblock + 4.0.19 + compile + + + com.songoda + griefprevention + 4.0.19 + compile + + + com.songoda + kingdoms + 4.0.19 + compile + + + com.songoda + plotsquared + 4.0.19 + compile + + + com.songoda + towny + 4.0.19 + compile + + + com.songoda + uskyblock + 4.0.19 + compile + + + com.songoda + redprotect + 4.0.19 + compile + + + com.songoda + factions + 4.0.19 + compile + + + diff --git a/core/src/main/java/com/songoda/epicfurnaces/EpicFurnaces.java b/core/src/main/java/com/songoda/epicfurnaces/EpicFurnaces.java new file mode 100644 index 0000000..3d26a0b --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/EpicFurnaces.java @@ -0,0 +1,584 @@ +package com.songoda.epicfurnaces; + +import com.gb6.songoda.epicfurnaces.hooks.PlotSquaredHook; +import com.google.common.base.Preconditions; +import com.songoda.arconix.api.methods.formatting.TextComponent; +import com.songoda.arconix.api.methods.serialize.Serialize; +import com.songoda.arconix.api.utils.ConfigWrapper; +import com.songoda.arconix.plugin.Arconix; +import com.songoda.epicfurnaces.boost.BoostData; +import com.songoda.epicfurnaces.boost.BoostManager; +import com.songoda.epicfurnaces.command.CommandManager; +import com.songoda.epicfurnaces.furnace.FurnaceManager; +import com.songoda.epicfurnaces.furnace.FurnaceObject; +import com.songoda.epicfurnaces.furnace.LevelManager; +import com.songoda.epicfurnaces.handlers.BlacklistHandler; +import com.songoda.epicfurnaces.hook.CraftBukkitHook; +import com.songoda.epicfurnaces.hook.ProtectionPluginHook; +import com.songoda.epicfurnaces.hooks.*; +import com.songoda.epicfurnaces.listeners.BlockListeners; +import com.songoda.epicfurnaces.listeners.FurnaceListeners; +import com.songoda.epicfurnaces.listeners.InteractListeners; +import com.songoda.epicfurnaces.listeners.InventoryListeners; +import com.songoda.epicfurnaces.storage.Storage; +import com.songoda.epicfurnaces.storage.StorageItem; +import com.songoda.epicfurnaces.storage.StorageRow; +import com.songoda.epicfurnaces.storage.types.StorageMysql; +import com.songoda.epicfurnaces.storage.types.StorageYaml; +import com.songoda.epicfurnaces.tasks.FurnaceTask; +import com.songoda.epicfurnaces.tasks.HologramTask; +import com.songoda.epicfurnaces.utils.BukkitEnums; +import com.songoda.epicfurnaces.utils.Debugger; +import com.songoda.epicfurnaces.utils.Methods; +import com.songoda.epicfurnaces.utils.SettingsManager; +import com.songoda.epicfurnaces.utils.gui.FastInv; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.Player; +import org.bukkit.inventory.FurnaceRecipe; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.function.Supplier; + +public class EpicFurnaces extends JavaPlugin { + private static CommandSender console = Bukkit.getConsoleSender(); + private static EpicFurnaces instance; + private BlacklistHandler blacklistHandler; + private BoostManager boostManager; + private BukkitEnums bukkitEnums; + private CommandManager commandManager; + private CraftBukkitHook craftBukkitHook; + private int currentVersion; + private ConfigWrapper dataFile = new ConfigWrapper(this, "", "data.yml"); + private FurnaceManager furnaceManager; + private ConfigWrapper furnaceRecipeFile; + private HologramTask hologramTask; + private ConfigWrapper hooksFile = new ConfigWrapper(this, "", "hooks.yml"); + private ConfigWrapper langFile = new ConfigWrapper(this, "", "lang.yml"); + private LevelManager levelManager; + private Locale locale; + private List protectionHooks = new ArrayList<>(); + private References references = null; + private SettingsManager settingsManager; + private Storage storage; + + public static EpicFurnaces getInstance() { + return instance; + } + + private boolean checkVersion() { + String version = getServer().getClass().getPackage().getName().split("\\.")[3]; + currentVersion = Integer.parseInt(version.split("_")[1]); + int workingVersion = 8; + + if (currentVersion < workingVersion) { + Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> { + Bukkit.getConsoleSender().sendMessage(""); + Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "You installed the 1." + workingVersion + "+ version of " + + this.getDescription().getName() + " on a 1." + currentVersion + " server. " + + "We currently do not support " + currentVersion + " and below."); + Bukkit.getConsoleSender().sendMessage(""); + }); + return false; + } + + switch (version) { + case "v1_8_R1": + craftBukkitHook = new CraftBukkit18R1(); + break; + case "v1_8_R2": + craftBukkitHook = new CraftBukkit18R2(); + break; + case "v1_8_R3": + craftBukkitHook = new CraftBukkit18R3(); + break; + default: + craftBukkitHook = new CraftBukkit19(); + break; + } + + File config = new File(getDataFolder(), "Furnace Recipes.yml"); + if (!config.exists()) { + saveResource("Furnace Recipes.yml", false); + } + + if (currentVersion < 13) { + getLogger().info("Converting recipes to fit server version..."); + + Charset charset = StandardCharsets.UTF_8; + Path path = Paths.get(config.getAbsolutePath()); + + try { + String content = new String(Files.readAllBytes(path), charset); + content = content.replaceAll("GOLDEN", "GOLD") + .replaceAll("SHOVEL", "SPADE") + .replaceAll("WOODEN", "WOOD") + .replaceAll("CLOCK", "WATCH"); + Files.write(path, content.getBytes(charset)); + } catch (IOException e) { + e.printStackTrace(); + } + } + return true; + } + + @Override + public void onEnable() { + if (!checkVersion()) { + getPluginLoader().disablePlugin(this); + return; + } + + instance = this; + console.sendMessage(TextComponent.formatText("&a=============================")); + console.sendMessage(TextComponent.formatText("&7EpicFurnaces " + this.getDescription().getVersion() + " by &5Brianna <3&7!")); + console.sendMessage(TextComponent.formatText("&7Action: &aEnabling&7...")); + settingsManager = new SettingsManager(this); + setupConfig(); + dataFile.createNewFile("Loading data file", "EpicFurnaces data file"); + langFile.createNewFile("Loading language file", "EpicFurnaces language file"); + loadDataFile(); + + String langMode = getConfig().getString("System.Language Mode"); + Locale.init(this); + Locale.saveDefaultLocale("en_US"); + this.locale = Locale.getLocale(getConfig().getString("System.Language Mode", langMode)); + + if (getConfig().getBoolean("System.Download Needed Data Files")) { + this.update(); + } + + loadLevelManager(); + FastInv.init(this); + + this.furnaceManager = new FurnaceManager(); + this.commandManager = new CommandManager(this); + this.boostManager = new BoostManager(); + this.blacklistHandler = new BlacklistHandler(); + this.bukkitEnums = new BukkitEnums(this); + + this.checkStorage(); + + /* + * Register furnaces into FurnaceManger from configuration + */ + Bukkit.getScheduler().runTaskLater(this, () -> { + if (storage.containsGroup("charged")) { + for (StorageRow row : storage.getRowsByGroup("charged")) { + Location location = Serialize.getInstance().unserializeLocation(row.getKey()); + if (location == null || location.getBlock() == null) return; + + int level = row.get("level").asInt(); + int uses = row.get("uses").asInt(); + int toLevel = row.get("level").asInt(); + String nickname = row.get("nickname").asString(); + + List accessList = row.get("accesslist").asStringList(); + String placedByStr = row.get("placedBy").asString(); + UUID placedBy = placedByStr == null ? null : UUID.fromString(placedByStr); + + FurnaceObject furnace = new FurnaceObject(location, levelManager.getLevel(level), nickname, uses, toLevel, accessList, placedBy); + furnaceManager.addFurnace(location, furnace); + } + + } + + // Adding in Boosts + if (storage.containsGroup("boosts")) { + for (StorageRow row : storage.getRowsByGroup("boosts")) { + if (row.getItems().get("uuid").asObject() != null) + continue; + + BoostData boostData = new BoostData( + row.get("amount").asInt(), + Long.parseLong(row.getKey()), + UUID.fromString(row.get("uuid").asString())); + + this.boostManager.addBoostToPlayer(boostData); + } + } + + }, 10); + + setupRecipes(); + references = new References(); + + int timeout = getConfig().getInt("Main.Auto Save Interval In Seconds") * 60 * 20; + Bukkit.getScheduler().runTaskTimerAsynchronously(this, this::saveToFile, timeout, timeout); + + PluginManager pluginManager = Bukkit.getPluginManager(); + + // Start Tasks + this.hologramTask = HologramTask.startTask(this); + FurnaceTask.startTask(this); + + // Register Listeners + pluginManager.registerEvents(new BlockListeners(this), this); + pluginManager.registerEvents(new FurnaceListeners(this), this); + pluginManager.registerEvents(new InteractListeners(this), this); + pluginManager.registerEvents(new InventoryListeners(this), this); + + // Register default hooks + if (pluginManager.isPluginEnabled("ASkyBlock")) this.register(ASkyBlockHook::new); + if (pluginManager.isPluginEnabled("FactionsFramework")) this.register(FactionsHook::new); + if (pluginManager.isPluginEnabled("GriefPrevention")) this.register(GriefPreventionHook::new); + if (pluginManager.isPluginEnabled("Kingdoms")) this.register(KingdomsHook::new); + if (pluginManager.isPluginEnabled("PlotSquared")) this.register(PlotSquaredHook::new); + if (pluginManager.isPluginEnabled("RedProtect")) this.register(RedProtectHook::new); + if (pluginManager.isPluginEnabled("Towny")) this.register(TownyHook::new); + if (pluginManager.isPluginEnabled("USkyBlock")) this.register(USkyBlockHook::new); + // if (pluginManager.isPluginEnabled("WorldGuard")) this.register(WorldGuardHook::new); + + console.sendMessage(TextComponent.formatText("&a=============================")); + } + + private void loadLevelManager() { + // Load an instance of LevelManager + levelManager = new LevelManager(); + /* + * Register Levels into LevelManager from configuration. + */ + levelManager.clear(); + for (String levelName : getConfig().getConfigurationSection("settings.levels").getKeys(false)) { + int level = Integer.valueOf(levelName.split("-")[1]); + int costExperiance = getConfig().getInt("settings.levels." + levelName + ".Cost-xp"); + int costEconomy = getConfig().getInt("settings.levels." + levelName + ".Cost-eco"); + + String performanceStr = getConfig().getString("settings.levels." + levelName + ".Performance"); + int performance = performanceStr == null ? 0 : Integer.parseInt(performanceStr.substring(0, performanceStr.length() - 1)); + + String reward = getConfig().getString("settings.levels." + levelName + ".Reward"); + + String fuelDurationStr = getConfig().getString("settings.levels." + levelName + ".Fuel-duration"); + int fuelDuration = fuelDurationStr == null ? 0 : Integer.parseInt(fuelDurationStr.substring(0, fuelDurationStr.length() - 1)); + + int overheat = getConfig().getInt("settings.levels." + levelName + ".Overheat"); + int fuelShare = getConfig().getInt("settings.levels." + levelName + ".Fuel-share"); + + levelManager.addLevel(level, costExperiance, costEconomy, performance, reward, fuelDuration, overheat, fuelShare); + } + } + + private void checkStorage() { + if (getConfig().getBoolean("Database.Activate Mysql Support")) { + this.storage = new StorageMysql(this); + } else { + this.storage = new StorageYaml(this); + } + } + + /* + * Saves registered furnaces to file. + */ + private void saveToFile() { + + this.storage.closeConnection(); + checkStorage(); + + /* + * Dump FurnaceManager to file. + */ + for (FurnaceObject furnace : furnaceManager.getFurnaces().values()) { + if (furnace == null || furnace.getLocation() == null || furnace.getLocation().getWorld() == null) continue; + String locationStr = Arconix.pl().getApi().serialize().serializeLocation(furnace.getLocation()); + + storage.prepareSaveItem("charged", + new StorageItem("location", locationStr), + new StorageItem("level", furnace.getLevel().getLevel()), + new StorageItem("uses", furnace.getUses()), + new StorageItem("tolevel", furnace.getToLevel()), + new StorageItem("nickname", furnace.getNickname()), + new StorageItem("accesslist", furnace.getOriginalAccessList()), + new StorageItem("placedby", furnace.getPlacedBy() == null ? null : furnace.getPlacedBy().toString())); + } + + /* + * Dump BoostManager to file. + */ + for (BoostData boostData : boostManager.getBoosts()) { + storage.prepareSaveItem("boosts", new StorageItem("endtime", String.valueOf(boostData.getEndTime())), + new StorageItem("amount", boostData.getMultiplier()), + new StorageItem("uuid", boostData.getPlayer().toString())); + } + + storage.doSave(); + + } + + private void setupConfig() { + settingsManager.updateSettings(); + + getConfig().addDefault("settings.levels.Level-1.Performance", "10%"); + getConfig().addDefault("settings.levels.Level-1.Reward", "10%:1"); + getConfig().addDefault("settings.levels.Level-1.Cost-xp", 20); + getConfig().addDefault("settings.levels.Level-1.Cost-eco", 5000); + + getConfig().addDefault("settings.levels.Level-2.Performance", "25%"); + getConfig().addDefault("settings.levels.Level-2.Reward", "20%:1-2"); + getConfig().addDefault("settings.levels.Level-2.Cost-xp", 25); + getConfig().addDefault("settings.levels.Level-2.Cost-eco", 7500); + + getConfig().addDefault("settings.levels.Level-3.Performance", "40%"); + getConfig().addDefault("settings.levels.Level-3.Reward", "35%:2-3"); + getConfig().addDefault("settings.levels.Level-3.Fuel-duration", "10%"); + getConfig().addDefault("settings.levels.Level-3.Cost-xp", 30); + getConfig().addDefault("settings.levels.Level-3.Cost-eco", 10000); + + getConfig().addDefault("settings.levels.Level-4.Performance", "55%"); + getConfig().addDefault("settings.levels.Level-4.Reward", "50%:2-4"); + getConfig().addDefault("settings.levels.Level-4.Fuel-duration", "25%"); + getConfig().addDefault("settings.levels.Level-4.Cost-xp", 35); + getConfig().addDefault("settings.levels.Level-4.Cost-eco", 12000); + + getConfig().addDefault("settings.levels.Level-5.Performance", "75%"); + getConfig().addDefault("settings.levels.Level-5.Reward", "70%:3-4"); + getConfig().addDefault("settings.levels.Level-5.Fuel-duration", "45%"); + getConfig().addDefault("settings.levels.Level-5.Overheat", 1); + getConfig().addDefault("settings.levels.Level-5.Cost-xp", 40); + getConfig().addDefault("settings.levels.Level-5.Cost-eco", 15000); + + getConfig().addDefault("settings.levels.Level-6.Performance", "75%"); + getConfig().addDefault("settings.levels.Level-6.Reward", "70%:3-4"); + getConfig().addDefault("settings.levels.Level-6.Fuel-duration", "45%"); + getConfig().addDefault("settings.levels.Level-6.Overheat", 2); + getConfig().addDefault("settings.levels.Level-6.Fuel-share", 1); + getConfig().addDefault("settings.levels.Level-6.Cost-xp", 40); + getConfig().addDefault("settings.levels.Level-6.Cost-eco", 15000); + + getConfig().options().copyDefaults(true); + saveConfig(); + } + + private void update() { + try { + URL url = new URL("http://update.songoda.com/index.php?plugin=" + getDescription().getName() + "&version=" + getDescription().getVersion()); + URLConnection urlConnection = url.openConnection(); + InputStream is = urlConnection.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + + int numCharsRead; + char[] charArray = new char[1024]; + StringBuilder sb = new StringBuilder(); + while ((numCharsRead = isr.read(charArray)) > 0) { + sb.append(charArray, 0, numCharsRead); + } + String jsonString = sb.toString(); + JSONObject json = (JSONObject) new JSONParser().parse(jsonString); + + JSONArray files = (JSONArray) json.get("neededFiles"); + for (Object o : files) { + JSONObject file = (JSONObject) o; + + if ("locale".equals((String) file.get("type"))) { + InputStream in = new URL((String) file.get("link")).openStream(); + Locale.saveDefaultLocale(in, (String) file.get("name")); + } + } + } catch (Exception e) { + System.out.println("Failed to update."); + //e.printStackTrace(); + } + } + + public void reload() { + String langMode = getConfig().getString("System.Language Mode"); + this.locale = Locale.getLocale(getConfig().getString("System.Language Mode", langMode)); + this.locale.reloadMessages(); + this.settingsManager.updateSettings(); + this.blacklistHandler.reload(); + references = new References(); + this.setupConfig(); + } + + private void loadDataFile() { + dataFile.getConfig().options().copyDefaults(true); + dataFile.saveConfig(); + } + + private void setupRecipes() { + furnaceRecipeFile = new ConfigWrapper(this, "", "Furnace Recipes.yml"); + if (!getConfig().getBoolean("Main.Use Custom Recipes")) { + return; + } + + ConfigurationSection cs = furnaceRecipeFile.getConfig().getConfigurationSection("Recipes"); + for (String key : cs.getKeys(false)) { + Material item; + try { + item = Material.valueOf(key.toUpperCase()); + } catch (IllegalArgumentException e) { + getLogger().info("Invalid material from recipes files: " + key.toUpperCase()); + continue; + } + + Material result; + try { + result = Material.valueOf(furnaceRecipeFile.getConfig().getString("Recipes." + key.toUpperCase() + ".result")); + } catch (IllegalArgumentException e) { + getLogger().info("Invalid material from recipes files: " + furnaceRecipeFile.getConfig().getString("Recipes." + key.toUpperCase() + ".result")); + continue; + } + + int amount = furnaceRecipeFile.getConfig().getInt("Recipes." + key.toUpperCase() + ".amount"); +// System.out.println("Adding- " + item.toString() + ":" + result.toString()); + + getServer().addRecipe(new FurnaceRecipe(new ItemStack(result, amount), item)); + } + + } + + public ItemStack createLeveledFurnace(int level, int uses) { + ItemStack item = new ItemStack(Material.FURNACE, 1); + ItemMeta itemmeta = item.getItemMeta(); + + if (getConfig().getBoolean("Main.Remember Furnace Item Levels")) { + itemmeta.setDisplayName(TextComponent.formatText(Methods.formatName(level, uses, true))); + } + + item.setItemMeta(itemmeta); + return item; + } + + private void register(Supplier hookSupplier) { + this.registerProtectionHook(hookSupplier.get()); + } + + public void registerProtectionHook(ProtectionPluginHook hook) { + Preconditions.checkNotNull(hook, "Cannot register null hooks"); + Preconditions.checkNotNull(hook.getPlugin(), "Protection plugin hooks returns null plugin instance (#getPlugin())"); + + JavaPlugin hookPlugin = hook.getPlugin(); + for (ProtectionPluginHook existingHook : protectionHooks) { + if (existingHook.getPlugin().equals(hookPlugin)) { + throw new IllegalArgumentException("Hook already registered"); + } + } + + this.hooksFile.getConfig().addDefault("hooks." + hookPlugin.getName(), true); + if (!hooksFile.getConfig().getBoolean("hooks." + hookPlugin.getName(), true)) return; + this.hooksFile.getConfig().options().copyDefaults(true); + this.hooksFile.saveConfig(); + + this.protectionHooks.add(hook); + this.getLogger().info("Registered protection hooks for plugin: " + hook.getPlugin().getName()); + } + + public boolean canBuild(Player player, Location location) { + if (player.hasPermission(getDescription().getName() + ".bypass")) { + return true; + } + + for (ProtectionPluginHook hook : protectionHooks) + if (!hook.canBuild(player, location)) return false; + return true; + } + + public int getFurnceLevel(ItemStack item) { + try { + if (item.getItemMeta().getDisplayName().contains(":")) { + String[] arr = (item.getItemMeta().getDisplayName().replace("§", "")).split(":"); + return Integer.parseInt(arr[0]); + } else { + return 1; + } + + } catch (Exception e) { + Debugger.runReport(e); + } + return 9999; + } + + public int getFurnaceUses(ItemStack item) { + try { + if (item.getItemMeta().getDisplayName().contains(":")) { + String[] arr = (item.getItemMeta().getDisplayName().replace("§", "")).split(":"); + return Integer.parseInt(arr[1]); + } else { + return 0; + } + } catch (Exception e) { + Debugger.runReport(e); + } + return 9999; + } + + public BlacklistHandler getBlacklistHandler() { + return blacklistHandler; + } + + public BoostManager getBoostManager() { + return boostManager; + } + + public CommandManager getCommandManager() { + return commandManager; + } + + public ConfigWrapper getDataFile() { + return dataFile; + } + + public FurnaceManager getFurnaceManager() { + return furnaceManager; + } + + public ConfigWrapper getFurnaceRecipeFile() { + return furnaceRecipeFile; + } + + public HologramTask getHologramTask() { + return hologramTask; + } + + public LevelManager getLevelManager() { + return levelManager; + } + + public Locale getLocale() { + return locale; + } + + public References getReferences() { + return references; + } + + public SettingsManager getSettingsManager() { + return settingsManager; + } + + public CraftBukkitHook getCraftBukkitHook() { + return craftBukkitHook; + } + + public int getCurrentVersion() { + return currentVersion; + } + + public BukkitEnums getBukkitEnums() { + return bukkitEnums; + } +} \ No newline at end of file diff --git a/core/src/main/java/com/songoda/epicfurnaces/Locale.java b/core/src/main/java/com/songoda/epicfurnaces/Locale.java new file mode 100644 index 0000000..80de95f --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/Locale.java @@ -0,0 +1,377 @@ +package com.songoda.epicfurnaces; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Lists; +import org.bukkit.ChatColor; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * Assists in the creation of multiple localizations and languages, + * as well as the generation of default .lang files + * + * @author Parker Hawke - 2008Choco + */ +public class Locale { + + private static final List LOCALES = Lists.newArrayList(); + private static final Pattern NODE_PATTERN = Pattern.compile("(\\w+(?:\\.{1}\\w+)*)\\s*=\\s*\"(.*)\""); + private static final String FILE_EXTENSION = ".lang"; + private static JavaPlugin plugin; + private static File localeFolder; + + private static String defaultLocale; + + private final Map nodes = new HashMap<>(); + + private final File file; + private final String name, region; + + private Locale(String name, String region) { + if (plugin == null) + throw new IllegalStateException("Cannot generate locales without first initializing the class (Locale#init(JavaPlugin))"); + + this.name = name.toLowerCase(); + this.region = region.toUpperCase(); + + String fileName = name + "_" + region + FILE_EXTENSION; + this.file = new File(localeFolder, fileName); + + if (this.reloadMessages()) return; + + plugin.getLogger().info("Loaded locale " + fileName); + } + + /** + * Initialize the locale class to generate information and search for localizations. + * This must be called before any other methods in the Locale class can be invoked. + * Note that this will also call {@link #searchForLocales()}, so there is no need to + * invoke it for yourself after the initialization + * + * @param plugin the plugin instance + */ + public static void init(JavaPlugin plugin) { + Locale.plugin = plugin; + + if (localeFolder == null) { + localeFolder = new File(plugin.getDataFolder(), "locales/"); + } + + localeFolder.mkdirs(); + Locale.searchForLocales(); + } + + /** + * Find all .lang file locales under the "locales" folder + */ + public static void searchForLocales() { + if (!localeFolder.exists()) { + localeFolder.mkdirs(); + } + + for (File file : localeFolder.listFiles()) { + String name = file.getName(); + if (!name.endsWith(".lang")) continue; + + String fileName = name.substring(0, name.lastIndexOf('.')); + String[] localeValues = fileName.split("_"); + + if (localeValues.length != 2) continue; + if (localeExists(localeValues[0] + "_" + localeValues[1])) continue; + + LOCALES.add(new Locale(localeValues[0], localeValues[1])); + plugin.getLogger().info("Found and loaded locale \"" + fileName + "\""); + } + } + + /** + * Get a locale by its entire proper name (i.e. "en_US") + * + * @param name the full name of the locale + * @return locale of the specified name + */ + public static Locale getLocale(String name) { + for (Locale locale : LOCALES) + if (locale.getLanguageTag().equalsIgnoreCase(name)) return locale; + return null; + } + + /** + * Get a locale from the cache by its name (i.e. "en" from "en_US") + * + * @param name the name of the language + * @return locale of the specified language. Null if not cached + */ + public static Locale getLocaleByName(String name) { + for (Locale locale : LOCALES) + if (locale.getName().equalsIgnoreCase(name)) return locale; + return null; + } + + /** + * Get a locale from the cache by its region (i.e. "US" from "en_US") + * + * @param region the name of the region + * @return locale of the specified region. Null if not cached + */ + public static Locale getLocaleByRegion(String region) { + for (Locale locale : LOCALES) + if (locale.getRegion().equalsIgnoreCase(region)) return locale; + return null; + } + + /** + * Check whether a locale exists and is registered or not + * + * @param name the whole language tag (i.e. "en_US") + * @return true if it exists + */ + public static boolean localeExists(String name) { + for (Locale locale : LOCALES) + if (locale.getLanguageTag().equals(name)) return true; + return false; + } + + /** + * Get an immutable list of all currently loaded locales + * + * @return list of all locales + */ + public static List getLocales() { + return ImmutableList.copyOf(LOCALES); + } + + /** + * Save a default locale file from the project source directory, to the locale folder + * + * @param in file to save + * @param fileName the name of the file to save + * @return true if the operation was successful, false otherwise + */ + public static boolean saveDefaultLocale(InputStream in, String fileName) { + if (!localeFolder.exists()) localeFolder.mkdirs(); + + if (!fileName.endsWith(FILE_EXTENSION)) + fileName = (fileName.lastIndexOf(".") == -1 ? fileName : fileName.substring(0, fileName.lastIndexOf('.'))) + FILE_EXTENSION; + + File destinationFile = new File(localeFolder, fileName); + if (destinationFile.exists()) { + return compareFiles(plugin.getResource(fileName), destinationFile); + } + + try (OutputStream outputStream = new FileOutputStream(destinationFile)) { + copy(in == null ? plugin.getResource(fileName) : in, outputStream); + + fileName = fileName.substring(0, fileName.lastIndexOf('.')); + String[] localeValues = fileName.split("_"); + + if (localeValues.length != 2) return false; + + LOCALES.add(new Locale(localeValues[0], localeValues[1])); + if (defaultLocale == null) defaultLocale = fileName; + + return true; + } catch (IOException e) { + return false; + } + } + + /** + * Save a default locale file from the project source directory, to the locale folder + * + * @param fileName the name of the file to save + * @return true if the operation was successful, false otherwise + */ + public static boolean saveDefaultLocale(String fileName) { + return saveDefaultLocale(null, fileName); + } + + /** + * Clear all current locale data + */ + public static void clearLocaleData() { + for (Locale locale : LOCALES) + locale.nodes.clear(); + LOCALES.clear(); + } + + // Write new changes to existing files, if any at all + private static boolean compareFiles(InputStream defaultFile, File existingFile) { + // Look for default + if (defaultFile == null) { + defaultFile = plugin.getResource(defaultLocale != null ? defaultLocale : "en_US"); + if (defaultFile == null) return false; // No default at all + } + + boolean changed = false; + + List defaultLines, existingLines; + try (BufferedReader defaultReader = new BufferedReader(new InputStreamReader(defaultFile)); + BufferedReader existingReader = new BufferedReader(new FileReader(existingFile)); + BufferedWriter writer = new BufferedWriter(new FileWriter(existingFile, true))) { + defaultLines = defaultReader.lines().collect(Collectors.toList()); + existingLines = existingReader.lines().map(s -> s.split("\\s*=")[0]).collect(Collectors.toList()); + + for (String defaultValue : defaultLines) { + if (defaultValue.isEmpty() || defaultValue.startsWith("#")) continue; + + String key = defaultValue.split("\\s*=")[0]; + + if (!existingLines.contains(key)) { + if (!changed) { + writer.newLine(); + writer.newLine(); + writer.write("# New messages for " + plugin.getName() + " v" + plugin.getDescription().getVersion()); + } + + writer.newLine(); + writer.write(defaultValue); + + changed = true; + } + } + } catch (IOException e) { + return false; + } + + return changed; + } + + private static void copy(InputStream input, OutputStream output) { + int n; + byte[] buffer = new byte[1024 * 4]; + + try { + while ((n = input.read(buffer)) != -1) { + output.write(buffer, 0, n); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * Get the name of the language that this locale is based on. + * (i.e. "en" for English, or "fr" for French) + * + * @return the name of the language + */ + public String getName() { + return name; + } + + /** + * Get the name of the region that this locale is from. + * (i.e. "US" for United States or "CA" for Canada) + * + * @return the name of the region + */ + public String getRegion() { + return region; + } + + /** + * Return the entire locale tag (i.e. "en_US") + * + * @return the language tag + */ + public String getLanguageTag() { + return name + "_" + region; + } + + /** + * Get the file that represents this locale + * + * @return the locale file (.lang) + */ + public File getFile() { + return file; + } + + /** + * Get a message set for a specific node + * + * @param node the node to get + * @return the message for the specified node + */ + public String getMessage(String node) { + return ChatColor.translateAlternateColorCodes('&', this.getMessageOrDefault(node, node)); + } + + /** + * Get a message set for a specific node and replace its params with a supplied arguments. + * + * @param node the node to get + * @param args the replacement arguments + * @return the message for the specified node + */ + public String getMessage(String node, Object... args) { + String message = getMessage(node); + for (Object arg : args) { + message = message.replaceFirst("%.*?%", arg.toString()); + } + return message; + } + + /** + * Get a message set for a specific node + * + * @param node the node to get + * @param defaultValue the default value given that a value for the node was not found + * @return the message for the specified node. Default if none found + */ + public String getMessageOrDefault(String node, String defaultValue) { + return this.nodes.getOrDefault(node, defaultValue); + } + + /** + * Get the key-value map of nodes to messages + * + * @return node-message map + */ + public Map getMessageNodeMap() { + return ImmutableMap.copyOf(nodes); + } + + /** + * Clear the previous message cache and load new messages directly from file + * + * @return reload messages from file + */ + public boolean reloadMessages() { + if (!this.file.exists()) { + plugin.getLogger().warning("Could not find file for locale " + this.name); + return false; + } + + this.nodes.clear(); // Clear previous data (if any) + + try (BufferedReader reader = new BufferedReader(new FileReader(file))) { + String line; + for (int lineNumber = 0; (line = reader.readLine()) != null; lineNumber++) { + if (line.isEmpty() || line.startsWith("#") /* Comment */) continue; + + Matcher matcher = NODE_PATTERN.matcher(line); + if (!matcher.find()) { + System.err.println("Invalid locale syntax at (line=" + lineNumber + ")"); + continue; + } + + nodes.put(matcher.group(1), matcher.group(2)); + } + } catch (IOException e) { + e.printStackTrace(); + return false; + } + return true; + } + +} \ No newline at end of file diff --git a/core/src/main/java/com/songoda/epicfurnaces/References.java b/core/src/main/java/com/songoda/epicfurnaces/References.java new file mode 100644 index 0000000..e15c468 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/References.java @@ -0,0 +1,14 @@ +package com.songoda.epicfurnaces; + +public class References { + + private String prefix; + + public References() { + prefix = EpicFurnaces.getInstance().getLocale().getMessage("general.nametag.prefix") + " "; + } + + public String getPrefix() { + return this.prefix; + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/boost/BoostData.java b/core/src/main/java/com/songoda/epicfurnaces/boost/BoostData.java new file mode 100644 index 0000000..b7d2dbc --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/boost/BoostData.java @@ -0,0 +1,50 @@ +package com.songoda.epicfurnaces.boost; + +import java.util.Objects; +import java.util.UUID; + +public class BoostData { + + private final int multiplier; + private final long endTime; + private final UUID player; + + public BoostData(int multiplier, long endTime, UUID player) { + this.multiplier = multiplier; + this.endTime = endTime; + this.player = player; + } + + public int getMultiplier() { + return multiplier; + } + + public UUID getPlayer() { + return player; + } + + public long getEndTime() { + return endTime; + } + + @Override + public int hashCode() { + int result = 31 * multiplier; + + result = 31 * result + (this.player == null ? 0 : player.hashCode()); + result = 31 * result + (int) (endTime ^ (endTime >>> 32)); + + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (!(obj instanceof BoostData)) return false; + + BoostData other = (BoostData) obj; + return multiplier == other.multiplier && endTime == other.endTime + && Objects.equals(player, other.player); + } + +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/boost/BoostManager.java b/core/src/main/java/com/songoda/epicfurnaces/boost/BoostManager.java new file mode 100644 index 0000000..c478ca0 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/boost/BoostManager.java @@ -0,0 +1,36 @@ +package com.songoda.epicfurnaces.boost; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +public class BoostManager { + + private final Set registeredBoosts = new HashSet<>(); + + public void addBoostToPlayer(BoostData data) { + this.registeredBoosts.add(data); + } + + public void removeBoostFromPlayer(BoostData data) { + this.registeredBoosts.remove(data); + } + + public Set getBoosts() { + return Collections.unmodifiableSet(registeredBoosts); + } + + public BoostData getBoost(UUID player) { + if (player == null) return null; + for (BoostData boostData : registeredBoosts) { + if (boostData.getPlayer().toString().equals(player.toString())) { + if (System.currentTimeMillis() >= boostData.getEndTime()) { + removeBoostFromPlayer(boostData); + } + return boostData; + } + } + return null; + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/command/AbstractCommand.java b/core/src/main/java/com/songoda/epicfurnaces/command/AbstractCommand.java new file mode 100644 index 0000000..79169ca --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/command/AbstractCommand.java @@ -0,0 +1,38 @@ +package com.songoda.epicfurnaces.command; + +import org.bukkit.command.CommandSender; + +public abstract class AbstractCommand { + + private final AbstractCommand parent; + private final String command; + private final boolean noConsole; + + protected AbstractCommand(String command, AbstractCommand parent, boolean noConsole) { + this.command = command; + this.parent = parent; + this.noConsole = noConsole; + } + + public AbstractCommand getParent() { + return parent; + } + + public String getCommand() { + return command; + } + + public boolean isNoConsole() { + return noConsole; + } + + protected abstract ReturnType runCommand(CommandSender sender, String... args); + + public abstract String getPermissionNode(); + + public abstract String getSyntax(); + + public abstract String getDescription(); + + public enum ReturnType {SUCCESS, FAILURE, SYNTAX_ERROR} +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/command/CommandManager.java b/core/src/main/java/com/songoda/epicfurnaces/command/CommandManager.java new file mode 100644 index 0000000..36e404c --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/command/CommandManager.java @@ -0,0 +1,79 @@ +package com.songoda.epicfurnaces.command; + +import com.songoda.arconix.api.methods.formatting.TextComponent; +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.command.commands.*; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class CommandManager implements CommandExecutor { + + private EpicFurnaces instance; + + private List commands = new ArrayList<>(); + + public CommandManager(EpicFurnaces instance) { + this.instance = instance; + + instance.getCommand("EpicFurnaces").setExecutor(this); + + AbstractCommand commandEpicFurnaces = addCommand(new CommandEpicFurnaces(instance)); + + addCommand(new CommandReload(instance, commandEpicFurnaces)); + addCommand(new CommandRemote(instance, commandEpicFurnaces)); + addCommand(new CommandSettings(instance, commandEpicFurnaces)); + addCommand(new CommandGive(instance, commandEpicFurnaces)); + addCommand(new CommandBoost(instance, commandEpicFurnaces)); + } + + private AbstractCommand addCommand(AbstractCommand abstractCommand) { + commands.add(abstractCommand); + return abstractCommand; + } + + @Override + public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { + for (AbstractCommand abstractCommand : commands) { + if (abstractCommand.getCommand().equalsIgnoreCase(command.getName())) { + if (strings.length == 0) { + processRequirements(abstractCommand, commandSender, strings); + return true; + } + } else if (strings.length != 0 && abstractCommand.getParent() != null && abstractCommand.getParent().getCommand().equalsIgnoreCase(command.getName())) { + String cmd = strings[0]; + if (cmd.equalsIgnoreCase(abstractCommand.getCommand())) { + processRequirements(abstractCommand, commandSender, strings); + return true; + } + } + } + commandSender.sendMessage(instance.getReferences().getPrefix() + TextComponent.formatText("&7The command you entered does not exist or is spelt incorrectly.")); + return true; + } + + private void processRequirements(AbstractCommand command, CommandSender sender, String[] strings) { + if (!(sender instanceof Player) && command.isNoConsole()) { + sender.sendMessage("You must be a player to use this command."); + return; + } + if (command.getPermissionNode() == null || sender.hasPermission(command.getPermissionNode())) { + AbstractCommand.ReturnType returnType = command.runCommand(sender, strings); + if (returnType == AbstractCommand.ReturnType.SYNTAX_ERROR) { + sender.sendMessage(instance.getReferences().getPrefix() + TextComponent.formatText("&cInvalid Syntax!")); + sender.sendMessage(instance.getReferences().getPrefix() + TextComponent.formatText("&7The valid syntax is: &6" + command.getSyntax() + "&7.")); + } + return; + } + sender.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("event.general.nopermission")); + } + + public List getCommands() { + return Collections.unmodifiableList(commands); + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandBoost.java b/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandBoost.java new file mode 100644 index 0000000..517ad34 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandBoost.java @@ -0,0 +1,87 @@ +package com.songoda.epicfurnaces.command.commands; + +import com.songoda.arconix.api.methods.formatting.TextComponent; +import com.songoda.arconix.api.methods.math.AMath; +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.boost.BoostData; +import com.songoda.epicfurnaces.command.AbstractCommand; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; + +import java.util.Calendar; +import java.util.Date; + +public class CommandBoost extends AbstractCommand { + private final EpicFurnaces instance; + + public CommandBoost(EpicFurnaces instance, AbstractCommand parent) { + super("boost", parent, false); + this.instance = instance; + } + + @Override + protected ReturnType runCommand(CommandSender sender, String... args) { + if (args.length < 3) { + return ReturnType.SYNTAX_ERROR; + } + + if (Bukkit.getPlayer(args[1]) == null) { + sender.sendMessage(TextComponent.formatText(instance.getReferences().getPrefix() + "&cThat player does not exist...")); + return ReturnType.FAILURE; + } else if (!AMath.isInt(args[2])) { + sender.sendMessage(TextComponent.formatText(instance.getReferences().getPrefix() + "&6" + args[2] + " &7is not a number...")); + return ReturnType.FAILURE; + } else { + Calendar c = Calendar.getInstance(); + Date currentDate = new Date(); + c.setTime(currentDate); + + String time = "&7."; + + if (args.length > 3) { + if (args[3].contains("m:")) { + String[] arr2 = (args[3]).split(":"); + c.add(Calendar.MINUTE, Integer.parseInt(arr2[1])); + time = " &7for &6" + arr2[1] + " minutes&7."; + } else if (args[3].contains("h:")) { + String[] arr2 = (args[3]).split(":"); + c.add(Calendar.HOUR, Integer.parseInt(arr2[1])); + time = " &7for &6" + arr2[1] + " hours&7."; + } else if (args[3].contains("d:")) { + String[] arr2 = (args[3]).split(":"); + c.add(Calendar.HOUR, Integer.parseInt(arr2[1]) * 24); + time = " &7for &6" + arr2[1] + " days&7."; + } else if (args[3].contains("y:")) { + String[] arr2 = (args[3]).split(":"); + c.add(Calendar.YEAR, Integer.parseInt(arr2[1])); + time = " &7for &6" + arr2[1] + " years&7."; + } else { + sender.sendMessage(TextComponent.formatText(instance.getReferences().getPrefix() + "&7" + args[3] + " &7is invalid.")); + return ReturnType.SUCCESS; + } + } else { + c.add(Calendar.YEAR, 10); + } + + BoostData boostData = new BoostData(Integer.parseInt(args[2]), c.getTime().getTime(), Bukkit.getPlayer(args[1]).getUniqueId()); + instance.getBoostManager().addBoostToPlayer(boostData); + sender.sendMessage(TextComponent.formatText(instance.getReferences().getPrefix() + "&7Successfully boosted &6" + Bukkit.getPlayer(args[1]).getName() + "'s &7furnaces reward amounts by &6" + args[2] + "x" + time)); + } + return ReturnType.FAILURE; + } + + @Override + public String getPermissionNode() { + return "epicfurnaces.admin"; + } + + @Override + public String getSyntax() { + return "/ef boost [m:minute, h:hour, d:day, y:year]"; + } + + @Override + public String getDescription() { + return "This allows you to boost a players furnace reward amounts by a multiplier (Put 2 for double, 3 for triple and so on)."; + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandEpicFurnaces.java b/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandEpicFurnaces.java new file mode 100644 index 0000000..76b515b --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandEpicFurnaces.java @@ -0,0 +1,46 @@ +package com.songoda.epicfurnaces.command.commands; + +import com.songoda.arconix.api.methods.formatting.TextComponent; +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.command.AbstractCommand; +import org.bukkit.command.CommandSender; + +public class CommandEpicFurnaces extends AbstractCommand { + private final EpicFurnaces instance; + + public CommandEpicFurnaces(EpicFurnaces instance) { + super("EpicFurnaces", null, false); + this.instance = instance; + + } + + @Override + protected ReturnType runCommand(CommandSender sender, String... args) { + sender.sendMessage(""); + sender.sendMessage(TextComponent.formatText(instance.getReferences().getPrefix() + "&7Version " + instance.getDescription().getVersion() + " Created with <3 by &5&l&oBrianna")); + + for (AbstractCommand command : instance.getCommandManager().getCommands()) { + if (command.getPermissionNode() == null || sender.hasPermission(command.getPermissionNode())) { + sender.sendMessage(TextComponent.formatText("&8 - &a" + command.getSyntax() + "&7 - " + command.getDescription())); + } + } + sender.sendMessage(""); + + return ReturnType.SUCCESS; + } + + @Override + public String getDescription() { + return "Displays this page."; + } + + @Override + public String getPermissionNode() { + return null; + } + + @Override + public String getSyntax() { + return "/EpicFurnaces"; + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandGive.java b/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandGive.java new file mode 100644 index 0000000..4c8fae2 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandGive.java @@ -0,0 +1,69 @@ +package com.songoda.epicfurnaces.command.commands; + +import com.songoda.arconix.plugin.Arconix; +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.command.AbstractCommand; +import com.songoda.epicfurnaces.furnace.Level; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class CommandGive extends AbstractCommand { + private final EpicFurnaces instance; + + public CommandGive(EpicFurnaces instance, AbstractCommand parent) { + super("give", parent, false); + this.instance = instance; + + } + + @Override + protected ReturnType runCommand(CommandSender sender, String... args) { + if (args.length == 2) { + return ReturnType.SYNTAX_ERROR; + } + + Level level = instance.getLevelManager().getLowestLevel(); + Player player; + if (args.length != 1 && Bukkit.getPlayer(args[1]) == null) { + sender.sendMessage(instance.getReferences().getPrefix() + Arconix.pl().getApi().format().formatText("&cThat player does not exist or is currently offline.")); + return ReturnType.FAILURE; + } else if (args.length == 1) { + if (!(sender instanceof Player)) { + sender.sendMessage(instance.getReferences().getPrefix() + Arconix.pl().getApi().format().formatText("&cYou need to be a player to give a farm item to yourself.")); + return ReturnType.FAILURE; + } + player = (Player) sender; + } else { + player = Bukkit.getPlayer(args[1]); + } + + + if (args.length >= 3 && !instance.getLevelManager().isLevel(Integer.parseInt(args[2]))) { + sender.sendMessage(instance.getReferences().getPrefix() + Arconix.pl().getApi().format().formatText("&cNot a valid level... The current valid levels are: &4" + instance.getLevelManager().getLowestLevel().getLevel() + "-" + instance.getLevelManager().getHighestLevel().getLevel() + "&c.")); + return ReturnType.FAILURE; + } else if (args.length != 1) { + + level = instance.getLevelManager().getLevel(Integer.parseInt(args[2])); + } + player.getInventory().addItem(instance.createLeveledFurnace(level.getLevel(), 0)); + player.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("command.give.success", level.getLevel())); + + return ReturnType.SUCCESS; + } + + @Override + public String getPermissionNode() { + return "epicfurnaces.admin"; + } + + @Override + public String getSyntax() { + return "/ef give [player] "; + } + + @Override + public String getDescription() { + return "Give a leveled furnace to a player."; + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandReload.java b/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandReload.java new file mode 100644 index 0000000..e7480c7 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandReload.java @@ -0,0 +1,37 @@ +package com.songoda.epicfurnaces.command.commands; + +import com.songoda.arconix.api.methods.formatting.TextComponent; +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.command.AbstractCommand; +import org.bukkit.command.CommandSender; + +public class CommandReload extends AbstractCommand { + private final EpicFurnaces instance; + + public CommandReload(EpicFurnaces instance, AbstractCommand parent) { + super("reload", parent, false); + this.instance = instance; + } + + @Override + protected ReturnType runCommand(CommandSender sender, String... args) { + instance.reload(); + sender.sendMessage(TextComponent.formatText(instance.getReferences().getPrefix() + "&7Configuration and Language files reloaded.")); + return ReturnType.SUCCESS; + } + + @Override + public String getPermissionNode() { + return "epicfurnaces.admin"; + } + + @Override + public String getSyntax() { + return "/ef reload"; + } + + @Override + public String getDescription() { + return "Reload the Configuration and Language files."; + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandRemote.java b/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandRemote.java new file mode 100644 index 0000000..57a99e2 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandRemote.java @@ -0,0 +1,76 @@ +package com.songoda.epicfurnaces.command.commands; + +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.command.AbstractCommand; +import com.songoda.epicfurnaces.furnace.FurnaceObject; +import org.bukkit.block.Block; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.UUID; + +public class CommandRemote extends AbstractCommand { + private final EpicFurnaces instance; + + public CommandRemote(EpicFurnaces instance, AbstractCommand abstractCommand) { + super("remote", abstractCommand, true); + this.instance = instance; + } + + @Override + protected ReturnType runCommand(CommandSender sender, String... args) { + if (!instance.getConfig().getBoolean("Main.Access Furnaces Remotely") || !sender.hasPermission("EpicFurnaces.Remote")) { + sender.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("event.general.nopermission")); + return ReturnType.FAILURE; + } + + if (!instance.getDataFile().getConfig().contains("data.charged")) { + return ReturnType.FAILURE; + } + + if (args.length < 2) { + return ReturnType.SYNTAX_ERROR; + } + + String furnaceName = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); + + for (FurnaceObject furnace : instance.getFurnaceManager().getFurnaces().values()) { + if (furnace.getNickname() == null) continue; + + if (!furnace.getNickname().equalsIgnoreCase(furnaceName)) { + continue; + } + + for (UUID uuid : furnace.getAccessList()) { + if (!uuid.equals(((Player) sender).getUniqueId())) { + continue; + } + Block b = furnace.getLocation().getBlock(); + org.bukkit.block.Furnace furnaceBlock = (org.bukkit.block.Furnace) b.getState(); + ((Player) sender).openInventory(furnaceBlock.getInventory()); + return ReturnType.SUCCESS; + } + + sender.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("event.general.nopermission")); + return ReturnType.SUCCESS; + } + sender.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("event.remote.notfound")); + return ReturnType.FAILURE; + } + + @Override + public String getPermissionNode() { + return null; + } + + @Override + public String getSyntax() { + return "/ef remote [nickname]"; + } + + @Override + public String getDescription() { + return "Remote control your furnace."; + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandSettings.java b/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandSettings.java new file mode 100644 index 0000000..fb31185 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/command/commands/CommandSettings.java @@ -0,0 +1,36 @@ +package com.songoda.epicfurnaces.command.commands; + +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.command.AbstractCommand; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class CommandSettings extends AbstractCommand { + private final EpicFurnaces instance; + + public CommandSettings(EpicFurnaces instance, AbstractCommand parent) { + super("settings", parent, true); + this.instance = instance; + } + + @Override + protected ReturnType runCommand(CommandSender sender, String... args) { + instance.getSettingsManager().openSettingsManager((Player) sender); + return ReturnType.SUCCESS; + } + + @Override + public String getPermissionNode() { + return "epicfurnaces.admin"; + } + + @Override + public String getSyntax() { + return "/ef settings"; + } + + @Override + public String getDescription() { + return "Edit the EpicFurnaces Settings."; + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/furnace/FurnaceManager.java b/core/src/main/java/com/songoda/epicfurnaces/furnace/FurnaceManager.java new file mode 100644 index 0000000..d2bc8a6 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/furnace/FurnaceManager.java @@ -0,0 +1,47 @@ +package com.songoda.epicfurnaces.furnace; + +import com.songoda.epicfurnaces.EpicFurnaces; +import org.bukkit.Location; +import org.bukkit.block.Block; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class FurnaceManager { + + private final Map registeredFurnaces = new HashMap<>(); + + + public void addFurnace(Location location, FurnaceObject furnace) { + registeredFurnaces.put(roundLocation(location), furnace); + } + + + public FurnaceObject removeFurnace(Location location) { + return registeredFurnaces.remove(location); + } + + + public FurnaceObject getFurnace(Location location) { + if (!registeredFurnaces.containsKey(location)) { + addFurnace(location, new FurnaceObject(location, EpicFurnaces.getInstance().getLevelManager().getLowestLevel(), null, 0, 0, new ArrayList<>(), null)); + } + return registeredFurnaces.get(location); + } + + + public FurnaceObject getFurnace(Block block) { + return getFurnace(block.getLocation()); + } + + + public Map getFurnaces() { + return Collections.unmodifiableMap(registeredFurnaces); + } + + private Location roundLocation(Location location) { + return location.getBlock().getLocation().clone(); + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/furnace/FurnaceObject.java b/core/src/main/java/com/songoda/epicfurnaces/furnace/FurnaceObject.java new file mode 100644 index 0000000..668226a --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/furnace/FurnaceObject.java @@ -0,0 +1,358 @@ +package com.songoda.epicfurnaces.furnace; + +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.boost.BoostData; +import com.songoda.epicfurnaces.menus.OverviewMenu; +import com.songoda.epicfurnaces.utils.Debugger; +import com.songoda.epicfurnaces.utils.Methods; +import net.milkbowl.vault.economy.Economy; +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.block.Furnace; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.FurnaceSmeltEvent; +import org.bukkit.inventory.FurnaceInventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.plugin.RegisteredServiceProvider; + +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import javax.script.ScriptException; +import java.util.*; + +/** + * Created by songoda on 3/7/2017. + */ +public class FurnaceObject { + + private final EpicFurnaces instance = EpicFurnaces.getInstance(); + private Location location; + private Level level; + private String nickname; + private UUID placedBy; + private int uses, toLevel, radiusOverheatLast, radiusFuelShareLast; + private List radiusOverheat = new ArrayList<>(); + private List radiusFuelShare = new ArrayList<>(); + private List accessList; + private Map cache = new HashMap<>(); + + public FurnaceObject(Location location, Level level, String nickname, int uses, int toLevel, List accessList, UUID placedBy) { + this.location = location; + this.level = level; + this.uses = uses; + this.toLevel = toLevel; + this.nickname = nickname; + this.placedBy = placedBy; + this.accessList = accessList; + this.syncName(); + } + + public FurnaceObject(Block block, Level level, String nickname, int uses, int toLevel, List accessList, UUID placedBy) { + this(block.getLocation(), level, nickname, uses, toLevel, accessList, placedBy); + } + + public void openOverview(Player player) { + if (!player.hasPermission("epicfurnaces.overview")) { + return; + } + + new OverviewMenu(instance, this, player).open(player); + } + + public void plus(FurnaceSmeltEvent e) { + try { + Block block = location.getBlock(); + if (block.getType() != Material.FURNACE && block.getType() != instance.getBukkitEnums().getBurningFurnace()) { + return; + } + + this.uses++; + this.toLevel++; + + int multi = instance.getConfig().getInt("Main.Level Cost Multiplier"); + + if (level.getReward() == null) return; + + String reward = level.getReward(); + String[] amt = {"1", "1"}; + if (reward.contains(":")) { + String[] rewardSplit = reward.split(":"); + reward = rewardSplit[0].substring(0, rewardSplit[0].length() - 1); + if (rewardSplit[1].contains("-")) + amt = rewardSplit[1].split("-"); + else { + amt[0] = rewardSplit[1]; + amt[1] = rewardSplit[0]; + } + } + + + int needed = ((multi * level.getLevel()) - toLevel) - 1; + + if (instance.getConfig().getBoolean("Main.Upgrade By Smelting Materials") + && needed <= 0 + && instance.getConfig().contains("settings.levels.Level-" + (level.getLevel() + 1))) { + toLevel = 0; + level = instance.getLevelManager().getLevel(this.level.getLevel() + 1); + } + + this.updateCook(); + + FurnaceInventory i = (FurnaceInventory) ((InventoryHolder) block.getState()).getInventory(); + + int num = Integer.parseInt(reward); + double rand = Math.random() * 100; + if (rand >= num + || e.getResult().getType().equals(Material.SPONGE) + || instance.getConfig().getBoolean("Main.No Rewards From Custom Recipes") + && instance.getFurnaceRecipeFile().getConfig().contains("Recipes." + i.getSmelting().getType().toString())) { + return; + } + + int r = Integer.parseInt(amt[0]); + if (Integer.parseInt(amt[0]) != + Integer.parseInt(amt[1].replace("%", ""))) + r = (int) (Math.random() * ((Integer.parseInt(amt[1].replace("%", "")) - Integer.parseInt(amt[0])))) + Integer.parseInt(amt[0]); + + BoostData boostData = instance.getBoostManager().getBoost(placedBy); + r = r * (boostData == null ? 1 : boostData.getMultiplier()); + + + if (e.getResult() != null) { + e.getResult().setAmount(e.getResult().getAmount() + r); + return; + } + +// e.setResult(new ItemStack(e.getResult().getType(), r)); + } catch (Exception ex) { + Debugger.runReport(ex); + } + } + + public void upgrade(String type, Player player) { + try { + if (!instance.getLevelManager().getLevels().containsKey(this.level.getLevel() + 1)) + return; + + int cost; + if (type.equals("XP")) { + cost = level.getCostExperiance(); + } else { + cost = level.getCostEconomy(); + } + Level level = instance.getLevelManager().getLevel(this.level.getLevel() + 1); + + if (type.equals("ECO")) { + if (instance.getServer().getPluginManager().getPlugin("Vault") != null) { + RegisteredServiceProvider rsp = instance.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); + net.milkbowl.vault.economy.Economy econ = rsp.getProvider(); + if (econ.has(player, cost)) { + econ.withdrawPlayer(player, cost); + upgradeFinal(level, player); + } else { + player.sendMessage(instance.getLocale().getMessage("event.upgrade.cannotafford")); + } + } else { + player.sendMessage("Vault is not installed."); + } + } else if (type.equals("XP")) { + if (player.getLevel() >= cost || player.getGameMode() == GameMode.CREATIVE) { + if (player.getGameMode() != GameMode.CREATIVE) { + player.setLevel(player.getLevel() - cost); + } + upgradeFinal(level, player); + } else { + player.sendMessage(instance.getLocale().getMessage("event.upgrade.cannotafford")); + } + } + } catch (Exception ex) { + Debugger.runReport(ex); + } + } + + private void upgradeFinal(Level level, Player player) { + try { + this.level = level; + syncName(); + if (instance.getLevelManager().getHighestLevel() != level) { + player.sendMessage(instance.getLocale().getMessage("event.upgrade.success", level.getLevel())); + } else { + player.sendMessage(instance.getLocale().getMessage("event.upgrade.maxed", level.getLevel())); + } + + Location loc = location.clone().add(.5, .5, .5); + player.getWorld().playEffect(loc, Effect.valueOf(instance.getConfig().getString("Main.Upgrade Particle Type")), 200); + + if (instance.getConfig().getBoolean("Main.Use Sounds")) { + if (instance.getLevelManager().getHighestLevel() == level) { + //TODO: Sound + player.playSound(player.getLocation(), instance.getBukkitEnums().getLevelUp(), 0.6F, 15.0F); + } else { + player.playSound(player.getLocation(), instance.getBukkitEnums().getLevelUp(), 2F, 25.0F); + } + } + } catch (Exception ex) { + Debugger.runReport(ex); + } + } + + private void syncName() { + if (location.getBlock().getType() != Material.FURNACE && location.getBlock().getType() != instance.getBukkitEnums().getBurningFurnace()) { + return; + } + + instance.getCraftBukkitHook().setName(location.getBlock(), Methods.formatName(level.getLevel(), uses, false)); + } + + public void updateCook() { + try { + Block block = location.getBlock(); + if (block == null || (block.getType() != Material.FURNACE && block.getType() != instance.getBukkitEnums().getBurningFurnace())) { + return; + } + Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(instance, () -> { + int num = getPerformanceTotal(); + + if (num > 200) { + num = 200; + } + + if (num != 0) { + BlockState bs = (block.getState()); // max is 200 + ((Furnace) bs).setCookTime(Short.parseShort(Integer.toString(num))); + bs.update(); + } + }, 1L); + } catch (Exception e) { + Debugger.runReport(e); + } + } + + + public boolean addToAccessList(String string) { + return accessList.add(string); + } + + + public boolean removeFromAccessList(String string) { + return accessList.remove(string); + } + + + public void clearAccessList() { + accessList.clear(); + } + + + public List getRadius(boolean overHeat) { + if (overHeat) + return radiusOverheat.isEmpty() ? null : Collections.unmodifiableList(radiusOverheat); + else + return radiusFuelShare.isEmpty() ? null : Collections.unmodifiableList(radiusFuelShare); + + } + + + public void addToRadius(Location location, boolean overHeat) { + if (overHeat) + radiusOverheat.add(location); + else + radiusFuelShare.add(location); + + } + + + public void clearRadius(boolean overHeat) { + if (overHeat) + radiusOverheat.clear(); + else + radiusFuelShare.clear(); + } + + + public int getRadiusLast(boolean overHeat) { + if (overHeat) + return radiusOverheatLast; + else + return radiusFuelShareLast; + } + + + public void setRadiusLast(int radiusLast, boolean overHeat) { + if (overHeat) + this.radiusOverheatLast = radiusLast; + else + this.radiusFuelShareLast = radiusLast; + } + + + public List getAccessList() { + List list = new ArrayList<>(); + for (String line : accessList) { + String[] halfs = line.split(":"); + list.add(UUID.fromString(halfs[0])); + } + + return list; + } + + + public Level getLevel() { + return level; + } + + + public Location getLocation() { + return location.clone(); + } + + + public String getNickname() { + return nickname; + } + + + public void setNickname(String nickname) { + this.nickname = nickname; + } + + + public List getOriginalAccessList() { + return Collections.unmodifiableList(accessList); + } + + + public int getPerformanceTotal() { + String equation = "(" + level.getPerformance() + " / 100) * 200"; + try { + if (!cache.containsKey(equation)) { + ScriptEngineManager mgr = new ScriptEngineManager(); + ScriptEngine engine = mgr.getEngineByName("JavaScript"); + int num = (int) Math.round(Double.parseDouble(engine.eval("(" + level.getPerformance() + " / 100) * 200").toString())); + cache.put(equation, num); + return num; + } else { + return cache.get(equation); + } + } catch (ScriptException e) { + Debugger.runReport(e); + } + return 0; + } + + + public UUID getPlacedBy() { + return placedBy; + } + + + public int getToLevel() { + return toLevel; + } + + + public int getUses() { + return uses; + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/furnace/Level.java b/core/src/main/java/com/songoda/epicfurnaces/furnace/Level.java new file mode 100644 index 0000000..0902c7e --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/furnace/Level.java @@ -0,0 +1,88 @@ +package com.songoda.epicfurnaces.furnace; + +import com.songoda.epicfurnaces.EpicFurnaces; + +import java.util.ArrayList; +import java.util.List; + +public class Level { + + private int level, costExperiance, costEconomy, performance, fuelDuration, overheat, fuelShare; + + private String reward; + + private List description = new ArrayList<>(); + + Level(int level, int costExperience, int costEconomy, int performance, String reward, int fuelDuration, int overheat, int fuelShare) { + this.level = level; + this.costExperiance = costExperience; + this.costEconomy = costEconomy; + this.performance = performance; + this.reward = reward; + this.fuelDuration = fuelDuration; + this.overheat = overheat; + this.fuelShare = fuelShare; + + EpicFurnaces instance = EpicFurnaces.getInstance(); + + if (performance != 0) + description.add(instance.getLocale().getMessage("interface.furnace.performance", performance + "%")); + + if (reward != null) + description.add(instance.getLocale().getMessage("interface.furnace.reward", reward.split("%:")[0] + "%")); + + if (fuelDuration != 0) + description.add(instance.getLocale().getMessage("interface.furnace.fuelduration", fuelDuration + "%")); + + if (fuelShare != 0) + description.add(instance.getLocale().getMessage("interface.furnace.fuelshare", fuelShare)); + + if (overheat != 0) + description.add(instance.getLocale().getMessage("interface.furnace.overheat", overheat)); + } + + + public List getDescription() { + return new ArrayList<>(description); + } + + + public int getLevel() { + return level; + } + + + public int getPerformance() { + return performance; + } + + + public String getReward() { + return reward; + } + + + public int getOverheat() { + return overheat; + } + + + public int getFuelShare() { + return fuelShare; + } + + + public int getFuelDuration() { + return fuelDuration; + } + + + public int getCostExperiance() { + return costExperiance; + } + + + public int getCostEconomy() { + return costEconomy; + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/furnace/LevelManager.java b/core/src/main/java/com/songoda/epicfurnaces/furnace/LevelManager.java new file mode 100644 index 0000000..becc854 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/furnace/LevelManager.java @@ -0,0 +1,46 @@ +package com.songoda.epicfurnaces.furnace; + +import java.util.Collections; +import java.util.Map; +import java.util.NavigableMap; +import java.util.TreeMap; + +public class LevelManager { + + private final NavigableMap registeredLevels = new TreeMap<>(); + + + public void addLevel(int level, int costExperience, int costEconomy, int performance, String reward, int fuelDuration, int overheat, int fuelShare) { + registeredLevels.put(level, new Level(level, costExperience, costEconomy, performance, reward, fuelDuration, overheat, fuelShare)); + } + + + public Level getLevel(int level) { + return registeredLevels.get(level); + } + + + public Level getLowestLevel() { + return registeredLevels.firstEntry().getValue(); + } + + + public Level getHighestLevel() { + return registeredLevels.lastEntry().getValue(); + } + + + public boolean isLevel(int level) { + return registeredLevels.containsKey(level); + } + + + public Map getLevels() { + return Collections.unmodifiableMap(registeredLevels); + } + + + public void clear() { + registeredLevels.clear(); + } +} \ No newline at end of file diff --git a/core/src/main/java/com/songoda/epicfurnaces/handlers/BlacklistHandler.java b/core/src/main/java/com/songoda/epicfurnaces/handlers/BlacklistHandler.java new file mode 100644 index 0000000..955fe34 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/handlers/BlacklistHandler.java @@ -0,0 +1,67 @@ +package com.songoda.epicfurnaces.handlers; + +import com.songoda.arconix.api.utils.ConfigWrapper; +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.utils.Debugger; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by songoda on 2/25/2017. + */ +public class BlacklistHandler { + + private ConfigWrapper blackFile = new ConfigWrapper(EpicFurnaces.getInstance(), "", "blacklist.yml"); + + public BlacklistHandler() { + try { + blackFile.createNewFile("Loading language file", "EpicFurnaces blacklist file"); + loadBlacklistFile(); + } catch (Exception e) { + Debugger.runReport(e); + } + } + + public boolean isBlacklisted(Player player) { + boolean blacklisted = false; + try { + List list = blackFile.getConfig().getStringList("settings.blacklist"); + String cWorld = player.getWorld().getName(); + for (String world : list) { + if (cWorld.equalsIgnoreCase(world)) { + blacklisted = true; + } + } + } catch (Exception e) { + Debugger.runReport(e); + } + return blacklisted; + } + + private void loadBlacklistFile() { + try { + List list = new ArrayList<>(); + list.add("world2"); + list.add("world3"); + list.add("world4"); + list.add("world5"); + blackFile.getConfig().addDefault("settings.blacklist", list); + + blackFile.getConfig().options().copyDefaults(true); + blackFile.saveConfig(); + } catch (Exception e) { + Debugger.runReport(e); + } + } + + public void reload() { + try { + blackFile.createNewFile("Loading blacklist file", "EpicFurnaces blacklist file"); + loadBlacklistFile(); + } catch (Exception e) { + Debugger.runReport(e); + } + } +} \ No newline at end of file diff --git a/core/src/main/java/com/songoda/epicfurnaces/listeners/BlockListeners.java b/core/src/main/java/com/songoda/epicfurnaces/listeners/BlockListeners.java new file mode 100644 index 0000000..8cc1954 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/listeners/BlockListeners.java @@ -0,0 +1,115 @@ +package com.songoda.epicfurnaces.listeners; + +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.furnace.FurnaceObject; +import com.songoda.epicfurnaces.utils.Debugger; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockFormEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; + +/** + * Created by songoda on 2/26/2017. + */ +public class BlockListeners implements Listener { + + private final EpicFurnaces instance; + + public BlockListeners(EpicFurnaces instance) { + this.instance = instance; + } + + @EventHandler + public void onSnowLand(BlockFormEvent event) { + Material material = event.getNewState().getType(); + + if (material != Material.SNOW && material != Material.ICE) { + return; + } + + for (FurnaceObject furnace : instance.getFurnaceManager().getFurnaces().values()) { + if (furnace.getRadius(false) == null || ((org.bukkit.block.Furnace) furnace.getLocation().getBlock().getState()).getBurnTime() == 0) { + continue; + } + + for (Location location : furnace.getRadius(false)) { + if (location.getX() != event.getNewState().getX() || location.getY() != event.getNewState().getY() || location.getZ() != event.getNewState().getZ()) { + continue; + } + + event.setCancelled(true); + return; + } + } + + } + + @EventHandler + public void onBlockPlace(BlockPlaceEvent event) { + try { + if (event.getBlock().getType() != Material.FURNACE || !event.getItemInHand().getItemMeta().hasDisplayName()) { + return; + } + + ItemStack item = event.getItemInHand(); + Location location = event.getBlock().getLocation(); + + if (instance.getFurnceLevel(item) != 1) { + if (instance.getBlacklistHandler().isBlacklisted(event.getPlayer())) { + event.setCancelled(true); + return; + } + + instance.getFurnaceManager().addFurnace(location, new FurnaceObject(location, instance.getLevelManager().getLevel(instance.getFurnceLevel(item)), null, instance.getFurnaceUses(item), 0, new ArrayList<>(), event.getPlayer().getUniqueId())); + } + + } catch (Exception e) { + Debugger.runReport(e); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + try { + if (!event.getPlayer().hasPermission("EpicFurnaces.overview") && !event.getPlayer().hasPermission("epicfurnaces.*")) { + return; + } + + Block block = event.getBlock(); + + if (block.getType() != Material.FURNACE) { + return; + } + + instance.getHologramTask().despawn(block); + + if (instance.getBlacklistHandler().isBlacklisted(event.getPlayer())) { + return; + } + + FurnaceObject furnace = instance.getFurnaceManager().getFurnace(block); + int level = instance.getFurnaceManager().getFurnace(block).getLevel().getLevel(); + + if (level != 0) { + event.setCancelled(true); + + ItemStack item = instance.createLeveledFurnace(level, furnace.getUses()); + + event.getBlock().setType(Material.AIR); + event.getBlock().getLocation().getWorld().dropItemNaturally(event.getBlock().getLocation(), item); + } + instance.getFurnaceManager().removeFurnace(block.getLocation()); + + } catch (Exception ee) { + Debugger.runReport(ee); + } + } +} \ No newline at end of file diff --git a/core/src/main/java/com/songoda/epicfurnaces/listeners/FurnaceListeners.java b/core/src/main/java/com/songoda/epicfurnaces/listeners/FurnaceListeners.java new file mode 100644 index 0000000..01b79d7 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/listeners/FurnaceListeners.java @@ -0,0 +1,66 @@ +package com.songoda.epicfurnaces.listeners; + +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.furnace.FurnaceObject; +import com.songoda.epicfurnaces.furnace.Level; +import com.songoda.epicfurnaces.utils.Debugger; +import org.bukkit.block.Block; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.FurnaceBurnEvent; +import org.bukkit.event.inventory.FurnaceSmeltEvent; + +/** + * Created by songoda on 2/26/2017. + */ +public class FurnaceListeners implements Listener { + + private final EpicFurnaces instance; + + public FurnaceListeners(EpicFurnaces instance) { + this.instance = instance; + } + + @EventHandler + public void onCook(FurnaceSmeltEvent event) { + try { + Block b = event.getBlock(); + + if ((event.getBlock().isBlockPowered() && instance.getConfig().getBoolean("Main.Redstone Deactivates Furnaces")) || event.getResult() == null) { + event.setCancelled(true); + return; + } + + FurnaceObject furnace = instance.getFurnaceManager().getFurnace(b.getLocation()); + + //TODO: wet sponge + if (furnace != null && event.getSource().getType() != instance.getBukkitEnums().getWetSponge()) { + furnace.plus(event); + } + } catch (Exception e) { + Debugger.runReport(e); + } + } + + @EventHandler + public void onFuel(FurnaceBurnEvent event) { + try { + if (event.getFuel() == null) { + return; + } + + FurnaceObject furnace = instance.getFurnaceManager().getFurnace(event.getBlock().getLocation()); + Level level = furnace != null ? furnace.getLevel() : instance.getLevelManager().getLowestLevel(); + + if (level.getFuelDuration() != 0) { + return; + } + + int num = level.getFuelDuration(); + int per = (event.getBurnTime() / 100) * num; + event.setBurnTime(event.getBurnTime() + per); + } catch (Exception e) { + Debugger.runReport(e); + } + } +} \ No newline at end of file diff --git a/core/src/main/java/com/songoda/epicfurnaces/listeners/InteractListeners.java b/core/src/main/java/com/songoda/epicfurnaces/listeners/InteractListeners.java new file mode 100644 index 0000000..9c906d0 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/listeners/InteractListeners.java @@ -0,0 +1,56 @@ +package com.songoda.epicfurnaces.listeners; + +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.utils.Debugger; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; + +/** + * Created by songoda on 2/26/2017. + */ +public class InteractListeners implements Listener { + + private final EpicFurnaces instance; + + public InteractListeners(EpicFurnaces instance) { + this.instance = instance; + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onClick(PlayerInteractEvent event) { + try { + if (event.getClickedBlock() == null) { + return; + } + + if (instance.getBlacklistHandler().isBlacklisted(event.getPlayer())) { + return; + } + + Player player = event.getPlayer(); + Block block = event.getClickedBlock(); + + if (!player.hasPermission("EpicFurnaces.overview") + || !instance.canBuild(player, event.getClickedBlock().getLocation()) + || event.getAction() != Action.LEFT_CLICK_BLOCK + || player.isSneaking() + || (block.getType() != Material.FURNACE) + || player.getInventory().getItemInHand().getType().name().contains("PICKAXE")) { + return; + } + + event.setCancelled(true); + + instance.getFurnaceManager().getFurnace(block.getLocation()).openOverview(player); + + } catch (Exception e) { + Debugger.runReport(e); + } + } +} \ No newline at end of file diff --git a/core/src/main/java/com/songoda/epicfurnaces/listeners/InventoryListeners.java b/core/src/main/java/com/songoda/epicfurnaces/listeners/InventoryListeners.java new file mode 100644 index 0000000..39185c8 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/listeners/InventoryListeners.java @@ -0,0 +1,66 @@ +package com.songoda.epicfurnaces.listeners; + +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.utils.Debugger; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.Furnace; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryAction; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryMoveItemEvent; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.ItemStack; + +/** + * Created by songoda on 2/26/2017. + */ +public class InventoryListeners implements Listener { + + private final EpicFurnaces instance; + + public InventoryListeners(EpicFurnaces instance) { + this.instance = instance; + } + + @EventHandler + public void onInventoryMove(InventoryMoveItemEvent event) { + if (!event.getDestination().getType().equals(InventoryType.FURNACE) + || event.getDestination().getItem(0) == null + || event.getDestination().getItem(0).getType() != event.getItem().getType() + || event.getDestination().getItem(0).getAmount() != 1) { + return; + } + instance.getFurnaceManager().getFurnace(((Furnace) event.getDestination().getHolder()).getLocation()).updateCook(); + } + + @EventHandler + public void onInventoryClick(InventoryClickEvent event) { + try { + if (event.getInventory().getType().equals(InventoryType.FURNACE) + && event.getInventory().getHolder() != null + && event.getSlotType() == InventoryType.SlotType.CRAFTING) { + Block block; + block = ((Furnace) event.getInventory().getHolder()).getLocation().getBlock(); + instance.getFurnaceManager().getFurnace(block).updateCook(); + } + if (event.getSlot() != 64537) { + if (event.getInventory().getType() == InventoryType.ANVIL) { + if (event.getAction() != InventoryAction.NOTHING) { + if (event.getCurrentItem().getType() != Material.AIR) { + ItemStack item = event.getCurrentItem(); + if (item.getType() == Material.FURNACE) { + event.setCancelled(true); + } + } + } + } + } + + } catch (Exception e) { + Debugger.runReport(e); + } + } + +} \ No newline at end of file diff --git a/core/src/main/java/com/songoda/epicfurnaces/menus/OverviewMenu.java b/core/src/main/java/com/songoda/epicfurnaces/menus/OverviewMenu.java new file mode 100644 index 0000000..77455a0 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/menus/OverviewMenu.java @@ -0,0 +1,216 @@ +package com.songoda.epicfurnaces.menus; + +import com.songoda.arconix.api.methods.formatting.TextComponent; +import com.songoda.arconix.api.methods.formatting.TimeComponent; +import com.songoda.arconix.plugin.Arconix; +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.boost.BoostData; +import com.songoda.epicfurnaces.furnace.FurnaceObject; +import com.songoda.epicfurnaces.furnace.Level; +import com.songoda.epicfurnaces.utils.Methods; +import com.songoda.epicfurnaces.utils.gui.AbstractAnvilGUI; +import com.songoda.epicfurnaces.utils.gui.FastInv; +import com.songoda.epicfurnaces.utils.gui.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +import static com.songoda.epicfurnaces.utils.gui.AbstractAnvilGUI.AnvilSlot.INPUT_LEFT; +import static org.bukkit.Material.*; + +public class OverviewMenu extends FastInv { + + public OverviewMenu(EpicFurnaces instance, FurnaceObject furnace, Player accessor) { + super(27, Arconix.pl().getApi().format().formatText(Methods.formatName(furnace.getLevel().getLevel(), 0, false))); + + Level nextLevel = instance.getLevelManager().getHighestLevel().getLevel() > furnace.getLevel().getLevel() ? instance.getLevelManager().getLevel(furnace.getLevel().getLevel() + 1) : null; + int multi = instance.getConfig().getInt("Main.Level Cost Multiplier"); + int needed = (multi * furnace.getLevel().getLevel()) - furnace.getToLevel(); + + ItemBuilder currentLevel = new ItemBuilder(FURNACE); + currentLevel.name(instance.getLocale().getMessage("interface.furnace.currentlevel", furnace.getLevel().getLevel())); + currentLevel.lore(instance.getLocale().getMessage("interface.furnace.smeltedx", furnace.getUses())); + currentLevel.addLore(furnace.getLevel().getDescription()); + currentLevel.addLore(""); + + if (nextLevel == null) + currentLevel.addLore(instance.getLocale().getMessage("interface.furnace.alreadymaxed")); + else { + currentLevel.addLore(instance.getLocale().getMessage("interface.furnace.level", nextLevel.getLevel())); + currentLevel.addLore(nextLevel.getDescription()); + + if (instance.getConfig().getBoolean("Main.Upgrade By Smelting Materials")) { + currentLevel.addLore(instance.getLocale().getMessage("interface.furnace.tolevel", needed, Methods.cleanString(instance.getConfig().getString("Main.Furnace Upgrade Cost")))); + } + } + + BoostData boostData = instance.getBoostManager().getBoost(furnace.getPlacedBy()); + if (boostData != null) { + String[] parts = instance.getLocale().getMessage("interface.button.boostedstats", Integer.toString(boostData.getMultiplier()), TimeComponent.makeReadable(boostData.getEndTime() - System.currentTimeMillis())).split("\\|"); + currentLevel.addLore(""); + for (String line : parts) { + currentLevel.addLore(TextComponent.formatText(line)); + } + } + + fill(Methods.getGlass()); + + ItemBuilder performance = new ItemBuilder(Material.valueOf(instance.getConfig().getString("Interfaces.Performance Icon"))); + performance.name(instance.getLocale().getMessage("interface.furnace.performancetitle")); + String[] parts = instance.getLocale().getMessage("interface.furnace.performanceinfo", furnace.getLevel().getPerformance()).split("\\|"); + performance.lore(Arrays.stream(parts).map(s -> Arconix.pl().getApi().format().formatText(s)).collect(Collectors.toList())); + + ItemBuilder reward = new ItemBuilder(Material.valueOf(instance.getConfig().getString("Interfaces.Reward Icon"))); + reward.name(instance.getLocale().getMessage("interface.furnace.rewardtitle")); + parts = instance.getLocale().getMessage("interface.furnace.rewardinfo", furnace.getLevel().getReward().split(":")[0].replace("%", "")).split("\\|"); + reward.lore(Arrays.stream(parts).map(s -> Arconix.pl().getApi().format().formatText(s)).collect(Collectors.toList())); + + ItemBuilder duration = new ItemBuilder(Material.valueOf(instance.getConfig().getString("Interfaces.FuelDuration Icon"))); + duration.name(instance.getLocale().getMessage("interface.furnace.fueldurationtitle")); + parts = instance.getLocale().getMessage("interface.furnace.fueldurationinfo", furnace.getLevel().getFuelDuration()).split("\\|"); + duration.lore(Arrays.stream(parts).map(s -> Arconix.pl().getApi().format().formatText(s)).collect(Collectors.toList())); + + ItemBuilder overheat = new ItemBuilder(Material.valueOf(instance.getConfig().getString("Interfaces.Overheat Icon"))); + overheat.name(instance.getLocale().getMessage("interface.furnace.overheattitle")); + parts = instance.getLocale().getMessage("interface.furnace.overheatinfo", furnace.getLevel().getOverheat() * 3).split("\\|"); + overheat.lore(Arrays.stream(parts).map(s -> Arconix.pl().getApi().format().formatText(s)).collect(Collectors.toList())); + + ItemBuilder fuelShare = new ItemBuilder(Material.valueOf(instance.getConfig().getString("Interfaces.FuelShare Icon"))); + fuelShare.name(instance.getLocale().getMessage("interface.furnace.fuelsharetitle")); + parts = instance.getLocale().getMessage("interface.furnace.fuelshareinfo", furnace.getLevel().getOverheat() * 3).split("\\|"); + fuelShare.lore(Arrays.stream(parts).map(s -> Arconix.pl().getApi().format().formatText(s)).collect(Collectors.toList())); + + ItemBuilder xp = new ItemBuilder(Material.valueOf(instance.getConfig().getString("Interfaces.XP Icon"))); + xp.name(instance.getLocale().getMessage("interface.furnace.upgradewithxp")); + xp.lore(nextLevel == null ? instance.getLocale().getMessage("interface.furnace.alreadymaxed") : + instance.getLocale().getMessage("interface.furnace.upgradewithxplore", furnace.getLevel().getCostExperiance())); + + ItemBuilder eco = new ItemBuilder(Material.valueOf(instance.getConfig().getString("Interfaces.Economy Icon"))); + eco.name(instance.getLocale().getMessage("interface.furnace.upgradewitheconomy")); + eco.lore(nextLevel == null ? instance.getLocale().getMessage("interface.furnace.alreadymaxed") : + instance.getLocale().getMessage("interface.furnace.upgradewitheconomylore", Arconix.pl().getApi().format().formatEconomy(furnace.getLevel().getCostEconomy()))); + + ItemBuilder remote = new ItemBuilder(TRIPWIRE_HOOK); + remote.name(instance.getLocale().getMessage("interface.furnace.remotefurnace")); + parts = instance.getLocale().getMessage("interface.furnace.remotefurnacelore", furnace.getNickname() == null ? "Unset" : furnace.getNickname()).split("\\|"); + remote.lore(Arrays.stream(parts).map(s -> Arconix.pl().getApi().format().formatText(s)).collect(Collectors.toList())); + + if (furnace.getNickname() != null) { + parts = instance.getLocale().getMessage("interface.furnace.utilize", furnace.getNickname()).split("\\|"); + remote.addLore(Arrays.stream(parts).map(s -> Arconix.pl().getApi().format().formatText(s)).collect(Collectors.toList())); + } + + if (!furnace.getOriginalAccessList().isEmpty()) { + remote.addLore(""); + remote.addLore(instance.getLocale().getMessage("interface.furnace.remotelist")); + } + + for (String line : furnace.getOriginalAccessList()) { + String[] halfs = line.split(":"); + String name = halfs[1]; + Player player = Bukkit.getPlayer(halfs[0]); + + if (player != null) { + name = player.getDisplayName(); + } + remote.addLore(Arconix.pl().getApi().format().formatText("&6" + name)); + } + + addItem(new int[]{0, 1, 7, 8, 9, 17, 18, 19, 25, 26}, Methods.getBackgroundGlass(true)); + addItem(new int[]{2, 6, 10, 16, 20, 24}, Methods.getBackgroundGlass(false)); + + int num = -1; + Map spots = new HashMap() {{ + put(0, new int[]{22}); + put(1, new int[]{21, 23}); + put(2, new int[]{21, 22, 23}); + put(3, new int[]{20, 21, 23, 24}); + put(4, new int[]{20, 21, 22, 23, 24}); + }}; + + num += furnace.getLevel().getPerformance() == 0 ? 0 : 1; + num += (furnace.getLevel().getReward() == null ? 0 : 1); + num += furnace.getLevel().getFuelDuration() == 0 ? 0 : 1; + num += furnace.getLevel().getFuelShare() == 0 ? 0 : 1; + num += furnace.getLevel().getOverheat() == 0 ? 0 : 1; + + int[] order = spots.get(num); + int current = 0; + + if (furnace.getLevel().getPerformance() != 0) { + addItem(order[current], performance.build()); + current++; + } + if (furnace.getLevel().getReward() != null) { + addItem(order[current], reward.build()); + current++; + } + if (furnace.getLevel().getFuelDuration() != 0) { + addItem(order[current], duration.build()); + current++; + } + if (furnace.getLevel().getFuelShare() != 0) { + addItem(order[current], fuelShare.build()); + current++; + } + if (furnace.getLevel().getOverheat() != 0) { + addItem(order[current], overheat.build()); + } + + if (instance.getConfig().getBoolean("Main.Access Furnaces Remotely") && accessor.hasPermission("EpicFurnaces.Remote")) { + addItem(4, remote.build(), event -> { + if (event.getClickType().isLeftClick()) { + event.getPlayer().sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("event.remote.enter")); + + AbstractAnvilGUI anvilGUI = new AbstractAnvilGUI(event.getPlayer(), anvilEvent -> { + for (FurnaceObject other : instance.getFurnaceManager().getFurnaces().values()) { + if (other.getNickname() == null) { + continue; + } + + if (other.getNickname().equalsIgnoreCase(anvilEvent.getName())) { + event.getPlayer().sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("event.remote.nicknameinuse")); + furnace.openOverview(event.getPlayer()); + return; + } + } + + furnace.setNickname(anvilEvent.getName()); + furnace.openOverview(event.getPlayer()); + event.getPlayer().sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("event.remote.nicknamesuccess")); + }); + + anvilGUI.setOnClose((closer, inv) -> furnace.openOverview(closer)); + anvilGUI.setSlot(INPUT_LEFT, new ItemBuilder(PAPER).name("Enter a nickname").build()); + anvilGUI.open(); + } else if (event.getClickType().isRightClick()) { + if (!furnace.getAccessList().contains(event.getPlayer().getUniqueId())) { + furnace.addToAccessList(event.getPlayer().getUniqueId().toString() + ":" + event.getPlayer().getName()); + furnace.openOverview(event.getPlayer()); + } + } + }); + } + + if (instance.getConfig().getBoolean("Main.Upgrade With XP") && accessor.hasPermission("EpicFurnaces.Upgrade.XP")) { + addItem(11, xp.build(), event -> { + furnace.upgrade("XP", event.getPlayer()); + event.getPlayer().closeInventory(); + }); + } + if (instance.getConfig().getBoolean("Main.Upgrade With Economy") && accessor.hasPermission("EpicFurnaces.Upgrade.ECO")) { + addItem(15, eco.build(), event -> { + furnace.upgrade("ECO", event.getPlayer()); + event.getPlayer().closeInventory(); + }); + } + + addItem(13, currentLevel.build()); + + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/storage/Storage.java b/core/src/main/java/com/songoda/epicfurnaces/storage/Storage.java new file mode 100644 index 0000000..14eb0e1 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/storage/Storage.java @@ -0,0 +1,31 @@ +package com.songoda.epicfurnaces.storage; + +import com.songoda.arconix.api.utils.ConfigWrapper; +import com.songoda.epicfurnaces.EpicFurnaces; + +import java.util.List; + +public abstract class Storage { + + protected final EpicFurnaces instance; + protected final ConfigWrapper dataFile; + + public Storage(EpicFurnaces instance) { + this.instance = instance; + this.dataFile = new ConfigWrapper(instance, "", "data.yml"); + this.dataFile.createNewFile(null, "EpicFurnaces Data File"); + this.dataFile.getConfig().options().copyDefaults(true); + this.dataFile.saveConfig(); + } + + public abstract boolean containsGroup(String group); + + public abstract List getRowsByGroup(String group); + + public abstract void prepareSaveItem(String group, StorageItem... items); + + public abstract void doSave(); + + public abstract void closeConnection(); + +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/storage/StorageItem.java b/core/src/main/java/com/songoda/epicfurnaces/storage/StorageItem.java new file mode 100644 index 0000000..4d99d5f --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/storage/StorageItem.java @@ -0,0 +1,64 @@ +package com.songoda.epicfurnaces.storage; + +import java.util.ArrayList; +import java.util.List; + +public class StorageItem { + + private String key = null; + + private final Object object; + + public StorageItem(Object object) { + this.object = object; + } + + public StorageItem(String key, Object object) { + this.key = key; + this.object = object; + } + + public StorageItem(String key, List string) { + StringBuilder object = new StringBuilder(); + for (String s : string) { + object.append(s).append(";"); + } + this.key = key; + this.object = object.toString(); + } + + public String getKey() { + return key; + } + + public String asString() { + if (object == null) return null; + return (String) object; + } + + public boolean asBoolean() { + if (object == null) return false; + return (boolean) object; + } + + public int asInt() { + if (object == null) return 0; + return (int) object; + } + + public Object asObject() { + return object; + } + + public List asStringList() { + if (object instanceof ArrayList) return new ArrayList<>(); + List list = new ArrayList<>(); + if (object == null) return list; + String[] stack = ((String) object).split(";"); + for (String item : stack) { + if (item.equals("")) continue; + list.add(item); + } + return list; + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/storage/StorageRow.java b/core/src/main/java/com/songoda/epicfurnaces/storage/StorageRow.java new file mode 100644 index 0000000..c52a321 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/storage/StorageRow.java @@ -0,0 +1,28 @@ +package com.songoda.epicfurnaces.storage; + +import java.util.Collections; +import java.util.Map; + +public class StorageRow { + private final String key; + + private final Map items; + + public StorageRow(String key, Map items) { + this.key = key; + this.items = items; + } + + public String getKey() { + return key; + } + + public Map getItems() { + return Collections.unmodifiableMap(items); + } + + public StorageItem get(String key) { + if (!items.containsKey(key) || items.get(key).asObject().toString().equals("")) return new StorageItem(null); + return items.get(key); + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/storage/types/StorageMysql.java b/core/src/main/java/com/songoda/epicfurnaces/storage/types/StorageMysql.java new file mode 100644 index 0000000..cd0a275 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/storage/types/StorageMysql.java @@ -0,0 +1,125 @@ +package com.songoda.epicfurnaces.storage.types; + +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.storage.Storage; +import com.songoda.epicfurnaces.storage.StorageItem; +import com.songoda.epicfurnaces.storage.StorageRow; +import com.songoda.epicfurnaces.utils.MySQLDatabase; + +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class StorageMysql extends Storage { + + private MySQLDatabase database; + private static List toSave = new ArrayList<>(); + + public StorageMysql(EpicFurnaces instance) { + super(instance); + this.database = new MySQLDatabase(instance); + } + + @Override + public boolean containsGroup(String group) { + try { + DatabaseMetaData dbm = database.getConnection().getMetaData(); + ResultSet rs = dbm.getTables(null, null, instance.getConfig().getString("Database.Prefix") + group, null); + if (rs.next()) { + return true; + } + } catch (SQLException e) { + e.printStackTrace(); + } + return false; + + } + + @Override + public List getRowsByGroup(String group) { + List rows = new ArrayList<>(); + try { + ResultSet set = database.getConnection().createStatement().executeQuery(String.format("SELECT * FROM `" + instance.getConfig().getString("Database.Prefix") + "%s`", group)); + while (set.next()) { + Map items = new HashMap<>(); + + String key = set.getString(1); + for (int i = 2; i <= set.getMetaData().getColumnCount(); i++) { + if (set.getObject(i) == null || set.getObject(i) == "") continue; + StorageItem item = new StorageItem(set.getObject(i)); + items.put(set.getMetaData().getColumnName(i), item); + } + StorageRow row = new StorageRow(key, items); + rows.add(row); + } + } catch (SQLException e) { + e.printStackTrace(); + } + return rows; + } + + @Override + public void prepareSaveItem(String group, StorageItem... items) { + StringBuilder sql = new StringBuilder(String.format("INSERT INTO `" + instance.getConfig().getString("Database.Prefix") + "%s`", group)); + + sql.append(" ("); + + for (StorageItem item : items) { + if (item == null || item.asObject() == null) continue; + sql.append(String.format("`%s`, ", item.getKey())); + } + + sql = new StringBuilder(sql.substring(0, sql.length() - 2)); + + sql.append(") VALUES ("); + + for (StorageItem item : items) { + if (item == null || item.asObject() == null) continue; + sql.append(String.format("'%s', ", item.asObject().toString())); + } + + sql = new StringBuilder(sql.substring(0, sql.length() - 2)); + + sql.append(");"); + + toSave.add(sql.toString()); + } + + @Override + public void doSave() { + try { + // Clear database + database.getConnection().createStatement().execute("TRUNCATE `" + instance.getConfig().getString("Database.Prefix") + "charged`"); + database.getConnection().createStatement().execute("TRUNCATE `" + instance.getConfig().getString("Database.Prefix") + "boosts`"); + + Statement stmt = database.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + + for (String line : toSave) { + stmt.addBatch(line); + } + + stmt.executeBatch(); + + toSave.clear(); + + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Override + public void closeConnection() { + try { + database.getConnection().close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } +} + + diff --git a/core/src/main/java/com/songoda/epicfurnaces/storage/types/StorageYaml.java b/core/src/main/java/com/songoda/epicfurnaces/storage/types/StorageYaml.java new file mode 100644 index 0000000..44125ed --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/storage/types/StorageYaml.java @@ -0,0 +1,103 @@ +package com.songoda.epicfurnaces.storage.types; + +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.storage.Storage; +import com.songoda.epicfurnaces.storage.StorageItem; +import com.songoda.epicfurnaces.storage.StorageRow; +import com.songoda.epicfurnaces.utils.Debugger; +import org.apache.commons.io.FileUtils; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.MemorySection; + +import java.io.File; +import java.io.IOException; +import java.util.*; + +public class StorageYaml extends Storage { + + private static final Map toSave = new HashMap<>(); + + public StorageYaml(EpicFurnaces instance) { + super(instance); + } + + @Override + public boolean containsGroup(String group) { + return dataFile.getConfig().contains("data." + group); + } + + @Override + public List getRowsByGroup(String group) { + List rows = new ArrayList<>(); + ConfigurationSection currentSection = dataFile.getConfig().getConfigurationSection("data." + group); + for (String key : currentSection.getKeys(false)) { + + Map items = new HashMap<>(); + ConfigurationSection currentSection2 = dataFile.getConfig().getConfigurationSection("data." + group + "." + key); + for (String key2 : currentSection2.getKeys(false)) { + String path = "data." + group + "." + key + "." + key2; + items.put(key2, new StorageItem(dataFile.getConfig().get(path) instanceof MemorySection + ? convertToInLineList(path) : dataFile.getConfig().get(path))); + } + if (items.isEmpty()) continue; + StorageRow row = new StorageRow(key, items); + rows.add(row); + } + return rows; + } + + private String convertToInLineList(String path) { + StringBuilder converted = new StringBuilder(); + for (String key : dataFile.getConfig().getConfigurationSection(path).getKeys(false)) { + converted.append(key).append(":").append(dataFile.getConfig().getInt(path + "." + key)).append(";"); + } + return converted.toString(); + } + + @Override + public void prepareSaveItem(String group, StorageItem... items) { + for (StorageItem item : items) { + if (item == null || item.asObject() == null) continue; + toSave.put("data." + group + "." + items[0].asString() + "." + item.getKey(), item.asObject()); + } + } + + @Override + public void doSave() { + try { + dataFile.getConfig().set("data", null); // Clear file + + File data = new File(instance.getDataFolder() + "/data.yml"); + File dataClone = new File(instance.getDataFolder() + "/data-backup-" + System.currentTimeMillis() + ".yml"); + try { + FileUtils.copyFile(data, dataClone); + } catch (IOException e) { + Debugger.runReport(e); + } + Deque backups = new ArrayDeque<>(); + for (File file : Objects.requireNonNull(instance.getDataFolder().listFiles())) { + if (file.getName().toLowerCase().contains("data-backup")) { + backups.add(file); + } + } + if (backups.size() > 5) { + backups.getFirst().delete(); + } + + for (Map.Entry entry : toSave.entrySet()) { + dataFile.getConfig().set(entry.getKey(), entry.getValue()); + } + + dataFile.saveConfig(); + + toSave.clear(); + } catch (NullPointerException e) { + Debugger.runReport(e); + } + } + + @Override + public void closeConnection() { + dataFile.saveConfig(); + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/tasks/FurnaceTask.java b/core/src/main/java/com/songoda/epicfurnaces/tasks/FurnaceTask.java new file mode 100644 index 0000000..1198bc0 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/tasks/FurnaceTask.java @@ -0,0 +1,166 @@ +package com.songoda.epicfurnaces.tasks; + +import com.songoda.arconix.plugin.Arconix; +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.furnace.FurnaceObject; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.concurrent.ThreadLocalRandom; + +public class FurnaceTask extends BukkitRunnable { + + private static FurnaceTask instance; + + private final EpicFurnaces plugin; + + private FurnaceTask(EpicFurnaces plugin) { + this.plugin = plugin; + } + + public static FurnaceTask startTask(EpicFurnaces plugin) { + if (instance == null) { + instance = new FurnaceTask(plugin); + instance.runTaskTimer(plugin, 0, plugin.getConfig().getInt("Main.Furnace Tick Speed")); + } + + return instance; + } + + @Override + public void run() { + for (FurnaceObject furnace : plugin.getFurnaceManager().getFurnaces().values()) { + Location furnaceLocation = furnace.getLocation(); + + if (furnaceLocation == null) { + continue; + } + + if (furnaceLocation.getWorld() == null) { + plugin.getFurnaceManager().removeFurnace(furnaceLocation); + continue; + } + + int x = furnaceLocation.getBlockX() >> 4; + int z = furnaceLocation.getBlockZ() >> 4; + + if (!furnaceLocation.getWorld().isChunkLoaded(x, z)) { + continue; + } + + if (furnace.getLocation().getBlock().getType() != Material.FURNACE && furnace.getLocation().getBlock().getType() != plugin.getBukkitEnums().getBurningFurnace()) { + continue; + } + + if (((org.bukkit.block.Furnace) furnaceLocation.getBlock().getState()).getBurnTime() == 0) { + continue; + } + + if (furnace.getLevel().getOverheat() != 0) { + overheat(furnace); + } + + if (furnace.getLevel().getFuelShare() != 0) { + fuelShare(furnace); + } + } + } + + private void overheat(FurnaceObject furnace) { + if (furnace.getRadius(true) == null || furnace.getRadiusLast(true) != furnace.getLevel().getOverheat()) { + furnace.setRadiusLast(furnace.getLevel().getOverheat(), true); + cache(furnace, true); + } + + for (Location location : furnace.getRadius(true)) { + int random = ThreadLocalRandom.current().nextInt(0, 10); + + if (random != 1) { + continue; + } + + Block block = location.getBlock(); + + if (block.getType() == Material.AIR || block.getRelative(BlockFace.UP).getType() != Material.AIR) { + continue; + } + + broadcastParticles(location); + + if (block.getType() == Material.SNOW) { + block.setType(Material.AIR); + continue; + } + + if (block.getType() == Material.ICE || block.getType() == Material.PACKED_ICE) { + block.setType(Material.WATER); + } + } + } + + private void fuelShare(FurnaceObject furnace) { + if (furnace.getRadius(false) == null || furnace.getRadiusLast(false) != furnace.getLevel().getOverheat()) { + furnace.setRadiusLast(furnace.getLevel().getOverheat(), false); + cache(furnace, false); + } + + for (Location location : furnace.getRadius(false)) { + int random = ThreadLocalRandom.current().nextInt(0, 10); + + if (random != 1) { + continue; + } + + Block block = location.getBlock(); + + if (block.getType() != Material.FURNACE && block.getType() != plugin.getBukkitEnums().getBurningFurnace()) { + continue; + } + + FurnaceObject other = plugin.getFurnaceManager().getFurnace(block); + + if (furnace != other) { + org.bukkit.block.Furnace furnaceBlock = ((org.bukkit.block.Furnace) block.getState()); + + if (furnaceBlock.getBurnTime() == 0) { + furnaceBlock.setBurnTime((short) 100); + furnaceBlock.update(); + broadcastParticles(location); + } + } + + } + } + + private void cache(FurnaceObject furnace, boolean overheat) { + Block block = furnace.getLocation().getBlock(); + int radius = 3 * (overheat ? furnace.getLevel().getOverheat() : furnace.getLevel().getFuelShare()); + int rSquared = radius * radius; + int bx = block.getX(); + int by = block.getY(); + int bz = block.getZ(); + + for (int fx = -radius; fx <= radius; fx++) { + for (int fy = -2; fy <= 1; fy++) { + for (int fz = -radius; fz <= radius; fz++) { + if ((fx * fx) + (fz * fz) <= rSquared) { + Location location = new Location(block.getWorld(), bx + fx, by + fy, bz + fz); + furnace.addToRadius(location, overheat); + } + } + } + } + } + + private void broadcastParticles(Location location) { + float px = (float) (0 + (Math.random() * 1)); + float pz = (float) (0 + (Math.random() * 1)); + + if (plugin.getConfig().getBoolean("Main.Overheat Particles")) { + Arconix.pl().getApi().packetLibrary.getParticleManager().broadcastParticle(location, px, .5F, pz, 0, "SMOKE_NORMAL", 25); + } + } +} \ No newline at end of file diff --git a/core/src/main/java/com/songoda/epicfurnaces/tasks/HologramTask.java b/core/src/main/java/com/songoda/epicfurnaces/tasks/HologramTask.java new file mode 100644 index 0000000..5c2b614 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/tasks/HologramTask.java @@ -0,0 +1,110 @@ +package com.songoda.epicfurnaces.tasks; + +import com.songoda.arconix.api.methods.formatting.TextComponent; +import com.songoda.arconix.plugin.Arconix; +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.furnace.FurnaceObject; +import com.songoda.epicfurnaces.utils.Debugger; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.Furnace; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.ArrayList; + +public class HologramTask extends BukkitRunnable { + + private static HologramTask instance; + + private final EpicFurnaces plugin; + + private HologramTask(EpicFurnaces plugin) { + this.plugin = plugin; + } + + public static HologramTask startTask(EpicFurnaces plugin) { + if (instance == null) { + instance = new HologramTask(plugin); + instance.runTaskTimer(plugin, 0, 20); + } + + return instance; + } + + @Override + public void run() { + if (!plugin.getConfig().getBoolean("Main.Furnaces Have Holograms")) { + return; + } + + if (plugin.getFurnaceManager() == null) { + return; + } + + for (FurnaceObject furnace : plugin.getFurnaceManager().getFurnaces().values()) { + if (furnace.getLocation() == null || furnace.getLocation().getWorld() == null || furnace.getLocation().getBlock() == null) { + continue; + } + + if (furnace.getLocation().getBlock().getType() != Material.FURNACE) { + continue; + } + + Location location = furnace.getLocation().add(0.5, 1.25, 0.5); + addHologram(location, furnace); + } + } + + public void despawn(Block b) { + Location location = b.getLocation().add(0.5, 1.25, 0.5); + Arconix.pl().getApi().packetLibrary.getHologramManager().despawnHologram(location); + } + + public void addHologram(Location location, FurnaceObject furnace) { + try { + Furnace furnaceBlock = ((Furnace) furnace.getLocation().getBlock().getState()); + + int performance = (furnaceBlock.getCookTime() - furnace.getPerformanceTotal()) <= 0 ? 0 : furnace.getPerformanceTotal(); + float percent = (float) (furnaceBlock.getCookTime() - performance) / (200 - performance); + int progressBars = (int) (6 * percent) + (percent == 0 ? 0 : 1); + int leftOver = (6 - progressBars); + + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < progressBars; i++) { + sb.append("&a="); + } + + for (int i = 0; i < leftOver; i++) { + sb.append("&c="); + } + + ArrayList list = new ArrayList<>(); + + String progress = TextComponent.formatText(sb.toString()); + + if (furnaceBlock.getInventory().getFuel() == null) { + progress = plugin.getLocale().getMessage("general.hologram.outoffuel"); + } + + int inAmt = 0; + int outAmt = 0; + if (furnaceBlock.getInventory().getSmelting() != null) { + inAmt = furnaceBlock.getInventory().getSmelting().getAmount(); + } + if (furnaceBlock.getInventory().getResult() != null) { + outAmt = furnaceBlock.getInventory().getResult().getAmount(); + } + + String stats = plugin.getLocale().getMessage("general.hologram.stats", inAmt, outAmt > 64 ? 64 : outAmt); + list.add(progress); + list.add(stats); + + Arconix.pl().getApi().packetLibrary.getHologramManager().spawnHolograms(location, list); + + } catch (Exception e) { + Debugger.runReport(e); + } + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/utils/BukkitEnums.java b/core/src/main/java/com/songoda/epicfurnaces/utils/BukkitEnums.java new file mode 100644 index 0000000..324aa5b --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/utils/BukkitEnums.java @@ -0,0 +1,29 @@ +package com.songoda.epicfurnaces.utils; + +import com.songoda.epicfurnaces.EpicFurnaces; +import org.bukkit.Material; +import org.bukkit.Sound; + +public class BukkitEnums { + private final EpicFurnaces instance; + + public BukkitEnums(EpicFurnaces instance) { + this.instance = instance; + } + + public Material getWool() { + return Material.valueOf(instance.getCurrentVersion() > 9 ? "WHITE_WOOL" : "WOOL"); + } + + public Material getWetSponge() { + return Material.valueOf(instance.getCurrentVersion() > 9 ? "WET_SPONGE" : "SPONGE"); + } + + public Material getBurningFurnace() { + return Material.valueOf(instance.getCurrentVersion() < 9 ? "BURNING_FURNACE" : "FURNACE"); + } + + public Sound getLevelUp() { + return Sound.valueOf(instance.getCurrentVersion() > 9 ? "PLAYER_LEVEL_UP" : "LEVEL_UP"); + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/utils/Debugger.java b/core/src/main/java/com/songoda/epicfurnaces/utils/Debugger.java new file mode 100644 index 0000000..148b2ec --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/utils/Debugger.java @@ -0,0 +1,31 @@ +package com.songoda.epicfurnaces.utils; + +import com.songoda.epicfurnaces.EpicFurnaces; + +/** + * Created by songoda on 3/21/2017. + */ +public class Debugger { + + + public static void runReport(Exception e) { + if (isDebug()) { + System.out.println("=============================================================="); + System.out.println("The following is an error encountered in EpicFurnaces."); + System.out.println("--------------------------------------------------------------"); + e.printStackTrace(); + System.out.println("=============================================================="); + } + sendReport(e); + } + + public static void sendReport(Exception e) { + + } + + public static boolean isDebug() { + EpicFurnaces plugin = EpicFurnaces.getInstance(); + return plugin.getConfig().getBoolean("System.Debugger Enabled"); + } + +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/utils/Methods.java b/core/src/main/java/com/songoda/epicfurnaces/utils/Methods.java new file mode 100644 index 0000000..0acd740 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/utils/Methods.java @@ -0,0 +1,81 @@ +package com.songoda.epicfurnaces.utils; + +import com.songoda.arconix.plugin.Arconix; +import com.songoda.epicfurnaces.EpicFurnaces; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +/** + * Created by songoda on 2/25/2017. + */ +public class Methods { + + public static ItemStack getGlass() { + try { + EpicFurnaces plugin = EpicFurnaces.getInstance(); + return Arconix.pl().getApi().getGUI().getGlass(plugin.getConfig().getBoolean("Interfaces.Replace Glass Type 1 With Rainbow Glass"), plugin.getConfig().getInt("Interfaces.Glass Type 1")); + } catch (Exception e) { + Debugger.runReport(e); + } + return null; + } + + public static void particles(Block b, Player p) { + try { + EpicFurnaces plugin = EpicFurnaces.getInstance(); + if (plugin.getConfig().getBoolean("settings.On-upgrade-particles")) { + Location location = b.getLocation(); + location.setX(location.getX() + .5); + location.setY(location.getY() + .5); + location.setZ(location.getZ() + .5); + //TODO: particles + //p.getWorld().spawnParticle(org.bukkit.Particle.valueOf(plugin.getConfig().getString("Main.Upgrade Particle Type")), location, 200, .5, .5, .5); + } + } catch (Exception e) { + Debugger.runReport(e); + } + } + + public static ItemStack getBackgroundGlass(boolean type) { + try { + EpicFurnaces plugin = EpicFurnaces.getInstance(); + if (type) + return Arconix.pl().getApi().getGUI().getGlass(false, plugin.getConfig().getInt("Interfaces.Glass Type 2")); + else + return Arconix.pl().getApi().getGUI().getGlass(false, plugin.getConfig().getInt("Interfaces.Glass Type 3")); + } catch (Exception e) { + Debugger.runReport(e); + } + return null; + } + + public static String cleanString(String typ) { + try { + String type = typ.replaceAll("_", " "); + type = ChatColor.stripColor(type.substring(0, 1).toUpperCase() + type.toLowerCase().substring(1)); + return type; + } catch (Exception e) { + Debugger.runReport(e); + } + return null; + } + + public static String formatName(int level, int uses, boolean full) { + try { + String name = EpicFurnaces.getInstance().getLocale().getMessage("general.nametag.nameformat", level); + + String info = ""; + if (full) { + info += Arconix.pl().getApi().format().convertToInvisibleString(level + ":" + uses + ":"); + } + + return info + Arconix.pl().getApi().format().formatText(name); + } catch (Exception e) { + Debugger.runReport(e); + } + return null; + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/utils/MySQLDatabase.java b/core/src/main/java/com/songoda/epicfurnaces/utils/MySQLDatabase.java new file mode 100644 index 0000000..1352954 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/utils/MySQLDatabase.java @@ -0,0 +1,49 @@ +package com.songoda.epicfurnaces.utils; + +import com.songoda.epicfurnaces.EpicFurnaces; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class MySQLDatabase { + + private final EpicFurnaces instance; + + private Connection connection; + + public MySQLDatabase(EpicFurnaces instance) { + this.instance = instance; + try { + Class.forName("com.mysql.jdbc.Driver"); + + String url = "jdbc:mysql://" + instance.getConfig().getString("Database.IP") + ":" + instance.getConfig().getString("Database.Port") + "/" + instance.getConfig().getString("Database.Database Name") + "?autoReconnect=true&useSSL=false"; + this.connection = DriverManager.getConnection(url, instance.getConfig().getString("Database.Username"), instance.getConfig().getString("Database.Password")); + + //ToDo: This is sloppy + connection.createStatement().execute( + "CREATE TABLE IF NOT EXISTS `" + instance.getConfig().getString("Database.Prefix") + "charged` (\n" + + "\t`location` TEXT NULL,\n" + + "\t`level` INT NULL,\n" + + "\t`uses` INT NULL,\n" + + "\t`tolevel` INT NULL,\n" + + "\t`nickname` TEXT NULL,\n" + + "\t`accesslist` TEXT NULL,\n" + + "\t`placedby` TEXT NULL\n" + + ")"); + + connection.createStatement().execute("CREATE TABLE IF NOT EXISTS `" + instance.getConfig().getString("Database.Prefix") + "boosts` (\n" + + "\t`endtime` TEXT NULL,\n" + + "\t`amount` INT NULL,\n" + + "\t`uuid` TEXT NULL\n" + + ")"); + + } catch (ClassNotFoundException | SQLException e) { + System.out.println("Database connection failed."); + } + } + + public Connection getConnection() { + return connection; + } +} \ No newline at end of file diff --git a/core/src/main/java/com/songoda/epicfurnaces/utils/NMSUtil.java b/core/src/main/java/com/songoda/epicfurnaces/utils/NMSUtil.java new file mode 100644 index 0000000..53040a6 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/utils/NMSUtil.java @@ -0,0 +1,100 @@ +package com.songoda.epicfurnaces.utils; + + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.lang.reflect.Field; + +public class NMSUtil { + + public static String getVersion() { + String name = Bukkit.getServer().getClass().getPackage().getName(); + return name.substring(name.lastIndexOf('.') + 1) + "."; + } + + public static int getVersionNumber() { + String name = getVersion().substring(3); + return Integer.valueOf(name.substring(0, name.length() - 4)); + } + + public static int getVersionReleaseNumber() { + String NMSVersion = getVersion(); + return Integer.valueOf(NMSVersion.substring(NMSVersion.length() - 2).replace(".", "")); + } + + public static Class getNMSClass(String className) { + try { + String fullName = "net.minecraft.server." + getVersion() + className; + return Class.forName(fullName); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static Class getCraftClass(String className) throws ClassNotFoundException { + try { + String fullName = "org.bukkit.craftbukkit." + getVersion() + className; + return Class.forName(fullName); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static Field getField(Class clazz, String name, boolean declared) { + try { + Field field; + + if (declared) { + field = clazz.getDeclaredField(name); + } else { + field = clazz.getField(name); + } + + field.setAccessible(true); + return field; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static Object getFieldObject(Object object, Field field) { + try { + return field.get(object); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static void setField(Object object, String fieldName, Object fieldValue, boolean declared) { + try { + Field field; + + if (declared) { + field = object.getClass().getDeclaredField(fieldName); + } else { + field = object.getClass().getField(fieldName); + } + + field.setAccessible(true); + field.set(object, fieldValue); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void sendPacket(Player player, Object packet) { + try { + Object handle = player.getClass().getMethod("getHandle").invoke(player); + Object playerConnection = handle.getClass().getField("playerConnection").get(handle); + playerConnection.getClass().getMethod("sendPacket", getNMSClass("Packet")).invoke(playerConnection, packet); + } catch (Exception e) { + e.printStackTrace(); + } + } +} + diff --git a/core/src/main/java/com/songoda/epicfurnaces/utils/SettingsManager.java b/core/src/main/java/com/songoda/epicfurnaces/utils/SettingsManager.java new file mode 100644 index 0000000..dd71e3d --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/utils/SettingsManager.java @@ -0,0 +1,256 @@ +package com.songoda.epicfurnaces.utils; + +import com.songoda.arconix.api.methods.formatting.TextComponent; +import com.songoda.arconix.api.utils.ConfigWrapper; +import com.songoda.epicfurnaces.EpicFurnaces; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Created by songo on 6/4/2017. + */ +public class SettingsManager implements Listener { + + private static final Pattern SETTINGS_PATTERN = Pattern.compile("(.{1,28}(?:\\s|$))|(.{0,28})", Pattern.DOTALL); + + private static ConfigWrapper defs; + private final EpicFurnaces instance; + private String pluginName = "EpicFurnaces"; + private Map cat = new HashMap<>(); + private Map current = new HashMap<>(); + + public SettingsManager(EpicFurnaces plugin) { + this.instance = plugin; + + plugin.saveResource("SettingDefinitions.yml", true); + defs = new ConfigWrapper(plugin, "", "SettingDefinitions.yml"); + defs.createNewFile("Loading data file", pluginName + " SettingDefinitions file"); + Bukkit.getPluginManager().registerEvents(this, plugin); + } + + @EventHandler + public void onInventoryClick(InventoryClickEvent event) { + ItemStack clickedItem = event.getCurrentItem(); + + if (event.getInventory() != event.getWhoClicked().getOpenInventory().getTopInventory() + || clickedItem == null || !clickedItem.hasItemMeta() + || !clickedItem.getItemMeta().hasDisplayName()) { + return; + } + + if (event.getInventory().getTitle().equals(pluginName + " Settings Manager")) { + event.setCancelled(true); + if (clickedItem.getType().name().contains("STAINED_GLASS")) return; + + String type = ChatColor.stripColor(clickedItem.getItemMeta().getDisplayName()); + this.cat.put((Player) event.getWhoClicked(), type); + this.openEditor((Player) event.getWhoClicked()); + } else if (event.getInventory().getTitle().equals(pluginName + " Settings Editor")) { + event.setCancelled(true); + if (clickedItem.getType().name().contains("STAINED_GLASS")) return; + + Player player = (Player) event.getWhoClicked(); + + String key = cat.get(player) + "." + ChatColor.stripColor(clickedItem.getItemMeta().getDisplayName()); + + if (instance.getConfig().get(key).getClass().getName().equals("java.lang.Boolean")) { + this.instance.getConfig().set(key, !instance.getConfig().getBoolean(key)); + this.finishEditing(player); + } else { + this.editObject(player, key); + } + } + } + + @EventHandler + public void onChat(AsyncPlayerChatEvent event) { + Player player = event.getPlayer(); + if (!current.containsKey(player)) return; + + String value = current.get(player); + FileConfiguration config = instance.getConfig(); + if (config.isInt(value)) { + config.set(value, Integer.parseInt(event.getMessage())); + } else if (config.isDouble(value)) { + config.set(value, Double.parseDouble(event.getMessage())); + } else if (config.isString(value)) { + config.set(value, event.getMessage()); + } + + this.finishEditing(player); + event.setCancelled(true); + } + + public void finishEditing(Player player) { + this.current.remove(player); + this.instance.saveConfig(); + this.openEditor(player); + } + + + public void editObject(Player player, String current) { + this.current.put(player, ChatColor.stripColor(current)); + + player.closeInventory(); + player.sendMessage(""); + player.sendMessage(TextComponent.formatText("&7Please enter a value for &6" + current + "&7.")); + if (instance.getConfig().isInt(current) || instance.getConfig().isDouble(current)) { + player.sendMessage(TextComponent.formatText("&cUse only numbers.")); + } + player.sendMessage(""); + } + + public void openSettingsManager(Player player) { + Inventory inventory = Bukkit.createInventory(null, 27, pluginName + " Settings Manager"); + ItemStack glass = Methods.getGlass(); + for (int i = 0; i < inventory.getSize(); i++) { + inventory.setItem(i, glass); + } + + int slot = 10; + for (String key : instance.getConfig().getDefaultSection().getKeys(false)) { + ItemStack item = new ItemStack(instance.getBukkitEnums().getWool(), 1, (byte) (slot - 9)); //ToDo: Make this function as it was meant to. + ItemMeta meta = item.getItemMeta(); + meta.setLore(Collections.singletonList(TextComponent.formatText("&6Click To Edit This Category."))); + meta.setDisplayName(TextComponent.formatText("&f&l" + key)); + item.setItemMeta(meta); + inventory.setItem(slot, item); + slot++; + } + + player.openInventory(inventory); + } + + public void openEditor(Player player) { + Inventory inventory = Bukkit.createInventory(null, 54, pluginName + " Settings Editor"); + FileConfiguration config = instance.getConfig(); + + int slot = 0; + for (String key : config.getConfigurationSection(cat.get(player)).getKeys(true)) { + String fKey = cat.get(player) + "." + key; + ItemStack item = new ItemStack(Material.DIAMOND_HELMET); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(TextComponent.formatText("&6" + key)); + + List lore = new ArrayList<>(); + if (config.isBoolean(fKey)) { + item.setType(Material.LEVER); + lore.add(TextComponent.formatText(config.getBoolean(fKey) ? "&atrue" : "&cfalse")); + } else if (config.isString(fKey)) { + item.setType(Material.PAPER); + lore.add(TextComponent.formatText("&9" + config.getString(fKey))); + } else if (config.isInt(fKey)) { + item.setType(Material.COMPASS); + lore.add(TextComponent.formatText("&5" + config.getInt(fKey))); + } + + if (defs.getConfig().contains(fKey)) { + String text = defs.getConfig().getString(key); + + Matcher m = SETTINGS_PATTERN.matcher(text); + while (m.find()) { + if (m.end() != text.length() || m.group().length() != 0) + lore.add(TextComponent.formatText("&7" + m.group())); + } + } + + meta.setLore(lore); + item.setItemMeta(meta); + + inventory.setItem(slot, item); + slot++; + } + + player.openInventory(inventory); + } + + public void updateSettings() { + FileConfiguration config = instance.getConfig(); + + for (Setting setting : Setting.values()) { + if (config.contains("settings." + setting.oldSetting)) { + config.addDefault(setting.setting, instance.getConfig().get("settings." + setting.oldSetting)); + config.set("settings." + setting.oldSetting, null); + } else { + config.addDefault(setting.setting, setting.option); + } + } + } + + public enum Setting { + + SOUNDS_ENABLED("Sounds", "Main.Sounds Enabled", true), + + o3("Upgrade-with-material", "Main.Upgrade By Smelting Materials", true), + UPGRADE_WITH_ECO_ENABLED("Upgrade-with-eco", "Main.Upgrade With Economy", true), + UPGRADE_WITH_XP_ENABLED("Upgrade-with-xp", "Main.Upgrade With XP", true), + + o6("Turbo-level-multiplier", "Main.Level Cost Multiplier", 50), + + o102("Remember-furnace-Levels", "Main.Remember Furnace Item Levels", true), + + owqr("-", "Main.Furnaces Have Holograms", true), + + o324("Redstone-Deactivate", "Main.Redstone Deactivates Furnaces", true), + + o11("furnace-upgrade-cost", "Main.Furnace Upgrade Cost", "IRON_INGOT"), + o12("Custom-recipes", "Main.Use Custom Recipes", true), + o13("Ignore-custom-recipes-for-rewards", "Main.No Rewards From Custom Recipes", true), + + UPGRADE_PARTICLE_TYPE("Upgrade-particle-Type", "Main.Upgrade Particle Type", "SPELL_WITCH"), + + o18("Remote-Furnaces", "Main.Access Furnaces Remotely", true), + + o543("-", "Main.Furnace Tick Speed", 10), + o5423("-", "Main.Auto Save Interval In Seconds", 15), + o54("-", "Main.Overheat Particles", true), + + o14("Reward-Icon", "Interfaces.Reward Icon", "GOLDEN_APPLE"), + o15("Performance-Icon", "Interfaces.Performance Icon", "REDSTONE"), + o16("FuelDuration-Icon", "Interfaces.FuelShare Icon", "COAL_BLOCK"), + o316("FuelDuration-Icon", "Interfaces.FuelDuration Icon", "COAL"), + o162("-", "Interfaces.Overheat Icon", "FIRE_CHARGE"), + ECO_ICON("ECO-Icon", "Interfaces.Economy Icon", "SUNFLOWER"), + XP_ICON("XP-Icon", "Interfaces.XP Icon", "EXPERIENCE_BOTTLE"), + GLASS_TYPE_1("Glass-Type-1", "Interfaces.Glass Type 1", 7), + GLASS_TYPE_2("Glass-Type-2", "Interfaces.Glass Type 2", 11), + GLASS_TYPE_3("Glass-Type-3", "Interfaces.Glass Type 3", 3), + RAINBOW_GLASS("Rainbow-Glass", "Interfaces.Replace Glass Type 1 With Rainbow Glass", false), + + DATABASE_SUPPORT("-", "Database.Activate Mysql Support", false), + DATABASE_IP("-", "Database.IP", "127.0.0.1"), + DATABASE_PORT("-", "Database.Port", 3306), + DATABASE_NAME("-", "Database.Database Name", "EpicFurnaces"), + DATABASE_PREFIX("-", "Database.Prefix", "EF-"), + DATABASE_USERNAME("-", "Database.Username", "PUT_USERNAME_HERE"), + DATABASE_PASSWORD("-", "Database.Password", "PUT_PASSWORD_HERE"), + + DOWNLOAD_FILES("-", "System.Download Needed Data Files", true), + LANGUAGE_MODE("-", "System.Language Mode", "en_US"), + DEBUG_MODE("Debug-Mode", "System.Debugger Enabled", false); + + private final String setting, oldSetting; + private final Object option; + + Setting(String oldSetting, String setting, Object option) { + this.oldSetting = oldSetting; + this.setting = setting; + this.option = option; + } + + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/utils/gui/AbstractAnvilGUI.java b/core/src/main/java/com/songoda/epicfurnaces/utils/gui/AbstractAnvilGUI.java new file mode 100644 index 0000000..41e382e --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/utils/gui/AbstractAnvilGUI.java @@ -0,0 +1,264 @@ +package com.songoda.epicfurnaces.utils.gui; + +import com.songoda.epicfurnaces.EpicFurnaces; +import com.songoda.epicfurnaces.utils.NMSUtil; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +public class AbstractAnvilGUI { + + private static Class BlockPosition; + private static Class PacketPlayOutOpenWindow; + private static Class ContainerAnvil; + private static Class ChatMessage; + private static Class EntityHuman; + private static boolean loadedClasses = false; + private Player player; + @SuppressWarnings("unused") + private AnvilClickEventHandler handler; + private Map items = new HashMap<>(); + private OnClose onClose = null; + private Inventory inv; + private Listener listener; + + public AbstractAnvilGUI(final Player player, final AnvilClickEventHandler handler) { + loadClasses(); + this.player = player; + this.handler = handler; + + this.listener = new Listener() { + @EventHandler + public void onInventoryClick(InventoryClickEvent event) { + if (!(event.getWhoClicked() instanceof Player) || !event.getInventory().equals(inv)) return; + + event.setCancelled(true); + + ItemStack item = event.getCurrentItem(); + int slot = event.getRawSlot(); + String name = ""; + + if (item != null) { + if (item.hasItemMeta()) { + ItemMeta meta = item.getItemMeta(); + + if (meta.hasDisplayName()) { + name = meta.getDisplayName(); + } + } + } + + AnvilClickEvent clickEvent = new AnvilClickEvent(AnvilSlot.bySlot(slot), name); + + handler.onAnvilClick(clickEvent); + + if (clickEvent.getWillClose()) { + event.getWhoClicked().closeInventory(); + } + + if (clickEvent.getWillDestroy()) { + destroy(); + } + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + if (!(event.getPlayer() instanceof Player)) return; + Inventory inv = event.getInventory(); + player.setLevel(player.getLevel() - 1); + if (!inv.equals(AbstractAnvilGUI.this.inv)) return; + inv.clear(); + OnClose onClose = getOnClose(); + Bukkit.getScheduler().scheduleSyncDelayedTask(EpicFurnaces.getInstance(), () -> { + if (onClose != null) onClose.OnClose(player, inv); + destroy(); + }, 1L); + } + + @EventHandler + public void onPlayerQuit(PlayerQuitEvent event) { + if (!event.getPlayer().equals(getPlayer())) return; + player.setLevel(player.getLevel() - 1); + destroy(); + } + }; + + Bukkit.getPluginManager().registerEvents(listener, EpicFurnaces.getInstance()); + } + + private void loadClasses() { + if (loadedClasses) return; + BlockPosition = NMSUtil.getNMSClass("BlockPosition"); + PacketPlayOutOpenWindow = NMSUtil.getNMSClass("PacketPlayOutOpenWindow"); + ContainerAnvil = NMSUtil.getNMSClass("ContainerAnvil"); + EntityHuman = NMSUtil.getNMSClass("EntityHuman"); + ChatMessage = NMSUtil.getNMSClass("ChatMessage"); + loadedClasses = true; + } + + public Player getPlayer() { + return player; + } + + public void setSlot(AnvilSlot slot, ItemStack item) { + items.put(slot, item); + } + + public void open() { + player.setLevel(player.getLevel() + 1); + + try { + Object craftPlayer = Objects.requireNonNull(NMSUtil.getCraftClass("entity.CraftPlayer")).cast(player); + Method getHandleMethod = craftPlayer.getClass().getMethod("getHandle"); + Object entityPlayer = getHandleMethod.invoke(craftPlayer); + + Object container; + + if (NMSUtil.getVersionNumber() == 7) { + container = ContainerAnvil.getConstructor(new Class[]{NMSUtil.getNMSClass("PlayerInventory"), NMSUtil.getNMSClass("World"), Integer.TYPE, Integer.TYPE, Integer.TYPE, EntityHuman}).newInstance(NMSUtil.getFieldObject(entityPlayer, NMSUtil.getField(entityPlayer.getClass(), "inventory", false)), NMSUtil.getFieldObject(entityPlayer, NMSUtil.getField(entityPlayer.getClass(), "world", false)), 0, 0, 0, entityPlayer); + } else { + container = ContainerAnvil.getConstructor(NMSUtil.getNMSClass("PlayerInventory"), NMSUtil.getNMSClass("World"), BlockPosition, EntityHuman).newInstance(NMSUtil.getFieldObject(entityPlayer, NMSUtil.getField(entityPlayer.getClass(), "inventory", false)), NMSUtil.getFieldObject(entityPlayer, NMSUtil.getField(entityPlayer.getClass(), "world", false)), BlockPosition.getConstructor(int.class, int.class, int.class).newInstance(0, 0, 0), entityPlayer); + } + + Objects.requireNonNull(NMSUtil.getField(NMSUtil.getNMSClass("Container"), "checkReachable", true)).set(container, false); + + Method getBukkitViewMethod = container.getClass().getMethod("getBukkitView"); + Object bukkitView = getBukkitViewMethod.invoke(container); + Method getTopInventoryMethod = bukkitView.getClass().getMethod("getTopInventory"); + inv = (Inventory) getTopInventoryMethod.invoke(bukkitView); + + for (AnvilSlot slot : items.keySet()) { + inv.setItem(slot.getSlot(), items.get(slot)); + } + + Method nextContainerCounterMethod = entityPlayer.getClass().getMethod("nextContainerCounter"); + int c = (int) nextContainerCounterMethod.invoke(entityPlayer); + + Constructor chatMessageConstructor = ChatMessage.getConstructor(String.class, Object[].class); + Object packet; + + if (NMSUtil.getVersionNumber() == 7) { + packet = PacketPlayOutOpenWindow.getConstructor(new Class[]{Integer.TYPE, Integer.TYPE, String.class, Integer.TYPE, Boolean.TYPE, Integer.TYPE}).newInstance(c, 8, "Repairing", 0, Boolean.TRUE, 0); + } else { + packet = PacketPlayOutOpenWindow.getConstructor(int.class, String.class, NMSUtil.getNMSClass("IChatBaseComponent"), int.class).newInstance(c, "minecraft:anvil", chatMessageConstructor.newInstance("Repairing", new Object[]{}), 0); + } + + NMSUtil.sendPacket(player, packet); + + Field activeContainerField = NMSUtil.getField(EntityHuman, "activeContainer", true); + + if (activeContainerField != null) { + activeContainerField.set(entityPlayer, container); + Objects.requireNonNull(NMSUtil.getField(NMSUtil.getNMSClass("Container"), "windowId", true)).set(activeContainerField.get(entityPlayer), c); + + Method addSlotListenerMethod = activeContainerField.get(entityPlayer).getClass().getMethod("addSlotListener", NMSUtil.getNMSClass("ICrafting")); + addSlotListenerMethod.invoke(activeContainerField.get(entityPlayer), entityPlayer); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void destroy() { + onClose = null; + player = null; + handler = null; + items = null; + + HandlerList.unregisterAll(listener); + + listener = null; + } + + private OnClose getOnClose() { + return onClose; + } + + public void setOnClose(OnClose onClose) { + this.onClose = onClose; + } + + public enum AnvilSlot { + INPUT_LEFT(0), + INPUT_RIGHT(1), + OUTPUT(2); + + private int slot; + + AnvilSlot(int slot) { + this.slot = slot; + } + + public static AnvilSlot bySlot(int slot) { + for (AnvilSlot anvilSlot : values()) { + if (anvilSlot.getSlot() == slot) { + return anvilSlot; + } + } + + return null; + } + + public int getSlot() { + return slot; + } + } + + public interface AnvilClickEventHandler { + void onAnvilClick(AnvilClickEvent event); + } + + public class AnvilClickEvent { + private AnvilSlot slot; + + private String name; + + private boolean close = true; + private boolean destroy = true; + + public AnvilClickEvent(AnvilSlot slot, String name) { + this.slot = slot; + this.name = name; + } + + public AnvilSlot getSlot() { + return slot; + } + + public String getName() { + return name; + } + + public boolean getWillClose() { + return close; + } + + public void setWillClose(boolean close) { + this.close = close; + } + + public boolean getWillDestroy() { + return destroy; + } + + public void setWillDestroy(boolean destroy) { + this.destroy = destroy; + } + } +} + diff --git a/core/src/main/java/com/songoda/epicfurnaces/utils/gui/FastInv.java b/core/src/main/java/com/songoda/epicfurnaces/utils/gui/FastInv.java new file mode 100644 index 0000000..931989b --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/utils/gui/FastInv.java @@ -0,0 +1,529 @@ +package com.songoda.epicfurnaces.utils.gui; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.*; +import org.bukkit.event.server.PluginDisableEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitTask; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * A fast API to easily create advanced GUI. + * The project is on GitHub + * + * @author MrMicky + * @version 2.0.3 - Now supports async operations + */ +public class FastInv implements InventoryHolder { + + private static Plugin plugin = null; + private boolean cancelTasksOnClose = true; + private Set closeListeners = new HashSet<>(); + private Set clickListeners = new HashSet<>(); + private Map itemListeners = new HashMap<>(); + private Set tasks = new HashSet<>(); + private Inventory inventory; + + /** + * Create a new FastInv with a custom size. + * + * @param size The size of the menus. + */ + public FastInv(int size) { + this(size, InventoryType.CHEST.getDefaultTitle()); + } + + /** + * Create a new FastInv with a custom size and title. + * + * @param size The size of the menus. + * @param title The title (name) of the menus. + */ + public FastInv(int size, String title) { + this(size, InventoryType.CHEST, title); + } + + /** + * Create a new FastInv with a custom type. + * + * @param type The type of the menus. + */ + public FastInv(InventoryType type) { + this(type, type.getDefaultTitle()); + } + + /** + * Create a new FastInv with a custom type and title. + * + * @param type The type of the menus. + * @param title The title of the menus. + * @throws IllegalStateException if FastInv is not init with FastInv.init(Plugin plugin) + */ + public FastInv(InventoryType type, String title) { + this(0, type, title); + } + + private FastInv(int size, InventoryType type, String title) { + if (plugin == null) { + throw new IllegalStateException("FastInv is not initialised"); + } + + runSync(() -> { + if (type == InventoryType.CHEST && size > 0) { + inventory = Bukkit.createInventory(this, size, title); + } else { + inventory = Bukkit.createInventory(this, type, title); + } + }); + } + + /** + * Register your FastInv instance. + * + * @param plugin The plugin that uses FastInv. + */ + public static void init(Plugin plugin) { + if (FastInv.plugin == null) { + FastInv.plugin = plugin; + Bukkit.getPluginManager().registerEvents(getListener(), plugin); + } + } + + /** + * Add an {@link ItemStack} to the menus. + * + * @param item The item to add + * @return This FastInv instance, for chaining. + */ + public FastInv addItem(ItemStack item) { + return addItem(item, null); + } + + /** + * Add an {@link ItemStack} to the menus with a {@link FastInvClickListener} to handle clicks. + * + * @param item The item to add. + * @param listener The {@link FastInvClickListener} for the item. + * @return This FastInv instance, for chaining. + */ + public FastInv addItem(ItemStack item, FastInvClickListener listener) { + runSync(() -> { + int slot = inventory.firstEmpty(); + if (slot >= 0) { + addItem(slot, item, listener); + } + }); + return this; + } + + /** + * Add an {@link ItemStack} to the menus on a specific slot. + * + * @param slot The slot of the item. + * @param item The item to add. + * @return This FastInv instance, for chaining. + */ + public FastInv addItem(int slot, ItemStack item) { + return addItem(slot, item, null); + } + + /** + * Add an {@link ItemStack} to the menus on specific slot with a {@link FastInvClickListener} to handle clicks. + * + * @param slot The slot of the item. + * @param item The item to add. + * @param listener The FastInvClickListener for the item. + * @return This FastInv instance, for chaining. + */ + public FastInv addItem(int slot, ItemStack item, FastInvClickListener listener) { + runSync(() -> { + inventory.setItem(slot, item); + + if (listener != null) { + itemListeners.put(slot, listener); + } else { + itemListeners.remove(slot); + } + }); + + return this; + } + + /** + * Add an {@link ItemStack} to the menus on a range of slots. + * + * @param slotFrom Starting slot to put the item in. + * @param slotTo Ending slot to put the item in. + * @param item The item to add. + * @return This FastInv instance, for chaining. + */ + public FastInv addItem(int slotFrom, int slotTo, ItemStack item) { + return addItem(slotFrom, slotTo, item, null); + } + + /** + * Add an {@link ItemStack} to the menus on a range of slots with a {@link FastInvClickListener} to handle clicks. + * + * @param slotFrom Starting slot to put the item in. + * @param slotTo Ending slot to put the item in. + * @param item The item to add. + * @param listener The FastInvClickListener for the item. + * @return This FastInv instance, for chaining. + */ + public FastInv addItem(int slotFrom, int slotTo, ItemStack item, FastInvClickListener listener) { + for (int i = slotFrom; i <= slotTo; i++) { + addItem(i, item, listener); + } + return this; + } + + /** + * Add an {@link ItemStack} to the menus on multiple slots. + * + * @param slots The slot of the item. + * @param item The item to add. + * @return This FastInv instance, for chaining. + */ + public FastInv addItem(int[] slots, ItemStack item) { + return addItem(slots, item, null); + } + + /** + * Add an {@link ItemStack} to the menus on the edges. + * + * @param item The item to add. + * @return This FastInv instance, for chaining. + */ + public FastInv edge(ItemStack item) { + int height = inventory.getSize() / 9; + + addItem(0, 9, item); + addItem(inventory.getSize() - 9, inventory.getSize() - 1, item); + + for (int i = 0; i < height; i++) { + addItem(i * 9, item); + addItem(i * 9 + 8, item); + } + + return this; + } + + /** + * Add an {@link ItemStack} to the menus on multiples slots with a {@link FastInvClickListener} to handle click. + * + * @param slots The slots to place the item. + * @param item The item to add. + * @param listener The FastInvClickListener for the item. + * @return This FastInv instance, for chaining. + */ + public FastInv addItem(int[] slots, ItemStack item, FastInvClickListener listener) { + for (int slot : slots) { + addItem(slot, item, listener); + } + return this; + } + + public FastInv fill(ItemStack itemStack) { + runSync(() -> { + for (int i = 0; i < inventory.getSize(); i++) { + if (inventory.getItem(i) == null) { + addItem(i, itemStack); + } + } + }); + return this; + } + + /** + * Add a {@link FastInvCloseListener} to listen on menus close. + * + * @param listener The {@link FastInvCloseListener} to add. + * @return This FastInv instance, for chaining. + */ + public FastInv onClose(FastInvCloseListener listener) { + closeListeners.add(listener); + return this; + } + + /** + * Add a {@link FastInvClickListener} to listen on menus click. + * + * @param listener The {@link FastInvClickListener} to add. + * @return This FastInv instance, for chaining. + */ + public FastInv onClick(FastInvClickListener listener) { + clickListeners.add(listener); + return this; + } + + /** + * Schedule a task to run. + * + * @param period Delay between each run. + * @param runnable The {@link Runnable} task to run. + * @return This FastInv instance, for chaining. + */ + public FastInv onUpdate(long period, Runnable runnable) { + return onUpdate(period, period, runnable); + } + + /** + * Schedule a task to run with a delay before starting. + * + * @param delay Ticks to wait before starting the task. + * @param period Delay between each run. + * @param runnable The {@link Runnable} task to run. + * @return This FastInv instance, for chaining + */ + public FastInv onUpdate(long delay, long period, Runnable runnable) { + tasks.add(Bukkit.getScheduler().runTaskTimer(plugin, runnable, delay, period)); + return this; + } + + /** + * Open the menus to a player. + * + * @param player The player to open the menu. + */ + public void open(Player player) { + Bukkit.getScheduler().runTask(plugin, () -> player.openInventory(inventory)); + } + + /** + * Open the menus to players. + * + * @param players The players to open the menu. + */ + public void open(Player... players) { + Bukkit.getScheduler().runTask(plugin, () -> { + for (Player p : players) { + p.openInventory(inventory); + } + }); + } + + /** + * Cancel all tasks. + */ + public void cancelTasks() { + tasks.forEach(BukkitTask::cancel); + tasks.clear(); + } + + /** + * Run a task on the server primary thread. + * + * @param runnable The runnable to run on the main thread + */ + public void runSync(Runnable runnable) { + if (Bukkit.isPrimaryThread()) { + runnable.run(); + } else { + Bukkit.getScheduler().runTask(plugin, runnable); + } + } + + public interface FastInvClickListener { + void onClick(FastInvClickEvent event); + } + + public interface FastInvCloseListener { + void onClose(FastInvCloseEvent event); + } + + public static abstract class FastInvEvent { + + private Player player; + private FastInv inventory; + private boolean cancelled; + + FastInvEvent(Player player, FastInv inventory, boolean cancelled) { + this.player = player; + this.inventory = inventory; + this.cancelled = cancelled; + } + + /** + * Get the FastInv menus. + * + * @return This associated FastInv instance. + */ + public FastInv getInventory() { + return inventory; + } + + /** + * Get the {@link Player} who clicked. + * + * @return the player who clicked. + */ + public Player getPlayer() { + return player; + } + + /** + * Get if the event is cancelled or not. + * + * @return Whether the event was cancelled. + */ + public boolean isCancelled() { + return cancelled; + } + + /** + * Set if the event will be cancel or not. + * + * @param cancel Whether the event should be cancelled. + */ + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + } + + public static class FastInvClickEvent extends FastInvEvent { + + private int slot; + private ItemStack item; + private InventoryAction action; + private ClickType clickType; + + private FastInvClickEvent(Player player, FastInv inventory, int slot, ItemStack item, + boolean cancelled, InventoryAction action, ClickType clickType) { + super(player, inventory, cancelled); + this.slot = slot; + this.item = item; + this.action = action; + this.clickType = clickType; + } + + /** + * Gets the {@link InventoryAction} + * + * @return The action of the event + */ + public InventoryAction getAction() { + return this.action; + } + + /** + * Gets the {@link ClickType} of the event. + * + * @return The click type + */ + public ClickType getClickType() { + return this.clickType; + } + + /** + * Get the clicked {@link ItemStack} + * + * @return The clicked item + */ + public ItemStack getItem() { + return this.item; + } + + /** + * Get the number of the clicked slot + * + * @return The slot number + */ + public int getSlot() { + return this.slot; + } + } + + public static class FastInvCloseEvent extends FastInvEvent { + private FastInvCloseEvent(Player player, FastInv inventory, boolean cancelled) { + super(player, inventory, cancelled); + } + } + + /** + * Get the Bukkit menus associated with this FastInv instance. + * + * @return The Bukkit {@link Inventory}. + */ + @Override + public Inventory getInventory() { + return inventory; + } + + private static Listener getListener() { + return new Listener() { + + @EventHandler + public void onClick(InventoryClickEvent event) { + if (event.getInventory().getHolder() instanceof FastInv && event.getWhoClicked() instanceof Player) { + int slot = event.getRawSlot(); + FastInv inv = (FastInv) event.getInventory().getHolder(); + + FastInvClickEvent clickEvent = new FastInvClickEvent((Player) event.getWhoClicked(), inv, slot, + event.getCurrentItem(), true, event.getAction(), event.getClick()); + + if (inv.itemListeners.containsKey(slot)) { + inv.itemListeners.get(slot).onClick(clickEvent); + } + + inv.clickListeners.forEach(listener -> listener.onClick(clickEvent)); + + if (clickEvent.isCancelled()) { + event.setCancelled(true); + } + } + } + + @EventHandler + public void onClose(InventoryCloseEvent event) { + if (event.getInventory().getHolder() instanceof FastInv && event.getPlayer() instanceof Player) { + Player player = (Player) event.getPlayer(); + FastInv inv = (FastInv) event.getInventory().getHolder(); + + FastInvCloseEvent closeEvent = new FastInvCloseEvent(player, inv, false); + inv.closeListeners.forEach(listener -> listener.onClose(closeEvent)); + + Bukkit.getScheduler().runTask(plugin, () -> { + // Tiny delay to prevent errors. + if (closeEvent.isCancelled() && player.isOnline()) { + player.openInventory(inv.getInventory()); + } else if (inv.getInventory().getViewers().isEmpty() && inv.cancelTasksOnClose) { + inv.cancelTasks(); + } + }); + } + } + + @EventHandler + public void onDisable(PluginDisableEvent event) { + if (event.getPlugin().equals(plugin)) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.getOpenInventory().getTopInventory().getHolder() instanceof FastInv) { + player.closeInventory(); + } + } + } + } + }; + } + + /** + * Set if the tasks will be cancel on menus close. + * + * @param cancelTasksOnClose Set if the tasks will be cancel + * @return This FastInv instance, for chaining. + */ + public FastInv setCancelTasksOnClose(boolean cancelTasksOnClose) { + this.cancelTasksOnClose = cancelTasksOnClose; + return this; + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/utils/gui/ItemBuilder.java b/core/src/main/java/com/songoda/epicfurnaces/utils/gui/ItemBuilder.java new file mode 100644 index 0000000..3b30dcd --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/utils/gui/ItemBuilder.java @@ -0,0 +1,294 @@ +package com.songoda.epicfurnaces.utils.gui; + +import org.bukkit.Color; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.block.banner.Pattern; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.*; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * A complete {@link ItemStack} builder for FastInv (only works on 1.8+). + *

+ * The project is on GitHub + * + * @author MrMicky + */ +public class ItemBuilder { + + private final ItemStack item; + private ItemMeta meta; + + /* + * Constructors: + */ + public ItemBuilder(Material material) { + this(new ItemStack(material)); + } + + public ItemBuilder(Material material, int amount) { + this(new ItemStack(material, amount)); + } + + public ItemBuilder(Material material, byte data) { + this(new ItemStack(material, 1, data)); + } + + public ItemBuilder(Material material, int amount, byte data) { + this(new ItemStack(material, amount, data)); + } + + public ItemBuilder(ItemStack item) { + this.item = item; + this.meta = item.getItemMeta(); + } + + /* + * Meta: + */ + public boolean hasMeta() { + return getMeta() != null; + } + + public ItemMeta getMeta() { + return meta; + } + + public ItemBuilder meta(ItemMeta meta) { + this.meta = meta; + return this; + } + + /* + * Name: + */ + public boolean hasName() { + return meta.hasDisplayName(); + } + + public String getName() { + return meta.getDisplayName(); + } + + public ItemBuilder name(String name) { + meta.setDisplayName(name); + return this; + } + + /* + * Lore: + */ + public boolean hasLore() { + return meta.hasLore(); + } + + public List getLore() { + return meta.getLore(); + } + + public ItemBuilder lore(String... lore) { + return lore(Arrays.asList(lore)); + } + + public ItemBuilder lore(List lore) { + meta.setLore(lore); + return this; + } + + public ItemBuilder addLore(List lore) { + if (!meta.hasLore()) { + meta.setLore(lore); + return this; + } + + List toAdd = meta.getLore(); + toAdd.addAll(lore); + meta.setLore(toAdd); + return this; + } + + public ItemBuilder addLore(String... lore) { + return addLore(Arrays.asList(lore)); + } + + /* + * Enchantments: + */ + public boolean hasEnchants() { + return meta.hasEnchants(); + } + + public boolean hasEnchant(Enchantment enchantment) { + return meta.hasEnchant(enchantment); + } + + public boolean hasConflictingEnchant(Enchantment enchantment) { + return meta.hasConflictingEnchant(enchantment); + } + + public Map getEnchants() { + return meta.getEnchants(); + } + + public ItemBuilder enchant(Enchantment enchantment, int level) { + meta.addEnchant(enchantment, level, true); + return this; + } + + public ItemBuilder removeEnchant(Enchantment enchantment) { + meta.removeEnchant(enchantment); + return this; + } + + /* + * Flags: + */ + public boolean hasFlag(ItemFlag flag) { + return meta.hasItemFlag(flag); + } + + public Set getFlags() { + return meta.getItemFlags(); + } + + public ItemBuilder addFlags(ItemFlag... flags) { + meta.addItemFlags(flags); + return this; + } + + public ItemBuilder removeFlags(ItemFlag... flags) { + meta.removeItemFlags(flags); + return this; + } + + /* + * Unbreakability: + */ + public boolean isUnbreakable() { + return meta.spigot().isUnbreakable(); + } + + public ItemBuilder unbreakable() { + return unbreakable(true); + } + + public ItemBuilder unbreakable(boolean unbreakable) { + meta.spigot().setUnbreakable(unbreakable); + return this; + } + + /* + * ========================== + * + * SPECIFIC META + * + * ========================== + */ + + /* + * Banners: + */ + public DyeColor getBannerBaseColor() { + return ((BannerMeta) meta).getBaseColor(); + } + + public List getBannerPatterns() { + return ((BannerMeta) meta).getPatterns(); + } + + public ItemBuilder bannerBaseColor(DyeColor color) { + ((BannerMeta) meta).setBaseColor(color); + return this; + } + + public ItemBuilder bannerPatterns(List patterns) { + ((BannerMeta) meta).setPatterns(patterns); + return this; + } + + public ItemBuilder bannerPattern(int i, Pattern pattern) { + ((BannerMeta) meta).setPattern(i, pattern); + return this; + } + + public ItemBuilder addBannerPatterns(Pattern pattern) { + ((BannerMeta) meta).addPattern(pattern); + return this; + } + + public ItemBuilder removeBannerPattern(int i) { + ((BannerMeta) meta).removePattern(i); + return this; + } + + /* + * Leather armor: + */ + public Color getLeatherArmorColor() { + return ((LeatherArmorMeta) meta).getColor(); + } + + public ItemBuilder leatherArmorColor(Color color) { + ((LeatherArmorMeta) meta).setColor(color); + return this; + } + + /* + * Skulls: + */ + public boolean hasSkullOwner() { + return ((SkullMeta) meta).hasOwner(); + } + + public String getSkullOwner() { + return ((SkullMeta) meta).getOwner(); + } + + public ItemBuilder skullOwner(String owner) { + item.setDurability((short) 3); + ((SkullMeta) meta).setOwner(owner); + return this; + } + + public ItemBuilder durability(int durability) { + item.setDurability((short) durability); + return this; + } + + /* + * Potions: + */ + public boolean hasPotionEffect(PotionEffectType type) { + return ((PotionMeta) meta).hasCustomEffect(type); + } + + public boolean hasPotionEffects() { + return ((PotionMeta) meta).hasCustomEffects(); + } + + public List getPotionEffects() { + return ((PotionMeta) meta).getCustomEffects(); + } + + public ItemBuilder addPotionEffect(PotionEffect effect, boolean overwrite) { + ((PotionMeta) meta).addCustomEffect(effect, overwrite); + return this; + } + + /* + * Build the ItemStack. + */ + public ItemStack build() { + item.setItemMeta(meta); + return item; + } +} diff --git a/core/src/main/java/com/songoda/epicfurnaces/utils/gui/OnClose.java b/core/src/main/java/com/songoda/epicfurnaces/utils/gui/OnClose.java new file mode 100644 index 0000000..6ccfa24 --- /dev/null +++ b/core/src/main/java/com/songoda/epicfurnaces/utils/gui/OnClose.java @@ -0,0 +1,10 @@ +package com.songoda.epicfurnaces.utils.gui; + +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; + +public interface OnClose { + + void OnClose(Player player, Inventory inventory); + +} diff --git a/core/src/main/resources/Furnace Recipes.yml b/core/src/main/resources/Furnace Recipes.yml new file mode 100644 index 0000000..d91fa47 --- /dev/null +++ b/core/src/main/resources/Furnace Recipes.yml @@ -0,0 +1,161 @@ +# TurboCharged furnace Recipe file +Recipes: + DIAMOND_SWORD: + result: DIAMOND + amount: 2 + DIAMOND_PICKAXE: + result: DIAMOND + amount: 3 + DIAMOND_AXE: + result: DIAMOND + amount: 3 + DIAMOND_SHOVEL: + result: DIAMOND + amount: 1 + DIAMOND_HOE: + result: DIAMOND + amount: 2 + DIAMOND_HELMET: + result: DIAMOND + amount: 5 + DIAMOND_CHESTPLATE: + result: DIAMOND + amount: 8 + DIAMOND_LEGGINGS: + result: DIAMOND + amount: 7 + DIAMOND_BOOTS: + result: DIAMOND + amount: 4 + IRON_SWORD: + result: IRON_INGOT + amount: 2 + IRON_PICKAXE: + result: IRON_INGOT + amount: 3 + IRON_AXE: + result: IRON_INGOT + amount: 3 + IRON_SHOVEL: + result: IRON_INGOT + amount: 1 + IRON_HOE: + result: IRON_INGOT + amount: 2 + IRON_HELMET: + result: IRON_INGOT + amount: 5 + IRON_CHESTPLATE: + result: IRON_INGOT + amount: 8 + IRON_LEGGINGS: + result: IRON_INGOT + amount: 7 + IRON_BOOTS: + result: IRON_INGOT + amount: 4 + GOLDEN_SWORD: + result: GOLD_INGOT + amount: 2 + GOLDEN_PICKAXE: + result: GOLD_INGOT + amount: 3 + GOLDEN_AXE: + result: GOLD_INGOT + amount: 3 + GOLDEN_SHOVEL: + result: GOLD_INGOT + amount: 1 + GOLDEN_HOE: + result: GOLD_INGOT + amount: 2 + GOLDEN_HELMET: + result: GOLD_INGOT + amount: 5 + GOLDEN_CHESTPLATE: + result: GOLD_INGOT + amount: 8 + GOLDEN_LEGGINGS: + result: GOLD_INGOT + amount: 7 + GOLDEN_BOOTS: + result: GOLD_INGOT + amount: 4 + CHAINMAIL_HELMET: + result: IRON_INGOT + amount: 3 + CHAINMAIL_CHESTPLATE: + result: IRON_INGOT + amount: 5 + CHAINMAIL_LEGGINGS: + result: IRON_INGOT + amount: 4 + CHAINMAIL_BOOTS: + result: IRON_INGOT + amount: 2 + LEATHER_HELMET: + result: LEATHER + amount: 5 + LEATHER_CHESTPLATE: + result: LEATHER + amount: 8 + LEATHER_LEGGINGS: + result: LEATHER + amount: 7 + LEATHER_BOOTS: + result: LEATHER + amount: 4 + STONE_SWORD: + result: COBBLESTONE + amount: 2 + STONE_PICKAXE: + result: COBBLESTONE + amount: 3 + STONE_AXE: + result: COBBLESTONE + amount: 3 + STONE_SHOVEL: + result: COBBLESTONE + amount: 1 + STONE_HOE: + result: COBBLESTONE + amount: 2 + WOODEN_SWORD: + result: COAL + amount: 2 + WOODEN_PICKAXE: + result: COAL + amount: 3 + WOODEN_AXE: + result: COAL + amount: 3 + WOODEN_SHOVEL: + result: COAL + amount: 1 + WOODEN_HOE: + result: COAL + amount: 2 + BOW: + result: COAL + amount: 3 + FISHING_ROD: + result: COAL + amount: 3 + COMPASS: + result: IRON_INGOT + amount: 4 + CLOCK: + result: GOLD_INGOT + amount: 4 + SHEARS: + result: IRON_INGOT + amount: 2 + BUCKET: + result: IRON_INGOT + amount: 3 + MINECART: + result: IRON_INGOT + amount: 5 + FLINT_AND_STEEL: + result: IRON_INGOT + amount: 1 \ No newline at end of file diff --git a/core/src/main/resources/SettingDefinitions.yml b/core/src/main/resources/SettingDefinitions.yml new file mode 100644 index 0000000..32d298c --- /dev/null +++ b/core/src/main/resources/SettingDefinitions.yml @@ -0,0 +1,16 @@ +ECO-Icon: 'This is the icon players will use to upgrade with Economy.' +XP-Icon: 'This is the icon players will use to upgrade with EXP.' +Upgrade-with-material: 'When enabled players will be able to smelt materials defined in the config to upgrade furnaces.' +Upgrade-with-eco: 'If enabled players will optionally be able to use Economy to upgrade their furnaces.' +Upgrade-with-xp: 'If enabled players will optionally be able to use XP to upgrade their furnaces.' +Turbo-level-multiplier: 'This is the amount the cost for each level, it is multiplied by the level you are currently on. So if the next level is 3 then the cost would be 100.' +On-upgrade-particles: 'If set to true particles will be generated on upgrade.' +Helpful-Tips: 'If this is enabled tips will be displayed to guide you on how to use the plugin.' +Glass-Type: 'This is the id of the glass used for the background in the guis.' +Rainbow-Glass: 'If this is enabled the glass background will be randomized colors.' +Furnace-upgrade-cost: 'This is the material that an upgrade will cost.' +Custom-recipes: 'If set to true custom recipes will be loaded from the recipe config.' +Ignore-custom-recipes-for-rewards: 'If set to true custom recipes wont count towards rewards. This is to prevent abuse.' +Reward-Icon: 'This is the icon players will use to upgrade reward.' +Performance-Icon: 'This is the icon players will use to upgrade performance.' +FuelDuration-Icon: 'This is the icon players will use to upgrade Fuel Duration.' diff --git a/core/src/main/resources/blacklist.yml b/core/src/main/resources/blacklist.yml new file mode 100644 index 0000000..e69de29 diff --git a/core/src/main/resources/config.yml b/core/src/main/resources/config.yml new file mode 100644 index 0000000..e69de29 diff --git a/core/src/main/resources/en_US.lang b/core/src/main/resources/en_US.lang new file mode 100644 index 0000000..e718326 --- /dev/null +++ b/core/src/main/resources/en_US.lang @@ -0,0 +1,55 @@ +#General Messages + +general.nametag.prefix= "&8[&6EpicFurnaces&8]" +general.nametag.next= "&9Next" +general.nametag.back= "&9Back" +general.nametag.nameformat= "&eLevel %level% &fFurnace" +general.hologram.outoffuel= "&cNo Fuel" +general.hologram.stats= "&a%in%&7/&c%out%"; + +#Interface Messages + +interface.furnace.upgradewithxp= "&aUpgrade with XP" +interface.furnace.upgradewithxplore= "&7Cost: &a%cost% Levels" +interface.furnace.upgradewitheconomy= "&aUpgrade with ECO" +interface.furnace.upgradewitheconomylore= "&7Cost: &a$%cost%" +interface.furnace.currentlevel= "&6Furnace Level &7%level%" +interface.furnace.level= "&6Next Level &7%level%" +interface.furnace.performance= "&7Performance: &6%amount%" +interface.furnace.reward= "&7Reward: &6%amount%" +interface.furnace.performancetitle= "&a&lPerformance" +interface.furnace.rewardtitle= "&c&lReward" +interface.furnace.fueldurationtitle= "&7&lFuel Duration" +interface.furnace.fuelduration= "&7Fuel Duration: &6%amount%" +interface.furnace.fuelshare= "&7Fuel Share: &6%amount%&7." +interface.furnace.fuelsharetitle= "&6&lFuel Share" +interface.furnace.fuelshareinfo= "&7This furnace will power other|&7furnaces within a &6%amount%&7 block radius." +interface.furnace.overheat= "&7Overheat: &6%amount%&7." +interface.furnace.overheattitle= "&6&lOverheat" +interface.furnace.overheatinfo= "&7This furnace will melt snow |&7and ice within a &6%amount%&7 block radius." +interface.furnace.performanceinfo= "&7This furnaces performance is |&7currently boosted an extra &6%amount%%&7. | |&7Performance boosts the speed in |&7which a furnace processes |&7materials." +interface.furnace.rewardinfo= "&7This furnace currently |&7has a &6%amount%%&7 chance of |&7producing multiple resources." +interface.furnace.fueldurationinfo= "&7This furnaces fuel duration is |&7currently boosted by &6%amount%%&7. | |&7Fuel Duration boosts how long |&7fuel in the furnace lasts." +interface.furnace.smeltedx= "&7Smelted &6%amount% Materials&7." +interface.furnace.tolevel= "&6%amount% %type%s &7away from leveling up." +interface.furnace.remotefurnace= "&5&lRemote Control" +interface.furnace.remotefurnacelore= "&7Left-Click to assign a nickname.|&7Right-Click to give yourself |&7remote access.|&7Current nickname is: &6%nickname%&7." +interface.furnace.utilize= "|&7To utilize remote access|&7use the command:|&6/EF Remote %nickname%" +interface.furnace.remotelist= "&7Players with remote access:" +interface.furnace.alreadymaxed= "&7This furnace is already maxed out!" +interface.button.boostedstats= "&a&lCurrently boosted!|&7Reward multiplied by &6%amount%x&7.|&7Expires in &6%time%&7." + +#Command Messages + +command.give.success= "&7You have been given a &6level %level% &7Furnace." + +#Event Messages + +event.general.nopermission= "&cYou do not have permission to do that." +event.upgrade.cannotafford= "&cYou cannot afford this upgrade." +event.upgrade.success= "&7You successfully upgraded this furnace to &6level %level%&7!" +event.upgrade.maxed= "&7You maxed out this furnace at &6level %level%&7." +event.remote.enter= "&7Enter a unique nickname for the furnace." +event.remote.notfound= "&cRemote furnace not found." +event.remote.nicknamesuccess= "&aNickname set successfully." +event.remote.nicknameinuse= "&cThat nickname is already in use." \ No newline at end of file diff --git a/core/src/main/resources/plugin.yml b/core/src/main/resources/plugin.yml new file mode 100644 index 0000000..f536748 --- /dev/null +++ b/core/src/main/resources/plugin.yml @@ -0,0 +1,13 @@ +name: EpicFurnaces +version: ${project.version} +main: com.songoda.epicfurnaces.EpicFurnaces +authors: [Brianna, GB6] +website: https://songoda.com/ +depend: [Arconix] +softdepend: [PlotSquared, GriefPrevention, USkyBlock, SkyBlock, WorldGuard, Factions] +commands: + epicfurnaces: + description: I have no idea. + default: true + aliases: [ef] + usage: / [reload] \ No newline at end of file diff --git a/hooks/askyblock/askyblock.iml b/hooks/askyblock/askyblock.iml new file mode 100644 index 0000000..0280491 --- /dev/null +++ b/hooks/askyblock/askyblock.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/hooks/askyblock/hook.askyblock.iml b/hooks/askyblock/hook.askyblock.iml new file mode 100644 index 0000000..2db53f6 --- /dev/null +++ b/hooks/askyblock/hook.askyblock.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/hooks/askyblock/pom.xml b/hooks/askyblock/pom.xml new file mode 100644 index 0000000..a6fe53f --- /dev/null +++ b/hooks/askyblock/pom.xml @@ -0,0 +1,35 @@ + + + + hooks + com.songoda + 4.0.19 + + 4.0.0 + + askyblock + + + + + com.wasteofplastic + askyblock + 3.0.6.8 + provided + + + org.spigotmc + spigot + 1.8.8 + provided + + + com.songoda + manager + 4.0.19 + compile + + + \ No newline at end of file diff --git a/hooks/askyblock/src/main/java/com/songoda/epicfurnaces/hooks/ASkyBlockHook.java b/hooks/askyblock/src/main/java/com/songoda/epicfurnaces/hooks/ASkyBlockHook.java new file mode 100644 index 0000000..a914bbf --- /dev/null +++ b/hooks/askyblock/src/main/java/com/songoda/epicfurnaces/hooks/ASkyBlockHook.java @@ -0,0 +1,60 @@ +package com.songoda.epicfurnaces.hooks; + +import com.songoda.epicfurnaces.hook.ClaimableProtectionPluginHook; +import com.wasteofplastic.askyblock.ASkyBlock; +import com.wasteofplastic.askyblock.ASkyBlockAPI; +import com.wasteofplastic.askyblock.Island; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.List; +import java.util.Set; +import java.util.UUID; + +public class ASkyBlockHook implements ClaimableProtectionPluginHook { + + private final ASkyBlockAPI skyblock; + + public ASkyBlockHook() { + this.skyblock = ASkyBlockAPI.getInstance(); + } + + @Override + public JavaPlugin getPlugin() { + return ASkyBlock.getPlugin(); + } + + @Override + public boolean canBuild(Player player, Location location) { + Island island = skyblock.getIslandAt(location); + if (island == null) return true; + + UUID owner = island.getOwner(); + UUID playerUUID = player.getUniqueId(); + if (owner == null || owner.equals(playerUUID)) return true; + + List teamMembers = skyblock.getTeamMembers(owner); + if (teamMembers.contains(playerUUID)) return true; + + Set coopIslands = skyblock.getCoopIslands(player); + for (Location islandLocation : coopIslands) { + if (skyblock.getIslandAt(islandLocation).getOwner().equals(playerUUID)) { + return true; + } + } + + return false; + } + + @Override + public boolean isInClaim(Location location, String id) { + return skyblock.getOwner(location).toString().equals(id); + } + + @Override + public String getClaimID(String name) { + return null; + } + +} diff --git a/hooks/craftbukkit-1-8-r1/craftbukkit-1-8-r1.iml b/hooks/craftbukkit-1-8-r1/craftbukkit-1-8-r1.iml new file mode 100644 index 0000000..0280491 --- /dev/null +++ b/hooks/craftbukkit-1-8-r1/craftbukkit-1-8-r1.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/hooks/craftbukkit-1-8-r1/pom.xml b/hooks/craftbukkit-1-8-r1/pom.xml new file mode 100644 index 0000000..0a0d5df --- /dev/null +++ b/hooks/craftbukkit-1-8-r1/pom.xml @@ -0,0 +1,27 @@ + + + + hooks + com.songoda + 4.0.19 + + 4.0.0 + + craftbukkit-1-8-r1 + + + com.songoda + manager + 4.0.19 + compile + + + org.bukkit + craftbukkit + 1.8-R0.1 + provided + + + \ No newline at end of file diff --git a/hooks/craftbukkit-1-8-r1/src/main/java/com/songoda/epicfurnaces/hooks/CraftBukkit18R1.java b/hooks/craftbukkit-1-8-r1/src/main/java/com/songoda/epicfurnaces/hooks/CraftBukkit18R1.java new file mode 100644 index 0000000..f3ea2e0 --- /dev/null +++ b/hooks/craftbukkit-1-8-r1/src/main/java/com/songoda/epicfurnaces/hooks/CraftBukkit18R1.java @@ -0,0 +1,16 @@ +package com.songoda.epicfurnaces.hooks; + +import com.songoda.epicfurnaces.hook.CraftBukkitHook; +import net.minecraft.server.v1_8_R1.TileEntityFurnace; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.v1_8_R1.CraftWorld; + +public class CraftBukkit18R1 implements CraftBukkitHook { + @Override + public void setName(Block block, String string) { + CraftWorld craftWorld = (CraftWorld) block.getWorld(); + TileEntityFurnace furnace = (TileEntityFurnace) craftWorld.getTileEntityAt(block.getX(), block.getY(), block.getZ()); + furnace.a(string); + } + +} diff --git a/hooks/craftbukkit-1-8-r2/craftbukkit-1-8-r2.iml b/hooks/craftbukkit-1-8-r2/craftbukkit-1-8-r2.iml new file mode 100644 index 0000000..0280491 --- /dev/null +++ b/hooks/craftbukkit-1-8-r2/craftbukkit-1-8-r2.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/hooks/craftbukkit-1-8-r2/pom.xml b/hooks/craftbukkit-1-8-r2/pom.xml new file mode 100644 index 0000000..9a78320 --- /dev/null +++ b/hooks/craftbukkit-1-8-r2/pom.xml @@ -0,0 +1,29 @@ + + + + hooks + com.songoda + 4.0.19 + + 4.0.0 + + craftbukkit-1-8-r2 + + + com.songoda + manager + 4.0.19 + compile + + + org.bukkit + craftbukkit + 1.8.3-R0.1 + provided + + + + + \ No newline at end of file diff --git a/hooks/craftbukkit-1-8-r2/src/main/java/com/songoda/epicfurnaces/hooks/CraftBukkit18R2.java b/hooks/craftbukkit-1-8-r2/src/main/java/com/songoda/epicfurnaces/hooks/CraftBukkit18R2.java new file mode 100644 index 0000000..789f93c --- /dev/null +++ b/hooks/craftbukkit-1-8-r2/src/main/java/com/songoda/epicfurnaces/hooks/CraftBukkit18R2.java @@ -0,0 +1,15 @@ +package com.songoda.epicfurnaces.hooks; + +import com.songoda.epicfurnaces.hook.CraftBukkitHook; +import net.minecraft.server.v1_8_R2.TileEntityFurnace; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.v1_8_R2.CraftWorld; + +public class CraftBukkit18R2 implements CraftBukkitHook { + public void setName(Block block, String string) { + CraftWorld craftWorld = (CraftWorld) block.getWorld(); + TileEntityFurnace furnace = (TileEntityFurnace) craftWorld.getTileEntityAt(block.getX(), block.getY(), block.getZ()); + furnace.a(string); + } + +} diff --git a/hooks/craftbukkit-1-8-r3/craftbukkit-1-8-r3.iml b/hooks/craftbukkit-1-8-r3/craftbukkit-1-8-r3.iml new file mode 100644 index 0000000..0280491 --- /dev/null +++ b/hooks/craftbukkit-1-8-r3/craftbukkit-1-8-r3.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/hooks/craftbukkit-1-8-r3/pom.xml b/hooks/craftbukkit-1-8-r3/pom.xml new file mode 100644 index 0000000..19f0d67 --- /dev/null +++ b/hooks/craftbukkit-1-8-r3/pom.xml @@ -0,0 +1,29 @@ + + + + hooks + com.songoda + 4.0.19 + + 4.0.0 + + craftbukkit-1-8-r3 + + + com.songoda + manager + 4.0.19 + compile + + + org.bukkit + craftbukkit + 1.8.8-R3 + provided + + + + + \ No newline at end of file diff --git a/hooks/craftbukkit-1-8-r3/src/main/java/com/songoda/epicfurnaces/hooks/CraftBukkit18R3.java b/hooks/craftbukkit-1-8-r3/src/main/java/com/songoda/epicfurnaces/hooks/CraftBukkit18R3.java new file mode 100644 index 0000000..20efca8 --- /dev/null +++ b/hooks/craftbukkit-1-8-r3/src/main/java/com/songoda/epicfurnaces/hooks/CraftBukkit18R3.java @@ -0,0 +1,15 @@ +package com.songoda.epicfurnaces.hooks; + +import com.songoda.epicfurnaces.hook.CraftBukkitHook; +import net.minecraft.server.v1_8_R3.TileEntityFurnace; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; + +public class CraftBukkit18R3 implements CraftBukkitHook { + public void setName(Block block, String string) { + CraftWorld craftWorld = (CraftWorld) block.getWorld(); + TileEntityFurnace furnace = (TileEntityFurnace) craftWorld.getTileEntityAt(block.getX(), block.getY(), block.getZ()); + furnace.a(string); + } + +} diff --git a/hooks/craftbukkit-1-9/craftbukkit-1-9.iml b/hooks/craftbukkit-1-9/craftbukkit-1-9.iml new file mode 100644 index 0000000..0280491 --- /dev/null +++ b/hooks/craftbukkit-1-9/craftbukkit-1-9.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/hooks/craftbukkit-1-9/craftbukkit19.iml b/hooks/craftbukkit-1-9/craftbukkit19.iml new file mode 100644 index 0000000..fa63d4b --- /dev/null +++ b/hooks/craftbukkit-1-9/craftbukkit19.iml @@ -0,0 +1,12 @@ + + + + + + + SPIGOT + + + + + \ No newline at end of file diff --git a/hooks/craftbukkit-1-9/pom.xml b/hooks/craftbukkit-1-9/pom.xml new file mode 100644 index 0000000..4c9a1bb --- /dev/null +++ b/hooks/craftbukkit-1-9/pom.xml @@ -0,0 +1,27 @@ + + + + hooks + com.songoda + 4.0.19 + + 4.0.0 + + craftbukkit-1-9 + + + com.songoda + manager + 4.0.19 + compile + + + org.spigotmc + spigot + 1.9.4 + provided + + + \ No newline at end of file diff --git a/hooks/craftbukkit-1-9/src/main/java/com/songoda/epicfurnaces/CraftBukkit19.java b/hooks/craftbukkit-1-9/src/main/java/com/songoda/epicfurnaces/CraftBukkit19.java new file mode 100644 index 0000000..fce8cc6 --- /dev/null +++ b/hooks/craftbukkit-1-9/src/main/java/com/songoda/epicfurnaces/CraftBukkit19.java @@ -0,0 +1,15 @@ +package com.songoda.epicfurnaces; + +import com.songoda.epicfurnaces.hook.CraftBukkitHook; +import net.minecraft.server.v1_9_R2.TileEntityFurnace; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.v1_9_R2.CraftWorld; + +public class CraftBukkit19 implements CraftBukkitHook { + public void setName(Block block, String string) { + CraftWorld craftWorld = (CraftWorld) block.getWorld(); + TileEntityFurnace furnace = (TileEntityFurnace) craftWorld.getTileEntityAt(block.getX(), block.getY(), block.getZ()); + furnace.a(string); + } + +} diff --git a/hooks/factions/factions.iml b/hooks/factions/factions.iml new file mode 100644 index 0000000..0280491 --- /dev/null +++ b/hooks/factions/factions.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/hooks/factions/hook.factions.iml b/hooks/factions/hook.factions.iml new file mode 100644 index 0000000..2db53f6 --- /dev/null +++ b/hooks/factions/hook.factions.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/hooks/factions/pom.xml b/hooks/factions/pom.xml new file mode 100644 index 0000000..5c6f1d7 --- /dev/null +++ b/hooks/factions/pom.xml @@ -0,0 +1,36 @@ + + + 4.0.0 + + + hooks + com.songoda + 4.0.19 + + + factions + + + + me.markeh + factionsframework + 1.2.0 + provided + + + org.spigotmc + spigot + 1.8.8 + provided + + + com.songoda + manager + 4.0.19 + compile + + + + \ No newline at end of file diff --git a/hooks/factions/src/main/java/com/songoda/epicfurnaces/hooks/FactionsHook.java b/hooks/factions/src/main/java/com/songoda/epicfurnaces/hooks/FactionsHook.java new file mode 100644 index 0000000..cde95c8 --- /dev/null +++ b/hooks/factions/src/main/java/com/songoda/epicfurnaces/hooks/FactionsHook.java @@ -0,0 +1,41 @@ +package com.songoda.epicfurnaces.hooks; + +import com.songoda.epicfurnaces.hook.ClaimableProtectionPluginHook; +import me.markeh.factionsframework.FactionsFramework; +import me.markeh.factionsframework.entities.FPlayer; +import me.markeh.factionsframework.entities.FPlayers; +import me.markeh.factionsframework.entities.Faction; +import me.markeh.factionsframework.entities.Factions; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +public class FactionsHook implements ClaimableProtectionPluginHook { + + private final FactionsFramework factions; + + public FactionsHook() { + this.factions = FactionsFramework.get(); + } + + public JavaPlugin getPlugin() { + return factions; + } + + public boolean canBuild(Player player, Location location) { + FPlayer fPlayer = FPlayers.getBySender(player); + Faction faction = Factions.getFactionAt(location); + + return faction.isNone() || fPlayer.getFaction().equals(faction); + } + + public boolean isInClaim(Location location, String id) { + return Factions.getFactionAt(location).getId().equals(id); + } + + public String getClaimID(String name) { + Faction faction = Factions.getByName(name, ""); + return (faction != null) ? faction.getId() : null; + } + +} \ No newline at end of file diff --git a/hooks/griefprevention/griefprevention.iml b/hooks/griefprevention/griefprevention.iml new file mode 100644 index 0000000..0280491 --- /dev/null +++ b/hooks/griefprevention/griefprevention.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/hooks/griefprevention/pom.xml b/hooks/griefprevention/pom.xml new file mode 100644 index 0000000..12c2234 --- /dev/null +++ b/hooks/griefprevention/pom.xml @@ -0,0 +1,36 @@ + + + + hooks + com.songoda + 4.0.19 + + 4.0.0 + + griefprevention + + + + me.ryanhamshire + GriefPrevention + LATEST + provided + + + org.spigotmc + spigot + 1.8.8 + provided + + + com.songoda + manager + 4.0.19 + compile + + + + + \ No newline at end of file diff --git a/hooks/griefprevention/src/main/java/com/songoda/epicfurnaces/hooks/GriefPreventionHook.java b/hooks/griefprevention/src/main/java/com/songoda/epicfurnaces/hooks/GriefPreventionHook.java new file mode 100644 index 0000000..f2f9f6c --- /dev/null +++ b/hooks/griefprevention/src/main/java/com/songoda/epicfurnaces/hooks/GriefPreventionHook.java @@ -0,0 +1,28 @@ +package com.songoda.epicfurnaces.hooks; + +import com.songoda.epicfurnaces.hook.ProtectionPluginHook; +import me.ryanhamshire.GriefPrevention.Claim; +import me.ryanhamshire.GriefPrevention.GriefPrevention; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +public class GriefPreventionHook implements ProtectionPluginHook { + + private final GriefPrevention griefPrevention; + + public GriefPreventionHook() { + this.griefPrevention = GriefPrevention.instance; + } + + public JavaPlugin getPlugin() { + return griefPrevention; + } + + public boolean canBuild(Player player, Location location) { + Claim claim = griefPrevention.dataStore.getClaimAt(location, false, null); + return claim != null && claim.allowBuild(player, Material.STONE) == null; + } + +} diff --git a/hooks/hooks.iml b/hooks/hooks.iml new file mode 100644 index 0000000..0280491 --- /dev/null +++ b/hooks/hooks.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/hooks/kingdoms/hook.kingdoms.iml b/hooks/kingdoms/hook.kingdoms.iml new file mode 100644 index 0000000..2db53f6 --- /dev/null +++ b/hooks/kingdoms/hook.kingdoms.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/hooks/kingdoms/kingdoms.iml b/hooks/kingdoms/kingdoms.iml new file mode 100644 index 0000000..0280491 --- /dev/null +++ b/hooks/kingdoms/kingdoms.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/hooks/kingdoms/pom.xml b/hooks/kingdoms/pom.xml new file mode 100644 index 0000000..0de5153 --- /dev/null +++ b/hooks/kingdoms/pom.xml @@ -0,0 +1,40 @@ + + + + hooks + com.songoda + 4.0.19 + + 4.0.0 + + kingdoms + + + + org.spigotmc + spigot + 1.8.8 + provided + + + org + kingdoms + LATEST + provided + + + com.songoda + manager + 4.0.19 + compile + + + com.songoda + manager + 4.0.19 + compile + + + \ No newline at end of file diff --git a/hooks/kingdoms/src/main/java/com/songoda/epicfurnaces/hooks/KingdomsHook.java b/hooks/kingdoms/src/main/java/com/songoda/epicfurnaces/hooks/KingdomsHook.java new file mode 100644 index 0000000..bb042fd --- /dev/null +++ b/hooks/kingdoms/src/main/java/com/songoda/epicfurnaces/hooks/KingdomsHook.java @@ -0,0 +1,36 @@ +package com.songoda.epicfurnaces.hooks; + +import com.songoda.epicfurnaces.hook.ProtectionPluginHook; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; +import org.kingdoms.constants.land.Land; +import org.kingdoms.constants.land.SimpleChunkLocation; +import org.kingdoms.constants.player.KingdomPlayer; +import org.kingdoms.main.Kingdoms; +import org.kingdoms.manager.game.GameManagement; + +public class KingdomsHook implements ProtectionPluginHook { + + private final Kingdoms kingdoms; + + public KingdomsHook() { + this.kingdoms = Kingdoms.getInstance(); + } + + public JavaPlugin getPlugin() { + return kingdoms; + } + + public boolean canBuild(Player player, Location location) { + KingdomPlayer kPlayer = GameManagement.getPlayerManager().getOfflineKingdomPlayer(player).getKingdomPlayer(); + if (kPlayer.getKingdom() == null) return true; + + SimpleChunkLocation chunkLocation = new SimpleChunkLocation(location.getChunk()); + Land land = GameManagement.getLandManager().getOrLoadLand(chunkLocation); + String owner = land.getOwner(); + + return owner == null || kPlayer.getKingdom().getKingdomName().equals(owner); + } + +} \ No newline at end of file diff --git a/hooks/manager/manager.iml b/hooks/manager/manager.iml new file mode 100644 index 0000000..0280491 --- /dev/null +++ b/hooks/manager/manager.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/hooks/manager/pom.xml b/hooks/manager/pom.xml new file mode 100644 index 0000000..b662529 --- /dev/null +++ b/hooks/manager/pom.xml @@ -0,0 +1,25 @@ + + + + hooks + com.songoda + 4.0.19 + ../pom.xml + + 4.0.0 + + manager + Hook-Manager + Provides intermediary support between the core and its hooks. + + + + org.spigot + spigot-api + 1.8.8-R0.1 + compile + + + \ No newline at end of file diff --git a/hooks/manager/src/main/java/com/songoda/epicfurnaces/hook/ClaimableProtectionPluginHook.java b/hooks/manager/src/main/java/com/songoda/epicfurnaces/hook/ClaimableProtectionPluginHook.java new file mode 100644 index 0000000..b703dbc --- /dev/null +++ b/hooks/manager/src/main/java/com/songoda/epicfurnaces/hook/ClaimableProtectionPluginHook.java @@ -0,0 +1,37 @@ +package com.songoda.epicfurnaces.hook; + +import org.bukkit.Location; + +/** + * A more specific implementation of {@link ProtectionPluginHook} used internally by + * EpicSpawners to retain more information about default hooks. Often times this + * interface is not recommended over the ProtectionPluginHook interface as its methods + * will not often be used by implementation, though they are available if more information + * is desired. It is, however, recommended to use the former + * + * @author Parker Hawke - 2008Choco + */ +public interface ClaimableProtectionPluginHook extends ProtectionPluginHook { + + /** + * Check whether the provided location is in the claim with the given String ID + * + * @param location the location to check + * @param id the ID of the claim to check + * @return true if the location is within the claim, false otherwise or if the + * claim ID does not exist + */ + boolean isInClaim(Location location, String id); + + /** + * Get the ID of the claim with the given name. Often times this is unnecessary + * as unique IDs are not provided by a claim implementation, though for plugins + * such as factions, the passed parameter is the name of the faction and the + * returned String is its unique ID + * + * @param name the name of the claim to check + * @return the unique String ID. null if no claim exists + */ + String getClaimID(String name); + +} \ No newline at end of file diff --git a/hooks/manager/src/main/java/com/songoda/epicfurnaces/hook/CraftBukkitHook.java b/hooks/manager/src/main/java/com/songoda/epicfurnaces/hook/CraftBukkitHook.java new file mode 100644 index 0000000..22f1226 --- /dev/null +++ b/hooks/manager/src/main/java/com/songoda/epicfurnaces/hook/CraftBukkitHook.java @@ -0,0 +1,8 @@ +package com.songoda.epicfurnaces.hook; + +import org.bukkit.block.Block; + +public interface CraftBukkitHook { + void setName(Block block, String string); + +} diff --git a/hooks/manager/src/main/java/com/songoda/epicfurnaces/hook/ProtectionPluginHook.java b/hooks/manager/src/main/java/com/songoda/epicfurnaces/hook/ProtectionPluginHook.java new file mode 100644 index 0000000..385f659 --- /dev/null +++ b/hooks/manager/src/main/java/com/songoda/epicfurnaces/hook/ProtectionPluginHook.java @@ -0,0 +1,45 @@ +package com.songoda.epicfurnaces.hook; + +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +/** + * Represents a hooks for a protection plugin. This is used by EpicSpawners to determine + * whether a block break should be successful or not according to the current state of + * another plugin. For plugins providing claims with unique String IDs, see the + * {@link ClaimableProtectionPluginHook} for a more detailed implementation. + */ +public interface ProtectionPluginHook { + + /** + * The plugin to which this plugin hooks belongs. Must not be null + * + * @return the hooking plugin + */ + JavaPlugin getPlugin(); + + /** + * Check whether the provided player may build at the specified location + * + * @param player the player to check + * @param location the location to check + * + * @return true if player is permitted to build, false otherwise + */ + boolean canBuild(Player player, Location location); + + /** + * Check whether the provided player may build at the specified block + * + * @param player the player to check + * @param block the block to check + * + * @return true if player is permitted to build, false otherwise + */ + default boolean canBuild(Player player, Block block) { + return block != null && canBuild(player, block.getLocation()); + } + +} \ No newline at end of file diff --git a/hooks/plotsquared/hook.plotsquared.iml b/hooks/plotsquared/hook.plotsquared.iml new file mode 100644 index 0000000..2db53f6 --- /dev/null +++ b/hooks/plotsquared/hook.plotsquared.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/hooks/plotsquared/plotsquared.iml b/hooks/plotsquared/plotsquared.iml new file mode 100644 index 0000000..0280491 --- /dev/null +++ b/hooks/plotsquared/plotsquared.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/hooks/plotsquared/pom.xml b/hooks/plotsquared/pom.xml new file mode 100644 index 0000000..9ece1e7 --- /dev/null +++ b/hooks/plotsquared/pom.xml @@ -0,0 +1,34 @@ + + + + hooks + com.songoda + 4.0.19 + + 4.0.0 + + plotsquared + + + + org.spigotmc + spigot + 1.8.8 + provided + + + com + plotsquared + RELEASE + provided + + + com.songoda + manager + 4.0.19 + compile + + + \ No newline at end of file diff --git a/hooks/plotsquared/src/main/java/com/gb6/songoda/epicfurnaces/hooks/PlotSquaredHook.java b/hooks/plotsquared/src/main/java/com/gb6/songoda/epicfurnaces/hooks/PlotSquaredHook.java new file mode 100644 index 0000000..5a5a5f5 --- /dev/null +++ b/hooks/plotsquared/src/main/java/com/gb6/songoda/epicfurnaces/hooks/PlotSquaredHook.java @@ -0,0 +1,27 @@ +package com.gb6.songoda.epicfurnaces.hooks; + +import com.intellectualcrafters.plot.api.PlotAPI; +import com.plotsquared.bukkit.BukkitMain; +import com.songoda.epicfurnaces.hook.ProtectionPluginHook; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +public class PlotSquaredHook implements ProtectionPluginHook { + + private final PlotAPI plotSquared; + + public PlotSquaredHook() { + this.plotSquared = new PlotAPI(); + } + + public JavaPlugin getPlugin() { // BukkitMain? Really? + return JavaPlugin.getPlugin(BukkitMain.class); + } + + public boolean canBuild(Player player, Location location) { + return plotSquared.getPlot(location) != null && plotSquared.isInPlot(player) + && plotSquared.getPlot(location) == plotSquared.getPlot(player); + } + +} diff --git a/hooks/pom.xml b/hooks/pom.xml new file mode 100644 index 0000000..109e6a9 --- /dev/null +++ b/hooks/pom.xml @@ -0,0 +1,33 @@ + + + 4.0.0 + + + EpicFurnaces-Parent + com.songoda + 4.0.19 + ../pom.xml + + + hooks + pom + + manager + uskyblock + towny + redprotect + plotsquared + kingdoms + factions + askyblock + griefprevention + craftbukkit-1-8-r1 + craftbukkit-1-8-r2 + craftbukkit-1-8-r3 + craftbukkit-1-9 + worldguard6 + worldguard7 + + \ No newline at end of file diff --git a/hooks/redprotect/hook.redprotect.iml b/hooks/redprotect/hook.redprotect.iml new file mode 100644 index 0000000..2db53f6 --- /dev/null +++ b/hooks/redprotect/hook.redprotect.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/hooks/redprotect/pom.xml b/hooks/redprotect/pom.xml new file mode 100644 index 0000000..59a0cb0 --- /dev/null +++ b/hooks/redprotect/pom.xml @@ -0,0 +1,36 @@ + + + + hooks + com.songoda + 4.0.19 + + 4.0.0 + + redprotect + + + + br.net.fabiozumbi12 + RedProtect + 7.3.0 + provided + + + org.spigotmc + spigot + 1.8.8 + provided + + + com.songoda + manager + 4.0.19 + compile + + + + + \ No newline at end of file diff --git a/hooks/redprotect/redprotect.iml b/hooks/redprotect/redprotect.iml new file mode 100644 index 0000000..0280491 --- /dev/null +++ b/hooks/redprotect/redprotect.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/hooks/redprotect/src/main/java/com/songoda/epicfurnaces/hooks/RedProtectHook.java b/hooks/redprotect/src/main/java/com/songoda/epicfurnaces/hooks/RedProtectHook.java new file mode 100644 index 0000000..c1ef4db --- /dev/null +++ b/hooks/redprotect/src/main/java/com/songoda/epicfurnaces/hooks/RedProtectHook.java @@ -0,0 +1,30 @@ +package com.songoda.epicfurnaces.hooks; + +import br.net.fabiozumbi12.RedProtect.Bukkit.API.RedProtectAPI; +import br.net.fabiozumbi12.RedProtect.Bukkit.RedProtect; +import br.net.fabiozumbi12.RedProtect.Bukkit.Region; +import com.songoda.epicfurnaces.hook.ProtectionPluginHook; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +public class RedProtectHook implements ProtectionPluginHook { + + private final RedProtect redProtect; + + public RedProtectHook() { + this.redProtect = RedProtect.get(); + } + + public JavaPlugin getPlugin() { + return redProtect; + } + + public boolean canBuild(Player player, Location location) { + RedProtectAPI api = redProtect.getAPI(); + Region region = api.getRegion(location); + + return region != null && region.canBuild(player); + } + +} \ No newline at end of file diff --git a/hooks/towny/hook.towny.iml b/hooks/towny/hook.towny.iml new file mode 100644 index 0000000..2db53f6 --- /dev/null +++ b/hooks/towny/hook.towny.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/hooks/towny/pom.xml b/hooks/towny/pom.xml new file mode 100644 index 0000000..eefa767 --- /dev/null +++ b/hooks/towny/pom.xml @@ -0,0 +1,36 @@ + + + + hooks + com.songoda + 4.0.19 + + 4.0.0 + + towny + + + + com.palmergames.bukkit + towny + LATEST + provided + + + org.spigotmc + spigot + 1.8.8 + provided + + + com.songoda + manager + 4.0.19 + compile + + + + + \ No newline at end of file diff --git a/hooks/towny/src/main/java/com/songoda/epicfurnaces/hooks/TownyHook.java b/hooks/towny/src/main/java/com/songoda/epicfurnaces/hooks/TownyHook.java new file mode 100644 index 0000000..a59de5e --- /dev/null +++ b/hooks/towny/src/main/java/com/songoda/epicfurnaces/hooks/TownyHook.java @@ -0,0 +1,55 @@ +package com.songoda.epicfurnaces.hooks; + +import com.palmergames.bukkit.towny.Towny; +import com.palmergames.bukkit.towny.exceptions.NotRegisteredException; +import com.palmergames.bukkit.towny.object.Resident; +import com.palmergames.bukkit.towny.object.TownyUniverse; +import com.songoda.epicfurnaces.hook.ClaimableProtectionPluginHook; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +public class TownyHook implements ClaimableProtectionPluginHook { + + private final Towny towny; + + public TownyHook() { + this.towny = Towny.getPlugin(); + } + + public JavaPlugin getPlugin() { + return towny; + } + + public boolean canBuild(Player player, Location location) { + if (TownyUniverse.isWilderness(location.getBlock()) || !TownyUniverse.getTownBlock(location).hasTown()) + return true; + + try { + Resident resident = TownyUniverse.getDataSource().getResident(player.getName()); + return resident.hasTown() && TownyUniverse.getTownName(location).equals(resident.getTown().getName()); + } catch (NotRegisteredException e) { + e.printStackTrace(); + return false; + } + } + + public boolean isInClaim(Location location, String id) { + try { + return TownyUniverse.isWilderness(location.getBlock()) && TownyUniverse.getTownBlock(location).getTown().getUID().toString().equals(id); + } catch (NotRegisteredException e) { + e.printStackTrace(); + return false; + } + } + + public String getClaimID(String name) { + try { + return TownyUniverse.getDataSource().getTown(name).getUID().toString(); + } catch (NotRegisteredException e) { + e.printStackTrace(); + return null; + } + } + +} \ No newline at end of file diff --git a/hooks/towny/towny.iml b/hooks/towny/towny.iml new file mode 100644 index 0000000..0280491 --- /dev/null +++ b/hooks/towny/towny.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/hooks/uskyblock/hook.uskyblock.iml b/hooks/uskyblock/hook.uskyblock.iml new file mode 100644 index 0000000..a5a3c50 --- /dev/null +++ b/hooks/uskyblock/hook.uskyblock.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/hooks/uskyblock/pom.xml b/hooks/uskyblock/pom.xml new file mode 100644 index 0000000..2e1709d --- /dev/null +++ b/hooks/uskyblock/pom.xml @@ -0,0 +1,33 @@ + + + + hooks + com.songoda + 4.0.19 + + 4.0.0 + + uskyblock + + + us.talabrek + ultimateskyblock + LATEST + provided + + + org.spigotmc + spigot + 1.8.8 + provided + + + com.songoda + manager + 4.0.19 + compile + + + \ No newline at end of file diff --git a/hooks/uskyblock/src/main/java/com/songoda/epicfurnaces/USkyBlockHook.java b/hooks/uskyblock/src/main/java/com/songoda/epicfurnaces/USkyBlockHook.java new file mode 100644 index 0000000..ef8cd48 --- /dev/null +++ b/hooks/uskyblock/src/main/java/com/songoda/epicfurnaces/USkyBlockHook.java @@ -0,0 +1,34 @@ +package com.songoda.epicfurnaces; + +import com.songoda.epicfurnaces.hook.ClaimableProtectionPluginHook; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; +import us.talabrek.ultimateskyblock.api.uSkyBlockAPI; + +public class USkyBlockHook implements ClaimableProtectionPluginHook { + + private final uSkyBlockAPI uSkyBlockAPI; + + public USkyBlockHook() { + this.uSkyBlockAPI = (uSkyBlockAPI) Bukkit.getPluginManager().getPlugin("USkyBlock"); + } + + public JavaPlugin getPlugin() { // uSkyBlockAPI is also an instance of JavaPlugin + return (JavaPlugin) uSkyBlockAPI; + } + + public boolean canBuild(Player player, Location location) { + return uSkyBlockAPI.getIslandInfo(location).getOnlineMembers().contains(player) || uSkyBlockAPI.getIslandInfo(location).isLeader(player); + } + + public boolean isInClaim(Location location, String id) { + return uSkyBlockAPI.getIslandInfo(location).getLeader().equals(id); + } + + public String getClaimID(String name) { + return null; + } + +} diff --git a/hooks/uskyblock/uskyblock.iml b/hooks/uskyblock/uskyblock.iml new file mode 100644 index 0000000..0280491 --- /dev/null +++ b/hooks/uskyblock/uskyblock.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/hooks/worldguard6/pom.xml b/hooks/worldguard6/pom.xml new file mode 100644 index 0000000..f7de2c2 --- /dev/null +++ b/hooks/worldguard6/pom.xml @@ -0,0 +1,34 @@ + + + + hooks + com.songoda + 4.0.19 + + 4.0.0 + + worldguard6 + + + + com.sk89q + worldguard + 6.2.2 + provided + + + org.spigotmc + spigot + 1.8.8 + provided + + + com.songoda + manager + 4.0.19 + compile + + + \ No newline at end of file diff --git a/hooks/worldguard6/src/main/java/com/songoda/epicfurnaces/hooks/WorldGuard6Hook.java b/hooks/worldguard6/src/main/java/com/songoda/epicfurnaces/hooks/WorldGuard6Hook.java new file mode 100644 index 0000000..e35a2af --- /dev/null +++ b/hooks/worldguard6/src/main/java/com/songoda/epicfurnaces/hooks/WorldGuard6Hook.java @@ -0,0 +1,23 @@ +package com.songoda.epicfurnaces.hooks; + +import com.sk89q.worldguard.bukkit.WorldGuardPlugin; +import com.songoda.epicfurnaces.hook.ProtectionPluginHook; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +public class WorldGuard6Hook implements ProtectionPluginHook { + private final WorldGuardPlugin worldGuard; + + public WorldGuard6Hook() { + this.worldGuard = WorldGuardPlugin.inst(); + } + + public JavaPlugin getPlugin() { + return WorldGuardPlugin.inst(); + } + + public boolean canBuild(Player player, Location location) { + return worldGuard.canBuild(player, location); + } +} diff --git a/hooks/worldguard6/worldguard6.iml b/hooks/worldguard6/worldguard6.iml new file mode 100644 index 0000000..0280491 --- /dev/null +++ b/hooks/worldguard6/worldguard6.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/hooks/worldguard7/hook.worldguard.iml b/hooks/worldguard7/hook.worldguard.iml new file mode 100644 index 0000000..18add28 --- /dev/null +++ b/hooks/worldguard7/hook.worldguard.iml @@ -0,0 +1,26 @@ + + + + + + + SPIGOT + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/hooks/worldguard7/pom.xml b/hooks/worldguard7/pom.xml new file mode 100644 index 0000000..151ce65 --- /dev/null +++ b/hooks/worldguard7/pom.xml @@ -0,0 +1,40 @@ + + + + hooks + com.songoda + 4.0.19 + + 4.0.0 + + worldguard + + + + com.sk89q + worldguard + 7.0.0 + provided + + + com.sk89q + worldedit + LATEST + provided + + + org.spigotmc + spigot + 1.13.2 + provided + + + com.songoda + manager + 4.0.19 + compile + + + \ No newline at end of file diff --git a/hooks/worldguard7/src/main/java/com/songoda/epicfurnaces/hooks/WorldGuard7Hook.java b/hooks/worldguard7/src/main/java/com/songoda/epicfurnaces/hooks/WorldGuard7Hook.java new file mode 100644 index 0000000..9bf11f6 --- /dev/null +++ b/hooks/worldguard7/src/main/java/com/songoda/epicfurnaces/hooks/WorldGuard7Hook.java @@ -0,0 +1,30 @@ +package com.songoda.epicfurnaces.hooks; + +import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldguard.WorldGuard; +import com.sk89q.worldguard.bukkit.WorldGuardPlugin; +import com.sk89q.worldguard.protection.ApplicableRegionSet; +import com.sk89q.worldguard.protection.flags.Flags; +import com.sk89q.worldguard.protection.regions.RegionQuery; +import com.songoda.epicfurnaces.hook.ProtectionPluginHook; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +public class WorldGuard7Hook implements ProtectionPluginHook { + private final WorldGuard worldGuard; + + public WorldGuard7Hook() { + this.worldGuard = WorldGuard.getInstance(); + } + + public JavaPlugin getPlugin() { + return WorldGuardPlugin.inst(); + } + + public boolean canBuild(Player player, Location location) { + RegionQuery q = worldGuard.getPlatform().getRegionContainer().createQuery(); + ApplicableRegionSet ars = q.getApplicableRegions(BukkitAdapter.adapt(player.getLocation())); + return ars.testState(WorldGuardPlugin.inst().wrapPlayer(player), Flags.BUILD); + } +} diff --git a/hooks/worldguard7/worldguard7.iml b/hooks/worldguard7/worldguard7.iml new file mode 100644 index 0000000..0280491 --- /dev/null +++ b/hooks/worldguard7/worldguard7.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..4d95b32 --- /dev/null +++ b/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + + com.songoda + EpicFurnaces-Parent + pom + maven-version-number + + + EpicFurnaces-API + EpicFurnaces-Plugin + + + + + org.spigotmc + spigot + 1.13.2 + provided + + + + + clean install + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.0 + + 1.8 + 1.8 + + + + + + + private + http://repo.songoda.com/repository/private/ + + +