From a5678c2671869427eb12799f4c40c942af8356ed Mon Sep 17 00:00:00 2001 From: Elikill58 Date: Sat, 22 Oct 2022 09:14:40 +0200 Subject: [PATCH] Clean repo --- .gitignore | 11 + TempFly/.classpath | 26 - TempFly/.gitignore | 5 - TempFly/.project | 23 - .../org.eclipse.core.resources.prefs | 2 - TempFly/.settings/org.eclipse.jdt.core.prefs | 16 - TempFly/.settings/org.eclipse.m2e.core.prefs | 4 - TempFly/bin/.gitignore | 1 - TempFly/pom.xml => pom.xml | 374 +-- {TempFly/resources => resources}/config.yml | 650 ++--- {TempFly/resources => resources}/data.yml | 2 +- {TempFly/resources => resources}/dbsetup.sql | 30 +- .../factions_preset_uuid.yml | 226 +- {TempFly/resources => resources}/lang.yml | 402 +-- {TempFly/resources => resources}/page.yml | 62 +- .../resources => resources}/permissions.yml | 262 +- {TempFly/resources => resources}/plugin.yml | 16 +- .../skyblock_preset_askyblock.yml | 246 +- .../skyblock_preset_bento.yml | 246 +- .../skyblock_preset_generic.yml | 318 +-- .../skyblock_preset_iridium.yml | 302 +-- .../skyblock_preset_superior.yml | 306 +-- .../skyblock_readme.yml | 126 +- .../com/moneybags/tempfly/Metrics.java | 1438 +++++------ .../com/moneybags/tempfly/TempFly.java | 390 +-- .../com/moneybags/tempfly/TempFlyAPI.java | 414 +-- .../tempfly/aesthetic/ActionBarAPI.java | 62 +- .../moneybags/tempfly/aesthetic/ClipAPI.java | 154 +- .../moneybags/tempfly/aesthetic/MvdWAPI.java | 214 +- .../moneybags/tempfly/aesthetic/TitleAPI.java | 60 +- .../aesthetic/actionbar/ActionBar.java | 0 .../aesthetic/actionbar/LegacyActionBar.java | 0 .../aesthetic/actionbar/ModernActionBar.java | 0 .../tempfly/aesthetic/particle/Particles.java | 198 +- .../tempfly/aesthetic/title/LegacyTitle.java | 180 +- .../tempfly/aesthetic/title/ModernTitle.java | 32 +- .../tempfly/aesthetic/title/Title.java | 20 +- .../tempfly/combat/CombatHandler.java | 388 +-- .../moneybags/tempfly/combat/CombatTag.java | 90 +- .../tempfly/command/CommandManager.java | 680 ++--- .../tempfly/command/TempFlyCommand.java | 142 +- .../tempfly/command/TempFlyExecutor.java | 134 +- .../tempfly/command/TempFlyTabCompleter.java | 126 +- .../tempfly/command/TimeCommand.java | 280 +-- .../tempfly/command/admin/CmdGive.java | 188 +- .../tempfly/command/admin/CmdGiveAll.java | 142 +- .../tempfly/command/admin/CmdMigrate.java | 272 +- .../tempfly/command/admin/CmdReload.java | 66 +- .../tempfly/command/admin/CmdRemove.java | 164 +- .../tempfly/command/admin/CmdSet.java | 166 +- .../tempfly/command/admin/CmdTrailRemove.java | 160 +- .../tempfly/command/admin/CmdTrailSet.java | 200 +- .../tempfly/command/player/CmdBypass.java | 112 +- .../tempfly/command/player/CmdFly.java | 288 +-- .../tempfly/command/player/CmdHelp.java | 80 +- .../tempfly/command/player/CmdInfinite.java | 124 +- .../tempfly/command/player/CmdPay.java | 224 +- .../tempfly/command/player/CmdShop.java | 92 +- .../tempfly/command/player/CmdSpeed.java | 240 +- .../tempfly/command/player/CmdTime.java | 192 +- .../tempfly/command/player/CmdTrails.java | 76 +- .../environment/FlightEnvironment.java | 696 +++--- .../environment/RelativeTimeRegion.java | 52 +- .../environment/StructureProximity.java | 160 +- .../tempfly/event/ActionBarSendEvent.java | 114 +- .../tempfly/event/FlightEnabledEvent.java | 80 +- .../event/FlightUserInitializedEvent.java | 62 +- .../tempfly/event/TitleSendEvent.java | 118 +- .../moneybags/tempfly/fly/FlightManager.java | 1304 +++++----- .../com/moneybags/tempfly/fly/Flyer.java | 180 +- .../tempfly/fly/RequirementProvider.java | 218 +- .../tempfly/fly/result/FlightResult.java | 122 +- .../tempfly/fly/result/ResultAllow.java | 34 +- .../tempfly/fly/result/ResultDeny.java | 34 +- .../com/moneybags/tempfly/gui/GuiManager.java | 226 +- .../com/moneybags/tempfly/gui/GuiSession.java | 106 +- .../tempfly/gui/abstraction/DynamicPage.java | 170 +- .../tempfly/gui/abstraction/Page.java | 74 +- .../moneybags/tempfly/gui/pages/PageShop.java | 374 +-- .../tempfly/gui/pages/PageTrails.java | 310 +-- .../moneybags/tempfly/hook/HookManager.java | 504 ++-- .../tempfly/hook/IslandSettings.java | 208 +- .../moneybags/tempfly/hook/TempFlyHook.java | 492 ++-- .../moneybags/tempfly/hook/TerritoryHook.java | 596 ++--- .../tempfly/hook/TerritoryWrapper.java | 24 +- .../hook/factions/FactionRequirement.java | 438 ++-- .../hook/factions/FactionRoleSettings.java | 96 +- .../tempfly/hook/factions/FactionWrapper.java | 36 +- .../tempfly/hook/factions/FactionsHook.java | 1424 +++++------ .../factions/plugins/FactionsUUIDHook.java | 462 ++-- .../tempfly/hook/region/CompatRegion.java | 82 +- .../tempfly/hook/region/RegionProvider.java | 44 +- .../hook/region/plugins/WorldGuardHook.java | 268 +- .../hook/skyblock/CmdIslandSettings.java | 76 +- .../tempfly/hook/skyblock/IslandWrapper.java | 76 +- .../hook/skyblock/PageIslandSettings.java | 268 +- .../hook/skyblock/SettingsProvider.java | 14 +- .../hook/skyblock/SkyblockChallenge.java | 64 +- .../tempfly/hook/skyblock/SkyblockHook.java | 1580 ++++++------ .../hook/skyblock/SkyblockRequirement.java | 142 +- .../hook/skyblock/plugins/AskyblockHook.java | 626 ++--- .../hook/skyblock/plugins/BentoHook.java | 644 ++--- .../hook/skyblock/plugins/BskyblockHook.java | 120 +- .../hook/skyblock/plugins/IridiumHook.java | 530 ++-- .../hook/skyblock/plugins/SuperiorHook.java | 454 ++-- .../tempfly/time/AsyncTimeExecutor.java | 14 +- .../tempfly/time/AsyncTimeParameters.java | 154 +- .../moneybags/tempfly/time/TimeManager.java | 794 +++--- .../moneybags/tempfly/user/FlightUser.java | 2212 ++++++++--------- .../tempfly/user/UserEnvironment.java | 318 +-- .../moneybags/tempfly/user/UserLoader.java | 176 +- .../com/moneybags/tempfly/util/AutoSave.java | 40 +- .../tempfly/util/CompatMaterial.java | 146 +- .../com/moneybags/tempfly/util/Console.java | 122 +- .../com/moneybags/tempfly/util/DailyDate.java | 50 +- .../moneybags/tempfly/util/ParticleTask.java | 50 +- .../com/moneybags/tempfly/util/U.java | 282 +-- .../com/moneybags/tempfly/util/V.java | 926 +++---- .../tempfly/util/data/DataBridge.java | 1386 +++++------ .../tempfly/util/data/DataFileHolder.java | 44 +- .../tempfly/util/data/DataPointer.java | 82 +- .../moneybags/tempfly/util/data/Files.java | 178 +- .../tempfly/util/data/Reloadable.java | 18 +- 123 files changed, 16036 insertions(+), 16102 deletions(-) create mode 100644 .gitignore delete mode 100644 TempFly/.classpath delete mode 100644 TempFly/.gitignore delete mode 100644 TempFly/.project delete mode 100644 TempFly/.settings/org.eclipse.core.resources.prefs delete mode 100644 TempFly/.settings/org.eclipse.jdt.core.prefs delete mode 100644 TempFly/.settings/org.eclipse.m2e.core.prefs delete mode 100644 TempFly/bin/.gitignore rename TempFly/pom.xml => pom.xml (96%) rename {TempFly/resources => resources}/config.yml (97%) rename {TempFly/resources => resources}/data.yml (95%) rename {TempFly/resources => resources}/dbsetup.sql (97%) rename {TempFly/resources => resources}/factions_preset_uuid.yml (97%) rename {TempFly/resources => resources}/lang.yml (97%) rename {TempFly/resources => resources}/page.yml (95%) rename {TempFly/resources => resources}/permissions.yml (96%) rename {TempFly/resources => resources}/plugin.yml (97%) rename {TempFly/resources => resources}/skyblock_preset_askyblock.yml (97%) rename {TempFly/resources => resources}/skyblock_preset_bento.yml (97%) rename {TempFly/resources => resources}/skyblock_preset_generic.yml (97%) rename {TempFly/resources => resources}/skyblock_preset_iridium.yml (97%) rename {TempFly/resources => resources}/skyblock_preset_superior.yml (97%) rename {TempFly/resources => resources}/skyblock_readme.yml (97%) rename {TempFly/src => src}/com/moneybags/tempfly/Metrics.java (97%) rename {TempFly/src => src}/com/moneybags/tempfly/TempFly.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/TempFlyAPI.java (97%) rename {TempFly/src => src}/com/moneybags/tempfly/aesthetic/ActionBarAPI.java (97%) rename {TempFly/src => src}/com/moneybags/tempfly/aesthetic/ClipAPI.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/aesthetic/MvdWAPI.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/aesthetic/TitleAPI.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/aesthetic/actionbar/ActionBar.java (100%) rename {TempFly/src => src}/com/moneybags/tempfly/aesthetic/actionbar/LegacyActionBar.java (100%) rename {TempFly/src => src}/com/moneybags/tempfly/aesthetic/actionbar/ModernActionBar.java (100%) rename {TempFly/src => src}/com/moneybags/tempfly/aesthetic/particle/Particles.java (97%) rename {TempFly/src => src}/com/moneybags/tempfly/aesthetic/title/LegacyTitle.java (98%) rename {TempFly/src => src}/com/moneybags/tempfly/aesthetic/title/ModernTitle.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/aesthetic/title/Title.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/combat/CombatHandler.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/combat/CombatTag.java (94%) rename {TempFly/src => src}/com/moneybags/tempfly/command/CommandManager.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/command/TempFlyCommand.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/command/TempFlyExecutor.java (97%) rename {TempFly/src => src}/com/moneybags/tempfly/command/TempFlyTabCompleter.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/command/TimeCommand.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/command/admin/CmdGive.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/command/admin/CmdGiveAll.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/command/admin/CmdMigrate.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/command/admin/CmdReload.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/command/admin/CmdRemove.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/command/admin/CmdSet.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/command/admin/CmdTrailRemove.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/command/admin/CmdTrailSet.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/command/player/CmdBypass.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/command/player/CmdFly.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/command/player/CmdHelp.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/command/player/CmdInfinite.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/command/player/CmdPay.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/command/player/CmdShop.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/command/player/CmdSpeed.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/command/player/CmdTime.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/command/player/CmdTrails.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/environment/FlightEnvironment.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/environment/RelativeTimeRegion.java (94%) rename {TempFly/src => src}/com/moneybags/tempfly/environment/StructureProximity.java (97%) rename {TempFly/src => src}/com/moneybags/tempfly/event/ActionBarSendEvent.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/event/FlightEnabledEvent.java (94%) rename {TempFly/src => src}/com/moneybags/tempfly/event/FlightUserInitializedEvent.java (94%) rename {TempFly/src => src}/com/moneybags/tempfly/event/TitleSendEvent.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/fly/FlightManager.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/fly/Flyer.java (94%) rename {TempFly/src => src}/com/moneybags/tempfly/fly/RequirementProvider.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/fly/result/FlightResult.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/fly/result/ResultAllow.java (97%) rename {TempFly/src => src}/com/moneybags/tempfly/fly/result/ResultDeny.java (97%) rename {TempFly/src => src}/com/moneybags/tempfly/gui/GuiManager.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/gui/GuiSession.java (94%) rename {TempFly/src => src}/com/moneybags/tempfly/gui/abstraction/DynamicPage.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/gui/abstraction/Page.java (94%) rename {TempFly/src => src}/com/moneybags/tempfly/gui/pages/PageShop.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/gui/pages/PageTrails.java (97%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/HookManager.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/IslandSettings.java (97%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/TempFlyHook.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/TerritoryHook.java (97%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/TerritoryWrapper.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/factions/FactionRequirement.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/factions/FactionRoleSettings.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/factions/FactionWrapper.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/factions/FactionsHook.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/factions/plugins/FactionsUUIDHook.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/region/CompatRegion.java (94%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/region/RegionProvider.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/region/plugins/WorldGuardHook.java (97%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/skyblock/CmdIslandSettings.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/skyblock/IslandWrapper.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/skyblock/PageIslandSettings.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/skyblock/SettingsProvider.java (94%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/skyblock/SkyblockChallenge.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/skyblock/SkyblockHook.java (97%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/skyblock/SkyblockRequirement.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/skyblock/plugins/AskyblockHook.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/skyblock/plugins/BentoHook.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/skyblock/plugins/BskyblockHook.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/skyblock/plugins/IridiumHook.java (97%) rename {TempFly/src => src}/com/moneybags/tempfly/hook/skyblock/plugins/SuperiorHook.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/time/AsyncTimeExecutor.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/time/AsyncTimeParameters.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/time/TimeManager.java (97%) rename {TempFly/src => src}/com/moneybags/tempfly/user/FlightUser.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/user/UserEnvironment.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/user/UserLoader.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/util/AutoSave.java (94%) rename {TempFly/src => src}/com/moneybags/tempfly/util/CompatMaterial.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/util/Console.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/util/DailyDate.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/util/ParticleTask.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/util/U.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/util/V.java (97%) rename {TempFly/src => src}/com/moneybags/tempfly/util/data/DataBridge.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/util/data/DataFileHolder.java (95%) rename {TempFly/src => src}/com/moneybags/tempfly/util/data/DataPointer.java (94%) rename {TempFly/src => src}/com/moneybags/tempfly/util/data/Files.java (96%) rename {TempFly/src => src}/com/moneybags/tempfly/util/data/Reloadable.java (93%) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6337df0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +/target/ + +# IntelliJ +.idea/ +*.iml + +# Eclipse +.settings/ +.classpath +.project +bin/ \ No newline at end of file diff --git a/TempFly/.classpath b/TempFly/.classpath deleted file mode 100644 index be583b0..0000000 --- a/TempFly/.classpath +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/TempFly/.gitignore b/TempFly/.gitignore deleted file mode 100644 index b01e549..0000000 --- a/TempFly/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -/target/ - -# IntelliJ -.idea/ -*.iml diff --git a/TempFly/.project b/TempFly/.project deleted file mode 100644 index b41fe23..0000000 --- a/TempFly/.project +++ /dev/null @@ -1,23 +0,0 @@ - - - TempFly - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - org.eclipse.jdt.core.javanature - - diff --git a/TempFly/.settings/org.eclipse.core.resources.prefs b/TempFly/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 3fc4e96..0000000 --- a/TempFly/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -encoding//resources/lang.yml=UTF-8 diff --git a/TempFly/.settings/org.eclipse.jdt.core.prefs b/TempFly/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 39e9a95..0000000 --- a/TempFly/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,16 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore -org.eclipse.jdt.core.compiler.release=disabled -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/TempFly/.settings/org.eclipse.m2e.core.prefs b/TempFly/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index 14b697b..0000000 --- a/TempFly/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/TempFly/bin/.gitignore b/TempFly/bin/.gitignore deleted file mode 100644 index c2d9872..0000000 --- a/TempFly/bin/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/com/ diff --git a/TempFly/pom.xml b/pom.xml similarity index 96% rename from TempFly/pom.xml rename to pom.xml index 984c9bb..0f8f15e 100644 --- a/TempFly/pom.xml +++ b/pom.xml @@ -1,187 +1,187 @@ - - 4.0.0 - ChiefBeef - TempFly - 3.1.7 - - src - - - maven-compiler-plugin - 3.7.0 - - 1.8 - 1.8 - - - - - - resources - - - - - - - - bg-repo - https://repo.bg-software.com/repository/api/ - - - - spigot-repo - https://hub.spigotmc.org/nexus/content/repositories/snapshots/ - - - - enginehub-maven - http://maven.enginehub.org/repo/ - - - - jitpack.io - https://jitpack.io - - - - codemc-repo - https://repo.codemc.org/repository/maven-public/ - - - - - false - - bintray-tastybento-maven-repo - bintray - https://dl.bintray.com/tastybento/maven-repo - - - - placeholderapi - http://repo.extendedclip.com/content/repositories/placeholderapi/ - - - - factionsuuid - https://ci.ender.zone/plugin/repository/everything/ - - - - sk89q-repo - https://maven.enginehub.org/repo/ - - - - mvdw-software - MVdW Public Repositories - http://repo.mvdw-software.be/content/groups/public/ - - - - savagelabs - https://nexus.savagelabs.net/repository/maven-releases/ - - - - - - - - mysql - mysql-connector-java - 8.0.28 - - - - - com.bgsoftware - SuperiorSkyblockAPI - 1.9.0 - - - - org.spigotmc - spigot-api - 1.16.4-R0.1-SNAPSHOT - provided - - - - com.sk89q.worldedit - worldedit-bukkit - 7.2.0-SNAPSHOT - provided - - - - com.sk89q.worldguard - worldguard-bukkit - 7.0.0 - provided - - - - com.github.MilkBowl - VaultAPI - 1.7 - provided - - - - - - me.clip - placeholderapi - 2.9.2 - provided - - - - be.maximvdw - MVdWPlaceholderAPI - 3.1.1-SNAPSHOT - provided - - - org.spigotmc - spigot - - - - - - - - com.iridium - IridiumSkyblock - 2.6.5 - provided - - - - com.wasteofplastic - askyblock - 3.0.9.4 - provided - - - - world.bentobox - bentobox - 1.16.0 - provided - - - - - - com.massivecraft - Factions - 1.6.9.5-U0.6.8 - provided - - - + + 4.0.0 + ChiefBeef + TempFly + 3.1.7 + + src + + + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + + + + + resources + + + + + + + + bg-repo + https://repo.bg-software.com/repository/api/ + + + + spigot-repo + https://hub.spigotmc.org/nexus/content/repositories/snapshots/ + + + + enginehub-maven + http://maven.enginehub.org/repo/ + + + + jitpack.io + https://jitpack.io + + + + codemc-repo + https://repo.codemc.org/repository/maven-public/ + + + + + false + + bintray-tastybento-maven-repo + bintray + https://dl.bintray.com/tastybento/maven-repo + + + + placeholderapi + http://repo.extendedclip.com/content/repositories/placeholderapi/ + + + + factionsuuid + https://ci.ender.zone/plugin/repository/everything/ + + + + sk89q-repo + https://maven.enginehub.org/repo/ + + + + mvdw-software + MVdW Public Repositories + http://repo.mvdw-software.be/content/groups/public/ + + + + savagelabs + https://nexus.savagelabs.net/repository/maven-releases/ + + + + + + + + mysql + mysql-connector-java + 8.0.28 + + + + + com.bgsoftware + SuperiorSkyblockAPI + 1.9.0 + + + + org.spigotmc + spigot-api + 1.16.4-R0.1-SNAPSHOT + provided + + + + com.sk89q.worldedit + worldedit-bukkit + 7.2.0-SNAPSHOT + provided + + + + com.sk89q.worldguard + worldguard-bukkit + 7.0.0 + provided + + + + com.github.MilkBowl + VaultAPI + 1.7 + provided + + + + + + me.clip + placeholderapi + 2.9.2 + provided + + + + be.maximvdw + MVdWPlaceholderAPI + 3.1.1-SNAPSHOT + provided + + + org.spigotmc + spigot + + + + + + + + com.iridium + IridiumSkyblock + 2.6.5 + provided + + + + com.wasteofplastic + askyblock + 3.0.9.4 + provided + + + + world.bentobox + bentobox + 1.16.0 + provided + + + + + + com.massivecraft + Factions + 1.6.9.5-U0.6.8 + provided + + + diff --git a/TempFly/resources/config.yml b/resources/config.yml similarity index 97% rename from TempFly/resources/config.yml rename to resources/config.yml index 142634f..b0d80f4 100644 --- a/TempFly/resources/config.yml +++ b/resources/config.yml @@ -1,326 +1,326 @@ -##======================================================================================## -#| |# -#| ,--------. ,------.,--. |# -#| '--. .--',---. ,--,--,--. ,---. | .---'| |,--. ,--. |# -#| | | | .-. :| || .-. || `--, | | \ ' / |# -#| | | \ --.| | | || '-' '| |` | | \ ' |# -#| `--' `----'`--`--`--'| |-' `--' `--'.-' / |# -#| `--' `---' |# -#| |# -##--------------------------------------------------------------------------------------## -#| |# -#| Author |# -#| =---=------=---= |# -#| Chief Beef |# -#| |# -##--------------------------------------------------------------------------------------## -#| |# -#| <--Commands & Permissions--> |# -#| |# -#| https://github.com/ChiefMoneyBags/TempFly/blob/Master/TempFly/permissions.yml |# -#| |# -##--------------------------------------------------------------------------------------## -#| |# -#| Time Placeholder Usage |# -#| |# -#| Single Units |# -#| {SECONDS} {MINUTES} {HOURS} {DAYS} |# -#| ---------------------------------- |# -#| Single unit placeholders will show the amount of time for only the unit specified |# -#| If a player has 65 secs of time {SECONDS} will be 5s and {MINUTES} will be 1m |# -#| |# -#| Formatted Time |# -#| {TIME_FORMATTED} |# -#| ---------------------------------- |# -#| Formatted time only includes time units currently applicable to the player |# -#| It does not display zeroes in between units like this [1d 0h 0m 1s] |# -#| If a player has 86401 seconds of time it will display [1d 1s] |# -#| |# -##======================================================================================## - - -system: - # Time in minutes to backup data - backup: 5 - # If true your console will be subjected to spam from the internal workings of the plugin. - # If you have an issue i may ask you to turn it on. - debug: false - # If true tempfly will not track player regions. This can improve performance but will disable ALL - # features of tempfly that rely on regions to function, such as disabled regions, relative time regions etc.. - disable_region_tracking: false - # If true this will disable all tab completions for tempfly commands - # Can be bypassed with tempfly.disable_tab.bypass - disable_tab: false - # database - mysql: - enabled: false - host: "127.0.0.1" - port: 3306 - name: "name" - user: "user" - pass: "pass" - -general: - # This feature prevents conflictions with other plugins fly features. - # By default tempfly will steal priority and take the command /fly away from other plugins. - # If the player has a permission listed below tempfly will not override the command /fly for them. - fly_override_permissions: - - 'essentials.fly' - - # This setting allows you to disable flight in specific worlds or regions. - disabled: - worlds: - - 'example_world' - regions: - - 'example_region' - - # This setting enables you to allow flight only in whitelisted worlds or regions. - whitelist: - worlds: - # - 'world' - - regions: - # - 'example_region' - - timer: - # If true the players timer will count down even when they have flight disabled. - # If you want the time to count down while they are offline please see the feature "time_decay" - constant: false - # If false the player will not lose flight time if standing on the ground with flight enabled. - ground: false - # If false the player will not lose flight time if they go idle with flight enabled. - # This will override the constant and ground timers. - idle: false - # If false the timer will not count down while a player uses creative flight. - # If true the player will be subject to all normal tempfly flight restrictions and time usage while in creative flight. - creative: false - # If false the timer will not count down while a player is in spectator. - # Due to the nature of spectator mode when the player runs out of flight time their flight cannot be disabled until - # they return to another gamemode. - spectator: false - - idle: - # The threshold in seconds to consider a player idle. -1 for no idle timer - threshold: 300 - # If true players tempfly will be disabled if they go idle in the sky (dropping them). - drop_player: false - - flight: - # Speed settings. - speed: - # Default global speed for all players. This speed is used as a base unless a value is otherwise specified below. - default: 1 - # If false the users speed will be forcefully set to the values defined below upon entering valid areas regardless of the - # speed chosen by the player or the default speed. This also overrides permission speeds. - - # If true the configured speeds will act as a maximum speed for the area - # and will only be forced if the users speed exceeds the maximum defined for the area. - # Upon leaving the area the users selected / default speed will be restored. - user_preference: true - # Default maximum speeds for worlds. - worlds: - #world: 1.25 - #world_nether: 0.35 - #world_the_end: 0.25 - # Default maximum speed for regions. Regions take priority over worlds. If 2 regions overlap the highest value is used. - regions: - despacito: 0.1 - initial_d: 10 - - # The maximum y level a player can reach before flight is disabled. - maximum_height: 275 - # If true a user will start flying again when they no longer have flight restrictions so long as their flight is enabled. - # Example; - # - A user flies into a disabled region and loses flight. - # - If auto_fly is true they will fly again automatically without needing to use the fly command. - auto_enable: true - # If true a user will always have their flight enabled for them when they receive flight time so - # long as their balance previous to receiving the time was 0. - enable_on_time_received: false - - time: - # If true players can send eachother time as if it were a currency. - payable: true - # Here you can set the maximum time players can have in their balance. -1 for no limit. - max: - # The base maximum time in seconds applied to everyone. - base: -1 - # Optionally you can include permission groups for a different max time. - # The groups listed below will override the global base defined above. - # If a player inherits more than 1 group the highest value will always be used. - # The permission is "tempfly.max.[group]" - groups: - # member: 60 - # vip: 120 - - # This setting allows you to give players infinite flight while they are in specific worlds or regions. - # Players do not need a permission to obtain infinite flight in these areas. - infinite: - worlds: - - 'example_world' - regions: - - 'example_region' - - bonus: - # Time in seconds given to a player when they first join the server. - first_join: 10 - # Permission based time given to a player as a daily login bonus. - # The permission is "tempfly.bonus.[group]" - # Time will stack for each permission the player inherits. Make sure to configure your permissions properly. - daily_login: - member: 10 - vip: 30 - - - time_decay: - # If enabled a player will lose time when logged off the server. - # info: - # - This will not track every offline player, it only updates when the player rejoins the server. no lags. - # - To use this in tandem with the constant_timer, set threshold and seconds_lost both to 1. (1 second lost per 1 second offline). - enabled: false - # The interval in which players will lose time (seconds) - threshold: 3600 - # Seconds of flight lost per interval - seconds_lost: 15 - - # If true, flight is disabled when the player; - combat: - # attacks another player - attack_player: true - # attacks a mob - attack_mob: false - # is attacked by a player - attacked_by_player: true - # is attacked by a mob - attacked_by_mob: false - # attacks themself - self_inflicted: false - - # Seconds before flight can be enabled after pvp - pvp_tag: 10 - # Seconds before flight can be enabled after pve - pve_tag: 5 - - # If false the player will not take fall damage when flight is disabled; - damage: - # ...by command - on_command: false - # ...by running out of time - out_of_time: true - # ...from combat - combat: true - # ...from going idle - idle: false - # ...from entering a disabled world - world: false - # ...from entering a disabled region - region: false - -aesthetic: - # Features that allow you to easily see if a player is flying using tempfly. - identifier: - - tab_list: - # If enabled, the players name on tab will change to this when they are in tempflight. - enabled: true - # Valid placeholders: {PLAYER} The players name | {OLD_TAG} The original name on tab, including prefixes. - # Supports placeholders for time - name: "&d~{OLD_TAG}" - # For use on servers with a custom tab overlay. This option will allow you to implement placeholders - # for tempfly in the tablist plugin so long as it supports placeholders from the authors clip or maximvdw. - # If you are using the placeholder you can set enabled to false so tempfly doesn't try to alter tab. - placeholder: - enabled: "&8[&6Fly&8]" - disabled: "" - - name_tag: - # If enabled, the players name tag above their head will change to this when they are in tempflight. - # (Not currently compatible with plugin "essentials") - enabled: true - # Valid placeholders: {PLAYER} The players name | {OLD_TAG} The original name tag, including prefixes. - # Supports placeholders for time - name: "&d~{OLD_TAG}" - # For use on servers with a custom name tags. This option will allow you to implement placeholders - # for tempfly in the tablist plugin so long as it supports placeholders from the authors clip or maximvdw. - # If you are using the placeholder you can set enabled to false so tempfly doesn't try to alter the name. - placeholder: - enabled: "&8[&6Fly&8]" - disabled: "" - - particles: - # If false all trails are disabled. - enabled: true - # The default particle type. - type: 'VILLAGER_HAPPY' - # If true all players will have the default particle trail enabled by default. - display_by_default: true - # If true particles will not be displayed if the player is vanished. - # Tested with plugins SuperVanish, PremiumVanish, VanishNoPacket. - hide_vanish: true - - # Title to warn players of remaining flight time - warning: - # If enabled, players will recieve a warning title when they reach a flight marker defined under seconds. - enabled: true - # Supports placeholders for time. - title: "&cWARNING!" - subtitle: "&fYou have {FORMATTED_TIME} &fof flight remaining!" - # Time intervals in seconds to display the title to players. - # ONLY use numbers - seconds: - - 30 - - 15 - - 5 - - action_bar: - enabled: true - text: "&6Flight meter&7: {FORMATTED_TIME}" - -# Oddball features and things many people probably wont use can be found here. -other: - # relative time is a feature that lets you control how fast time will be used in worlds and regions. - # In the example below; - # - time will pass '0.5' times or 50% slower than in real time on world 'example_world' - # - time will pass '1.5' times or 50% faster than in real time in region 'example_region'. - # If the player is in both 'example_world' and 'example_region' at once the values will - # be factored together resulting in a value of 0.75 or 25% slower. - relative_time: - worlds: - example_world: 0.5 - regions: - example_region: 1.5 - -# Quality of life feature for servers that dont want to implement a whole shop gui plugin, but just want a simple tempfly shop. -shop: - general: - # If false the built in shop will not exist. - enabled: false - # You can add as many options with any name you want - options: - five_mins: - # The time to give the player in seconds - time: 300 - # The cost of the time, any vault currency is supported - cost: 7500 - thirty_mins: - time: 1800 - cost: 30000 - one_hour: - time: 3600 - cost: 50000 - -# This is where i will put last ditch efforts to fix bugs I either cannot reproduce or otherwise fix. -workarounds: - # Regarding the infinite flight bug. This bug has been produced in a wide range of situations and - # conflictions with various plugins. Everytime I fix it something else will cause it to occur. - # If you encounter an unlimited flight bug this may help you. - infinite_flight: - # If true a player will ALWAYS have flight disabled if they are not using tempfly. - # This workaround can be disabled for users with the permission - # tempfly.workaround.infinite.bypass.fix_a - fix_a: false - # If true a player will Always have tempfly enabled if they are flying without - # a tempfly timer. If the player has no time flight will be disabled. - # This workaround can be disabled for users with the permission - # tempfly.workaround.infinite.bypass.fix_b +##======================================================================================## +#| |# +#| ,--------. ,------.,--. |# +#| '--. .--',---. ,--,--,--. ,---. | .---'| |,--. ,--. |# +#| | | | .-. :| || .-. || `--, | | \ ' / |# +#| | | \ --.| | | || '-' '| |` | | \ ' |# +#| `--' `----'`--`--`--'| |-' `--' `--'.-' / |# +#| `--' `---' |# +#| |# +##--------------------------------------------------------------------------------------## +#| |# +#| Author |# +#| =---=------=---= |# +#| Chief Beef |# +#| |# +##--------------------------------------------------------------------------------------## +#| |# +#| <--Commands & Permissions--> |# +#| |# +#| https://github.com/ChiefMoneyBags/TempFly/blob/Master/TempFly/permissions.yml |# +#| |# +##--------------------------------------------------------------------------------------## +#| |# +#| Time Placeholder Usage |# +#| |# +#| Single Units |# +#| {SECONDS} {MINUTES} {HOURS} {DAYS} |# +#| ---------------------------------- |# +#| Single unit placeholders will show the amount of time for only the unit specified |# +#| If a player has 65 secs of time {SECONDS} will be 5s and {MINUTES} will be 1m |# +#| |# +#| Formatted Time |# +#| {TIME_FORMATTED} |# +#| ---------------------------------- |# +#| Formatted time only includes time units currently applicable to the player |# +#| It does not display zeroes in between units like this [1d 0h 0m 1s] |# +#| If a player has 86401 seconds of time it will display [1d 1s] |# +#| |# +##======================================================================================## + + +system: + # Time in minutes to backup data + backup: 5 + # If true your console will be subjected to spam from the internal workings of the plugin. + # If you have an issue i may ask you to turn it on. + debug: false + # If true tempfly will not track player regions. This can improve performance but will disable ALL + # features of tempfly that rely on regions to function, such as disabled regions, relative time regions etc.. + disable_region_tracking: false + # If true this will disable all tab completions for tempfly commands + # Can be bypassed with tempfly.disable_tab.bypass + disable_tab: false + # database + mysql: + enabled: false + host: "127.0.0.1" + port: 3306 + name: "name" + user: "user" + pass: "pass" + +general: + # This feature prevents conflictions with other plugins fly features. + # By default tempfly will steal priority and take the command /fly away from other plugins. + # If the player has a permission listed below tempfly will not override the command /fly for them. + fly_override_permissions: + - 'essentials.fly' + + # This setting allows you to disable flight in specific worlds or regions. + disabled: + worlds: + - 'example_world' + regions: + - 'example_region' + + # This setting enables you to allow flight only in whitelisted worlds or regions. + whitelist: + worlds: + # - 'world' + + regions: + # - 'example_region' + + timer: + # If true the players timer will count down even when they have flight disabled. + # If you want the time to count down while they are offline please see the feature "time_decay" + constant: false + # If false the player will not lose flight time if standing on the ground with flight enabled. + ground: false + # If false the player will not lose flight time if they go idle with flight enabled. + # This will override the constant and ground timers. + idle: false + # If false the timer will not count down while a player uses creative flight. + # If true the player will be subject to all normal tempfly flight restrictions and time usage while in creative flight. + creative: false + # If false the timer will not count down while a player is in spectator. + # Due to the nature of spectator mode when the player runs out of flight time their flight cannot be disabled until + # they return to another gamemode. + spectator: false + + idle: + # The threshold in seconds to consider a player idle. -1 for no idle timer + threshold: 300 + # If true players tempfly will be disabled if they go idle in the sky (dropping them). + drop_player: false + + flight: + # Speed settings. + speed: + # Default global speed for all players. This speed is used as a base unless a value is otherwise specified below. + default: 1 + # If false the users speed will be forcefully set to the values defined below upon entering valid areas regardless of the + # speed chosen by the player or the default speed. This also overrides permission speeds. + + # If true the configured speeds will act as a maximum speed for the area + # and will only be forced if the users speed exceeds the maximum defined for the area. + # Upon leaving the area the users selected / default speed will be restored. + user_preference: true + # Default maximum speeds for worlds. + worlds: + #world: 1.25 + #world_nether: 0.35 + #world_the_end: 0.25 + # Default maximum speed for regions. Regions take priority over worlds. If 2 regions overlap the highest value is used. + regions: + despacito: 0.1 + initial_d: 10 + + # The maximum y level a player can reach before flight is disabled. + maximum_height: 275 + # If true a user will start flying again when they no longer have flight restrictions so long as their flight is enabled. + # Example; + # - A user flies into a disabled region and loses flight. + # - If auto_fly is true they will fly again automatically without needing to use the fly command. + auto_enable: true + # If true a user will always have their flight enabled for them when they receive flight time so + # long as their balance previous to receiving the time was 0. + enable_on_time_received: false + + time: + # If true players can send eachother time as if it were a currency. + payable: true + # Here you can set the maximum time players can have in their balance. -1 for no limit. + max: + # The base maximum time in seconds applied to everyone. + base: -1 + # Optionally you can include permission groups for a different max time. + # The groups listed below will override the global base defined above. + # If a player inherits more than 1 group the highest value will always be used. + # The permission is "tempfly.max.[group]" + groups: + # member: 60 + # vip: 120 + + # This setting allows you to give players infinite flight while they are in specific worlds or regions. + # Players do not need a permission to obtain infinite flight in these areas. + infinite: + worlds: + - 'example_world' + regions: + - 'example_region' + + bonus: + # Time in seconds given to a player when they first join the server. + first_join: 10 + # Permission based time given to a player as a daily login bonus. + # The permission is "tempfly.bonus.[group]" + # Time will stack for each permission the player inherits. Make sure to configure your permissions properly. + daily_login: + member: 10 + vip: 30 + + + time_decay: + # If enabled a player will lose time when logged off the server. + # info: + # - This will not track every offline player, it only updates when the player rejoins the server. no lags. + # - To use this in tandem with the constant_timer, set threshold and seconds_lost both to 1. (1 second lost per 1 second offline). + enabled: false + # The interval in which players will lose time (seconds) + threshold: 3600 + # Seconds of flight lost per interval + seconds_lost: 15 + + # If true, flight is disabled when the player; + combat: + # attacks another player + attack_player: true + # attacks a mob + attack_mob: false + # is attacked by a player + attacked_by_player: true + # is attacked by a mob + attacked_by_mob: false + # attacks themself + self_inflicted: false + + # Seconds before flight can be enabled after pvp + pvp_tag: 10 + # Seconds before flight can be enabled after pve + pve_tag: 5 + + # If false the player will not take fall damage when flight is disabled; + damage: + # ...by command + on_command: false + # ...by running out of time + out_of_time: true + # ...from combat + combat: true + # ...from going idle + idle: false + # ...from entering a disabled world + world: false + # ...from entering a disabled region + region: false + +aesthetic: + # Features that allow you to easily see if a player is flying using tempfly. + identifier: + + tab_list: + # If enabled, the players name on tab will change to this when they are in tempflight. + enabled: true + # Valid placeholders: {PLAYER} The players name | {OLD_TAG} The original name on tab, including prefixes. + # Supports placeholders for time + name: "&d~{OLD_TAG}" + # For use on servers with a custom tab overlay. This option will allow you to implement placeholders + # for tempfly in the tablist plugin so long as it supports placeholders from the authors clip or maximvdw. + # If you are using the placeholder you can set enabled to false so tempfly doesn't try to alter tab. + placeholder: + enabled: "&8[&6Fly&8]" + disabled: "" + + name_tag: + # If enabled, the players name tag above their head will change to this when they are in tempflight. + # (Not currently compatible with plugin "essentials") + enabled: true + # Valid placeholders: {PLAYER} The players name | {OLD_TAG} The original name tag, including prefixes. + # Supports placeholders for time + name: "&d~{OLD_TAG}" + # For use on servers with a custom name tags. This option will allow you to implement placeholders + # for tempfly in the tablist plugin so long as it supports placeholders from the authors clip or maximvdw. + # If you are using the placeholder you can set enabled to false so tempfly doesn't try to alter the name. + placeholder: + enabled: "&8[&6Fly&8]" + disabled: "" + + particles: + # If false all trails are disabled. + enabled: true + # The default particle type. + type: 'VILLAGER_HAPPY' + # If true all players will have the default particle trail enabled by default. + display_by_default: true + # If true particles will not be displayed if the player is vanished. + # Tested with plugins SuperVanish, PremiumVanish, VanishNoPacket. + hide_vanish: true + + # Title to warn players of remaining flight time + warning: + # If enabled, players will recieve a warning title when they reach a flight marker defined under seconds. + enabled: true + # Supports placeholders for time. + title: "&cWARNING!" + subtitle: "&fYou have {FORMATTED_TIME} &fof flight remaining!" + # Time intervals in seconds to display the title to players. + # ONLY use numbers + seconds: + - 30 + - 15 + - 5 + + action_bar: + enabled: true + text: "&6Flight meter&7: {FORMATTED_TIME}" + +# Oddball features and things many people probably wont use can be found here. +other: + # relative time is a feature that lets you control how fast time will be used in worlds and regions. + # In the example below; + # - time will pass '0.5' times or 50% slower than in real time on world 'example_world' + # - time will pass '1.5' times or 50% faster than in real time in region 'example_region'. + # If the player is in both 'example_world' and 'example_region' at once the values will + # be factored together resulting in a value of 0.75 or 25% slower. + relative_time: + worlds: + example_world: 0.5 + regions: + example_region: 1.5 + +# Quality of life feature for servers that dont want to implement a whole shop gui plugin, but just want a simple tempfly shop. +shop: + general: + # If false the built in shop will not exist. + enabled: false + # You can add as many options with any name you want + options: + five_mins: + # The time to give the player in seconds + time: 300 + # The cost of the time, any vault currency is supported + cost: 7500 + thirty_mins: + time: 1800 + cost: 30000 + one_hour: + time: 3600 + cost: 50000 + +# This is where i will put last ditch efforts to fix bugs I either cannot reproduce or otherwise fix. +workarounds: + # Regarding the infinite flight bug. This bug has been produced in a wide range of situations and + # conflictions with various plugins. Everytime I fix it something else will cause it to occur. + # If you encounter an unlimited flight bug this may help you. + infinite_flight: + # If true a player will ALWAYS have flight disabled if they are not using tempfly. + # This workaround can be disabled for users with the permission + # tempfly.workaround.infinite.bypass.fix_a + fix_a: false + # If true a player will Always have tempfly enabled if they are flying without + # a tempfly timer. If the player has no time flight will be disabled. + # This workaround can be disabled for users with the permission + # tempfly.workaround.infinite.bypass.fix_b fix_b: false \ No newline at end of file diff --git a/TempFly/resources/data.yml b/resources/data.yml similarity index 95% rename from TempFly/resources/data.yml rename to resources/data.yml index c0f0796..8efa694 100644 --- a/TempFly/resources/data.yml +++ b/resources/data.yml @@ -1,2 +1,2 @@ -version: 3.0 +version: 3.0 players: \ No newline at end of file diff --git a/TempFly/resources/dbsetup.sql b/resources/dbsetup.sql similarity index 97% rename from TempFly/resources/dbsetup.sql rename to resources/dbsetup.sql index f8c3080..76c531c 100644 --- a/TempFly/resources/dbsetup.sql +++ b/resources/dbsetup.sql @@ -1,16 +1,16 @@ - -CREATE TABLE IF NOT EXISTS TEMPFLY_DATA -( - uuid CHAR(36) NOT NULL, - player_time DOUBLE(10, 2) DEFAULT 0, - logged_in_flight BOOLEAN DEFAULT 0, - compat_logged_in_flight BOOLEAN DEFAULT 0, - damage_protection BOOLEAN DEFAULT 0, - last_daily_bonus BIGINT DEFAULT 0, - trail VARCHAR(32) DEFAULT NULL, - infinite BOOLEAN DEFAULT 0, - bypass BOOLEAN DEFAULT 0, - speed DOUBLE(5, 2) DEFAULT -999.00, - - PRIMARY KEY (uuid) + +CREATE TABLE IF NOT EXISTS TEMPFLY_DATA +( + uuid CHAR(36) NOT NULL, + player_time DOUBLE(10, 2) DEFAULT 0, + logged_in_flight BOOLEAN DEFAULT 0, + compat_logged_in_flight BOOLEAN DEFAULT 0, + damage_protection BOOLEAN DEFAULT 0, + last_daily_bonus BIGINT DEFAULT 0, + trail VARCHAR(32) DEFAULT NULL, + infinite BOOLEAN DEFAULT 0, + bypass BOOLEAN DEFAULT 0, + speed DOUBLE(5, 2) DEFAULT -999.00, + + PRIMARY KEY (uuid) ); \ No newline at end of file diff --git a/TempFly/resources/factions_preset_uuid.yml b/resources/factions_preset_uuid.yml similarity index 97% rename from TempFly/resources/factions_preset_uuid.yml rename to resources/factions_preset_uuid.yml index d352327..3e20ef5 100644 --- a/TempFly/resources/factions_preset_uuid.yml +++ b/resources/factions_preset_uuid.yml @@ -1,114 +1,114 @@ -enable_hook: true - -##------------------------------------------------------------------## -#| Valid power requirements include |# -##--------------------------+---------------------------------------## -#| self_power_percentage | The power of the home faction as a |# -#| | percentage of its max power |# -#| Effect: (>=) | Home power must be _% or greater |# -#| | IE: 75 equals 75% or greater power |# -##--------------------------+---------------------------------------## -#| foreign_power_percentage | The power of the foreign faction as a |# -#| | percentage of its max power |# -#| Effect: (<=) | Foreign power must be _% or less |# -#| | IE: 75 equals 75% or less power |# -##--------------------------+---------------------------------------## -#| allied_power_percentage | The power of the allied faction as a |# -#| | percentage of its max power |# -#| Effect: (>=) | Ally's power must be _% or greater |# -#| | IE: 75 equals 75% or greater power |# -##--------------------------+---------------------------------------## -#| self_power_absolute | The power of the home faction as an |# -#| | absolute number |# -#| Effect: (>=) | Home power must be this or greater |# -#| | IE: 115 equals at least 115 power |# -##--------------------------+---------------------------------------## -#| foreign_power_absolute | The power of the foreign faction as |# -#| | an absolute number |# -#| Effect: (<=) | Foreign power must be this or less |# -#| | IE: 115 equals less than 75 power |# -##--------------------------+---------------------------------------## -#| allied_power_absolute | The power of the allied faction as |# -#| | an absolute number |# -#| Effect: (>=) | Ally's power must be this or greater |# -#| | IE: 115 equals at least 115 power |# -##--------------------------+---------------------------------------## - -# Allows you to configure fall damage for factions related flight restrictions. -fall_damage: - # Should the player take fall damage if flight is lost due to power restrictions in the following territories? - power: - home: true - enemy: true - neutral: false - allied: true - wilderness: false - - # Should the player take fall damage if they fall due to entering flight disabled territories? - disabled: - home: false - enemy: true - neutral: false - allied: false - wilderness: false - -language: - requirements: - illegal_territory: "{PREFIX} &f{ROLE}'s &cfrom your faction may not fly in &f{FACTION_NAME} &cland!" - power_self: "{PREFIX} &cYou must have at least &f{POWER} &cpower to fly in &f{FACTION_NAME} &cland!" - power_foreign: "{PREFIX} &cThe faction &f{FACTION_NAME} &cmust have less than &f{POWER} &cpower!" - power_allied: "{PREFIX} &cThe faction &f{FACTION_NAME} &cmust have at least &f{POWER} &cpower!" - faction_self: "{PREFIX} &cYou must be in a faction to fly in &f{FACTION_NAME} &cland!" - -# These are the base values regarding flight requirements for all faction roles. -# If you do not want to use the power requirements you may remove them. -# My default values are geared more towards ease of raiding rather than ease of defense. -base_requirements: - home: - # If false players will never be allowed to fly in home territory. - allowed: true - # To fly in home faction land, the players faction must have at least this much power. - home_power_percentage: 65 - - enemy: - # If false players will never be allowed to fly in enemy land - allowed: true - # To fly in enemy land the players faction must have at least this much power - home_power_percentage: 50 - # To fly in enemy land the enemy faction must be weakened to this amount or less before flight is allowed in their land. - # This setting may also be applied to neutal territory. - foreign_power_percentage: 80 - - allied: - # If false players will never be allowed to fly in allied land - allowed: true - # To fly in allied land the players faction must have at least this much power - home_power_percentage: 65 - # To fly in allied land the allied faction must have at least this much power before flight is allowed in their land. - allied_power_percentage: 80 - - neutral: - # If false players will never be allowed to fly in neutral faction land. - allowed: false - - wilderness: - # If false players will never be allowed to fly in unclaimed land. - allowed: false - -# Here you can specify special requirements for each faction role. -# Any values specified here will override the default values. -# FactionsUUID faction roles; -# recruit | normal | moderator | coleader | admin -role_requirements: - -# admin: -# home: -# home_power_percentage: 50 - -# enemy: -# home_power_percentage: 30 - -# neutral: -# allowed: true -# home_power_percentage: 25 +enable_hook: true + +##------------------------------------------------------------------## +#| Valid power requirements include |# +##--------------------------+---------------------------------------## +#| self_power_percentage | The power of the home faction as a |# +#| | percentage of its max power |# +#| Effect: (>=) | Home power must be _% or greater |# +#| | IE: 75 equals 75% or greater power |# +##--------------------------+---------------------------------------## +#| foreign_power_percentage | The power of the foreign faction as a |# +#| | percentage of its max power |# +#| Effect: (<=) | Foreign power must be _% or less |# +#| | IE: 75 equals 75% or less power |# +##--------------------------+---------------------------------------## +#| allied_power_percentage | The power of the allied faction as a |# +#| | percentage of its max power |# +#| Effect: (>=) | Ally's power must be _% or greater |# +#| | IE: 75 equals 75% or greater power |# +##--------------------------+---------------------------------------## +#| self_power_absolute | The power of the home faction as an |# +#| | absolute number |# +#| Effect: (>=) | Home power must be this or greater |# +#| | IE: 115 equals at least 115 power |# +##--------------------------+---------------------------------------## +#| foreign_power_absolute | The power of the foreign faction as |# +#| | an absolute number |# +#| Effect: (<=) | Foreign power must be this or less |# +#| | IE: 115 equals less than 75 power |# +##--------------------------+---------------------------------------## +#| allied_power_absolute | The power of the allied faction as |# +#| | an absolute number |# +#| Effect: (>=) | Ally's power must be this or greater |# +#| | IE: 115 equals at least 115 power |# +##--------------------------+---------------------------------------## + +# Allows you to configure fall damage for factions related flight restrictions. +fall_damage: + # Should the player take fall damage if flight is lost due to power restrictions in the following territories? + power: + home: true + enemy: true + neutral: false + allied: true + wilderness: false + + # Should the player take fall damage if they fall due to entering flight disabled territories? + disabled: + home: false + enemy: true + neutral: false + allied: false + wilderness: false + +language: + requirements: + illegal_territory: "{PREFIX} &f{ROLE}'s &cfrom your faction may not fly in &f{FACTION_NAME} &cland!" + power_self: "{PREFIX} &cYou must have at least &f{POWER} &cpower to fly in &f{FACTION_NAME} &cland!" + power_foreign: "{PREFIX} &cThe faction &f{FACTION_NAME} &cmust have less than &f{POWER} &cpower!" + power_allied: "{PREFIX} &cThe faction &f{FACTION_NAME} &cmust have at least &f{POWER} &cpower!" + faction_self: "{PREFIX} &cYou must be in a faction to fly in &f{FACTION_NAME} &cland!" + +# These are the base values regarding flight requirements for all faction roles. +# If you do not want to use the power requirements you may remove them. +# My default values are geared more towards ease of raiding rather than ease of defense. +base_requirements: + home: + # If false players will never be allowed to fly in home territory. + allowed: true + # To fly in home faction land, the players faction must have at least this much power. + home_power_percentage: 65 + + enemy: + # If false players will never be allowed to fly in enemy land + allowed: true + # To fly in enemy land the players faction must have at least this much power + home_power_percentage: 50 + # To fly in enemy land the enemy faction must be weakened to this amount or less before flight is allowed in their land. + # This setting may also be applied to neutal territory. + foreign_power_percentage: 80 + + allied: + # If false players will never be allowed to fly in allied land + allowed: true + # To fly in allied land the players faction must have at least this much power + home_power_percentage: 65 + # To fly in allied land the allied faction must have at least this much power before flight is allowed in their land. + allied_power_percentage: 80 + + neutral: + # If false players will never be allowed to fly in neutral faction land. + allowed: false + + wilderness: + # If false players will never be allowed to fly in unclaimed land. + allowed: false + +# Here you can specify special requirements for each faction role. +# Any values specified here will override the default values. +# FactionsUUID faction roles; +# recruit | normal | moderator | coleader | admin +role_requirements: + +# admin: +# home: +# home_power_percentage: 50 + +# enemy: +# home_power_percentage: 30 + +# neutral: +# allowed: true +# home_power_percentage: 25 # foreign_power_percentage: 100 \ No newline at end of file diff --git a/TempFly/resources/lang.yml b/resources/lang.yml similarity index 97% rename from TempFly/resources/lang.yml rename to resources/lang.yml index 5b56c4e..58d6598 100644 --- a/TempFly/resources/lang.yml +++ b/resources/lang.yml @@ -1,202 +1,202 @@ -system: - prefix: "&8[&dTemp&fFly&8]" - reload: "{PREFIX} &aYou reloaded the plugin." - help: - - "&8&l------&dTemp&fFly&8&l------" - - "&6/tf" - - "&7- Toggle tempfly" - - "&6/tf time" - - "&7- View remaining fly time" - - "&6/tf pay [player] [time]" - - "&7- send another player fly time" - help_extended: - - "&6/tf give [player] [time]" - - "&7- Give a player fly time" - - "&6/tf remove [player] [time]" - - "&7- Remove fly time from a player" - - "&6/tf set [player] [time]" - - "&7- Set a players fly time" - -general: - - unit: - seconds: "s" - minutes: "m" - hours: "h" - days: "d" - - invalid: - time_other: "{PREFIX} &f{PLAYER} &chas no more flight time!" - time_self: "{PREFIX} &cYou have no more flight time!" - number: "{PREFIX} &f{NUMBER} &cis not a valid number!" - particle: "{PREFIX} &f{PARTICLE} &cis not a valid particle type!" - player: "{PREFIX} &cThe player &f{PLAYER} &cwas not found..." - permission: "{PREFIX} &cYou have insufficient permissions..." - command: "&fUnknown command. Type /help for more information." - reciever: "{PREFIX} &cYou cannot pay yourself!" - sender: "{PREFIX} &cOnly players can use this command!" - flyer_self: "{PREFIX} &cYou are not flying!" - funds: "{PREFIX} &cThis costs &f{COST}&c! You do not have enough money!" - economy: "{PREFIX} &cYou must have a (&fvault&c) economy installed to use the shop!" - vault_perms: "{PREFIX} &cYou must install the plugin (&fvault&c) for the ability to set offline player time!" - - time: - format: "&f{QUANTITY}&f{UNIT}" - given_other: "{PREFIX} &f{PLAYER} &agot {FORMATTED_TIME}&a." - given_all: "{PREFIX} &aYou gave &fALL &aplayers {FORMATTED_TIME}&a." - given_self: "{PREFIX} &aYou recieved {FORMATTED_TIME}&a." - removed_other: "{PREFIX} &f{PLAYER} &clost {FORMATTED_TIME}&c." - removed_self: "{PREFIX} &cYou lost {FORMATTED_TIME}&c." - sent_other: "{PREFIX} &aYou sent &f{PLAYER}&a {FORMATTED_TIME}&a." - sent_self: "{PREFIX} &f{PLAYER} &asent you {FORMATTED_TIME}&a." - set_other: "{PREFIX} &f{PLAYER} &ahad their time set to {FORMATTED_TIME}&a." - set_self: "{PREFIX} &aYour time was set to {FORMATTED_TIME}&a." - max_other: "{PREFIX} &f{PLAYER} &chas reached the maximum allowed time&c!" - max_self: "{PREFIX} &cYou have reached the maximum allowed time&c!" - decay: "{PREFIX} &cYou lost {FORMATTED_TIME} &cfor inactivity!" - first_join: "{PREFIX} &aYou recieved {FORMATTED_TIME} &aof flight time. Fly with &f/tf&a." - daily_login: "{PREFIX} &aYou recieved a daily bonus of {FORMATTED_TIME}&a!" - purchased: "{PREFIX} &aYou purchased {FORMATTED_TIME} &afor &e${COST}&a!" - - info: - header: "&8&m--------&dTime&8&m--------" - player: "&fPlayer&7: &e{PLAYER}" - infinite: "&fInfinite: &c&lUser has unlimited flight!" - days: "&fDays&7: &e{DAYS}" - hours: "&fHours&7: &e{HOURS}" - minutes: "&fMinutes&7: &e{MINUTES}" - seconds: "&fSeconds&7: &e{SECONDS}" - footer: "&8&m-------------------" - - fly: - enabled_other: "{PREFIX} &f{PLAYER} &ais now flying" - enabled_self: "{PREFIX} &aYour flight was enabled!" - disabled_other: "{PREFIX} &f{PLAYER} &cis no longer flying!" - disabled_self: "{PREFIX} &cYour flight was disabled!" - speed_other: "{PREFIX} &f{PLAYER} &ahad their speed set to {SPEED}&a." - speed_self: "{PREFIX} &aYour fly speed was set to &f{SPEED}&a." - speed_limit_other: "{PREFIX} &f{PLAYER} &cIs currently limited to fly speed &f{SPEED}&c." - speed_limit_self: "{PREFIX} &cYour fly speed is currently limited to &f{SPEED}&c." - speed_restricted: "{PREFIX} &cYou are not allowed to change your fly speed!" - already_enabled: "{PREFIX} &aYour flight is already enabled!" - already_disabled: "{PREFIX} &cYour flight is already disabled!" - idle_drop: "{PREFIX} &cYou lost flight due to being idle!" - idle: "{PREFIX} &cYou are now considered idle." - infinite_enabled: "{PREFIX} &aYou enabled your infinite flight!" - infinite_disabled: "{PREFIX} &cYou disabled your infinite flight!" - bypass_enabled: "{PREFIX} &aYou enabled flight bypass mode!" - bypass_disabled: "{PREFIX} &cYou disabled flight bypass mode!" - - requirement: - fail: - default_other: "{PREFIX} &f{PLAYER} &ccannot currently fly!" - default: "{PREFIX} &cThe requirements have not been met to fly in this area." - region: "{PREFIX} &cFlight is disabled in this region!" - world: "{PREFIX} &cFlight is disabled in this world!" - combat: "{PREFIX} &cYou are currently combat tagged!" - height: "{PREFIX} &f{MAX_Y} &cis the maximum altitude for flight!" - pass: - default: "{PREFIX} &aYou may now fly!" - combat: "{PREFIX} &aYou are no longer combat tagged, fly away!" - -aesthetic: - symbols: - infinity: "∞" - featherboard: - days: "&e{DAYS}&fd " - hours: "&e{HOURS}&fh " - minutes: "&e{MINUTES}&fm " - seconds: "&e{SECONDS}&fs " - trail: - removed_self: "{PREFIX} &aYour trail was removed!" - removed_other: "{PREFIX} &e{PLAYER} &ahad their trail removed!" - set_self: "{PREFIX} &aYour trail was set to &f{PARTICLE}&a!" - set_other: "{PREFIX} &f{PLAYER} &ahad their trail set to &f{PARTICLE}&a!" - -command: - # Here you can configure the command arguments. This will help players on foriegn servers that dont understand english. - # Everything here must be unique so be careful, you could break the commands if you put duplicate entries. - # Note: It is not reccomended to put hundreds of translations in here. just the main ones your server would need. - unit: - seconds: - # The unit that will be shown on tab completion of the command - tab_complete: "second" - # Identifiers that represent this time unit. - recognized: - - "s" - - "sec" - - "second" - - "zweite" #German - minutes: - tab_complete: "minute" - recognized: - - "m" - - "min" - - "minute" # english and german - hours: - tab_complete: "hour" - recognized: - - "h" - - "hour" - - "stunde" #German - days: - tab_complete: "day" - recognized: - - "d" - - "day" - - "tag" #German - - # Here you can specify all the tempfly sub commands. - base: - give: - - "give" - - "add" - givall: - - "givall" - - "addall" - reload: - - "reload" - remove: - - "remove" - - "take" - set: - - "set" - trail_remove: - - "remove_trail" - bypass: - - "bypass" - help: - - "help" - - "commands" - infinite: - - "infinite" - pay: - - "pay" - - "send" - shop: - - "shop" - - "buy" - speed: - - "speed" - time: - - "time" - - "bal" - - "balance" - trails: - - "trails" - - "particles" - trail_set: - - "trail" - - enable: - - "on" - - "enable" - disable: - - "off" - - "disable" - - syntax_error: - cmd_fly: - toggle_other: "&c/tf [player] [on / off]" - toggle_self: "&c/tf [on / off]" +system: + prefix: "&8[&dTemp&fFly&8]" + reload: "{PREFIX} &aYou reloaded the plugin." + help: + - "&8&l------&dTemp&fFly&8&l------" + - "&6/tf" + - "&7- Toggle tempfly" + - "&6/tf time" + - "&7- View remaining fly time" + - "&6/tf pay [player] [time]" + - "&7- send another player fly time" + help_extended: + - "&6/tf give [player] [time]" + - "&7- Give a player fly time" + - "&6/tf remove [player] [time]" + - "&7- Remove fly time from a player" + - "&6/tf set [player] [time]" + - "&7- Set a players fly time" + +general: + + unit: + seconds: "s" + minutes: "m" + hours: "h" + days: "d" + + invalid: + time_other: "{PREFIX} &f{PLAYER} &chas no more flight time!" + time_self: "{PREFIX} &cYou have no more flight time!" + number: "{PREFIX} &f{NUMBER} &cis not a valid number!" + particle: "{PREFIX} &f{PARTICLE} &cis not a valid particle type!" + player: "{PREFIX} &cThe player &f{PLAYER} &cwas not found..." + permission: "{PREFIX} &cYou have insufficient permissions..." + command: "&fUnknown command. Type /help for more information." + reciever: "{PREFIX} &cYou cannot pay yourself!" + sender: "{PREFIX} &cOnly players can use this command!" + flyer_self: "{PREFIX} &cYou are not flying!" + funds: "{PREFIX} &cThis costs &f{COST}&c! You do not have enough money!" + economy: "{PREFIX} &cYou must have a (&fvault&c) economy installed to use the shop!" + vault_perms: "{PREFIX} &cYou must install the plugin (&fvault&c) for the ability to set offline player time!" + + time: + format: "&f{QUANTITY}&f{UNIT}" + given_other: "{PREFIX} &f{PLAYER} &agot {FORMATTED_TIME}&a." + given_all: "{PREFIX} &aYou gave &fALL &aplayers {FORMATTED_TIME}&a." + given_self: "{PREFIX} &aYou recieved {FORMATTED_TIME}&a." + removed_other: "{PREFIX} &f{PLAYER} &clost {FORMATTED_TIME}&c." + removed_self: "{PREFIX} &cYou lost {FORMATTED_TIME}&c." + sent_other: "{PREFIX} &aYou sent &f{PLAYER}&a {FORMATTED_TIME}&a." + sent_self: "{PREFIX} &f{PLAYER} &asent you {FORMATTED_TIME}&a." + set_other: "{PREFIX} &f{PLAYER} &ahad their time set to {FORMATTED_TIME}&a." + set_self: "{PREFIX} &aYour time was set to {FORMATTED_TIME}&a." + max_other: "{PREFIX} &f{PLAYER} &chas reached the maximum allowed time&c!" + max_self: "{PREFIX} &cYou have reached the maximum allowed time&c!" + decay: "{PREFIX} &cYou lost {FORMATTED_TIME} &cfor inactivity!" + first_join: "{PREFIX} &aYou recieved {FORMATTED_TIME} &aof flight time. Fly with &f/tf&a." + daily_login: "{PREFIX} &aYou recieved a daily bonus of {FORMATTED_TIME}&a!" + purchased: "{PREFIX} &aYou purchased {FORMATTED_TIME} &afor &e${COST}&a!" + + info: + header: "&8&m--------&dTime&8&m--------" + player: "&fPlayer&7: &e{PLAYER}" + infinite: "&fInfinite: &c&lUser has unlimited flight!" + days: "&fDays&7: &e{DAYS}" + hours: "&fHours&7: &e{HOURS}" + minutes: "&fMinutes&7: &e{MINUTES}" + seconds: "&fSeconds&7: &e{SECONDS}" + footer: "&8&m-------------------" + + fly: + enabled_other: "{PREFIX} &f{PLAYER} &ais now flying" + enabled_self: "{PREFIX} &aYour flight was enabled!" + disabled_other: "{PREFIX} &f{PLAYER} &cis no longer flying!" + disabled_self: "{PREFIX} &cYour flight was disabled!" + speed_other: "{PREFIX} &f{PLAYER} &ahad their speed set to {SPEED}&a." + speed_self: "{PREFIX} &aYour fly speed was set to &f{SPEED}&a." + speed_limit_other: "{PREFIX} &f{PLAYER} &cIs currently limited to fly speed &f{SPEED}&c." + speed_limit_self: "{PREFIX} &cYour fly speed is currently limited to &f{SPEED}&c." + speed_restricted: "{PREFIX} &cYou are not allowed to change your fly speed!" + already_enabled: "{PREFIX} &aYour flight is already enabled!" + already_disabled: "{PREFIX} &cYour flight is already disabled!" + idle_drop: "{PREFIX} &cYou lost flight due to being idle!" + idle: "{PREFIX} &cYou are now considered idle." + infinite_enabled: "{PREFIX} &aYou enabled your infinite flight!" + infinite_disabled: "{PREFIX} &cYou disabled your infinite flight!" + bypass_enabled: "{PREFIX} &aYou enabled flight bypass mode!" + bypass_disabled: "{PREFIX} &cYou disabled flight bypass mode!" + + requirement: + fail: + default_other: "{PREFIX} &f{PLAYER} &ccannot currently fly!" + default: "{PREFIX} &cThe requirements have not been met to fly in this area." + region: "{PREFIX} &cFlight is disabled in this region!" + world: "{PREFIX} &cFlight is disabled in this world!" + combat: "{PREFIX} &cYou are currently combat tagged!" + height: "{PREFIX} &f{MAX_Y} &cis the maximum altitude for flight!" + pass: + default: "{PREFIX} &aYou may now fly!" + combat: "{PREFIX} &aYou are no longer combat tagged, fly away!" + +aesthetic: + symbols: + infinity: "∞" + featherboard: + days: "&e{DAYS}&fd " + hours: "&e{HOURS}&fh " + minutes: "&e{MINUTES}&fm " + seconds: "&e{SECONDS}&fs " + trail: + removed_self: "{PREFIX} &aYour trail was removed!" + removed_other: "{PREFIX} &e{PLAYER} &ahad their trail removed!" + set_self: "{PREFIX} &aYour trail was set to &f{PARTICLE}&a!" + set_other: "{PREFIX} &f{PLAYER} &ahad their trail set to &f{PARTICLE}&a!" + +command: + # Here you can configure the command arguments. This will help players on foriegn servers that dont understand english. + # Everything here must be unique so be careful, you could break the commands if you put duplicate entries. + # Note: It is not reccomended to put hundreds of translations in here. just the main ones your server would need. + unit: + seconds: + # The unit that will be shown on tab completion of the command + tab_complete: "second" + # Identifiers that represent this time unit. + recognized: + - "s" + - "sec" + - "second" + - "zweite" #German + minutes: + tab_complete: "minute" + recognized: + - "m" + - "min" + - "minute" # english and german + hours: + tab_complete: "hour" + recognized: + - "h" + - "hour" + - "stunde" #German + days: + tab_complete: "day" + recognized: + - "d" + - "day" + - "tag" #German + + # Here you can specify all the tempfly sub commands. + base: + give: + - "give" + - "add" + givall: + - "givall" + - "addall" + reload: + - "reload" + remove: + - "remove" + - "take" + set: + - "set" + trail_remove: + - "remove_trail" + bypass: + - "bypass" + help: + - "help" + - "commands" + infinite: + - "infinite" + pay: + - "pay" + - "send" + shop: + - "shop" + - "buy" + speed: + - "speed" + time: + - "time" + - "bal" + - "balance" + trails: + - "trails" + - "particles" + trail_set: + - "trail" + + enable: + - "on" + - "enable" + disable: + - "off" + - "disable" + + syntax_error: + cmd_fly: + toggle_other: "&c/tf [player] [on / off]" + toggle_self: "&c/tf [on / off]" \ No newline at end of file diff --git a/TempFly/resources/page.yml b/resources/page.yml similarity index 95% rename from TempFly/resources/page.yml rename to resources/page.yml index 7053c39..48d0850 100644 --- a/TempFly/resources/page.yml +++ b/resources/page.yml @@ -1,31 +1,31 @@ -page: - - trails: - title: '&dParticle Trails' - background: - name: '&7- Please select an option' - toolbar: - name: '&7- Please select an option' - next: - name: '&fNext page' - prev: - name: '&fPrevious page' - remove: - name: '&cRemove trail' - - shop: - title: '&dTempfly Shop' - background: - name: '&7- Please select an option' - toolbar: - name: '&7- Please select an option' - next: - name: '&fNext page' - prev: - name: '&fPrevious page' - option: - name: '&f{FORMATTED_TIME}' - lore: - - '&8&m================' - - '&fPurchase: &e{FORMATTED_TIME}' - - '&fCost: &e${COST}' +page: + + trails: + title: '&dParticle Trails' + background: + name: '&7- Please select an option' + toolbar: + name: '&7- Please select an option' + next: + name: '&fNext page' + prev: + name: '&fPrevious page' + remove: + name: '&cRemove trail' + + shop: + title: '&dTempfly Shop' + background: + name: '&7- Please select an option' + toolbar: + name: '&7- Please select an option' + next: + name: '&fNext page' + prev: + name: '&fPrevious page' + option: + name: '&f{FORMATTED_TIME}' + lore: + - '&8&m================' + - '&fPurchase: &e{FORMATTED_TIME}' + - '&fCost: &e${COST}' diff --git a/TempFly/resources/permissions.yml b/resources/permissions.yml similarity index 96% rename from TempFly/resources/permissions.yml rename to resources/permissions.yml index 0b09a49..e375e83 100644 --- a/TempFly/resources/permissions.yml +++ b/resources/permissions.yml @@ -1,131 +1,131 @@ - -tempfly.toggle.self: - desc: Allows user to toggle the use of temp flight. - command: - -/tempfly - -/fly - -/tf - -tempfly.toggle.other: - desc: Allows user to toggle anothers use of temp flight. - command: /tf toggle [player] - -tempfly.speed.self: - desc: Allows user to set their fly speed. - command: /tf speed [speed] - -tempfly.speed.other: - desc: Allows user to set another users fly speed. - command: /tf speed [speed] [player] - -tempfly.speed.region.[region_name].[speed]: - desc: Define the users max fly speed for a world. goes up to 10. - -tempfly.speed.world.[world_name].[speed]: - desc: Define the users max fly speed for a region. goes up to 10. Takes priority over world speed. - -tempfly.time.self: - desc: Allow user to view thier remaining time. - command: /tf time - -tempfly.time.other: - desc: Allow user to view another players remaining time. - command: /tf time [player] - -tempfly.max.[group]: - desc: Define the users max time. These groups should be set in the config under max_time. - -tempfly.pay: - desc: Allow user to pay another player time. - command: /tf pay [player] - -tempfly.give: - desc: Allow user to give time. valid arguments; [s {secs}] [m {mins}] [h {hours}] [d {days}] - command: /tf give [player] [amount] - -tempfly.giveall: - desc: Gives all users on the server time - command: /tf giveall [player] [amount] - -tempfly.remove: - desc: Allow user to remove time. valid arguments; [s {secs}] [m {mins}] [h {hours}] [d {days}] - command: /tf remove [player] [amount] - -tempfly.set: - desc: Allow user to set time. valid arguments; [s {secs}] [m {mins}] [h {hours}] [d {days}] - command: /tf set [player] [amount] - -tempfly.reload: - desc: Reloads the plugins configs and settings. - command: /tf reload - -tempfly.help: - desc: Allow user to see the help page. - command: /tf help - -tempfly.help.admin: - desc: Allow user to see the help page with admin commands. - command: /tf help - -tempfly.shop: - desc: Allow user to open the tempfly shop - command: /tf shop - -tempfly.infinite: - desc: - - Infinite flight. This simply will not charge the player flight time for flying. - - However, they will still have their actual time balance stored in the background. They dont lose it. - - IT DOES NOT let them pay infinite time to other players. - - In addition it does not affect their max_time, they are completely seperate things. - -tempfly.infinite.toggle: - desc: Allow the user to toggle their infinite flight. - -tempfly.bonus.[group]: - desc: Gives user the bonus defined for this group in the config daily. - -tempfly.bypass: - desc: Allow the user to bypass flight requirements. - -tempfly.bypass.toggle: - desc: Allow the user to toggle their tempfly bypass. - - -# Servers using old versions of spigot will need to use the 'Effect' list for trails -# OLD VERSIONS = https://helpch.at/docs/1.8/org/bukkit/Effect.html -# -# Newer versions -# https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Particle.html - -tempfly.trails: - desc: Allow user access to the praticle trail gui - command: /tf trails - -tempfly.trails.remove.self: - desc: Allow user to remove their trail. - -tempfly.trails.remove.other: - desc: Allow user to remove another players trail. - -tempfly.trails.set.self: - desc: Allow user to set their trail with command. - command: /tf trail {player} {trail} - -tempfly.trails.set.other: - desc: Allow user to set another players trail with command. - command: /tf trail {player} {trail} - -tempfly.trail.[particle]: - desc: Gives user access to use individual trails - - -#-----------------# -# Hook permissions -#-----------------# - - -tempfly.skyblock.island.settings: - desc: - - Allows island owners to adjust fly settings for skyblock plugins. - - Select hooks will implement this functionality directly into the island protection panel. - command: /tf settings + +tempfly.toggle.self: + desc: Allows user to toggle the use of temp flight. + command: + -/tempfly + -/fly + -/tf + +tempfly.toggle.other: + desc: Allows user to toggle anothers use of temp flight. + command: /tf toggle [player] + +tempfly.speed.self: + desc: Allows user to set their fly speed. + command: /tf speed [speed] + +tempfly.speed.other: + desc: Allows user to set another users fly speed. + command: /tf speed [speed] [player] + +tempfly.speed.region.[region_name].[speed]: + desc: Define the users max fly speed for a world. goes up to 10. + +tempfly.speed.world.[world_name].[speed]: + desc: Define the users max fly speed for a region. goes up to 10. Takes priority over world speed. + +tempfly.time.self: + desc: Allow user to view thier remaining time. + command: /tf time + +tempfly.time.other: + desc: Allow user to view another players remaining time. + command: /tf time [player] + +tempfly.max.[group]: + desc: Define the users max time. These groups should be set in the config under max_time. + +tempfly.pay: + desc: Allow user to pay another player time. + command: /tf pay [player] + +tempfly.give: + desc: Allow user to give time. valid arguments; [s {secs}] [m {mins}] [h {hours}] [d {days}] + command: /tf give [player] [amount] + +tempfly.giveall: + desc: Gives all users on the server time + command: /tf giveall [player] [amount] + +tempfly.remove: + desc: Allow user to remove time. valid arguments; [s {secs}] [m {mins}] [h {hours}] [d {days}] + command: /tf remove [player] [amount] + +tempfly.set: + desc: Allow user to set time. valid arguments; [s {secs}] [m {mins}] [h {hours}] [d {days}] + command: /tf set [player] [amount] + +tempfly.reload: + desc: Reloads the plugins configs and settings. + command: /tf reload + +tempfly.help: + desc: Allow user to see the help page. + command: /tf help + +tempfly.help.admin: + desc: Allow user to see the help page with admin commands. + command: /tf help + +tempfly.shop: + desc: Allow user to open the tempfly shop + command: /tf shop + +tempfly.infinite: + desc: + - Infinite flight. This simply will not charge the player flight time for flying. + - However, they will still have their actual time balance stored in the background. They dont lose it. + - IT DOES NOT let them pay infinite time to other players. + - In addition it does not affect their max_time, they are completely seperate things. + +tempfly.infinite.toggle: + desc: Allow the user to toggle their infinite flight. + +tempfly.bonus.[group]: + desc: Gives user the bonus defined for this group in the config daily. + +tempfly.bypass: + desc: Allow the user to bypass flight requirements. + +tempfly.bypass.toggle: + desc: Allow the user to toggle their tempfly bypass. + + +# Servers using old versions of spigot will need to use the 'Effect' list for trails +# OLD VERSIONS = https://helpch.at/docs/1.8/org/bukkit/Effect.html +# +# Newer versions +# https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Particle.html + +tempfly.trails: + desc: Allow user access to the praticle trail gui + command: /tf trails + +tempfly.trails.remove.self: + desc: Allow user to remove their trail. + +tempfly.trails.remove.other: + desc: Allow user to remove another players trail. + +tempfly.trails.set.self: + desc: Allow user to set their trail with command. + command: /tf trail {player} {trail} + +tempfly.trails.set.other: + desc: Allow user to set another players trail with command. + command: /tf trail {player} {trail} + +tempfly.trail.[particle]: + desc: Gives user access to use individual trails + + +#-----------------# +# Hook permissions +#-----------------# + + +tempfly.skyblock.island.settings: + desc: + - Allows island owners to adjust fly settings for skyblock plugins. + - Select hooks will implement this functionality directly into the island protection panel. + command: /tf settings diff --git a/TempFly/resources/plugin.yml b/resources/plugin.yml similarity index 97% rename from TempFly/resources/plugin.yml rename to resources/plugin.yml index c5b9315..da3025d 100644 --- a/TempFly/resources/plugin.yml +++ b/resources/plugin.yml @@ -1,9 +1,9 @@ -name: TempFly -main: com.moneybags.tempfly.TempFly -softdepend: [Factions, ASkyBlock, Essentials, MVdWPlaceholderAPI, PlaceholderAPI, aSkyBlock, Vault, WorldGuard, WorldEdit, IridiumSkyblock, BentoBox, SuperiorSkyblock2] -api-version: 1.13 -version: 3.1.7 -commands: - tempfly: - description: base command +name: TempFly +main: com.moneybags.tempfly.TempFly +softdepend: [Factions, ASkyBlock, Essentials, MVdWPlaceholderAPI, PlaceholderAPI, aSkyBlock, Vault, WorldGuard, WorldEdit, IridiumSkyblock, BentoBox, SuperiorSkyblock2] +api-version: 1.13 +version: 3.1.7 +commands: + tempfly: + description: base command aliases: [tfly, tf] \ No newline at end of file diff --git a/TempFly/resources/skyblock_preset_askyblock.yml b/resources/skyblock_preset_askyblock.yml similarity index 97% rename from TempFly/resources/skyblock_preset_askyblock.yml rename to resources/skyblock_preset_askyblock.yml index e3492e3..9a9d7a8 100644 --- a/TempFly/resources/skyblock_preset_askyblock.yml +++ b/resources/skyblock_preset_askyblock.yml @@ -1,123 +1,123 @@ -# This setting allows you to disable the skyblock hook even if you have askyblock plugin on the server. -# If you just want to disable flight in the island worlds use disabled worlds in the base config and disable the hook. -enable_hook: true - -# Unlockables allow you to set island requirements to allow users flight on islands and elsewhere on the server. -##---------------------------------------------------------## -#| Valid requirements include |# -##-------------------+-------------------------------------## -#| player_level | the island level for the player |# -#| | trying to fly. |# -##-------------------+-------------------------------------## -#| player_challenges | the challenges for the player |# -#| | trying to fly. |# -##-------------------+-------------------------------------## -#| If the role specified is a member of the island, |# -#| for example, (team, moderator, owner) there is no need |# -#| to specify both island_level and owner_level. |# -##---------------------------------------------------------## -unlockables: - - environment: - # Requirements needed for island members to fly in specified regions - regions: - super_awesome_vip_region: - player_level: 950 - player_challenges: - alchemist: 1 - beaconator: 1 - - # Requirements needed for island members to fly in specified worlds - worlds: - example_world: - player_level: 1 - - # requirements to fly when not on an island. - wilderness: - player_level: 0 - - ##---------------------------------------------------------## - #| Additional requirements for island roles |# - ##-------------------+-------------------------------------## - #| island_level | the island level for the island |# - #| | they are trying to fly on. |# - ##-------------------+-------------------------------------## - #| island_challenges | the challenges for the owner of the |# - #| | island they are trying to fly on. |# - ##-------------------+-------------------------------------## - island_roles: - owner: - player_level: 5 - - team: - player_level: 50 - - coop: - player_level: 75 - island_level: 75 - - visitor: - player_level: 100 - island_level: 75 - - player_challenges: - stewmaker: - completed: 1 - island_challenges: - papermaker: - completed: 1 - -flight_settings: - # If false the player cannot fly when they are not on an island - wilderness: true - - # The following settings are the default values for the tempfly's island protection panel - # Island owners may allow or disallow island roles flight on their island. - # You will need to enter the roles specific to your skyblock plugin here. The defaults may not apply to you. - base_permissions: - # Team members can fly on the island - team: true - # Coop players can fly on the island - coop: true - # Visitors can fly on the island - visitor: false - -language: - invalid: - island: "{PREFIX} &cYou must have an island to fly here!" - - requirements: - # Challenges support the placeholders; {CHALLENGE} | {PROGRESS} | {COMPLETIONS} | {ROLE} - challenge_self: "{PREFIX} &cYou must complete the challenge &f{CHALLENGE} &cto fly here!" - challenge_other: "{PREFIX} &cThis island has not unlocked flight for &f{ROLE}&c's!" - # Levels support the placeholders; {LEVEL} | {ROLE} - level_self: "{PREFIX} &cYou must have an island level of &f{LEVEL} &cto fly here!" - level_other: "{PREFIX} &cThis island needs level &f{LEVEL} &cfor &f{ROLE}'s &cto fly!" - role_denied: "{PREFIX} &cThis island does not allow &f{ROLE}'s &cto fly!" - -gui: - # This setting will allow you to place a button inside the island settings panel for your respective - # skyblock plugin that will take the user to the tempfly island settings page. - hook_settings: - enabled: true - button: - name: "&dTemp&fFly &fIsland Settings" - - page: - # Placeholders; {ROLE} - settings: - title: "&dIsland Flight Settings" - background: - name: "&7- Please select an option" - toolbar: - name: "&7- Please select an option" - allowed: - name: "&e&l{ROLE}" - lore: - - "&a&m================" - - "&7- {ROLE}'s can currently fly" - disallowed: - name: "&e&l{ROLE}" - lore: - - "&c&m================" - - "&7- {ROLE}'s can not currently fly" +# This setting allows you to disable the skyblock hook even if you have askyblock plugin on the server. +# If you just want to disable flight in the island worlds use disabled worlds in the base config and disable the hook. +enable_hook: true + +# Unlockables allow you to set island requirements to allow users flight on islands and elsewhere on the server. +##---------------------------------------------------------## +#| Valid requirements include |# +##-------------------+-------------------------------------## +#| player_level | the island level for the player |# +#| | trying to fly. |# +##-------------------+-------------------------------------## +#| player_challenges | the challenges for the player |# +#| | trying to fly. |# +##-------------------+-------------------------------------## +#| If the role specified is a member of the island, |# +#| for example, (team, moderator, owner) there is no need |# +#| to specify both island_level and owner_level. |# +##---------------------------------------------------------## +unlockables: + + environment: + # Requirements needed for island members to fly in specified regions + regions: + super_awesome_vip_region: + player_level: 950 + player_challenges: + alchemist: 1 + beaconator: 1 + + # Requirements needed for island members to fly in specified worlds + worlds: + example_world: + player_level: 1 + + # requirements to fly when not on an island. + wilderness: + player_level: 0 + + ##---------------------------------------------------------## + #| Additional requirements for island roles |# + ##-------------------+-------------------------------------## + #| island_level | the island level for the island |# + #| | they are trying to fly on. |# + ##-------------------+-------------------------------------## + #| island_challenges | the challenges for the owner of the |# + #| | island they are trying to fly on. |# + ##-------------------+-------------------------------------## + island_roles: + owner: + player_level: 5 + + team: + player_level: 50 + + coop: + player_level: 75 + island_level: 75 + + visitor: + player_level: 100 + island_level: 75 + + player_challenges: + stewmaker: + completed: 1 + island_challenges: + papermaker: + completed: 1 + +flight_settings: + # If false the player cannot fly when they are not on an island + wilderness: true + + # The following settings are the default values for the tempfly's island protection panel + # Island owners may allow or disallow island roles flight on their island. + # You will need to enter the roles specific to your skyblock plugin here. The defaults may not apply to you. + base_permissions: + # Team members can fly on the island + team: true + # Coop players can fly on the island + coop: true + # Visitors can fly on the island + visitor: false + +language: + invalid: + island: "{PREFIX} &cYou must have an island to fly here!" + + requirements: + # Challenges support the placeholders; {CHALLENGE} | {PROGRESS} | {COMPLETIONS} | {ROLE} + challenge_self: "{PREFIX} &cYou must complete the challenge &f{CHALLENGE} &cto fly here!" + challenge_other: "{PREFIX} &cThis island has not unlocked flight for &f{ROLE}&c's!" + # Levels support the placeholders; {LEVEL} | {ROLE} + level_self: "{PREFIX} &cYou must have an island level of &f{LEVEL} &cto fly here!" + level_other: "{PREFIX} &cThis island needs level &f{LEVEL} &cfor &f{ROLE}'s &cto fly!" + role_denied: "{PREFIX} &cThis island does not allow &f{ROLE}'s &cto fly!" + +gui: + # This setting will allow you to place a button inside the island settings panel for your respective + # skyblock plugin that will take the user to the tempfly island settings page. + hook_settings: + enabled: true + button: + name: "&dTemp&fFly &fIsland Settings" + + page: + # Placeholders; {ROLE} + settings: + title: "&dIsland Flight Settings" + background: + name: "&7- Please select an option" + toolbar: + name: "&7- Please select an option" + allowed: + name: "&e&l{ROLE}" + lore: + - "&a&m================" + - "&7- {ROLE}'s can currently fly" + disallowed: + name: "&e&l{ROLE}" + lore: + - "&c&m================" + - "&7- {ROLE}'s can not currently fly" diff --git a/TempFly/resources/skyblock_preset_bento.yml b/resources/skyblock_preset_bento.yml similarity index 97% rename from TempFly/resources/skyblock_preset_bento.yml rename to resources/skyblock_preset_bento.yml index d223bcd..6a1422a 100644 --- a/TempFly/resources/skyblock_preset_bento.yml +++ b/resources/skyblock_preset_bento.yml @@ -1,123 +1,123 @@ -# This setting allows you to disable the skyblock hook even if you have askyblock plugin on the server. -# If you just want to disable flight in the island worlds use disabled worlds in the base config and disable the hook. -enable_hook: true - -# Unlockables allow you to set island requirements to allow users flight on islands and elsewhere on the server. -##---------------------------------------------------------## -#| Valid requirements include |# -##-------------------+-------------------------------------## -#| player_level | the island level for the player |# -#| | trying to fly. |# -##-------------------+-------------------------------------## -#| player_challenges | the challenges for the player |# -#| | trying to fly. |# -##-------------------+-------------------------------------## -#| If the role specified is a member of the island, |# -#| for example, (team, moderator, owner) there is no need |# -#| to specify both island_level and owner_level. |# -##---------------------------------------------------------## -unlockables: - - environment: - # Requirements needed for island members to fly in specified regions - regions: - super_awesome_vip_region: - player_level: 950 - player_challenges: - alchemist: 1 - beaconator: 1 - - # Requirements needed for island members to fly in specified worlds - worlds: - example_world: - player_level: 1 - - # requirements to fly when not on an island. - wilderness: - player_level: 0 - - ##---------------------------------------------------------## - #| Additional requirements for island roles |# - ##-------------------+-------------------------------------## - #| island_level | the island level for the island |# - #| | they are trying to fly on. |# - ##-------------------+-------------------------------------## - #| island_challenges | the challenges for the owner of the |# - #| | island they are trying to fly on. |# - ##-------------------+-------------------------------------## - island_roles: - owner: - player_level: 5 - - member: - player_level: 50 - - coop: - player_level: 75 - island_level: 75 - - visitor: - player_level: 100 - island_level: 75 - - player_challenges: - stewmaker: - completed: 1 - island_challenges: - papermaker: - completed: 1 - -flight_settings: - # If false the player cannot fly when they are not on an island - wilderness: true - - # The following settings are the default values for the tempfly's island protection panel - # Island owners may allow or disallow island roles flight on their island. - # You will need to enter the roles specific to your skyblock plugin here. The defaults may not apply to you. - base_permissions: - # Team members can fly on the island - team: true - # Coop players can fly on the island - coop: true - # Visitors can fly on the island - visitor: false - -language: - invalid: - island: "{PREFIX} &cYou must have an island to fly here!" - - requirements: - # Challenges support the placeholders; {CHALLENGE} | {COMPLETIONS} | {ROLE} - challenge_self: "{PREFIX} &f{CHALLENGE} &cmust be completed &f{COMPLETIONS} &ctimes to fly here!" - challenge_other: "{PREFIX} &cThis island has not unlocked flight for &f{ROLE}&c's!" - # Levels support the placeholders; {LEVEL} | {ROLE} - level_self: "{PREFIX} &cYou must have an island level of &f{LEVEL} &cto fly here!" - level_other: "{PREFIX} &cThis island needs level &f{LEVEL} &cfor &f{ROLE}'s &cto fly!" - role_denied: "{PREFIX} &cThis island does not allow &f{ROLE}'s &cto fly!" - -gui: - # This setting will allow you to place a button inside the island settings panel for your respective - # skyblock plugin that will take the user to the tempfly island settings page. - hook_settings: - enabled: true - button: - name: "&dTemp&fFly &fIsland Settings" - - page: - # Placeholders; {ROLE} - settings: - title: "&dIsland Flight Settings" - background: - name: "&7- Please select an option" - toolbar: - name: "&7- Please select an option" - allowed: - name: "&e&l{ROLE}" - lore: - - "&a&m================" - - "&7- {ROLE}'s can currently fly" - disallowed: - name: "&e&l{ROLE}" - lore: - - "&c&m================" - - "&7- {ROLE}'s can not currently fly" +# This setting allows you to disable the skyblock hook even if you have askyblock plugin on the server. +# If you just want to disable flight in the island worlds use disabled worlds in the base config and disable the hook. +enable_hook: true + +# Unlockables allow you to set island requirements to allow users flight on islands and elsewhere on the server. +##---------------------------------------------------------## +#| Valid requirements include |# +##-------------------+-------------------------------------## +#| player_level | the island level for the player |# +#| | trying to fly. |# +##-------------------+-------------------------------------## +#| player_challenges | the challenges for the player |# +#| | trying to fly. |# +##-------------------+-------------------------------------## +#| If the role specified is a member of the island, |# +#| for example, (team, moderator, owner) there is no need |# +#| to specify both island_level and owner_level. |# +##---------------------------------------------------------## +unlockables: + + environment: + # Requirements needed for island members to fly in specified regions + regions: + super_awesome_vip_region: + player_level: 950 + player_challenges: + alchemist: 1 + beaconator: 1 + + # Requirements needed for island members to fly in specified worlds + worlds: + example_world: + player_level: 1 + + # requirements to fly when not on an island. + wilderness: + player_level: 0 + + ##---------------------------------------------------------## + #| Additional requirements for island roles |# + ##-------------------+-------------------------------------## + #| island_level | the island level for the island |# + #| | they are trying to fly on. |# + ##-------------------+-------------------------------------## + #| island_challenges | the challenges for the owner of the |# + #| | island they are trying to fly on. |# + ##-------------------+-------------------------------------## + island_roles: + owner: + player_level: 5 + + member: + player_level: 50 + + coop: + player_level: 75 + island_level: 75 + + visitor: + player_level: 100 + island_level: 75 + + player_challenges: + stewmaker: + completed: 1 + island_challenges: + papermaker: + completed: 1 + +flight_settings: + # If false the player cannot fly when they are not on an island + wilderness: true + + # The following settings are the default values for the tempfly's island protection panel + # Island owners may allow or disallow island roles flight on their island. + # You will need to enter the roles specific to your skyblock plugin here. The defaults may not apply to you. + base_permissions: + # Team members can fly on the island + team: true + # Coop players can fly on the island + coop: true + # Visitors can fly on the island + visitor: false + +language: + invalid: + island: "{PREFIX} &cYou must have an island to fly here!" + + requirements: + # Challenges support the placeholders; {CHALLENGE} | {COMPLETIONS} | {ROLE} + challenge_self: "{PREFIX} &f{CHALLENGE} &cmust be completed &f{COMPLETIONS} &ctimes to fly here!" + challenge_other: "{PREFIX} &cThis island has not unlocked flight for &f{ROLE}&c's!" + # Levels support the placeholders; {LEVEL} | {ROLE} + level_self: "{PREFIX} &cYou must have an island level of &f{LEVEL} &cto fly here!" + level_other: "{PREFIX} &cThis island needs level &f{LEVEL} &cfor &f{ROLE}'s &cto fly!" + role_denied: "{PREFIX} &cThis island does not allow &f{ROLE}'s &cto fly!" + +gui: + # This setting will allow you to place a button inside the island settings panel for your respective + # skyblock plugin that will take the user to the tempfly island settings page. + hook_settings: + enabled: true + button: + name: "&dTemp&fFly &fIsland Settings" + + page: + # Placeholders; {ROLE} + settings: + title: "&dIsland Flight Settings" + background: + name: "&7- Please select an option" + toolbar: + name: "&7- Please select an option" + allowed: + name: "&e&l{ROLE}" + lore: + - "&a&m================" + - "&7- {ROLE}'s can currently fly" + disallowed: + name: "&e&l{ROLE}" + lore: + - "&c&m================" + - "&7- {ROLE}'s can not currently fly" diff --git a/TempFly/resources/skyblock_preset_generic.yml b/resources/skyblock_preset_generic.yml similarity index 97% rename from TempFly/resources/skyblock_preset_generic.yml rename to resources/skyblock_preset_generic.yml index 4b56148..33a069e 100644 --- a/TempFly/resources/skyblock_preset_generic.yml +++ b/resources/skyblock_preset_generic.yml @@ -1,159 +1,159 @@ -##----------------------------------------------------## -#| Usage Info |# -#| Depending on your specific skyblock plugin |# -##----------------------------------------------------## - -##----------------------------------------------------## -#| When island level is specified it will refer to |# -##----------------------------------------------------## -#| a) The level of the island. |# -#| b) The worth/value of the island |# -##----------------------------------------------------## - -##----------------------------------------------------## -#| When challenges are specified |# -##----------------------------------------------------## -#| The value progress will refer to; |# -#| ---------------------------------- |# -#| a) The percentage of progress towards completion |# -#| b) The required step within a multi step challenge |# -#| |# -#| Some plugins do not support this feature and hence |# -#| putting it in the config will have no effect. |# -##----------------------------------------------------## -#| The value completed will refer to |# -#| ---------------------------------- |# -#| a) The amount of times the challenge was completed |# -#| |# -#| In plugins that do not support the ability to |# -#| complete a challenge multiple times, setting this |# -#| to anything higher than 1 has no effect. |# -##----------------------------------------------------## -#| Please see the generated file skyblock.readme for |# -#| config info about your specific skyblock plugin. |# -##----------------------------------------------------## -#| This default config has been configured for the |# -#| plugin askyblock and hence may need to be altered |# -#| to properly support your plugin. |# -##----------------------------------------------------## - -# This setting allows you to disable the skyblock hook even if you have a skyblock plugin on the server. -# If you just want to disable flight in the island worlds use disabled worlds in the base config and disable the hook. -enable_hook: true - -# Unlockables allow you to set island requirements to allow users flight on islands and elsewhere on the server. -##---------------------------------------------------------## -#| Valid requirements include |# -##-------------------+-------------------------------------## -#| player_level | the island level for the player |# -#| | trying to fly. |# -##-------------------+-------------------------------------## -#| player_challenges | the challenges for the player |# -#| | trying to fly. |# -##-------------------+-------------------------------------## -#| If the role specified is a member of the island, |# -#| for example, (team, moderator, owner) there is no need |# -#| to specify both island_level and owner_level. |# -##---------------------------------------------------------## -unlockables: - - environment: - # Requirements needed for island members to fly in specified regions - regions: - super_awesome_vip_region: - player_level: 950 - player_challenges: - alchemist: - completed: 1 - dj: - completed: 1 - beaconator: - completed: 1 - - # Requirements needed for island members to fly in specified worlds - worlds: - example_world: - player_level: 1 - - # requirements to fly when not on an island. - wilderness: - player_level: 0 - - ##---------------------------------------------------------## - #| Additional requirements for island roles |# - ##-------------------+-------------------------------------## - #| island_level | the island level for the island |# - #| | they are trying to fly on. |# - ##-------------------+-------------------------------------## - #| island_challenges | the challenges for the owner of the |# - #| | island they are trying to fly on. |# - ##-------------------+-------------------------------------## - island_roles: - owner: - player_level: 5 - - visitor: - player_level: 75 - island_level: 50 - - player_challenges: - stewmaker: - completed: 1 - island_challenges: - papermaker: - completed: 1 - -flight_settings: - # If false the player cannot fly when they are not on an island - wilderness: true - - # The following settings are the default values for the tempfly's island protection panel - # Island owners may allow or disallow island roles flight on their island. - # You will need to enter the roles specific to your skyblock plugin here. The defaults may not apply to you. - base_permissions: - # Team members can fly on the island - team: true - # Coop players can fly on the island - coop: true - # Visitors can fly on the island - visitor: false - -language: - invalid: - island: "{PREFIX} &cYou must have an island to fly here!" - - requirements: - # Challenges support the placeholders; {CHALLENGE} | {PROGRESS} | {ROLE} - challenge_self: "{PREFIX} &cYou must complete the challenge &f{CHALLENGE} &cto fly here!" - challenge_other: "{PREFIX} &cThis island has not unlocked flight for &f{ROLE}&c's!" - # Levels support the placeholders; {LEVEL} | {ROLE} - level_self: "{PREFIX} &cYou must have an island level of &f{LEVEL} &cto fly here!" - level_other: "{PREFIX} &cThis island does not meet the level requirement for &f{ROLE}'s &cto fly!" - role_denied: "{PREFIX} &cThis island does not allow &f{ROLE}'s &cto fly!" - -gui: - # This setting will allow you to place a button inside the island settings panel for your respective - # skyblock plugin that will take the user to the tempfly island settings page. - hook_settings: - enabled: true - button: - name: "&dTemp&fFly &fIsland Settings" - - page: - # Placeholders; {ROLE} - settings: - title: "&dIsland Flight Settings" - background: - name: "&7- Please select an option" - toolbar: - name: "&7- Please select an option" - allowed: - name: "&e&l{ROLE}" - lore: - - "&a&m================" - - "&7- {ROLE}'s can currently fly" - disallowed: - name: "&e&l{ROLE}" - lore: - - "&c&m================" - - "&7- {ROLE}'s can not currently fly" +##----------------------------------------------------## +#| Usage Info |# +#| Depending on your specific skyblock plugin |# +##----------------------------------------------------## + +##----------------------------------------------------## +#| When island level is specified it will refer to |# +##----------------------------------------------------## +#| a) The level of the island. |# +#| b) The worth/value of the island |# +##----------------------------------------------------## + +##----------------------------------------------------## +#| When challenges are specified |# +##----------------------------------------------------## +#| The value progress will refer to; |# +#| ---------------------------------- |# +#| a) The percentage of progress towards completion |# +#| b) The required step within a multi step challenge |# +#| |# +#| Some plugins do not support this feature and hence |# +#| putting it in the config will have no effect. |# +##----------------------------------------------------## +#| The value completed will refer to |# +#| ---------------------------------- |# +#| a) The amount of times the challenge was completed |# +#| |# +#| In plugins that do not support the ability to |# +#| complete a challenge multiple times, setting this |# +#| to anything higher than 1 has no effect. |# +##----------------------------------------------------## +#| Please see the generated file skyblock.readme for |# +#| config info about your specific skyblock plugin. |# +##----------------------------------------------------## +#| This default config has been configured for the |# +#| plugin askyblock and hence may need to be altered |# +#| to properly support your plugin. |# +##----------------------------------------------------## + +# This setting allows you to disable the skyblock hook even if you have a skyblock plugin on the server. +# If you just want to disable flight in the island worlds use disabled worlds in the base config and disable the hook. +enable_hook: true + +# Unlockables allow you to set island requirements to allow users flight on islands and elsewhere on the server. +##---------------------------------------------------------## +#| Valid requirements include |# +##-------------------+-------------------------------------## +#| player_level | the island level for the player |# +#| | trying to fly. |# +##-------------------+-------------------------------------## +#| player_challenges | the challenges for the player |# +#| | trying to fly. |# +##-------------------+-------------------------------------## +#| If the role specified is a member of the island, |# +#| for example, (team, moderator, owner) there is no need |# +#| to specify both island_level and owner_level. |# +##---------------------------------------------------------## +unlockables: + + environment: + # Requirements needed for island members to fly in specified regions + regions: + super_awesome_vip_region: + player_level: 950 + player_challenges: + alchemist: + completed: 1 + dj: + completed: 1 + beaconator: + completed: 1 + + # Requirements needed for island members to fly in specified worlds + worlds: + example_world: + player_level: 1 + + # requirements to fly when not on an island. + wilderness: + player_level: 0 + + ##---------------------------------------------------------## + #| Additional requirements for island roles |# + ##-------------------+-------------------------------------## + #| island_level | the island level for the island |# + #| | they are trying to fly on. |# + ##-------------------+-------------------------------------## + #| island_challenges | the challenges for the owner of the |# + #| | island they are trying to fly on. |# + ##-------------------+-------------------------------------## + island_roles: + owner: + player_level: 5 + + visitor: + player_level: 75 + island_level: 50 + + player_challenges: + stewmaker: + completed: 1 + island_challenges: + papermaker: + completed: 1 + +flight_settings: + # If false the player cannot fly when they are not on an island + wilderness: true + + # The following settings are the default values for the tempfly's island protection panel + # Island owners may allow or disallow island roles flight on their island. + # You will need to enter the roles specific to your skyblock plugin here. The defaults may not apply to you. + base_permissions: + # Team members can fly on the island + team: true + # Coop players can fly on the island + coop: true + # Visitors can fly on the island + visitor: false + +language: + invalid: + island: "{PREFIX} &cYou must have an island to fly here!" + + requirements: + # Challenges support the placeholders; {CHALLENGE} | {PROGRESS} | {ROLE} + challenge_self: "{PREFIX} &cYou must complete the challenge &f{CHALLENGE} &cto fly here!" + challenge_other: "{PREFIX} &cThis island has not unlocked flight for &f{ROLE}&c's!" + # Levels support the placeholders; {LEVEL} | {ROLE} + level_self: "{PREFIX} &cYou must have an island level of &f{LEVEL} &cto fly here!" + level_other: "{PREFIX} &cThis island does not meet the level requirement for &f{ROLE}'s &cto fly!" + role_denied: "{PREFIX} &cThis island does not allow &f{ROLE}'s &cto fly!" + +gui: + # This setting will allow you to place a button inside the island settings panel for your respective + # skyblock plugin that will take the user to the tempfly island settings page. + hook_settings: + enabled: true + button: + name: "&dTemp&fFly &fIsland Settings" + + page: + # Placeholders; {ROLE} + settings: + title: "&dIsland Flight Settings" + background: + name: "&7- Please select an option" + toolbar: + name: "&7- Please select an option" + allowed: + name: "&e&l{ROLE}" + lore: + - "&a&m================" + - "&7- {ROLE}'s can currently fly" + disallowed: + name: "&e&l{ROLE}" + lore: + - "&c&m================" + - "&7- {ROLE}'s can not currently fly" diff --git a/TempFly/resources/skyblock_preset_iridium.yml b/resources/skyblock_preset_iridium.yml similarity index 97% rename from TempFly/resources/skyblock_preset_iridium.yml rename to resources/skyblock_preset_iridium.yml index 50d4907..e379ec6 100644 --- a/TempFly/resources/skyblock_preset_iridium.yml +++ b/resources/skyblock_preset_iridium.yml @@ -1,151 +1,151 @@ -# This setting allows you to disable the skyblock hook even if you have iridium skyblock on the server. -# If you just want to disable flight in the island worlds use disabled worlds in the base config and disable the hook. -enable_hook: true - -# Unlockables allow you to set island requirements to allow users flight on islands and elsewhere on the server. -##---------------------------------------------------------## -#| Valid requirements include |# -##-------------------+-------------------------------------## -#| player_value | the island level for the player |# -#| | trying to fly. |# -##-------------------+-------------------------------------## -#| player_challenges | the challenges for the player |# -#| | trying to fly. |# -##-------------------+-------------------------------------## -#| If the role specified is a member of the island, |# -#| for example, (team, moderator, owner) there is no need |# -#| to specify both island_level and owner_level. |# -##---------------------------------------------------------## -unlockables: - - environment: - # Requirements needed for island members to fly in specified regions - regions: - super_awesome_vip_region: - player_value: 10000 - player_challenges: - Miner: 3 - Farmer: 3 - - # Requirements needed for island members to fly in specified worlds - worlds: - example_world: - player_value: 350 - challenges: - Miner: 2 - - # requirements to fly when not on an island. - wilderness: - player_level: 0 - - ##---------------------------------------------------------## - #| Additional requirements for island roles |# - ##-------------------+-------------------------------------## - #| island_value | the island level for the island |# - #| | they are trying to fly on. |# - ##-------------------+-------------------------------------## - #| island_challenges | the challenges for the owner of the |# - #| | island they are trying to fly on. |# - ##-------------------+-------------------------------------## - island_roles: - owner: - player_value: 50 - - coowner: - player_value: 75 - player_missions: - Miner: 2 - - moderator: - player_value: 200 - player_missions: - Miner: 2 - Hunter: 2 - - member: - player_value: 250 - player_missions: - Miner: 2 - Hunter: 2 - - coop: - player_value: 300 - island_value: 250 - - player_missions: - Miner: 4 - island_missions: - Miner: 4 - - visitor: - # This line specifies that the visitor needs to have an island value of 150 to fly on other peoples islands. - player_value: 250 - # This line specifies that the island needs a value of 50 to allow visitors flight on their island. - island_value: 250 - - # This specifies that the visitor needs miner level 2 to fly on other peoples islands - player_missions: - Miner: - progress: 2 - # This specifies that the island needs hunter level 5 to allow visitors flight on their island. - island_missions: - Hunter: - progress: 5 - -flight_settings: - # If false the player cannot fly when they are not on an island - wilderness: true - - # The following settings are the default values for the tempfly's island protection panel - # Island owners may allow or disallow island roles flight on their island. - # You will need to enter the roles specific to your skyblock plugin here. The defaults may not apply to you. - base_permissions: - # Coowners can fly on the island - coowner: true - # Moderators can fly on the island - moderator: true - # Team members can fly on the island - member: true - # Coop players can fly on the island - coop: true - # Visitors can fly on the island - visitor: false - -language: - invalid: - island: "{PREFIX} &cYou must have an island to fly here!" - - requirements: - # Challenges support the placeholders; {CHALLENGE} | {PROGRESS} | {ROLE} - challenge_self: "{PREFIX} &cYou must have mission &f{CHALLENGE} &clevel &f{PROGRESS} &cto fly here!" - challenge_other: "{PREFIX} &cThis island has not unlocked flight for &f{ROLE}&c's!" - # Levels support the placeholders; {LEVEL} | {ROLE} - level_self: "{PREFIX} &cYou must have an island value of &f{LEVEL} &cto fly here!" - level_other: "{PREFIX} &cThis island does not meet the value requirement for &f{ROLE}'s &cto fly!" - role_denied: "{PREFIX} &cThis island does not allow &f{ROLE}'s &cto fly!" - -gui: - # This setting will allow you to place a button inside the island settings panel for iridium skyblock. - hook_settings: - enabled: true - button: - name: "&dTemp&fFly &fIsland Settings" - - page: - # Placeholders; {ROLE} - settings: - title: "&dIsland Flight Settings" - background: - name: "&7- Please select an option" - toolbar: - name: "&7- Please select an option" - allowed: - name: "&e&l{ROLE}" - lore: - - "&a&m================" - - "&7- {ROLE}'s can currently fly" - disallowed: - name: "&e&l{ROLE}" - lore: - - "&c&m================" - - "&7- {ROLE}'s can not currently fly" +# This setting allows you to disable the skyblock hook even if you have iridium skyblock on the server. +# If you just want to disable flight in the island worlds use disabled worlds in the base config and disable the hook. +enable_hook: true + +# Unlockables allow you to set island requirements to allow users flight on islands and elsewhere on the server. +##---------------------------------------------------------## +#| Valid requirements include |# +##-------------------+-------------------------------------## +#| player_value | the island level for the player |# +#| | trying to fly. |# +##-------------------+-------------------------------------## +#| player_challenges | the challenges for the player |# +#| | trying to fly. |# +##-------------------+-------------------------------------## +#| If the role specified is a member of the island, |# +#| for example, (team, moderator, owner) there is no need |# +#| to specify both island_level and owner_level. |# +##---------------------------------------------------------## +unlockables: + + environment: + # Requirements needed for island members to fly in specified regions + regions: + super_awesome_vip_region: + player_value: 10000 + player_challenges: + Miner: 3 + Farmer: 3 + + # Requirements needed for island members to fly in specified worlds + worlds: + example_world: + player_value: 350 + challenges: + Miner: 2 + + # requirements to fly when not on an island. + wilderness: + player_level: 0 + + ##---------------------------------------------------------## + #| Additional requirements for island roles |# + ##-------------------+-------------------------------------## + #| island_value | the island level for the island |# + #| | they are trying to fly on. |# + ##-------------------+-------------------------------------## + #| island_challenges | the challenges for the owner of the |# + #| | island they are trying to fly on. |# + ##-------------------+-------------------------------------## + island_roles: + owner: + player_value: 50 + + coowner: + player_value: 75 + player_missions: + Miner: 2 + + moderator: + player_value: 200 + player_missions: + Miner: 2 + Hunter: 2 + + member: + player_value: 250 + player_missions: + Miner: 2 + Hunter: 2 + + coop: + player_value: 300 + island_value: 250 + + player_missions: + Miner: 4 + island_missions: + Miner: 4 + + visitor: + # This line specifies that the visitor needs to have an island value of 150 to fly on other peoples islands. + player_value: 250 + # This line specifies that the island needs a value of 50 to allow visitors flight on their island. + island_value: 250 + + # This specifies that the visitor needs miner level 2 to fly on other peoples islands + player_missions: + Miner: + progress: 2 + # This specifies that the island needs hunter level 5 to allow visitors flight on their island. + island_missions: + Hunter: + progress: 5 + +flight_settings: + # If false the player cannot fly when they are not on an island + wilderness: true + + # The following settings are the default values for the tempfly's island protection panel + # Island owners may allow or disallow island roles flight on their island. + # You will need to enter the roles specific to your skyblock plugin here. The defaults may not apply to you. + base_permissions: + # Coowners can fly on the island + coowner: true + # Moderators can fly on the island + moderator: true + # Team members can fly on the island + member: true + # Coop players can fly on the island + coop: true + # Visitors can fly on the island + visitor: false + +language: + invalid: + island: "{PREFIX} &cYou must have an island to fly here!" + + requirements: + # Challenges support the placeholders; {CHALLENGE} | {PROGRESS} | {ROLE} + challenge_self: "{PREFIX} &cYou must have mission &f{CHALLENGE} &clevel &f{PROGRESS} &cto fly here!" + challenge_other: "{PREFIX} &cThis island has not unlocked flight for &f{ROLE}&c's!" + # Levels support the placeholders; {LEVEL} | {ROLE} + level_self: "{PREFIX} &cYou must have an island value of &f{LEVEL} &cto fly here!" + level_other: "{PREFIX} &cThis island does not meet the value requirement for &f{ROLE}'s &cto fly!" + role_denied: "{PREFIX} &cThis island does not allow &f{ROLE}'s &cto fly!" + +gui: + # This setting will allow you to place a button inside the island settings panel for iridium skyblock. + hook_settings: + enabled: true + button: + name: "&dTemp&fFly &fIsland Settings" + + page: + # Placeholders; {ROLE} + settings: + title: "&dIsland Flight Settings" + background: + name: "&7- Please select an option" + toolbar: + name: "&7- Please select an option" + allowed: + name: "&e&l{ROLE}" + lore: + - "&a&m================" + - "&7- {ROLE}'s can currently fly" + disallowed: + name: "&e&l{ROLE}" + lore: + - "&c&m================" + - "&7- {ROLE}'s can not currently fly" diff --git a/TempFly/resources/skyblock_preset_superior.yml b/resources/skyblock_preset_superior.yml similarity index 97% rename from TempFly/resources/skyblock_preset_superior.yml rename to resources/skyblock_preset_superior.yml index 87b9729..fcd0c3b 100644 --- a/TempFly/resources/skyblock_preset_superior.yml +++ b/resources/skyblock_preset_superior.yml @@ -1,153 +1,153 @@ -# This setting allows you to disable the skyblock hook even if you have Superior Skyblock on the server. -# If you just want to disable flight in the island worlds use disabled worlds in the base config and disable the hook. -enable_hook: true - -# Unlockables allow you to set island requirements to allow users flight on islands and elsewhere on the server. -##---------------------------------------------------------## -#| Valid requirements include |# -##-------------------+-------------------------------------## -#| player_level | the island level for the player |# -#| | trying to fly. |# -##-------------------+-------------------------------------## -#| player_missions | the missions needed for the player |# -#| | trying to fly. |# -##-------------------+-------------------------------------## - -unlockables: - - environment: - # Requirements needed for island members to fly in specified regions - regions: - super_awesome_vip_region: - player_level: 10000 - player_missions: - Miner: 3 - Farmer: 3 - - # Requirements needed for island members to fly in specified worlds - worlds: - example_world: - player_level: 350 - player_missions: - Miner: 2 - - # requirements to fly when not on an island. - wilderness: - player_level: 0 - - ##---------------------------------------------------------## - #| Additional requirements for island roles |# - ##-------------------+-------------------------------------## - #| island_level | the island level for the island |# - #| | they are trying to fly on. |# - ##-------------------+-------------------------------------## - #| island_missions | the missions for the owner of the |# - #| | island they are trying to fly on. |# - ##-------------------+-------------------------------------## - #| If the role specified is a member of the island, |# - #| for example, (team, moderator) there is no need |# - #| to specify both island_level and player_level. |# - ##---------------------------------------------------------## - island_roles: - leader: - player_level: 500 - - admin: - player_level: 750 - player_missions: - - "miner_2" - - moderator: - player_level: 2000 - player_missions: - - "miner_2" - - member: - player_level: 2500 - player_missions: - - "miner_2" - - coop: - player_level: 3000 - island_level: 2500 - - player_missions: - - "miner_2" - island_missions: - - "miner_2" - - guest: - # This line specifies that the visitor needs to have an island level of 150 to fly on other peoples islands. - player_level: 2500 - # This line specifies that the island needs a level of 50 to allow visitors flight on their island. - island_level: 3500 - - # This specifies that the visitor needs miner level 2 to fly on other peoples islands - player_missions: - - "miner_1" - # This specifies that the island needs hunter level 5 to allow visitors flight on their island. - island_missions: - - "slayer_1" - -flight_settings: - # If false the player cannot fly when they are not on an island - wilderness: true - - # The following settings are the default levels for the tempfly's island protection panel - # Island owners may allow or disallow island roles flight on their island. - # You will need to enter the roles specific to your skyblock plugin here. The defaults may not apply to you. - base_permissions: - leader: true - # Coowners can fly on the island - admin: true - # Moderators can fly on the island - moderator: true - # Team members can fly on the island - member: true - # Coop players can fly on the island - coop: true - # Visitors can fly on the island - guest: false - -language: - - invalid: - island: "{PREFIX} &cYou must have an island to fly here!" - - requirements: - # Challenges support the placeholders; {CHALLENGE} | {PROGRESS} | {ROLE} - challenge_self: "{PREFIX} &cYou must complete the mission &f{CHALLENGE} &cto fly here!" - challenge_other: "{PREFIX} &cThis island has not unlocked flight for &f{ROLE}&c's!" - # Levels support the placeholders; {LEVEL} | {ROLE} - level_self: "{PREFIX} &cYou must have an island level of &f{LEVEL} &cto fly here!" - level_other: "{PREFIX} &cThis island does not meet the level requirement for &f{ROLE}'s &cto fly!" - - role_denied: "{PREFIX} &cThis island does not allow &f{ROLE}'s &cto fly!" - -gui: - # This setting will allow you to place a button inside the island settings panel for superior skyblock. - - # Not yet implemented for Superior Skyblock... - hook_settings: - enabled: true - button: - name: "&dTemp&fFly &fIsland Settings" - - page: - # Placeholders; {ROLE} - settings: - title: "&dIsland Flight Settings" - background: - name: "&7- Please select an option" - toolbar: - name: "&7- Please select an option" - allowed: - name: "&e&l{ROLE}" - lore: - - "&a&m================" - - "&7- {ROLE}'s can currently fly" - disallowed: - name: "&e&l{ROLE}" - lore: - - "&c&m================" - - "&7- {ROLE}'s can not currently fly" +# This setting allows you to disable the skyblock hook even if you have Superior Skyblock on the server. +# If you just want to disable flight in the island worlds use disabled worlds in the base config and disable the hook. +enable_hook: true + +# Unlockables allow you to set island requirements to allow users flight on islands and elsewhere on the server. +##---------------------------------------------------------## +#| Valid requirements include |# +##-------------------+-------------------------------------## +#| player_level | the island level for the player |# +#| | trying to fly. |# +##-------------------+-------------------------------------## +#| player_missions | the missions needed for the player |# +#| | trying to fly. |# +##-------------------+-------------------------------------## + +unlockables: + + environment: + # Requirements needed for island members to fly in specified regions + regions: + super_awesome_vip_region: + player_level: 10000 + player_missions: + Miner: 3 + Farmer: 3 + + # Requirements needed for island members to fly in specified worlds + worlds: + example_world: + player_level: 350 + player_missions: + Miner: 2 + + # requirements to fly when not on an island. + wilderness: + player_level: 0 + + ##---------------------------------------------------------## + #| Additional requirements for island roles |# + ##-------------------+-------------------------------------## + #| island_level | the island level for the island |# + #| | they are trying to fly on. |# + ##-------------------+-------------------------------------## + #| island_missions | the missions for the owner of the |# + #| | island they are trying to fly on. |# + ##-------------------+-------------------------------------## + #| If the role specified is a member of the island, |# + #| for example, (team, moderator) there is no need |# + #| to specify both island_level and player_level. |# + ##---------------------------------------------------------## + island_roles: + leader: + player_level: 500 + + admin: + player_level: 750 + player_missions: + - "miner_2" + + moderator: + player_level: 2000 + player_missions: + - "miner_2" + + member: + player_level: 2500 + player_missions: + - "miner_2" + + coop: + player_level: 3000 + island_level: 2500 + + player_missions: + - "miner_2" + island_missions: + - "miner_2" + + guest: + # This line specifies that the visitor needs to have an island level of 150 to fly on other peoples islands. + player_level: 2500 + # This line specifies that the island needs a level of 50 to allow visitors flight on their island. + island_level: 3500 + + # This specifies that the visitor needs miner level 2 to fly on other peoples islands + player_missions: + - "miner_1" + # This specifies that the island needs hunter level 5 to allow visitors flight on their island. + island_missions: + - "slayer_1" + +flight_settings: + # If false the player cannot fly when they are not on an island + wilderness: true + + # The following settings are the default levels for the tempfly's island protection panel + # Island owners may allow or disallow island roles flight on their island. + # You will need to enter the roles specific to your skyblock plugin here. The defaults may not apply to you. + base_permissions: + leader: true + # Coowners can fly on the island + admin: true + # Moderators can fly on the island + moderator: true + # Team members can fly on the island + member: true + # Coop players can fly on the island + coop: true + # Visitors can fly on the island + guest: false + +language: + + invalid: + island: "{PREFIX} &cYou must have an island to fly here!" + + requirements: + # Challenges support the placeholders; {CHALLENGE} | {PROGRESS} | {ROLE} + challenge_self: "{PREFIX} &cYou must complete the mission &f{CHALLENGE} &cto fly here!" + challenge_other: "{PREFIX} &cThis island has not unlocked flight for &f{ROLE}&c's!" + # Levels support the placeholders; {LEVEL} | {ROLE} + level_self: "{PREFIX} &cYou must have an island level of &f{LEVEL} &cto fly here!" + level_other: "{PREFIX} &cThis island does not meet the level requirement for &f{ROLE}'s &cto fly!" + + role_denied: "{PREFIX} &cThis island does not allow &f{ROLE}'s &cto fly!" + +gui: + # This setting will allow you to place a button inside the island settings panel for superior skyblock. + + # Not yet implemented for Superior Skyblock... + hook_settings: + enabled: true + button: + name: "&dTemp&fFly &fIsland Settings" + + page: + # Placeholders; {ROLE} + settings: + title: "&dIsland Flight Settings" + background: + name: "&7- Please select an option" + toolbar: + name: "&7- Please select an option" + allowed: + name: "&e&l{ROLE}" + lore: + - "&a&m================" + - "&7- {ROLE}'s can currently fly" + disallowed: + name: "&e&l{ROLE}" + lore: + - "&c&m================" + - "&7- {ROLE}'s can not currently fly" diff --git a/TempFly/resources/skyblock_readme.yml b/resources/skyblock_readme.yml similarity index 97% rename from TempFly/resources/skyblock_readme.yml rename to resources/skyblock_readme.yml index 1b6b13a..de44dee 100644 --- a/TempFly/resources/skyblock_readme.yml +++ b/resources/skyblock_readme.yml @@ -1,63 +1,63 @@ -##==================================================================## -#| ____ __ _ _ _ ____ __ __ ___ __ _ |# -#| / ___)( / )( \/ )( _ \( ) / \ / __)( / ) |# -#| \___ \ ) ( ) / ) _ (/ (_/\( O )( (__ | ( |# -#| (____/(__\_)(__/ (____/\____/ \__/ \___)(__\_) |# -#| |# -##------------------------------------------------------------------## -#| This file contains all the information you need to know in order |# -#| to properly configure tempfly for your skyblock plugin |# -##------------------------------------------------------------------## -#| Supported Skyblock Plugins |# -#| -------------------------- |# -#| AskyBlock |# -#| Iridium Skyblock |# -##==================================================================## - -##================================================## -#| |# -#| ASkyBlock |# -#| |# -##------------------------------------------------## -#| Valid Island Roles |# -#| ------------------ |# -#| owner | team | coop | visitor |# -##------------------------------------------------## -#| Challenge info |# -#| ------------------ |# -#| When specifying challenges for askyblock you |# -#| only have the option to specify whether |# -#| the challenge has been completed or not. |# -#| askyblock does not support challenge progress |# -#| or multiple completions, below is an example. |# -##================================================## -unlockables: - wilderness: - island_level: 50 - challenges: - stewmaker: - completed: 1 - - island_roles: - owner: - challenges: - papermaker: - completed: 1 - team: - island_level: 75 - - -##================================================## -#| |# -#| IridiumSkyblock |# -#| |# -##------------------------------------------------## -#| Valid Island Roles |# -#| ------------------ |# -#| owner | coowner | coop |# -#| member | moderator | visitor |# -##------------------------------------------------## -#| Challenge info |# -#| ------------------ |# -#| When specifying challenges for iridiumskyblock |# -#| you may specify +##==================================================================## +#| ____ __ _ _ _ ____ __ __ ___ __ _ |# +#| / ___)( / )( \/ )( _ \( ) / \ / __)( / ) |# +#| \___ \ ) ( ) / ) _ (/ (_/\( O )( (__ | ( |# +#| (____/(__\_)(__/ (____/\____/ \__/ \___)(__\_) |# +#| |# +##------------------------------------------------------------------## +#| This file contains all the information you need to know in order |# +#| to properly configure tempfly for your skyblock plugin |# +##------------------------------------------------------------------## +#| Supported Skyblock Plugins |# +#| -------------------------- |# +#| AskyBlock |# +#| Iridium Skyblock |# +##==================================================================## + +##================================================## +#| |# +#| ASkyBlock |# +#| |# +##------------------------------------------------## +#| Valid Island Roles |# +#| ------------------ |# +#| owner | team | coop | visitor |# +##------------------------------------------------## +#| Challenge info |# +#| ------------------ |# +#| When specifying challenges for askyblock you |# +#| only have the option to specify whether |# +#| the challenge has been completed or not. |# +#| askyblock does not support challenge progress |# +#| or multiple completions, below is an example. |# +##================================================## +unlockables: + wilderness: + island_level: 50 + challenges: + stewmaker: + completed: 1 + + island_roles: + owner: + challenges: + papermaker: + completed: 1 + team: + island_level: 75 + + +##================================================## +#| |# +#| IridiumSkyblock |# +#| |# +##------------------------------------------------## +#| Valid Island Roles |# +#| ------------------ |# +#| owner | coowner | coop |# +#| member | moderator | visitor |# +##------------------------------------------------## +#| Challenge info |# +#| ------------------ |# +#| When specifying challenges for iridiumskyblock |# +#| you may specify diff --git a/TempFly/src/com/moneybags/tempfly/Metrics.java b/src/com/moneybags/tempfly/Metrics.java similarity index 97% rename from TempFly/src/com/moneybags/tempfly/Metrics.java rename to src/com/moneybags/tempfly/Metrics.java index ed8937f..57784f4 100644 --- a/TempFly/src/com/moneybags/tempfly/Metrics.java +++ b/src/com/moneybags/tempfly/Metrics.java @@ -1,720 +1,720 @@ -package com.moneybags.tempfly; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.JsonPrimitive; -import com.moneybags.tempfly.util.U; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.RegisteredServiceProvider; -import org.bukkit.plugin.ServicePriority; - -import javax.net.ssl.HttpsURLConnection; -import java.io.*; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.concurrent.Callable; -import java.util.logging.Level; -import java.util.zip.GZIPOutputStream; - -/** - * bStats collects some data for plugin authors. - *

- * Check out https://bStats.org/ to learn more about bStats! - */ -@SuppressWarnings({"unused"}) -public class Metrics { - - static { - // You can use the property to disable the check in your test environment - if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { - // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D - final String defaultPackage = new String( - new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); - final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); - // We want to make sure nobody just copy & pastes the example and use the wrong package names - if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { - throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); - } - } - } - - // The version of this bStats class.. - public static final int B_STATS_VERSION = 1; - - // The url to which the data is sent - private static final String URL = "https://bStats.org/submitData/bukkit"; - - // Is bStats enabled on this server? - private boolean enabled; - - // Should failed requests be logged? - private static boolean logFailedRequests; - - // Should the sent data be logged? - private static boolean logSentData; - - // Should the response text be logged? - private static boolean logResponseStatusText; - - // The uuid of the server - private static String serverUUID; - - // The plugin - private final Plugin plugin; - - // The plugin id - private final int pluginId; - - // A list with all custom charts - private final List charts = new ArrayList<>(); - - /** - * Class constructor. - * - * @param plugin The plugin which stats should be submitted. - * @param pluginId The id of the plugin. - * It can be found at What is my plugin id? - */ - public Metrics(Plugin plugin, int pluginId) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null!"); - } - this.plugin = plugin; - this.pluginId = pluginId; - - // Get the config file - File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); - File configFile = new File(bStatsFolder, "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - // Check if the config file exists - if (!config.isSet("serverUuid")) { - - // Add default values - config.addDefault("enabled", true); - // Every server gets it's unique random id. - config.addDefault("serverUuid", UUID.randomUUID().toString()); - // Should failed request be logged? - config.addDefault("logFailedRequests", false); - // Should the sent data be logged? - config.addDefault("logSentData", false); - // Should the response text be logged? - config.addDefault("logResponseStatusText", false); - - // Inform the server owners about bStats - config.options().header( - "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + - "To honor their work, you should not disable it.\n" + - "This has nearly no effect on the server performance!\n" + - "Check out https://bStats.org/ to learn more :)" - ).copyDefaults(true); - try { - config.save(configFile); - } catch (IOException ignored) { } - } - - // Load the data - enabled = config.getBoolean("enabled", true); - serverUUID = config.getString("serverUuid"); - logFailedRequests = config.getBoolean("logFailedRequests", false); - logSentData = config.getBoolean("logSentData", false); - logResponseStatusText = config.getBoolean("logResponseStatusText", false); - if (enabled) { - boolean found = false; - // Search for all other bStats Metrics classes to see if we are the first one - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - found = true; // We aren't the first - break; - } catch (NoSuchFieldException ignored) { } - } - // Register our service - Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); - if (!found) { - // We are the first! - startSubmitting(); - } - } - } - - /** - * Checks if bStats is enabled. - * - * @return Whether bStats is enabled or not. - */ - public boolean isEnabled() { - return enabled; - } - - /** - * Adds a custom chart. - * - * @param chart The chart to add. - */ - public void addCustomChart(CustomChart chart) { - if (chart == null) { - throw new IllegalArgumentException("Chart cannot be null!"); - } - charts.add(chart); - } - - /** - * Starts the Scheduler which submits our data every 30 minutes. - */ - private void startSubmitting() { - final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - if (!plugin.isEnabled()) { // Plugin was disabled - timer.cancel(); - return; - } - // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler - // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) - Bukkit.getScheduler().runTask(plugin, () -> submitData()); - } - }, 1000 * 60 * 5, 1000 * 60 * 30); - // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start - // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! - // WARNING: Just don't do it! - } - - /** - * Gets the plugin specific data. - * This method is called using Reflection. - * - * @return The plugin specific data. - */ - public JsonObject getPluginData() { - JsonObject data = new JsonObject(); - - String pluginName = plugin.getDescription().getName(); - String pluginVersion = plugin.getDescription().getVersion(); - - data.addProperty("pluginName", pluginName); // Append the name of the plugin - data.addProperty("id", pluginId); // Append the id of the plugin - data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin - JsonArray customCharts = new JsonArray(); - for (CustomChart customChart : charts) { - // Add the data of the custom charts - JsonObject chart = customChart.getRequestJsonObject(); - if (chart == null) { // If the chart is null, we skip it - continue; - } - customCharts.add(chart); - } - data.add("customCharts", customCharts); - - return data; - } - - /** - * Gets the server specific data. - * - * @return The server specific data. - */ - private JsonObject getServerData() { - // Minecraft specific data - int playerAmount; - try { - // Around MC 1.8 the return type was changed to a collection from an array, - // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; - Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); - playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) - ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() - : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; - } catch (Exception e) { - playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed - } - int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; - String bukkitVersion = Bukkit.getVersion(); - String bukkitName = Bukkit.getName(); - - // OS/Java specific data - String javaVersion = System.getProperty("java.version"); - String osName = System.getProperty("os.name"); - String osArch = System.getProperty("os.arch"); - String osVersion = System.getProperty("os.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - JsonObject data = new JsonObject(); - - data.addProperty("serverUUID", serverUUID); - - data.addProperty("playerAmount", playerAmount); - data.addProperty("onlineMode", onlineMode); - data.addProperty("bukkitVersion", bukkitVersion); - data.addProperty("bukkitName", bukkitName); - - data.addProperty("javaVersion", javaVersion); - data.addProperty("osName", osName); - data.addProperty("osArch", osArch); - data.addProperty("osVersion", osVersion); - data.addProperty("coreCount", coreCount); - - return data; - } - - /** - * Collects the data and sends it afterwards. - */ - private void submitData() { - final JsonObject data = getServerData(); - - JsonArray pluginData = new JsonArray(); - // Search for all other bStats Metrics classes to get their plugin data - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - - for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { - try { - Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); - if (plugin instanceof JsonObject) { - pluginData.add((JsonObject) plugin); - } else { // old bstats version compatibility - try { - Class jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); - if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { - Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); - jsonStringGetter.setAccessible(true); - String jsonString = (String) jsonStringGetter.invoke(plugin); - JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); - pluginData.add(object); - } - } catch (ClassNotFoundException e) { - // minecraft version 1.14+ - if (logFailedRequests) { - this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e); - } - } - } - } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } - } - } catch (NoSuchFieldException ignored) { } - } - - data.add("plugins", pluginData); - - // Create a new thread for the connection to the bStats server - new Thread(() -> { - try { - // Send the data - sendData(plugin, data); - } catch (Exception e) { - // Something went wrong! :( - if (logFailedRequests) { - plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); - } - } - }).start(); - } - - /** - * Sends the data to the bStats server. - * - * @param plugin Any plugin. It's just used to get a logger instance. - * @param data The data to send. - * @throws Exception If the request failed. - */ - private static void sendData(Plugin plugin, JsonObject data) throws Exception { - if (data == null) { - throw new IllegalArgumentException("Data cannot be null!"); - } - if (Bukkit.isPrimaryThread()) { - throw new IllegalAccessException("This method must not be called from the main thread!"); - } - if (logSentData) { - plugin.getLogger().info("Sending data to bStats: " + data); - } - HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); - - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - - // Add headers - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format - connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); - - // Send data - connection.setDoOutput(true); - try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { - outputStream.write(compressedData); - } - - StringBuilder builder = new StringBuilder(); - try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { - String line; - while ((line = bufferedReader.readLine()) != null) { - builder.append(line); - } - } - - if (logResponseStatusText) { - plugin.getLogger().info("Sent data to bStats and received response: " + builder); - } - } - - /** - * Gzips the given String. - * - * @param str The string to gzip. - * @return The gzipped String. - * @throws IOException If the compression failed. - */ - private static byte[] compress(final String str) throws IOException { - if (str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { - gzip.write(str.getBytes(StandardCharsets.UTF_8)); - } - return outputStream.toByteArray(); - } - - /** - * Represents a custom chart. - */ - public static abstract class CustomChart { - - // The id of the chart - final String chartId; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - CustomChart(String chartId) { - if (chartId == null || chartId.isEmpty()) { - throw new IllegalArgumentException("ChartId cannot be null or empty!"); - } - this.chartId = chartId; - } - - private JsonObject getRequestJsonObject() { - JsonObject chart = new JsonObject(); - chart.addProperty("chartId", chartId); - try { - JsonObject data = getChartData(); - if (data == null) { - // If the data is null we don't send the chart. - return null; - } - chart.add("data", data); - } catch (Throwable t) { - if (logFailedRequests) { - Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); - } - return null; - } - return chart; - } - - protected abstract JsonObject getChartData() throws Exception; - - } - - /** - * Represents a custom simple pie. - */ - public static class SimplePie extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimplePie(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - String value = callable.call(); - if (value == null || value.isEmpty()) { - // Null = skip the chart - return null; - } - data.addProperty("value", value); - return data; - } - } - - /** - * Represents a custom advanced pie. - */ - public static class AdvancedPie extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedPie(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.addProperty(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - } - - /** - * Represents a custom drilldown pie. - */ - public static class DrilldownPie extends CustomChart { - - private final Callable>> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public DrilldownPie(String chartId, Callable>> callable) { - super(chartId); - this.callable = callable; - } - - @Override - public JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map> map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean reallyAllSkipped = true; - for (Map.Entry> entryValues : map.entrySet()) { - JsonObject value = new JsonObject(); - boolean allSkipped = true; - for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { - value.addProperty(valueEntry.getKey(), valueEntry.getValue()); - allSkipped = false; - } - if (!allSkipped) { - reallyAllSkipped = false; - values.add(entryValues.getKey(), value); - } - } - if (reallyAllSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - } - - /** - * Represents a custom single line chart. - */ - public static class SingleLineChart extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SingleLineChart(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - int value = callable.call(); - if (value == 0) { - // Null = skip the chart - return null; - } - data.addProperty("value", value); - return data; - } - - } - - /** - * Represents a custom multi line chart. - */ - public static class MultiLineChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public MultiLineChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.addProperty(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - - } - - /** - * Represents a custom simple bar chart. - */ - public static class SimpleBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimpleBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - for (Map.Entry entry : map.entrySet()) { - JsonArray categoryValues = new JsonArray(); - categoryValues.add(new JsonPrimitive(entry.getValue())); - values.add(entry.getKey(), categoryValues); - } - data.add("values", values); - return data; - } - - } - - /** - * Represents a custom advanced bar chart. - */ - public static class AdvancedBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue().length == 0) { - continue; // Skip this invalid - } - allSkipped = false; - JsonArray categoryValues = new JsonArray(); - for (int categoryValue : entry.getValue()) { - categoryValues.add(new JsonPrimitive(categoryValue)); - } - values.add(entry.getKey(), categoryValues); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - } - +package com.moneybags.tempfly; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonPrimitive; +import com.moneybags.tempfly.util.U; + +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.ServicePriority; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; + +/** + * bStats collects some data for plugin authors. + *

+ * Check out https://bStats.org/ to learn more about bStats! + */ +@SuppressWarnings({"unused"}) +public class Metrics { + + static { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D + final String defaultPackage = new String( + new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); + final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure nobody just copy & pastes the example and use the wrong package names + if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } + + // The version of this bStats class.. + public static final int B_STATS_VERSION = 1; + + // The url to which the data is sent + private static final String URL = "https://bStats.org/submitData/bukkit"; + + // Is bStats enabled on this server? + private boolean enabled; + + // Should failed requests be logged? + private static boolean logFailedRequests; + + // Should the sent data be logged? + private static boolean logSentData; + + // Should the response text be logged? + private static boolean logResponseStatusText; + + // The uuid of the server + private static String serverUUID; + + // The plugin + private final Plugin plugin; + + // The plugin id + private final int pluginId; + + // A list with all custom charts + private final List charts = new ArrayList<>(); + + /** + * Class constructor. + * + * @param plugin The plugin which stats should be submitted. + * @param pluginId The id of the plugin. + * It can be found at What is my plugin id? + */ + public Metrics(Plugin plugin, int pluginId) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null!"); + } + this.plugin = plugin; + this.pluginId = pluginId; + + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + // Check if the config file exists + if (!config.isSet("serverUuid")) { + + // Add default values + config.addDefault("enabled", true); + // Every server gets it's unique random id. + config.addDefault("serverUuid", UUID.randomUUID().toString()); + // Should failed request be logged? + config.addDefault("logFailedRequests", false); + // Should the sent data be logged? + config.addDefault("logSentData", false); + // Should the response text be logged? + config.addDefault("logResponseStatusText", false); + + // Inform the server owners about bStats + config.options().header( + "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + + "To honor their work, you should not disable it.\n" + + "This has nearly no effect on the server performance!\n" + + "Check out https://bStats.org/ to learn more :)" + ).copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { } + } + + // Load the data + enabled = config.getBoolean("enabled", true); + serverUUID = config.getString("serverUuid"); + logFailedRequests = config.getBoolean("logFailedRequests", false); + logSentData = config.getBoolean("logSentData", false); + logResponseStatusText = config.getBoolean("logResponseStatusText", false); + if (enabled) { + boolean found = false; + // Search for all other bStats Metrics classes to see if we are the first one + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + found = true; // We aren't the first + break; + } catch (NoSuchFieldException ignored) { } + } + // Register our service + Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); + if (!found) { + // We are the first! + startSubmitting(); + } + } + } + + /** + * Checks if bStats is enabled. + * + * @return Whether bStats is enabled or not. + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + if (chart == null) { + throw new IllegalArgumentException("Chart cannot be null!"); + } + charts.add(chart); + } + + /** + * Starts the Scheduler which submits our data every 30 minutes. + */ + private void startSubmitting() { + final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + if (!plugin.isEnabled()) { // Plugin was disabled + timer.cancel(); + return; + } + // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler + // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) + Bukkit.getScheduler().runTask(plugin, () -> submitData()); + } + }, 1000 * 60 * 5, 1000 * 60 * 30); + // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start + // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! + // WARNING: Just don't do it! + } + + /** + * Gets the plugin specific data. + * This method is called using Reflection. + * + * @return The plugin specific data. + */ + public JsonObject getPluginData() { + JsonObject data = new JsonObject(); + + String pluginName = plugin.getDescription().getName(); + String pluginVersion = plugin.getDescription().getVersion(); + + data.addProperty("pluginName", pluginName); // Append the name of the plugin + data.addProperty("id", pluginId); // Append the id of the plugin + data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin + JsonArray customCharts = new JsonArray(); + for (CustomChart customChart : charts) { + // Add the data of the custom charts + JsonObject chart = customChart.getRequestJsonObject(); + if (chart == null) { // If the chart is null, we skip it + continue; + } + customCharts.add(chart); + } + data.add("customCharts", customCharts); + + return data; + } + + /** + * Gets the server specific data. + * + * @return The server specific data. + */ + private JsonObject getServerData() { + // Minecraft specific data + int playerAmount; + try { + // Around MC 1.8 the return type was changed to a collection from an array, + // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed + } + int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; + String bukkitVersion = Bukkit.getVersion(); + String bukkitName = Bukkit.getName(); + + // OS/Java specific data + String javaVersion = System.getProperty("java.version"); + String osName = System.getProperty("os.name"); + String osArch = System.getProperty("os.arch"); + String osVersion = System.getProperty("os.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + + JsonObject data = new JsonObject(); + + data.addProperty("serverUUID", serverUUID); + + data.addProperty("playerAmount", playerAmount); + data.addProperty("onlineMode", onlineMode); + data.addProperty("bukkitVersion", bukkitVersion); + data.addProperty("bukkitName", bukkitName); + + data.addProperty("javaVersion", javaVersion); + data.addProperty("osName", osName); + data.addProperty("osArch", osArch); + data.addProperty("osVersion", osVersion); + data.addProperty("coreCount", coreCount); + + return data; + } + + /** + * Collects the data and sends it afterwards. + */ + private void submitData() { + final JsonObject data = getServerData(); + + JsonArray pluginData = new JsonArray(); + // Search for all other bStats Metrics classes to get their plugin data + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + + for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { + try { + Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); + if (plugin instanceof JsonObject) { + pluginData.add((JsonObject) plugin); + } else { // old bstats version compatibility + try { + Class jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); + if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { + Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); + jsonStringGetter.setAccessible(true); + String jsonString = (String) jsonStringGetter.invoke(plugin); + JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); + pluginData.add(object); + } + } catch (ClassNotFoundException e) { + // minecraft version 1.14+ + if (logFailedRequests) { + this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e); + } + } + } + } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } + } + } catch (NoSuchFieldException ignored) { } + } + + data.add("plugins", pluginData); + + // Create a new thread for the connection to the bStats server + new Thread(() -> { + try { + // Send the data + sendData(plugin, data); + } catch (Exception e) { + // Something went wrong! :( + if (logFailedRequests) { + plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); + } + } + }).start(); + } + + /** + * Sends the data to the bStats server. + * + * @param plugin Any plugin. It's just used to get a logger instance. + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(Plugin plugin, JsonObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null!"); + } + if (Bukkit.isPrimaryThread()) { + throw new IllegalAccessException("This method must not be called from the main thread!"); + } + if (logSentData) { + plugin.getLogger().info("Sending data to bStats: " + data); + } + HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); + + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + + // Add headers + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format + connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); + + // Send data + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + + StringBuilder builder = new StringBuilder(); + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + + if (logResponseStatusText) { + plugin.getLogger().info("Sent data to bStats and received response: " + builder); + } + } + + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } + + /** + * Represents a custom chart. + */ + public static abstract class CustomChart { + + // The id of the chart + final String chartId; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + CustomChart(String chartId) { + if (chartId == null || chartId.isEmpty()) { + throw new IllegalArgumentException("ChartId cannot be null or empty!"); + } + this.chartId = chartId; + } + + private JsonObject getRequestJsonObject() { + JsonObject chart = new JsonObject(); + chart.addProperty("chartId", chartId); + try { + JsonObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + chart.add("data", data); + } catch (Throwable t) { + if (logFailedRequests) { + Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return chart; + } + + protected abstract JsonObject getChartData() throws Exception; + + } + + /** + * Represents a custom simple pie. + */ + public static class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + data.addProperty("value", value); + return data; + } + } + + /** + * Represents a custom advanced pie. + */ + public static class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.addProperty(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + + /** + * Represents a custom drilldown pie. + */ + public static class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JsonObject value = new JsonObject(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + value.addProperty(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + values.add(entryValues.getKey(), value); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + + /** + * Represents a custom single line chart. + */ + public static class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + data.addProperty("value", value); + return data; + } + + } + + /** + * Represents a custom multi line chart. + */ + public static class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.addProperty(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + + } + + /** + * Represents a custom simple bar chart. + */ + public static class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + JsonArray categoryValues = new JsonArray(); + categoryValues.add(new JsonPrimitive(entry.getValue())); + values.add(entry.getKey(), categoryValues); + } + data.add("values", values); + return data; + } + + } + + /** + * Represents a custom advanced bar chart. + */ + public static class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + continue; // Skip this invalid + } + allSkipped = false; + JsonArray categoryValues = new JsonArray(); + for (int categoryValue : entry.getValue()) { + categoryValues.add(new JsonPrimitive(categoryValue)); + } + values.add(entry.getKey(), categoryValues); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + } \ No newline at end of file diff --git a/TempFly/src/com/moneybags/tempfly/TempFly.java b/src/com/moneybags/tempfly/TempFly.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/TempFly.java rename to src/com/moneybags/tempfly/TempFly.java index 9a9b098..cfb92ea 100644 --- a/TempFly/src/com/moneybags/tempfly/TempFly.java +++ b/src/com/moneybags/tempfly/TempFly.java @@ -1,195 +1,195 @@ -package com.moneybags.tempfly; - -import java.io.IOException; -import java.sql.SQLException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.bukkit.Bukkit; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scheduler.BukkitTask; - -import com.moneybags.tempfly.aesthetic.ActionBarAPI; -import com.moneybags.tempfly.aesthetic.ClipAPI; -import com.moneybags.tempfly.aesthetic.MvdWAPI; -import com.moneybags.tempfly.aesthetic.TitleAPI; -import com.moneybags.tempfly.aesthetic.particle.Particles; -import com.moneybags.tempfly.command.CommandManager; -import com.moneybags.tempfly.fly.FlightManager; -import com.moneybags.tempfly.gui.GuiManager; -import com.moneybags.tempfly.gui.pages.PageShop; -import com.moneybags.tempfly.gui.pages.PageTrails; -import com.moneybags.tempfly.hook.HookManager; -import com.moneybags.tempfly.hook.TempFlyHook; -import com.moneybags.tempfly.time.TimeManager; -import com.moneybags.tempfly.util.AutoSave; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.ParticleTask; -import com.moneybags.tempfly.util.V; -import com.moneybags.tempfly.util.data.DataBridge; -import com.moneybags.tempfly.util.data.Files; - -public class TempFly extends JavaPlugin { - - // static abusers unite - private static TempFlyAPI tfApi; - public static TempFlyAPI getAPI() { - return tfApi; - } - - - private HookManager hooks; - private DataBridge bridge; - private FlightManager flight; - private TimeManager time; - private CommandManager commands; - private GuiManager gui; - private BukkitTask autosave; - - public HookManager getHookManager() { - return hooks; - } - - public DataBridge getDataBridge() { - return bridge; - } - - public FlightManager getFlightManager() { - return flight; - } - - public TimeManager getTimeManager() { - return time; - } - - public CommandManager getCommandManager() { - return commands; - } - - public GuiManager getGuiManager() { - return gui; - } - - @Override - public void onEnable() { - Console.setLogger(this.getLogger()); - - Files.createFiles(this); - V.loadValues(); - - try { - this.bridge = new DataBridge(this); - } catch (IOException | SQLException e1) { - e1.printStackTrace(); - getServer().getPluginManager().disablePlugin(this); - return; - } - - tfApi = new TempFlyAPI(this); - this.flight = new FlightManager(this); - this.time = new TimeManager(this); - this.hooks = new HookManager(this); - this.commands = new CommandManager(this); - this.gui = new GuiManager(this); - - hooks.loadInternalGenres(); - initializeGui(); - initializeAesthetics(); - - - try { - Metrics metrics = new Metrics(this, 8196); - // Hooks - metrics.addCustomChart(new Metrics.DrilldownPie("gamemode_hooks", () -> { - Map> map = new HashMap<>(); - Map entry = new HashMap<>(); - - for (TempFlyHook hook: hooks.getEnabled()) { - entry.put(hook.getHookedPlugin(), 1); - map.put(hook.getHookedPlugin(), entry); - } - if (map.size() == 0) { - entry.put("No Hooks", 1); - map.put("No Hooks", entry); - } - return map; - })); - } catch (Exception e) {e.printStackTrace();} - - autosave = new AutoSave(bridge).runTaskTimerAsynchronously(this, V.save * 20 * 60, V.save * 20 * 60); - - // Support "/reload" - for (Player p: Bukkit.getOnlinePlayers()) { - flight.addUser(p); - } - } - - private void initializeAesthetics() { - Particles.initialize(this); - - if (V.particles) { - new ParticleTask(this).runTaskTimer(this, 0, 5); - } - if (V.actionBar) { - ActionBarAPI.initialize(this); - } - - TitleAPI.initialize(this); - - if (Bukkit.getPluginManager().isPluginEnabled("MVdWPlaceholderAPI")) { - Console.info("Initializing MvdwAPI"); - MvdWAPI.initialize(this); - } - if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { - Console.info("Initializing ClipAPI"); - ClipAPI.initialize(this); - } - } - - private void initializeGui() { - PageTrails.initialize(this); - PageShop.initialize(this); - } - - @Override - public void onDisable() { - flight.onDisable(); - gui.endAllSessions(); - bridge.commitAll(); - } - - /* - * Reload the plugin, this is the method called upon command /tempfly reload - */ - //TODO reload hooks - public void reloadTempfly() { - gui.endAllSessions(); - - bridge.commitAll(); - Files.createFiles(this); - V.loadValues(); - initializeGui(); - - flight.onTempflyReload(); - hooks.onTempflyReload(); - - if (autosave != null) { - autosave.cancel(); - autosave = new AutoSave(bridge).runTaskTimerAsynchronously(this, 0, V.save * 20 * 60); - } - } - - @Override - public List onTabComplete(CommandSender s, Command cmd, String label, String[] args) { - if (cmd.getName().equalsIgnoreCase("fly")) { - return commands.getTabCompleter().onTabComplete(s, cmd, label, args); - } else { - return Arrays.asList(args); - } - } - -} +package com.moneybags.tempfly; + +import java.io.IOException; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitTask; + +import com.moneybags.tempfly.aesthetic.ActionBarAPI; +import com.moneybags.tempfly.aesthetic.ClipAPI; +import com.moneybags.tempfly.aesthetic.MvdWAPI; +import com.moneybags.tempfly.aesthetic.TitleAPI; +import com.moneybags.tempfly.aesthetic.particle.Particles; +import com.moneybags.tempfly.command.CommandManager; +import com.moneybags.tempfly.fly.FlightManager; +import com.moneybags.tempfly.gui.GuiManager; +import com.moneybags.tempfly.gui.pages.PageShop; +import com.moneybags.tempfly.gui.pages.PageTrails; +import com.moneybags.tempfly.hook.HookManager; +import com.moneybags.tempfly.hook.TempFlyHook; +import com.moneybags.tempfly.time.TimeManager; +import com.moneybags.tempfly.util.AutoSave; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.ParticleTask; +import com.moneybags.tempfly.util.V; +import com.moneybags.tempfly.util.data.DataBridge; +import com.moneybags.tempfly.util.data.Files; + +public class TempFly extends JavaPlugin { + + // static abusers unite + private static TempFlyAPI tfApi; + public static TempFlyAPI getAPI() { + return tfApi; + } + + + private HookManager hooks; + private DataBridge bridge; + private FlightManager flight; + private TimeManager time; + private CommandManager commands; + private GuiManager gui; + private BukkitTask autosave; + + public HookManager getHookManager() { + return hooks; + } + + public DataBridge getDataBridge() { + return bridge; + } + + public FlightManager getFlightManager() { + return flight; + } + + public TimeManager getTimeManager() { + return time; + } + + public CommandManager getCommandManager() { + return commands; + } + + public GuiManager getGuiManager() { + return gui; + } + + @Override + public void onEnable() { + Console.setLogger(this.getLogger()); + + Files.createFiles(this); + V.loadValues(); + + try { + this.bridge = new DataBridge(this); + } catch (IOException | SQLException e1) { + e1.printStackTrace(); + getServer().getPluginManager().disablePlugin(this); + return; + } + + tfApi = new TempFlyAPI(this); + this.flight = new FlightManager(this); + this.time = new TimeManager(this); + this.hooks = new HookManager(this); + this.commands = new CommandManager(this); + this.gui = new GuiManager(this); + + hooks.loadInternalGenres(); + initializeGui(); + initializeAesthetics(); + + + try { + Metrics metrics = new Metrics(this, 8196); + // Hooks + metrics.addCustomChart(new Metrics.DrilldownPie("gamemode_hooks", () -> { + Map> map = new HashMap<>(); + Map entry = new HashMap<>(); + + for (TempFlyHook hook: hooks.getEnabled()) { + entry.put(hook.getHookedPlugin(), 1); + map.put(hook.getHookedPlugin(), entry); + } + if (map.size() == 0) { + entry.put("No Hooks", 1); + map.put("No Hooks", entry); + } + return map; + })); + } catch (Exception e) {e.printStackTrace();} + + autosave = new AutoSave(bridge).runTaskTimerAsynchronously(this, V.save * 20 * 60, V.save * 20 * 60); + + // Support "/reload" + for (Player p: Bukkit.getOnlinePlayers()) { + flight.addUser(p); + } + } + + private void initializeAesthetics() { + Particles.initialize(this); + + if (V.particles) { + new ParticleTask(this).runTaskTimer(this, 0, 5); + } + if (V.actionBar) { + ActionBarAPI.initialize(this); + } + + TitleAPI.initialize(this); + + if (Bukkit.getPluginManager().isPluginEnabled("MVdWPlaceholderAPI")) { + Console.info("Initializing MvdwAPI"); + MvdWAPI.initialize(this); + } + if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { + Console.info("Initializing ClipAPI"); + ClipAPI.initialize(this); + } + } + + private void initializeGui() { + PageTrails.initialize(this); + PageShop.initialize(this); + } + + @Override + public void onDisable() { + flight.onDisable(); + gui.endAllSessions(); + bridge.commitAll(); + } + + /* + * Reload the plugin, this is the method called upon command /tempfly reload + */ + //TODO reload hooks + public void reloadTempfly() { + gui.endAllSessions(); + + bridge.commitAll(); + Files.createFiles(this); + V.loadValues(); + initializeGui(); + + flight.onTempflyReload(); + hooks.onTempflyReload(); + + if (autosave != null) { + autosave.cancel(); + autosave = new AutoSave(bridge).runTaskTimerAsynchronously(this, 0, V.save * 20 * 60); + } + } + + @Override + public List onTabComplete(CommandSender s, Command cmd, String label, String[] args) { + if (cmd.getName().equalsIgnoreCase("fly")) { + return commands.getTabCompleter().onTabComplete(s, cmd, label, args); + } else { + return Arrays.asList(args); + } + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/TempFlyAPI.java b/src/com/moneybags/tempfly/TempFlyAPI.java similarity index 97% rename from TempFly/src/com/moneybags/tempfly/TempFlyAPI.java rename to src/com/moneybags/tempfly/TempFlyAPI.java index fd77969..6ae37df 100644 --- a/TempFly/src/com/moneybags/tempfly/TempFlyAPI.java +++ b/src/com/moneybags/tempfly/TempFlyAPI.java @@ -1,207 +1,207 @@ -package com.moneybags.tempfly; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.fly.Flyer; -import com.moneybags.tempfly.fly.RequirementProvider; -import com.moneybags.tempfly.hook.region.RegionProvider; -import com.moneybags.tempfly.time.AsyncTimeParameters; -import com.moneybags.tempfly.user.FlightUser; - -@SuppressWarnings("deprecation") -public class TempFlyAPI { - - private final TempFly tempfly; - - public TempFlyAPI(TempFly tempfly) { - this.tempfly = tempfly; - } - - /** - * @param player Player uuid - * @return The amount of flight in seconds a player has. - */ - public double getFlightTime(UUID player) { - return tempfly.getTimeManager().getTime(player); - } - - /** - * Set the flight time of a player in seconds. - * The server must have vault installed to set flight time to an offline player - * @param player Player uuid - */ - public void setFlightTime(UUID player, double seconds) { - new AsyncTimeParameters(tempfly, (AsyncTimeParameters parameters) -> { - parameters.getTempfly().getTimeManager().setTime(player, parameters); - }, null, Bukkit.getOfflinePlayer(player), seconds).run(); - } - - /** - * Add flight time in seconds - * The server must have vault installed to add flight time to an offline player - * @param player Player uuid - * @param seconds Seconds to give the player - */ - public void addFlightTime(UUID player, double seconds) { - new AsyncTimeParameters(tempfly, (AsyncTimeParameters parameters) -> { - parameters.getTempfly().getTimeManager().addTime(player, parameters); - }, null, Bukkit.getOfflinePlayer(player), seconds).run(); - } - - /** - * Remove flight time from the player. - * @param player Player uuid - * @param seconds Seconds to remove from the player - */ - public void removeFlightTime(UUID player, double seconds) { - new AsyncTimeParameters(tempfly, (AsyncTimeParameters parameters) -> { - parameters.getTempfly().getTimeManager().removeTime(player, parameters); - }, null, Bukkit.getOfflinePlayer(player), seconds).run(); - } - - /** - * @deprecated Since 3.0, checking if fly is allowed should now be done with the - * method that includes the player as a parameter. This is due to the integration of - * conditional requirements based on factors about the player other than just the location. - * --=--------------=-- - * Players now have flight requirements stored in their FlightUser object that keep track - * of all the reasons a player cannot fly. These can be dynamically added and removed by - * myself and other plugins that hook into tempfly for many reasons. Therefore it is no longer - * feasable to check if flight is allowed with a location. Instead you need to see if they - * have failed requirements. - * --=--------------=-- - * This method will still work as it used to by checking disabled regions and worlds, - * but that is it. - * - * @param loc The location to check - * @return True if flight is allowed at the given location. - */ - @Deprecated - public boolean canFlyAt(Location loc) { - return tempfly.getFlightManager().getFlightEnvironment().flyAllowed(loc); - } - - /** - * Check if a player is currently allowed to fly. - * @param p - * @return - */ - public boolean canCurrentlyFly(Player p) { - return getUser(p).hasFlightRequirements(); - } - - /** - * Deprecated as of TempFly 3.0. You should now use FlightUser. - * This method will emulate the old function of the flyer object for legacy hooks with tempfly. - * In old tempfly the flyer object was instantiated when flight was enabled then destroyed when flight was disabled. - * Now every player has a persistent FlightUser object where flight can be enabled and disabled. - * @return All flyer objects for players using TempFly. - */ - @Deprecated - public Flyer[] getAllFlyers() { - List flyers = new ArrayList<>(); - for (FlightUser user: tempfly.getFlightManager().getUsers()) { - if (user.getPlayer().isFlying()) { - flyers.add(new Flyer(user)); - } - } - return flyers.toArray(new Flyer[flyers.size()]); - } - - /** - * Deprecated as of TempFly 3.0. You should now use FlightUser. - * This method will emulate the old function of the flyer object for legacy hooks with tempfly. - * In old tempfly the flyer object was instantiated when flight was enabled then destroyed when flight was disabled. - * Now every player has a persistent FlightUser object where flight can be enabled and disabled. - * @return The flyer object if the player is flying. Null if the player is not flying. - */ - @Deprecated - public Flyer getFlyer(Player p) { - FlightUser user = getUser(p); - return user.getPlayer().isFlying() ? new Flyer(user) : null; - } - - /** - * Get the FlightUser object for a player. There are many things you can do in here that are not - * part of the API but beware that they may be subject to change in future releases. - * @param p The player in question - * @return The players FlightUser - */ - public FlightUser getUser(Player p) { - return tempfly.getFlightManager().getUser(p); - } - - /** - * Get the FlightUser object for all players. There are many things you can do in here that are not - * part of the API but beware that they may be subject to change in future releases. - * @return All registered FlightUsers - */ - public FlightUser[] getUsers() { - return tempfly.getFlightManager().getUsers(); - } - - - /** - * - * @param p Player to toggle - * @param enabled Toggle enabled true or false - * @param fallDamage If true the player will take fall damage when their flight is toggled off. - */ - public void toggleTempfly(Player p, boolean enable, boolean fallDamage) { - FlightUser user = getUser(p); - if (enable) { - user.disableFlight(1, !fallDamage); - user.setAutoFly(false); - } else { - user.enableFlight(); - } - } - - /** - * Force TempFly to process a combat tag. - * This will use all the settings in the config like normal combat. - * Useful for plugins that manually handle entity damage and do not - * allow entities to directly harm each other. For instance, if a plugin - * has a custom health system and deals damage on combat with .damage(), TempFly - * would have no way to know this combat occured unless you use this. - * - * @param victim The entity that got attacked - * @param actor The attacking entity - */ - public void processCombat(Entity victim, Entity actor) { - tempfly.getFlightManager().getCombatHandler().processCombat(victim, actor); - } - - /** - * Register a new requirement provider with tempfly. - * All users will automatically be updated with the new requirements. - * @param provider The new requirements - */ - public void registerRequirementProvider(RequirementProvider provider) { - tempfly.getFlightManager().registerRequirementProvider(provider); - } - - /** - * unregister an existing requirement provider in tempfly. - * All users will automatically be updated and the requirements removed. - * @param provider The new requirements - */ - public void unregisterRequirementProvider(RequirementProvider provider) { - tempfly.getFlightManager().unregisterRequirementProvider(provider); - } - - /** - * Manually set tempfly's region provider. - * @param provider The regbion provider - */ - public void setRegionProvider(RegionProvider provider) { - tempfly.getHookManager().setRegionProvider(provider); - } -} +package com.moneybags.tempfly; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.fly.Flyer; +import com.moneybags.tempfly.fly.RequirementProvider; +import com.moneybags.tempfly.hook.region.RegionProvider; +import com.moneybags.tempfly.time.AsyncTimeParameters; +import com.moneybags.tempfly.user.FlightUser; + +@SuppressWarnings("deprecation") +public class TempFlyAPI { + + private final TempFly tempfly; + + public TempFlyAPI(TempFly tempfly) { + this.tempfly = tempfly; + } + + /** + * @param player Player uuid + * @return The amount of flight in seconds a player has. + */ + public double getFlightTime(UUID player) { + return tempfly.getTimeManager().getTime(player); + } + + /** + * Set the flight time of a player in seconds. + * The server must have vault installed to set flight time to an offline player + * @param player Player uuid + */ + public void setFlightTime(UUID player, double seconds) { + new AsyncTimeParameters(tempfly, (AsyncTimeParameters parameters) -> { + parameters.getTempfly().getTimeManager().setTime(player, parameters); + }, null, Bukkit.getOfflinePlayer(player), seconds).run(); + } + + /** + * Add flight time in seconds + * The server must have vault installed to add flight time to an offline player + * @param player Player uuid + * @param seconds Seconds to give the player + */ + public void addFlightTime(UUID player, double seconds) { + new AsyncTimeParameters(tempfly, (AsyncTimeParameters parameters) -> { + parameters.getTempfly().getTimeManager().addTime(player, parameters); + }, null, Bukkit.getOfflinePlayer(player), seconds).run(); + } + + /** + * Remove flight time from the player. + * @param player Player uuid + * @param seconds Seconds to remove from the player + */ + public void removeFlightTime(UUID player, double seconds) { + new AsyncTimeParameters(tempfly, (AsyncTimeParameters parameters) -> { + parameters.getTempfly().getTimeManager().removeTime(player, parameters); + }, null, Bukkit.getOfflinePlayer(player), seconds).run(); + } + + /** + * @deprecated Since 3.0, checking if fly is allowed should now be done with the + * method that includes the player as a parameter. This is due to the integration of + * conditional requirements based on factors about the player other than just the location. + * --=--------------=-- + * Players now have flight requirements stored in their FlightUser object that keep track + * of all the reasons a player cannot fly. These can be dynamically added and removed by + * myself and other plugins that hook into tempfly for many reasons. Therefore it is no longer + * feasable to check if flight is allowed with a location. Instead you need to see if they + * have failed requirements. + * --=--------------=-- + * This method will still work as it used to by checking disabled regions and worlds, + * but that is it. + * + * @param loc The location to check + * @return True if flight is allowed at the given location. + */ + @Deprecated + public boolean canFlyAt(Location loc) { + return tempfly.getFlightManager().getFlightEnvironment().flyAllowed(loc); + } + + /** + * Check if a player is currently allowed to fly. + * @param p + * @return + */ + public boolean canCurrentlyFly(Player p) { + return getUser(p).hasFlightRequirements(); + } + + /** + * Deprecated as of TempFly 3.0. You should now use FlightUser. + * This method will emulate the old function of the flyer object for legacy hooks with tempfly. + * In old tempfly the flyer object was instantiated when flight was enabled then destroyed when flight was disabled. + * Now every player has a persistent FlightUser object where flight can be enabled and disabled. + * @return All flyer objects for players using TempFly. + */ + @Deprecated + public Flyer[] getAllFlyers() { + List flyers = new ArrayList<>(); + for (FlightUser user: tempfly.getFlightManager().getUsers()) { + if (user.getPlayer().isFlying()) { + flyers.add(new Flyer(user)); + } + } + return flyers.toArray(new Flyer[flyers.size()]); + } + + /** + * Deprecated as of TempFly 3.0. You should now use FlightUser. + * This method will emulate the old function of the flyer object for legacy hooks with tempfly. + * In old tempfly the flyer object was instantiated when flight was enabled then destroyed when flight was disabled. + * Now every player has a persistent FlightUser object where flight can be enabled and disabled. + * @return The flyer object if the player is flying. Null if the player is not flying. + */ + @Deprecated + public Flyer getFlyer(Player p) { + FlightUser user = getUser(p); + return user.getPlayer().isFlying() ? new Flyer(user) : null; + } + + /** + * Get the FlightUser object for a player. There are many things you can do in here that are not + * part of the API but beware that they may be subject to change in future releases. + * @param p The player in question + * @return The players FlightUser + */ + public FlightUser getUser(Player p) { + return tempfly.getFlightManager().getUser(p); + } + + /** + * Get the FlightUser object for all players. There are many things you can do in here that are not + * part of the API but beware that they may be subject to change in future releases. + * @return All registered FlightUsers + */ + public FlightUser[] getUsers() { + return tempfly.getFlightManager().getUsers(); + } + + + /** + * + * @param p Player to toggle + * @param enabled Toggle enabled true or false + * @param fallDamage If true the player will take fall damage when their flight is toggled off. + */ + public void toggleTempfly(Player p, boolean enable, boolean fallDamage) { + FlightUser user = getUser(p); + if (enable) { + user.disableFlight(1, !fallDamage); + user.setAutoFly(false); + } else { + user.enableFlight(); + } + } + + /** + * Force TempFly to process a combat tag. + * This will use all the settings in the config like normal combat. + * Useful for plugins that manually handle entity damage and do not + * allow entities to directly harm each other. For instance, if a plugin + * has a custom health system and deals damage on combat with .damage(), TempFly + * would have no way to know this combat occured unless you use this. + * + * @param victim The entity that got attacked + * @param actor The attacking entity + */ + public void processCombat(Entity victim, Entity actor) { + tempfly.getFlightManager().getCombatHandler().processCombat(victim, actor); + } + + /** + * Register a new requirement provider with tempfly. + * All users will automatically be updated with the new requirements. + * @param provider The new requirements + */ + public void registerRequirementProvider(RequirementProvider provider) { + tempfly.getFlightManager().registerRequirementProvider(provider); + } + + /** + * unregister an existing requirement provider in tempfly. + * All users will automatically be updated and the requirements removed. + * @param provider The new requirements + */ + public void unregisterRequirementProvider(RequirementProvider provider) { + tempfly.getFlightManager().unregisterRequirementProvider(provider); + } + + /** + * Manually set tempfly's region provider. + * @param provider The regbion provider + */ + public void setRegionProvider(RegionProvider provider) { + tempfly.getHookManager().setRegionProvider(provider); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/aesthetic/ActionBarAPI.java b/src/com/moneybags/tempfly/aesthetic/ActionBarAPI.java similarity index 97% rename from TempFly/src/com/moneybags/tempfly/aesthetic/ActionBarAPI.java rename to src/com/moneybags/tempfly/aesthetic/ActionBarAPI.java index ee7e2ec..d0d7c6c 100644 --- a/TempFly/src/com/moneybags/tempfly/aesthetic/ActionBarAPI.java +++ b/src/com/moneybags/tempfly/aesthetic/ActionBarAPI.java @@ -1,31 +1,31 @@ -package com.moneybags.tempfly.aesthetic; - -import com.moneybags.tempfly.aesthetic.actionbar.ActionBar; -import com.moneybags.tempfly.aesthetic.actionbar.LegacyActionBar; -import com.moneybags.tempfly.aesthetic.actionbar.ModernActionBar; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; - -public class ActionBarAPI { - - private static ActionBar actionBar; - - public static void initialize(TempFly tempfly) { - // Check if we're on 1.12 or above - if (Bukkit.getServer().getVersion().matches(".*1\\.(?!10|11)\\d{2,}.*")) { - actionBar = new ModernActionBar(tempfly); - } else { - actionBar = new LegacyActionBar(tempfly); - } - } - - public static void sendActionBar(final Player player, final String message) { - actionBar.sendActionBar(player, message); - } - - public static void sendActionBar(final Player player, final String message, int duration) { - actionBar.sendActionBar(player, message, duration); - } -} +package com.moneybags.tempfly.aesthetic; + +import com.moneybags.tempfly.aesthetic.actionbar.ActionBar; +import com.moneybags.tempfly.aesthetic.actionbar.LegacyActionBar; +import com.moneybags.tempfly.aesthetic.actionbar.ModernActionBar; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; + +public class ActionBarAPI { + + private static ActionBar actionBar; + + public static void initialize(TempFly tempfly) { + // Check if we're on 1.12 or above + if (Bukkit.getServer().getVersion().matches(".*1\\.(?!10|11)\\d{2,}.*")) { + actionBar = new ModernActionBar(tempfly); + } else { + actionBar = new LegacyActionBar(tempfly); + } + } + + public static void sendActionBar(final Player player, final String message) { + actionBar.sendActionBar(player, message); + } + + public static void sendActionBar(final Player player, final String message, int duration) { + actionBar.sendActionBar(player, message, duration); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/aesthetic/ClipAPI.java b/src/com/moneybags/tempfly/aesthetic/ClipAPI.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/aesthetic/ClipAPI.java rename to src/com/moneybags/tempfly/aesthetic/ClipAPI.java index db75939..9189d63 100644 --- a/TempFly/src/com/moneybags/tempfly/aesthetic/ClipAPI.java +++ b/src/com/moneybags/tempfly/aesthetic/ClipAPI.java @@ -1,77 +1,77 @@ -package com.moneybags.tempfly.aesthetic; - -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.time.TimeManager.Placeholder; - -import me.clip.placeholderapi.expansion.PlaceholderExpansion; - -public class ClipAPI { - - private static TempFly tempfly; - private static PlaceHolders instance; - - public static void initialize(TempFly plugin) { - tempfly = plugin; - if (instance == null) { - instance = new PlaceHolders(); - instance.register(); - } - } - - public static class PlaceHolders extends PlaceholderExpansion { - - @Override - public boolean persist() { - return true; - } - - @Override - public boolean canRegister(){ - return true; - } - - @Override - public String getAuthor() { - return "ChiefMoneyBags"; - } - - @Override - public String getIdentifier() { - return "tempfly"; - } - - @Override - public String getVersion() { - return tempfly.getDescription().getVersion(); - } - - @Override - public String onPlaceholderRequest(Player p, String identifier) { - if (p == null) { - return null; - } - switch (identifier) { - case "time-formatted": - return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_FORMATTED); - case "time-days": - return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_DAYS); - case "time-hours": - return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_HOURS); - case "time-minutes": - return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_MINUTES); - case "time-seconds": - return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_SECONDS); - case "time-seconds-total": - return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_SECONDS_TOTAL); - case "list-name": - return p.isOnline() ? tempfly.getFlightManager().getUser(p).getListPlaceholder() : ""; - case "name-tag": - return p.isOnline() ? tempfly.getFlightManager().getUser(p).getTagPlaceholder() : ""; - default: - return "Invalid placeholder.. :( "; - } - } - } -} +package com.moneybags.tempfly.aesthetic; + +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.time.TimeManager.Placeholder; + +import me.clip.placeholderapi.expansion.PlaceholderExpansion; + +public class ClipAPI { + + private static TempFly tempfly; + private static PlaceHolders instance; + + public static void initialize(TempFly plugin) { + tempfly = plugin; + if (instance == null) { + instance = new PlaceHolders(); + instance.register(); + } + } + + public static class PlaceHolders extends PlaceholderExpansion { + + @Override + public boolean persist() { + return true; + } + + @Override + public boolean canRegister(){ + return true; + } + + @Override + public String getAuthor() { + return "ChiefMoneyBags"; + } + + @Override + public String getIdentifier() { + return "tempfly"; + } + + @Override + public String getVersion() { + return tempfly.getDescription().getVersion(); + } + + @Override + public String onPlaceholderRequest(Player p, String identifier) { + if (p == null) { + return null; + } + switch (identifier) { + case "time-formatted": + return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_FORMATTED); + case "time-days": + return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_DAYS); + case "time-hours": + return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_HOURS); + case "time-minutes": + return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_MINUTES); + case "time-seconds": + return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_SECONDS); + case "time-seconds-total": + return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_SECONDS_TOTAL); + case "list-name": + return p.isOnline() ? tempfly.getFlightManager().getUser(p).getListPlaceholder() : ""; + case "name-tag": + return p.isOnline() ? tempfly.getFlightManager().getUser(p).getTagPlaceholder() : ""; + default: + return "Invalid placeholder.. :( "; + } + } + } +} diff --git a/TempFly/src/com/moneybags/tempfly/aesthetic/MvdWAPI.java b/src/com/moneybags/tempfly/aesthetic/MvdWAPI.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/aesthetic/MvdWAPI.java rename to src/com/moneybags/tempfly/aesthetic/MvdWAPI.java index 36156a1..4f6f221 100644 --- a/TempFly/src/com/moneybags/tempfly/aesthetic/MvdWAPI.java +++ b/src/com/moneybags/tempfly/aesthetic/MvdWAPI.java @@ -1,107 +1,107 @@ -package com.moneybags.tempfly.aesthetic; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.time.TimeManager.Placeholder; - -import be.maximvdw.placeholderapi.PlaceholderAPI; -import be.maximvdw.placeholderapi.PlaceholderReplaceEvent; -import be.maximvdw.placeholderapi.PlaceholderReplacer; - - -public class MvdWAPI { - - public static void initialize(TempFly tempfly) { - if (Bukkit.getPluginManager().isPluginEnabled("MVdWPlaceholderAPI")) { - - PlaceholderAPI.registerPlaceholder(tempfly, "tempfly_time_formatted", new PlaceholderReplacer() { - @Override - public String onPlaceholderReplace(PlaceholderReplaceEvent e) { - Player p = e.getPlayer(); - if (p != null){ - return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_FORMATTED); - } - return null; - } - }); - - PlaceholderAPI.registerPlaceholder(tempfly, "tempfly_time_days", new PlaceholderReplacer() { - @Override - public String onPlaceholderReplace(PlaceholderReplaceEvent e) { - Player p = e.getPlayer(); - if (p != null){ - return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_DAYS); - } - return null; - } - }); - - PlaceholderAPI.registerPlaceholder(tempfly, "tempfly_time_hours", new PlaceholderReplacer() { - @Override - public String onPlaceholderReplace(PlaceholderReplaceEvent e) { - Player p = e.getPlayer(); - if (p != null){ - return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_HOURS); - } - return null; - } - }); - - PlaceholderAPI.registerPlaceholder(tempfly, "tempfly_time_minutes", new PlaceholderReplacer() { - @Override - public String onPlaceholderReplace(PlaceholderReplaceEvent e) { - Player p = e.getPlayer(); - if (p != null){ - return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_MINUTES); - } - return null; - } - }); - - PlaceholderAPI.registerPlaceholder(tempfly, "tempfly_time_seconds", new PlaceholderReplacer() { - @Override - public String onPlaceholderReplace(PlaceholderReplaceEvent e) { - Player p = e.getPlayer(); - if (p != null){ - return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_SECONDS); - } - return null; - } - }); - - PlaceholderAPI.registerPlaceholder(tempfly, "tempfly_time_seconds_total", new PlaceholderReplacer() { - @Override - public String onPlaceholderReplace(PlaceholderReplaceEvent e) { - Player p = e.getPlayer(); - if (p != null){ - return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_SECONDS_TOTAL); - } - return null; - } - }); - - PlaceholderAPI.registerPlaceholder(tempfly, "tempfly_list_name", new PlaceholderReplacer() { - @Override - public String onPlaceholderReplace(PlaceholderReplaceEvent e) { - Player p = e.getPlayer(); - if (p != null && p.isOnline()) { - return tempfly.getFlightManager().getUser(p).getListPlaceholder(); - } - return null; - } - }); - PlaceholderAPI.registerPlaceholder(tempfly, "tempfly_name_tag", new PlaceholderReplacer() { - @Override - public String onPlaceholderReplace(PlaceholderReplaceEvent e) { - Player p = e.getPlayer(); - if (p != null && p.isOnline()){ - return tempfly.getFlightManager().getUser(p).getTagPlaceholder(); - } - return null; - } - }); - } - } -} +package com.moneybags.tempfly.aesthetic; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.time.TimeManager.Placeholder; + +import be.maximvdw.placeholderapi.PlaceholderAPI; +import be.maximvdw.placeholderapi.PlaceholderReplaceEvent; +import be.maximvdw.placeholderapi.PlaceholderReplacer; + + +public class MvdWAPI { + + public static void initialize(TempFly tempfly) { + if (Bukkit.getPluginManager().isPluginEnabled("MVdWPlaceholderAPI")) { + + PlaceholderAPI.registerPlaceholder(tempfly, "tempfly_time_formatted", new PlaceholderReplacer() { + @Override + public String onPlaceholderReplace(PlaceholderReplaceEvent e) { + Player p = e.getPlayer(); + if (p != null){ + return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_FORMATTED); + } + return null; + } + }); + + PlaceholderAPI.registerPlaceholder(tempfly, "tempfly_time_days", new PlaceholderReplacer() { + @Override + public String onPlaceholderReplace(PlaceholderReplaceEvent e) { + Player p = e.getPlayer(); + if (p != null){ + return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_DAYS); + } + return null; + } + }); + + PlaceholderAPI.registerPlaceholder(tempfly, "tempfly_time_hours", new PlaceholderReplacer() { + @Override + public String onPlaceholderReplace(PlaceholderReplaceEvent e) { + Player p = e.getPlayer(); + if (p != null){ + return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_HOURS); + } + return null; + } + }); + + PlaceholderAPI.registerPlaceholder(tempfly, "tempfly_time_minutes", new PlaceholderReplacer() { + @Override + public String onPlaceholderReplace(PlaceholderReplaceEvent e) { + Player p = e.getPlayer(); + if (p != null){ + return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_MINUTES); + } + return null; + } + }); + + PlaceholderAPI.registerPlaceholder(tempfly, "tempfly_time_seconds", new PlaceholderReplacer() { + @Override + public String onPlaceholderReplace(PlaceholderReplaceEvent e) { + Player p = e.getPlayer(); + if (p != null){ + return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_SECONDS); + } + return null; + } + }); + + PlaceholderAPI.registerPlaceholder(tempfly, "tempfly_time_seconds_total", new PlaceholderReplacer() { + @Override + public String onPlaceholderReplace(PlaceholderReplaceEvent e) { + Player p = e.getPlayer(); + if (p != null){ + return tempfly.getTimeManager().getPlaceHolder(p, Placeholder.TIME_SECONDS_TOTAL); + } + return null; + } + }); + + PlaceholderAPI.registerPlaceholder(tempfly, "tempfly_list_name", new PlaceholderReplacer() { + @Override + public String onPlaceholderReplace(PlaceholderReplaceEvent e) { + Player p = e.getPlayer(); + if (p != null && p.isOnline()) { + return tempfly.getFlightManager().getUser(p).getListPlaceholder(); + } + return null; + } + }); + PlaceholderAPI.registerPlaceholder(tempfly, "tempfly_name_tag", new PlaceholderReplacer() { + @Override + public String onPlaceholderReplace(PlaceholderReplaceEvent e) { + Player p = e.getPlayer(); + if (p != null && p.isOnline()){ + return tempfly.getFlightManager().getUser(p).getTagPlaceholder(); + } + return null; + } + }); + } + } +} diff --git a/TempFly/src/com/moneybags/tempfly/aesthetic/TitleAPI.java b/src/com/moneybags/tempfly/aesthetic/TitleAPI.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/aesthetic/TitleAPI.java rename to src/com/moneybags/tempfly/aesthetic/TitleAPI.java index b4d327b..a272221 100644 --- a/TempFly/src/com/moneybags/tempfly/aesthetic/TitleAPI.java +++ b/src/com/moneybags/tempfly/aesthetic/TitleAPI.java @@ -1,30 +1,30 @@ -package com.moneybags.tempfly.aesthetic; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.aesthetic.title.LegacyTitle; -import com.moneybags.tempfly.aesthetic.title.ModernTitle; -import com.moneybags.tempfly.aesthetic.title.Title; - -public class TitleAPI { - - private static Title title; - - public static void initialize(TempFly tempfly) { - if (Bukkit.getServer().getVersion().matches(".*1\\.(?!10|11)\\d{2,}.*")) { - title = new ModernTitle(); - } else { - title = new LegacyTitle(); - } - } - - public static void sendTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String title, String subtitle) { - TitleAPI.title.sendTitle(player, fadeIn, stay, fadeOut, title, subtitle); - } - - public static void clearTitle(Player player) { - TitleAPI.title.clearTitle(player); - } -} +package com.moneybags.tempfly.aesthetic; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.aesthetic.title.LegacyTitle; +import com.moneybags.tempfly.aesthetic.title.ModernTitle; +import com.moneybags.tempfly.aesthetic.title.Title; + +public class TitleAPI { + + private static Title title; + + public static void initialize(TempFly tempfly) { + if (Bukkit.getServer().getVersion().matches(".*1\\.(?!10|11)\\d{2,}.*")) { + title = new ModernTitle(); + } else { + title = new LegacyTitle(); + } + } + + public static void sendTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String title, String subtitle) { + TitleAPI.title.sendTitle(player, fadeIn, stay, fadeOut, title, subtitle); + } + + public static void clearTitle(Player player) { + TitleAPI.title.clearTitle(player); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/aesthetic/actionbar/ActionBar.java b/src/com/moneybags/tempfly/aesthetic/actionbar/ActionBar.java similarity index 100% rename from TempFly/src/com/moneybags/tempfly/aesthetic/actionbar/ActionBar.java rename to src/com/moneybags/tempfly/aesthetic/actionbar/ActionBar.java diff --git a/TempFly/src/com/moneybags/tempfly/aesthetic/actionbar/LegacyActionBar.java b/src/com/moneybags/tempfly/aesthetic/actionbar/LegacyActionBar.java similarity index 100% rename from TempFly/src/com/moneybags/tempfly/aesthetic/actionbar/LegacyActionBar.java rename to src/com/moneybags/tempfly/aesthetic/actionbar/LegacyActionBar.java diff --git a/TempFly/src/com/moneybags/tempfly/aesthetic/actionbar/ModernActionBar.java b/src/com/moneybags/tempfly/aesthetic/actionbar/ModernActionBar.java similarity index 100% rename from TempFly/src/com/moneybags/tempfly/aesthetic/actionbar/ModernActionBar.java rename to src/com/moneybags/tempfly/aesthetic/actionbar/ModernActionBar.java diff --git a/TempFly/src/com/moneybags/tempfly/aesthetic/particle/Particles.java b/src/com/moneybags/tempfly/aesthetic/particle/Particles.java similarity index 97% rename from TempFly/src/com/moneybags/tempfly/aesthetic/particle/Particles.java rename to src/com/moneybags/tempfly/aesthetic/particle/Particles.java index 44dd8b9..859ec0d 100644 --- a/TempFly/src/com/moneybags/tempfly/aesthetic/particle/Particles.java +++ b/src/com/moneybags/tempfly/aesthetic/particle/Particles.java @@ -1,99 +1,99 @@ -package com.moneybags.tempfly.aesthetic.particle; - -import java.util.Random; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.Color; -import org.bukkit.Effect; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Particle; -import org.bukkit.Particle.DustOptions; -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.user.FlightUser; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.V; -import com.moneybags.tempfly.util.data.DataBridge.DataValue; -import com.moneybags.tempfly.util.data.DataPointer; - -public class Particles { - - private static Class - dustOptions = null, - blockData; - private static TempFly tempfly; - private static boolean oldParticles; - - public static void initialize(TempFly plugin) { - tempfly = plugin; - try {dustOptions = Class.forName("org.bukkit.Particle$DustOptions");} catch (Exception e) {} - try {blockData = Class.forName("org.bukkit.block.data.BlockData");} catch (Exception e) {} - oldParticles = oldParticles(); - } - - public static boolean oldParticles() { - String version = Bukkit.getVersion(); - return (version.contains("1.6")) || (version.contains("1.7")) || (version.contains("1.8")) || version.contains("1.9"); - } - - public static void play(Location loc, String s) { - if (!oldParticles) { - Particle particle = null; - try {particle = Particle.valueOf(s.toUpperCase());} catch (Exception e1) { - try {particle = Particle.valueOf(V.particleType.toUpperCase());} catch (Exception e2) { - particle = Particle.VILLAGER_HAPPY; - }; - } - - Class c = particle.getDataType(); - try { - if (dustOptions != null && dustOptions.equals(c)) { - Random rand = new Random(); - loc.getWorld().spawnParticle(particle, loc, 1, new DustOptions(Color.fromRGB(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)), 2f)); - } else if (blockData != null && blockData.equals(c)) { - loc.getWorld().spawnParticle(particle, loc, 1, Material.STONE.createBlockData()); - } else { - loc.getWorld().spawnParticle(particle, loc, 1, 0, 0, 0, 0.1); - } - } catch (Exception e) { - loc.getWorld().spawnParticle(Particle.VILLAGER_HAPPY, loc, 1, 0, 0, 0, 0.1); - } - } else { - Effect particle = null; - // This effect value crashes clients and prevents them from joining the server again. - if (s != null && s.equalsIgnoreCase("ITEM_BREAK")) { - s = "HAPPY_VILLAGER"; - } - try {particle = Effect.valueOf(s.toUpperCase());} catch (Exception e1) { - try {particle = Effect.valueOf(V.particleType);} catch (Exception e2) { - particle = Effect.valueOf("HAPPY_VILLAGER"); - } - } - loc.getWorld().playEffect(loc, particle, 1); - } - } - - public static String loadTrail(UUID u) { - String particle = (String) tempfly.getDataBridge().getOrDefault(DataPointer.of(DataValue.PLAYER_TRAIL, u.toString()), null); - if (V.debug) {Console.debug("", "------Loading particle trail------", "Player: " + u.toString(), "Value from data: " + String.valueOf(particle), "Default trail enabled: " + V.particleDefault, "Default trail is: " + V.particleType, "Returning trail: " + (particle != null ? particle: (V.particleDefault ? V.particleType : "")), "------End particle trail------", "");} - return particle != null ? particle: (V.particleDefault ? V.particleType : ""); - } - - /** - * Set a players particle trail. - * If particle is set to null or if the trail specified does not exist TempFly will attempt to use the default trail if enabled in the config. - * If it is set to an empty string however the particle will be disabled, IE no trail. This is what the remove trail command does. - * @param u the player - * @param particle the particle - */ - public static void setTrail(UUID u, String particle) { - FlightUser user = tempfly.getFlightManager().getUser(Bukkit.getPlayer(u)); - if (user != null) { - user.setTrail(particle); - return; - } - tempfly.getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_TRAIL, u.toString()), particle); - } - -} +package com.moneybags.tempfly.aesthetic.particle; + +import java.util.Random; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Effect; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.Particle.DustOptions; +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.user.FlightUser; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.V; +import com.moneybags.tempfly.util.data.DataBridge.DataValue; +import com.moneybags.tempfly.util.data.DataPointer; + +public class Particles { + + private static Class + dustOptions = null, + blockData; + private static TempFly tempfly; + private static boolean oldParticles; + + public static void initialize(TempFly plugin) { + tempfly = plugin; + try {dustOptions = Class.forName("org.bukkit.Particle$DustOptions");} catch (Exception e) {} + try {blockData = Class.forName("org.bukkit.block.data.BlockData");} catch (Exception e) {} + oldParticles = oldParticles(); + } + + public static boolean oldParticles() { + String version = Bukkit.getVersion(); + return (version.contains("1.6")) || (version.contains("1.7")) || (version.contains("1.8")) || version.contains("1.9"); + } + + public static void play(Location loc, String s) { + if (!oldParticles) { + Particle particle = null; + try {particle = Particle.valueOf(s.toUpperCase());} catch (Exception e1) { + try {particle = Particle.valueOf(V.particleType.toUpperCase());} catch (Exception e2) { + particle = Particle.VILLAGER_HAPPY; + }; + } + + Class c = particle.getDataType(); + try { + if (dustOptions != null && dustOptions.equals(c)) { + Random rand = new Random(); + loc.getWorld().spawnParticle(particle, loc, 1, new DustOptions(Color.fromRGB(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)), 2f)); + } else if (blockData != null && blockData.equals(c)) { + loc.getWorld().spawnParticle(particle, loc, 1, Material.STONE.createBlockData()); + } else { + loc.getWorld().spawnParticle(particle, loc, 1, 0, 0, 0, 0.1); + } + } catch (Exception e) { + loc.getWorld().spawnParticle(Particle.VILLAGER_HAPPY, loc, 1, 0, 0, 0, 0.1); + } + } else { + Effect particle = null; + // This effect value crashes clients and prevents them from joining the server again. + if (s != null && s.equalsIgnoreCase("ITEM_BREAK")) { + s = "HAPPY_VILLAGER"; + } + try {particle = Effect.valueOf(s.toUpperCase());} catch (Exception e1) { + try {particle = Effect.valueOf(V.particleType);} catch (Exception e2) { + particle = Effect.valueOf("HAPPY_VILLAGER"); + } + } + loc.getWorld().playEffect(loc, particle, 1); + } + } + + public static String loadTrail(UUID u) { + String particle = (String) tempfly.getDataBridge().getOrDefault(DataPointer.of(DataValue.PLAYER_TRAIL, u.toString()), null); + if (V.debug) {Console.debug("", "------Loading particle trail------", "Player: " + u.toString(), "Value from data: " + String.valueOf(particle), "Default trail enabled: " + V.particleDefault, "Default trail is: " + V.particleType, "Returning trail: " + (particle != null ? particle: (V.particleDefault ? V.particleType : "")), "------End particle trail------", "");} + return particle != null ? particle: (V.particleDefault ? V.particleType : ""); + } + + /** + * Set a players particle trail. + * If particle is set to null or if the trail specified does not exist TempFly will attempt to use the default trail if enabled in the config. + * If it is set to an empty string however the particle will be disabled, IE no trail. This is what the remove trail command does. + * @param u the player + * @param particle the particle + */ + public static void setTrail(UUID u, String particle) { + FlightUser user = tempfly.getFlightManager().getUser(Bukkit.getPlayer(u)); + if (user != null) { + user.setTrail(particle); + return; + } + tempfly.getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_TRAIL, u.toString()), particle); + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/aesthetic/title/LegacyTitle.java b/src/com/moneybags/tempfly/aesthetic/title/LegacyTitle.java similarity index 98% rename from TempFly/src/com/moneybags/tempfly/aesthetic/title/LegacyTitle.java rename to src/com/moneybags/tempfly/aesthetic/title/LegacyTitle.java index 435badb..95dba05 100644 --- a/TempFly/src/com/moneybags/tempfly/aesthetic/title/LegacyTitle.java +++ b/src/com/moneybags/tempfly/aesthetic/title/LegacyTitle.java @@ -1,90 +1,90 @@ -package com.moneybags.tempfly.aesthetic.title; - -import java.lang.reflect.Constructor; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.event.TitleSendEvent; -import com.moneybags.tempfly.util.U; - -public class LegacyTitle implements Title { - - 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(); - } - } - - public static Class getNMSClass(String name) { - String version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; - try { - return Class.forName("net.minecraft.server." + version + "." + name); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - return null; - } - } - - @Override - public void sendTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String title, String subtitle) { - TitleSendEvent titleSendEvent = new TitleSendEvent(player, title, subtitle); - Bukkit.getPluginManager().callEvent(titleSendEvent); - if (titleSendEvent.isCancelled()) - return; - - try { - Object e; - Object chatTitle; - Object chatSubtitle; - Constructor subtitleConstructor; - Object titlePacket; - Object subtitlePacket; - - if (title != null) { - title = U.cc(title); - title = title.replaceAll("%player%", player.getDisplayName()); - // Times packets - e = getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0].getField("TIMES").get((Object) null); - chatTitle = getNMSClass("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", new Class[]{String.class}).invoke((Object) null, new Object[]{"{\"text\":\"" + title + "\"}"}); - subtitleConstructor = getNMSClass("PacketPlayOutTitle").getConstructor(new Class[]{getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0], getNMSClass("IChatBaseComponent"), Integer.TYPE, Integer.TYPE, Integer.TYPE}); - titlePacket = subtitleConstructor.newInstance(new Object[]{e, chatTitle, fadeIn, stay, fadeOut}); - sendPacket(player, titlePacket); - - e = getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0].getField("TITLE").get((Object) null); - chatTitle = getNMSClass("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", new Class[]{String.class}).invoke((Object) null, new Object[]{"{\"text\":\"" + title + "\"}"}); - subtitleConstructor = getNMSClass("PacketPlayOutTitle").getConstructor(new Class[]{getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0], getNMSClass("IChatBaseComponent")}); - titlePacket = subtitleConstructor.newInstance(new Object[]{e, chatTitle}); - sendPacket(player, titlePacket); - } - - if (subtitle != null) { - subtitle = U.cc(subtitle); - subtitle = subtitle.replaceAll("%player%", player.getDisplayName()); - // Times packets - e = getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0].getField("TIMES").get((Object) null); - chatSubtitle = getNMSClass("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", new Class[]{String.class}).invoke((Object) null, new Object[]{"{\"text\":\"" + title + "\"}"}); - subtitleConstructor = getNMSClass("PacketPlayOutTitle").getConstructor(new Class[]{getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0], getNMSClass("IChatBaseComponent"), Integer.TYPE, Integer.TYPE, Integer.TYPE}); - subtitlePacket = subtitleConstructor.newInstance(new Object[]{e, chatSubtitle, fadeIn, stay, fadeOut}); - sendPacket(player, subtitlePacket); - - e = getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0].getField("SUBTITLE").get((Object) null); - chatSubtitle = getNMSClass("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", new Class[]{String.class}).invoke((Object) null, new Object[]{"{\"text\":\"" + subtitle + "\"}"}); - subtitleConstructor = getNMSClass("PacketPlayOutTitle").getConstructor(new Class[]{getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0], getNMSClass("IChatBaseComponent"), Integer.TYPE, Integer.TYPE, Integer.TYPE}); - subtitlePacket = subtitleConstructor.newInstance(new Object[]{e, chatSubtitle, fadeIn, stay, fadeOut}); - sendPacket(player, subtitlePacket); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public void clearTitle(Player player) { - this.sendTitle(player, 0, 0, 0, "", ""); - } -} +package com.moneybags.tempfly.aesthetic.title; + +import java.lang.reflect.Constructor; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.event.TitleSendEvent; +import com.moneybags.tempfly.util.U; + +public class LegacyTitle implements Title { + + 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(); + } + } + + public static Class getNMSClass(String name) { + String version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; + try { + return Class.forName("net.minecraft.server." + version + "." + name); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + return null; + } + } + + @Override + public void sendTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String title, String subtitle) { + TitleSendEvent titleSendEvent = new TitleSendEvent(player, title, subtitle); + Bukkit.getPluginManager().callEvent(titleSendEvent); + if (titleSendEvent.isCancelled()) + return; + + try { + Object e; + Object chatTitle; + Object chatSubtitle; + Constructor subtitleConstructor; + Object titlePacket; + Object subtitlePacket; + + if (title != null) { + title = U.cc(title); + title = title.replaceAll("%player%", player.getDisplayName()); + // Times packets + e = getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0].getField("TIMES").get((Object) null); + chatTitle = getNMSClass("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", new Class[]{String.class}).invoke((Object) null, new Object[]{"{\"text\":\"" + title + "\"}"}); + subtitleConstructor = getNMSClass("PacketPlayOutTitle").getConstructor(new Class[]{getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0], getNMSClass("IChatBaseComponent"), Integer.TYPE, Integer.TYPE, Integer.TYPE}); + titlePacket = subtitleConstructor.newInstance(new Object[]{e, chatTitle, fadeIn, stay, fadeOut}); + sendPacket(player, titlePacket); + + e = getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0].getField("TITLE").get((Object) null); + chatTitle = getNMSClass("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", new Class[]{String.class}).invoke((Object) null, new Object[]{"{\"text\":\"" + title + "\"}"}); + subtitleConstructor = getNMSClass("PacketPlayOutTitle").getConstructor(new Class[]{getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0], getNMSClass("IChatBaseComponent")}); + titlePacket = subtitleConstructor.newInstance(new Object[]{e, chatTitle}); + sendPacket(player, titlePacket); + } + + if (subtitle != null) { + subtitle = U.cc(subtitle); + subtitle = subtitle.replaceAll("%player%", player.getDisplayName()); + // Times packets + e = getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0].getField("TIMES").get((Object) null); + chatSubtitle = getNMSClass("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", new Class[]{String.class}).invoke((Object) null, new Object[]{"{\"text\":\"" + title + "\"}"}); + subtitleConstructor = getNMSClass("PacketPlayOutTitle").getConstructor(new Class[]{getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0], getNMSClass("IChatBaseComponent"), Integer.TYPE, Integer.TYPE, Integer.TYPE}); + subtitlePacket = subtitleConstructor.newInstance(new Object[]{e, chatSubtitle, fadeIn, stay, fadeOut}); + sendPacket(player, subtitlePacket); + + e = getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0].getField("SUBTITLE").get((Object) null); + chatSubtitle = getNMSClass("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", new Class[]{String.class}).invoke((Object) null, new Object[]{"{\"text\":\"" + subtitle + "\"}"}); + subtitleConstructor = getNMSClass("PacketPlayOutTitle").getConstructor(new Class[]{getNMSClass("PacketPlayOutTitle").getDeclaredClasses()[0], getNMSClass("IChatBaseComponent"), Integer.TYPE, Integer.TYPE, Integer.TYPE}); + subtitlePacket = subtitleConstructor.newInstance(new Object[]{e, chatSubtitle, fadeIn, stay, fadeOut}); + sendPacket(player, subtitlePacket); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + public void clearTitle(Player player) { + this.sendTitle(player, 0, 0, 0, "", ""); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/aesthetic/title/ModernTitle.java b/src/com/moneybags/tempfly/aesthetic/title/ModernTitle.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/aesthetic/title/ModernTitle.java rename to src/com/moneybags/tempfly/aesthetic/title/ModernTitle.java index 0c2f4e2..8f515c3 100644 --- a/TempFly/src/com/moneybags/tempfly/aesthetic/title/ModernTitle.java +++ b/src/com/moneybags/tempfly/aesthetic/title/ModernTitle.java @@ -1,16 +1,16 @@ -package com.moneybags.tempfly.aesthetic.title; - -import org.bukkit.entity.Player; - -public class ModernTitle implements Title { - - @Override - public void sendTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String title, String subtitle) { - player.sendTitle(title, subtitle, fadeIn, stay, fadeOut); - } - - @Override - public void clearTitle(Player player) { - player.sendTitle("", "", 0, 0, 0); - } -} +package com.moneybags.tempfly.aesthetic.title; + +import org.bukkit.entity.Player; + +public class ModernTitle implements Title { + + @Override + public void sendTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String title, String subtitle) { + player.sendTitle(title, subtitle, fadeIn, stay, fadeOut); + } + + @Override + public void clearTitle(Player player) { + player.sendTitle("", "", 0, 0, 0); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/aesthetic/title/Title.java b/src/com/moneybags/tempfly/aesthetic/title/Title.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/aesthetic/title/Title.java rename to src/com/moneybags/tempfly/aesthetic/title/Title.java index 9e97ade..b13bcde 100644 --- a/TempFly/src/com/moneybags/tempfly/aesthetic/title/Title.java +++ b/src/com/moneybags/tempfly/aesthetic/title/Title.java @@ -1,10 +1,10 @@ -package com.moneybags.tempfly.aesthetic.title; - -import org.bukkit.entity.Player; - -public interface Title { - - void sendTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String title, String subtitle); - - void clearTitle(Player player); -} +package com.moneybags.tempfly.aesthetic.title; + +import org.bukkit.entity.Player; + +public interface Title { + + void sendTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String title, String subtitle); + + void clearTitle(Player player); +} diff --git a/TempFly/src/com/moneybags/tempfly/combat/CombatHandler.java b/src/com/moneybags/tempfly/combat/CombatHandler.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/combat/CombatHandler.java rename to src/com/moneybags/tempfly/combat/CombatHandler.java index e67fd2b..f7aaa0b 100644 --- a/TempFly/src/com/moneybags/tempfly/combat/CombatHandler.java +++ b/src/com/moneybags/tempfly/combat/CombatHandler.java @@ -1,194 +1,194 @@ -package com.moneybags.tempfly.combat; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.PlayerDeathEvent; -import com.moneybags.tempfly.fly.FlightManager; -import com.moneybags.tempfly.fly.RequirementProvider; -import com.moneybags.tempfly.fly.result.FlightResult.DenyReason; -import com.moneybags.tempfly.fly.result.ResultAllow; -import com.moneybags.tempfly.fly.result.ResultDeny; -import com.moneybags.tempfly.user.FlightUser; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.V; - -public class CombatHandler implements RequirementProvider, Listener { - - private FlightManager manager; - - private Map tags = new HashMap<>(); - - public CombatHandler(FlightManager manager) { - this.manager = manager; - manager.getTempFly().getServer().getPluginManager().registerEvents(this, manager.getTempFly()); - } - - public FlightManager getFlightManager() { - return manager; - } - - public void processCombat(Entity vic, Entity act) { - if (act instanceof Projectile) { - if (!(((Projectile)act).getShooter() instanceof Entity)) { - return; - } - act = (Entity) ((Projectile)act).getShooter(); - } - if (vic instanceof Player) { - if (act instanceof Player) { - if (act.equals(vic)) { - onCombat(CombatType.FLYER_ATTACKS_SELF, vic, act); - } else { - onCombat(CombatType.PLAYER_ATTACKS_FLYER, vic, act); - onCombat(CombatType.FLYER_ATTACKS_PLAYER, vic, act); - } - } else if (act instanceof LivingEntity) { - onCombat(CombatType.MOB_ATTACKS_FLYER, vic, act); - } - } else if (vic instanceof LivingEntity) { - if (act instanceof Player) { - onCombat(CombatType.FLYER_ATTACKS_MOB, vic, act); - } - } - } - - public void onCombat(CombatType type, Entity vic, Entity act) { - if (!combatDisable(type)) { - return; - } - - if (!(act instanceof Player) && !(vic instanceof Player)) { - return; - } - - Player p = (type == CombatType.FLYER_ATTACKS_MOB || type == CombatType.FLYER_ATTACKS_PLAYER) ? (Player)act : (Player)vic; - FlightUser user = manager.getUser(p); - if (user == null) { - return; - } - addTag(p.getUniqueId(), type.isPvp() ? V.combatTagPvp : V.combatTagPve); - user.submitFlightResult(new ResultDeny(DenyReason.COMBAT, this, InquiryType.OUT_OF_SCOPE, V.requireFailCombat, !V.damageCombat)); - } - - public boolean combatDisable(CombatType type) { - switch (type) { - case FLYER_ATTACKS_MOB: - return V.tagAttackMob; - case FLYER_ATTACKS_PLAYER: - return V.tagAttackPlayer; - case MOB_ATTACKS_FLYER: - return V.tagAttackedByMob; - case PLAYER_ATTACKS_FLYER: - return V.tagAttackedByPlayer; - case FLYER_ATTACKS_SELF: - return V.tagAttackedBySelf; - } - return false; - } - - public enum CombatType { - PLAYER_ATTACKS_FLYER(true), - MOB_ATTACKS_FLYER(false), - FLYER_ATTACKS_PLAYER(true), - FLYER_ATTACKS_MOB(false), - FLYER_ATTACKS_SELF(true); - - private boolean pvp; - - private CombatType(boolean pvp) { - this.pvp = pvp; - } - - public boolean isPvp() { - return pvp; - } - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void on(PlayerDeathEvent e) { - Player p = e.getEntity(); - if (isTagged(p.getUniqueId())) { - cancelTag(p.getUniqueId()); - } - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void on(EntityDamageByEntityEvent e) { - Entity vic = e.getEntity(); - Entity act = e.getDamager(); - processCombat(vic, act); - } - - public boolean isTagged(UUID u) { - return tags.containsKey(u); - } - - public CombatTag getTag(UUID u) { - return tags.get(u); - } - - public void cancelTag(UUID u) { - if (isTagged(u)) { - getTag(u).cancel(); - tags.remove(u); - } - - Player p = Bukkit.getPlayer(u); - if (p != null && p.isOnline()) { - evaluate(manager.getUser(p)); - } - } - - public void addTag(UUID u, int time) { - Console.debug("Adding combat tag for player, time=: " + time); - if (isTagged(u)) { - Console.debug("Player is already tagged!"); - CombatTag current = getTag(u); - // If combat PvP is longer than PvE, we don't want users escaping PvP by attacking a sheep and having their combat time reset to the PvE timer. - if (current.getRemainingTime() > time) { - Console.debug("Current tag has more time remaining than the new tag! returning."); - return; - } - Console.debug("Canceling players current tag!"); - current.cancel(); - } - tags.put(u, new CombatTag(u, time, this)); - } - - private void evaluate(FlightUser user) { - if (user == null) { - return; - } - if (!isTagged(user.getPlayer().getUniqueId())) { - if (user.hasFlightRequirement(this)) { - Console.debug("", "--|> User has combat requirement but is no longer tagged!"); - user.submitFlightResult(new ResultAllow(this, InquiryType.OUT_OF_SCOPE, V.requirePassCombat)); - } - return; - } - user.submitFlightResult(new ResultDeny(DenyReason.COMBAT, this, InquiryType.OUT_OF_SCOPE, V.requireFailCombat, !V.damageCombat)); - } - - @Override - public boolean handles(InquiryType type) { - return true; - } - - @Override - public void onUserInitialized(FlightUser user) { - if (tags.containsKey(user.getPlayer().getUniqueId())) { - user.submitFlightResult(new ResultDeny(DenyReason.COMBAT, this, InquiryType.OUT_OF_SCOPE, V.requireFailCombat, false)); - } - } -} +package com.moneybags.tempfly.combat; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import com.moneybags.tempfly.fly.FlightManager; +import com.moneybags.tempfly.fly.RequirementProvider; +import com.moneybags.tempfly.fly.result.FlightResult.DenyReason; +import com.moneybags.tempfly.fly.result.ResultAllow; +import com.moneybags.tempfly.fly.result.ResultDeny; +import com.moneybags.tempfly.user.FlightUser; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.V; + +public class CombatHandler implements RequirementProvider, Listener { + + private FlightManager manager; + + private Map tags = new HashMap<>(); + + public CombatHandler(FlightManager manager) { + this.manager = manager; + manager.getTempFly().getServer().getPluginManager().registerEvents(this, manager.getTempFly()); + } + + public FlightManager getFlightManager() { + return manager; + } + + public void processCombat(Entity vic, Entity act) { + if (act instanceof Projectile) { + if (!(((Projectile)act).getShooter() instanceof Entity)) { + return; + } + act = (Entity) ((Projectile)act).getShooter(); + } + if (vic instanceof Player) { + if (act instanceof Player) { + if (act.equals(vic)) { + onCombat(CombatType.FLYER_ATTACKS_SELF, vic, act); + } else { + onCombat(CombatType.PLAYER_ATTACKS_FLYER, vic, act); + onCombat(CombatType.FLYER_ATTACKS_PLAYER, vic, act); + } + } else if (act instanceof LivingEntity) { + onCombat(CombatType.MOB_ATTACKS_FLYER, vic, act); + } + } else if (vic instanceof LivingEntity) { + if (act instanceof Player) { + onCombat(CombatType.FLYER_ATTACKS_MOB, vic, act); + } + } + } + + public void onCombat(CombatType type, Entity vic, Entity act) { + if (!combatDisable(type)) { + return; + } + + if (!(act instanceof Player) && !(vic instanceof Player)) { + return; + } + + Player p = (type == CombatType.FLYER_ATTACKS_MOB || type == CombatType.FLYER_ATTACKS_PLAYER) ? (Player)act : (Player)vic; + FlightUser user = manager.getUser(p); + if (user == null) { + return; + } + addTag(p.getUniqueId(), type.isPvp() ? V.combatTagPvp : V.combatTagPve); + user.submitFlightResult(new ResultDeny(DenyReason.COMBAT, this, InquiryType.OUT_OF_SCOPE, V.requireFailCombat, !V.damageCombat)); + } + + public boolean combatDisable(CombatType type) { + switch (type) { + case FLYER_ATTACKS_MOB: + return V.tagAttackMob; + case FLYER_ATTACKS_PLAYER: + return V.tagAttackPlayer; + case MOB_ATTACKS_FLYER: + return V.tagAttackedByMob; + case PLAYER_ATTACKS_FLYER: + return V.tagAttackedByPlayer; + case FLYER_ATTACKS_SELF: + return V.tagAttackedBySelf; + } + return false; + } + + public enum CombatType { + PLAYER_ATTACKS_FLYER(true), + MOB_ATTACKS_FLYER(false), + FLYER_ATTACKS_PLAYER(true), + FLYER_ATTACKS_MOB(false), + FLYER_ATTACKS_SELF(true); + + private boolean pvp; + + private CombatType(boolean pvp) { + this.pvp = pvp; + } + + public boolean isPvp() { + return pvp; + } + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void on(PlayerDeathEvent e) { + Player p = e.getEntity(); + if (isTagged(p.getUniqueId())) { + cancelTag(p.getUniqueId()); + } + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void on(EntityDamageByEntityEvent e) { + Entity vic = e.getEntity(); + Entity act = e.getDamager(); + processCombat(vic, act); + } + + public boolean isTagged(UUID u) { + return tags.containsKey(u); + } + + public CombatTag getTag(UUID u) { + return tags.get(u); + } + + public void cancelTag(UUID u) { + if (isTagged(u)) { + getTag(u).cancel(); + tags.remove(u); + } + + Player p = Bukkit.getPlayer(u); + if (p != null && p.isOnline()) { + evaluate(manager.getUser(p)); + } + } + + public void addTag(UUID u, int time) { + Console.debug("Adding combat tag for player, time=: " + time); + if (isTagged(u)) { + Console.debug("Player is already tagged!"); + CombatTag current = getTag(u); + // If combat PvP is longer than PvE, we don't want users escaping PvP by attacking a sheep and having their combat time reset to the PvE timer. + if (current.getRemainingTime() > time) { + Console.debug("Current tag has more time remaining than the new tag! returning."); + return; + } + Console.debug("Canceling players current tag!"); + current.cancel(); + } + tags.put(u, new CombatTag(u, time, this)); + } + + private void evaluate(FlightUser user) { + if (user == null) { + return; + } + if (!isTagged(user.getPlayer().getUniqueId())) { + if (user.hasFlightRequirement(this)) { + Console.debug("", "--|> User has combat requirement but is no longer tagged!"); + user.submitFlightResult(new ResultAllow(this, InquiryType.OUT_OF_SCOPE, V.requirePassCombat)); + } + return; + } + user.submitFlightResult(new ResultDeny(DenyReason.COMBAT, this, InquiryType.OUT_OF_SCOPE, V.requireFailCombat, !V.damageCombat)); + } + + @Override + public boolean handles(InquiryType type) { + return true; + } + + @Override + public void onUserInitialized(FlightUser user) { + if (tags.containsKey(user.getPlayer().getUniqueId())) { + user.submitFlightResult(new ResultDeny(DenyReason.COMBAT, this, InquiryType.OUT_OF_SCOPE, V.requireFailCombat, false)); + } + } +} diff --git a/TempFly/src/com/moneybags/tempfly/combat/CombatTag.java b/src/com/moneybags/tempfly/combat/CombatTag.java similarity index 94% rename from TempFly/src/com/moneybags/tempfly/combat/CombatTag.java rename to src/com/moneybags/tempfly/combat/CombatTag.java index 2683a8b..45fa925 100644 --- a/TempFly/src/com/moneybags/tempfly/combat/CombatTag.java +++ b/src/com/moneybags/tempfly/combat/CombatTag.java @@ -1,45 +1,45 @@ -package com.moneybags.tempfly.combat; - -import java.util.UUID; - -import org.bukkit.scheduler.BukkitRunnable; - -public class CombatTag extends BukkitRunnable { - - private CombatHandler combat; - private long duration; - private long progress; - private UUID u; - - public CombatTag(UUID u, long duration, CombatHandler combat) { - this.duration = duration; - this.u = u; - this.combat = combat; - this.runTaskTimer(combat.getFlightManager().getTempFly(), 0, 1); - } - - public UUID getPlayer() { - return u; - } - - public long getDuration() { - return duration; - } - - public long getProgress() { - return progress; - } - - public long getRemainingTime() { - return duration-progress; - } - - @Override - public void run() { - progress++; - if (progress >= duration) { - combat.cancelTag(u); - } - } - -} +package com.moneybags.tempfly.combat; + +import java.util.UUID; + +import org.bukkit.scheduler.BukkitRunnable; + +public class CombatTag extends BukkitRunnable { + + private CombatHandler combat; + private long duration; + private long progress; + private UUID u; + + public CombatTag(UUID u, long duration, CombatHandler combat) { + this.duration = duration; + this.u = u; + this.combat = combat; + this.runTaskTimer(combat.getFlightManager().getTempFly(), 0, 1); + } + + public UUID getPlayer() { + return u; + } + + public long getDuration() { + return duration; + } + + public long getProgress() { + return progress; + } + + public long getRemainingTime() { + return duration-progress; + } + + @Override + public void run() { + progress++; + if (progress >= duration) { + combat.cancelTag(u); + } + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/command/CommandManager.java b/src/com/moneybags/tempfly/command/CommandManager.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/command/CommandManager.java rename to src/com/moneybags/tempfly/command/CommandManager.java index 054b6d1..0b51f83 100644 --- a/TempFly/src/com/moneybags/tempfly/command/CommandManager.java +++ b/src/com/moneybags/tempfly/command/CommandManager.java @@ -1,340 +1,340 @@ -package com.moneybags.tempfly.command; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.TimeUnit; - -import org.bukkit.configuration.ConfigurationSection; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.admin.CmdGive; -import com.moneybags.tempfly.command.admin.CmdGiveAll; -import com.moneybags.tempfly.command.admin.CmdMigrate; -import com.moneybags.tempfly.command.admin.CmdReload; -import com.moneybags.tempfly.command.admin.CmdRemove; -import com.moneybags.tempfly.command.admin.CmdSet; -import com.moneybags.tempfly.command.admin.CmdTrailRemove; -import com.moneybags.tempfly.command.admin.CmdTrailSet; -import com.moneybags.tempfly.command.player.CmdBypass; -import com.moneybags.tempfly.command.player.CmdFly; -import com.moneybags.tempfly.command.player.CmdHelp; -import com.moneybags.tempfly.command.player.CmdInfinite; -import com.moneybags.tempfly.command.player.CmdPay; -import com.moneybags.tempfly.command.player.CmdShop; -import com.moneybags.tempfly.command.player.CmdSpeed; -import com.moneybags.tempfly.command.player.CmdTime; -import com.moneybags.tempfly.command.player.CmdTrails; -import com.moneybags.tempfly.util.V; -import com.moneybags.tempfly.util.data.Files; - -public class CommandManager { - - private TempFly tempfly; - private TempFlyExecutor executor; - private TempFlyTabCompleter tab; - - private List enable = new ArrayList<>(); - private List disable = new ArrayList<>(); - - private Map> subCommands = new HashMap<>(); - private Map> timeArgs = new HashMap<>(); - private Map timeComplete = new HashMap<>(); - - private Map> hookRegistry = new HashMap<>(); - - public CommandManager(TempFly tempfly) { - this.tempfly = tempfly; - executor = new TempFlyExecutor(this); - tab = new TempFlyTabCompleter(this); - tempfly.getCommand("tempfly").setExecutor(executor); - tempfly.getCommand("tempfly").setTabCompleter(tab); - - for (CommandType type: CommandType.values()) { - if (!type.isEnabled(tempfly)) { - continue; - } - List subs = Files.lang.getStringList("command.base." + type.toString().toLowerCase()); - if (subs == null || subs.size() == 0) { - subCommands.put(type, Arrays.asList(type.getBase())); - continue; - } - subCommands.put(type, subs); - } - - ConfigurationSection csUnits = Files.lang.getConfigurationSection("command.unit"); - if (csUnits != null) { - String path = "command.unit"; - for (String key: csUnits.getKeys(false)) { - try { - TimeUnit unit = TimeUnit.valueOf(key.toUpperCase()); - List recognized = Files.lang.getStringList(path + "." + key + ".recognized"); - String complete = Files.lang.getString(path + "." + key + ".tab_complete"); - - if (recognized != null) timeArgs.put(unit, recognized); - if (complete != null) timeComplete.put(unit, complete); - } - catch (Exception e) {} - } - } - if (!timeArgs.containsKey(TimeUnit.SECONDS)) - timeArgs.put(TimeUnit.SECONDS, Arrays.asList(TimeType.SECONDS.getBase())); - if (!timeArgs.containsKey(TimeUnit.MINUTES)) - timeArgs.put(TimeUnit.MINUTES, Arrays.asList(TimeType.MINUTES.getBase())); - if (!timeArgs.containsKey(TimeUnit.HOURS)) - timeArgs.put(TimeUnit.HOURS, Arrays.asList(TimeType.HOURS.getBase())); - if (!timeArgs.containsKey(TimeUnit.DAYS)) - timeArgs.put(TimeUnit.DAYS, Arrays.asList(TimeType.DAYS.getBase())); - - if (!timeComplete.containsKey(TimeUnit.SECONDS)) - timeComplete.put(TimeUnit.SECONDS, TimeType.SECONDS.getCompletion()); - if (!timeComplete.containsKey(TimeUnit.MINUTES)) - timeComplete.put(TimeUnit.MINUTES, TimeType.MINUTES.getCompletion()); - if (!timeComplete.containsKey(TimeUnit.HOURS)) - timeComplete.put(TimeUnit.HOURS, TimeType.HOURS.getCompletion()); - if (!timeComplete.containsKey(TimeUnit.DAYS)) - timeComplete.put(TimeUnit.DAYS, TimeType.DAYS.getCompletion()); - - List temp = null; - - enable.addAll((temp = Files.lang.getStringList("command.enable")) == null || temp.size() == 0 ? - Arrays.asList("on", "enable") : temp); - disable.addAll((temp = Files.lang.getStringList("command.disable")) == null || temp.size() == 0 ? - Arrays.asList("off", "disable") : temp); - } - - public TempFlyTabCompleter getTabCompleter() { - return tab; - } - - public TempFly getTempFly() { - return tempfly; - } - - public List getEnable() { - return enable; - } - - public List getDisable() { - return disable; - } - - public List getAllTimeArguments() { - List args = new ArrayList<>(); - for (Entry> unit: timeArgs.entrySet()) { - args.addAll(unit.getValue()); - } - return args; - } - - public List getTimeArguments(TimeUnit unit) { - return timeArgs.getOrDefault(unit, Arrays.asList("{unit}")); - } - - public TimeUnit parseUnit(String s) { - for (Entry> entry: timeArgs.entrySet()) { - if (entry.getValue().contains(s)) { - return entry.getKey(); - } - } - return null; - } - - public List getAllTimeCompletions() { - List args = new ArrayList<>(); - for (Entry unit: timeComplete.entrySet()) { - args.add(unit.getValue()); - } - return args; - } - - public List getTimeCompletions(List exclude) { - List args = new ArrayList<>(); - for (Entry entry: timeComplete.entrySet()) { - if (exclude.contains(entry.getKey())) continue; - args.add(entry.getValue()); - } - return args; - } - - public String getTimeCompletion(TimeUnit unit) { - return timeComplete.getOrDefault(unit, "{unit}"); - } - - public List getToggleCompletions(boolean filter) { - if (filter) return Arrays.asList(enable.get(0), disable.get(0)); - List all = new ArrayList<>(); - all.addAll(enable); all.addAll(disable); - return all; - } - - public TempFlyCommand getCommand(String[] args) { - if (args == null) { - return null; - } - if (args.length == 0 || getEnable().contains(args[0]) || getDisable().contains(args[0])) { - return new CmdFly(tempfly, args); - } else { - for (CommandType type: CommandType.values()) { - for (String base: getCommandBases(type)) { - if (base.equals(args[0])) { - try {return type.getDeclaredClass().getConstructor(TempFly.class, String[].class).newInstance(tempfly, args);} catch (Exception e) { - e.printStackTrace(); - } - } - } - } - for (Entry> entry: hookRegistry.entrySet()) { - if (entry.getKey().equals(args[0])) { - try {return entry.getValue().getConstructor(TempFly.class, String[].class).newInstance(tempfly, args);} catch (Exception e) { - e.printStackTrace(); - } - } - } - } - return null; - } - - public void registerHookCommand(String base, Class command) throws IllegalArgumentException { - if (hookRegistry.containsKey(base)) { - throw new IllegalArgumentException("Sub command bases must be unique! This command is already taken: " + base); - } - - try {command.getConstructor(TempFly.class, String[].class).newInstance(tempfly, new String[0]);} catch (Exception e) { - throw new IllegalArgumentException("This sub command is not properly structured: " + base); - } - hookRegistry.put(base, command); - } - - public void unregisterHookCommand(String base) { - hookRegistry.remove(base); - } - - public List getAllCommandBases() { - List bases = new ArrayList<>(); - bases.addAll(getToggleCompletions(true)); - for (CommandType type: CommandType.values()) { - for (String base: getCommandBases(type)) { - bases.add(base); - } - bases.addAll(hookRegistry.keySet()); - } - return bases; - } - - public List getPartialCommandBases(String partial) { - List matches = new ArrayList<>(); - for (CommandType type: CommandType.values()) { - for (String base: getCommandBases(type)) { - if (compare(base, partial)) { - matches.add(base); - } - } - } - for (String base: getToggleCompletions(false)) { - if (compare(base, partial)) { - matches.add(base); - } - } - - for (String base: hookRegistry.keySet()) { - if (compare(base, partial)) { - matches.add(base); - } - } - - return matches; - } - - private boolean compare(String base, String partial) { - char[] baseChars = base.toCharArray(); - if (partial.length() > baseChars.length) { - return false; - } - for (int i = 0; i < partial.length(); i++) { - char partialChar = partial.charAt(i); - if (partialChar != baseChars[i]) { - return false; - } - } - return true; - } - - public List getCommandBases(CommandType type) { - return subCommands.getOrDefault(type, Arrays.asList(type.getBase())); - } - - public static enum TimeType { - SECONDS("s", "sec", "second", "seconds"), - MINUTES("m", "min", "minute", "minutes"), - HOURS("h", "hour", "hours"), - DAYS("d", "day", "days"); - - private String[] base; - - private TimeType(String... base) { - this.base = base; - } - - public String[] getBase() { - return base; - } - - public String getCompletion() { - return base[base.length-1]; - } - - public TimeType valueOf(TimeUnit unit) { - return TimeType.valueOf(unit.toString()); - } - } - - public static enum CommandType { - GIVE(CmdGive.class, "give"), - GIVE_ALL(CmdGiveAll.class, "giveall"), - RELOAD(CmdReload.class, "reload"), - REMOVE(CmdRemove.class, "remove"), - SET(CmdSet.class, "set"), - TRAIL_REMOVE(CmdTrailRemove.class, "remove_trail"), - TRAIL_SET(CmdTrailSet.class, "set_trail"), - BYPASS(CmdBypass.class, "bypass"), - FLY(CmdFly.class, "toggle"), - HELP(CmdHelp.class, "help"), - INFINITE(CmdInfinite.class, "infinite"), - PAY(CmdPay.class, "pay"), - SHOP(CmdShop.class, "shop"), - SPEED(CmdSpeed.class, "speed"), - TIME(CmdTime.class, "time"), - TRAILS(CmdTrails.class, "trails"), - MIGRATE(CmdMigrate.class, "migrate"); - - private Class clazz; - private String base; - - private CommandType(Class clazz, String base) { - this.clazz = clazz; - this.base = base; - } - - public boolean isEnabled(TempFly tempfly) { - switch (this) { - case SHOP: - return V.shop; - default: - return true; - } - } - - public String getBase() { - return base; - } - - public Class getDeclaredClass() { - return clazz; - } - } - -} +package com.moneybags.tempfly.command; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.TimeUnit; + +import org.bukkit.configuration.ConfigurationSection; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.admin.CmdGive; +import com.moneybags.tempfly.command.admin.CmdGiveAll; +import com.moneybags.tempfly.command.admin.CmdMigrate; +import com.moneybags.tempfly.command.admin.CmdReload; +import com.moneybags.tempfly.command.admin.CmdRemove; +import com.moneybags.tempfly.command.admin.CmdSet; +import com.moneybags.tempfly.command.admin.CmdTrailRemove; +import com.moneybags.tempfly.command.admin.CmdTrailSet; +import com.moneybags.tempfly.command.player.CmdBypass; +import com.moneybags.tempfly.command.player.CmdFly; +import com.moneybags.tempfly.command.player.CmdHelp; +import com.moneybags.tempfly.command.player.CmdInfinite; +import com.moneybags.tempfly.command.player.CmdPay; +import com.moneybags.tempfly.command.player.CmdShop; +import com.moneybags.tempfly.command.player.CmdSpeed; +import com.moneybags.tempfly.command.player.CmdTime; +import com.moneybags.tempfly.command.player.CmdTrails; +import com.moneybags.tempfly.util.V; +import com.moneybags.tempfly.util.data.Files; + +public class CommandManager { + + private TempFly tempfly; + private TempFlyExecutor executor; + private TempFlyTabCompleter tab; + + private List enable = new ArrayList<>(); + private List disable = new ArrayList<>(); + + private Map> subCommands = new HashMap<>(); + private Map> timeArgs = new HashMap<>(); + private Map timeComplete = new HashMap<>(); + + private Map> hookRegistry = new HashMap<>(); + + public CommandManager(TempFly tempfly) { + this.tempfly = tempfly; + executor = new TempFlyExecutor(this); + tab = new TempFlyTabCompleter(this); + tempfly.getCommand("tempfly").setExecutor(executor); + tempfly.getCommand("tempfly").setTabCompleter(tab); + + for (CommandType type: CommandType.values()) { + if (!type.isEnabled(tempfly)) { + continue; + } + List subs = Files.lang.getStringList("command.base." + type.toString().toLowerCase()); + if (subs == null || subs.size() == 0) { + subCommands.put(type, Arrays.asList(type.getBase())); + continue; + } + subCommands.put(type, subs); + } + + ConfigurationSection csUnits = Files.lang.getConfigurationSection("command.unit"); + if (csUnits != null) { + String path = "command.unit"; + for (String key: csUnits.getKeys(false)) { + try { + TimeUnit unit = TimeUnit.valueOf(key.toUpperCase()); + List recognized = Files.lang.getStringList(path + "." + key + ".recognized"); + String complete = Files.lang.getString(path + "." + key + ".tab_complete"); + + if (recognized != null) timeArgs.put(unit, recognized); + if (complete != null) timeComplete.put(unit, complete); + } + catch (Exception e) {} + } + } + if (!timeArgs.containsKey(TimeUnit.SECONDS)) + timeArgs.put(TimeUnit.SECONDS, Arrays.asList(TimeType.SECONDS.getBase())); + if (!timeArgs.containsKey(TimeUnit.MINUTES)) + timeArgs.put(TimeUnit.MINUTES, Arrays.asList(TimeType.MINUTES.getBase())); + if (!timeArgs.containsKey(TimeUnit.HOURS)) + timeArgs.put(TimeUnit.HOURS, Arrays.asList(TimeType.HOURS.getBase())); + if (!timeArgs.containsKey(TimeUnit.DAYS)) + timeArgs.put(TimeUnit.DAYS, Arrays.asList(TimeType.DAYS.getBase())); + + if (!timeComplete.containsKey(TimeUnit.SECONDS)) + timeComplete.put(TimeUnit.SECONDS, TimeType.SECONDS.getCompletion()); + if (!timeComplete.containsKey(TimeUnit.MINUTES)) + timeComplete.put(TimeUnit.MINUTES, TimeType.MINUTES.getCompletion()); + if (!timeComplete.containsKey(TimeUnit.HOURS)) + timeComplete.put(TimeUnit.HOURS, TimeType.HOURS.getCompletion()); + if (!timeComplete.containsKey(TimeUnit.DAYS)) + timeComplete.put(TimeUnit.DAYS, TimeType.DAYS.getCompletion()); + + List temp = null; + + enable.addAll((temp = Files.lang.getStringList("command.enable")) == null || temp.size() == 0 ? + Arrays.asList("on", "enable") : temp); + disable.addAll((temp = Files.lang.getStringList("command.disable")) == null || temp.size() == 0 ? + Arrays.asList("off", "disable") : temp); + } + + public TempFlyTabCompleter getTabCompleter() { + return tab; + } + + public TempFly getTempFly() { + return tempfly; + } + + public List getEnable() { + return enable; + } + + public List getDisable() { + return disable; + } + + public List getAllTimeArguments() { + List args = new ArrayList<>(); + for (Entry> unit: timeArgs.entrySet()) { + args.addAll(unit.getValue()); + } + return args; + } + + public List getTimeArguments(TimeUnit unit) { + return timeArgs.getOrDefault(unit, Arrays.asList("{unit}")); + } + + public TimeUnit parseUnit(String s) { + for (Entry> entry: timeArgs.entrySet()) { + if (entry.getValue().contains(s)) { + return entry.getKey(); + } + } + return null; + } + + public List getAllTimeCompletions() { + List args = new ArrayList<>(); + for (Entry unit: timeComplete.entrySet()) { + args.add(unit.getValue()); + } + return args; + } + + public List getTimeCompletions(List exclude) { + List args = new ArrayList<>(); + for (Entry entry: timeComplete.entrySet()) { + if (exclude.contains(entry.getKey())) continue; + args.add(entry.getValue()); + } + return args; + } + + public String getTimeCompletion(TimeUnit unit) { + return timeComplete.getOrDefault(unit, "{unit}"); + } + + public List getToggleCompletions(boolean filter) { + if (filter) return Arrays.asList(enable.get(0), disable.get(0)); + List all = new ArrayList<>(); + all.addAll(enable); all.addAll(disable); + return all; + } + + public TempFlyCommand getCommand(String[] args) { + if (args == null) { + return null; + } + if (args.length == 0 || getEnable().contains(args[0]) || getDisable().contains(args[0])) { + return new CmdFly(tempfly, args); + } else { + for (CommandType type: CommandType.values()) { + for (String base: getCommandBases(type)) { + if (base.equals(args[0])) { + try {return type.getDeclaredClass().getConstructor(TempFly.class, String[].class).newInstance(tempfly, args);} catch (Exception e) { + e.printStackTrace(); + } + } + } + } + for (Entry> entry: hookRegistry.entrySet()) { + if (entry.getKey().equals(args[0])) { + try {return entry.getValue().getConstructor(TempFly.class, String[].class).newInstance(tempfly, args);} catch (Exception e) { + e.printStackTrace(); + } + } + } + } + return null; + } + + public void registerHookCommand(String base, Class command) throws IllegalArgumentException { + if (hookRegistry.containsKey(base)) { + throw new IllegalArgumentException("Sub command bases must be unique! This command is already taken: " + base); + } + + try {command.getConstructor(TempFly.class, String[].class).newInstance(tempfly, new String[0]);} catch (Exception e) { + throw new IllegalArgumentException("This sub command is not properly structured: " + base); + } + hookRegistry.put(base, command); + } + + public void unregisterHookCommand(String base) { + hookRegistry.remove(base); + } + + public List getAllCommandBases() { + List bases = new ArrayList<>(); + bases.addAll(getToggleCompletions(true)); + for (CommandType type: CommandType.values()) { + for (String base: getCommandBases(type)) { + bases.add(base); + } + bases.addAll(hookRegistry.keySet()); + } + return bases; + } + + public List getPartialCommandBases(String partial) { + List matches = new ArrayList<>(); + for (CommandType type: CommandType.values()) { + for (String base: getCommandBases(type)) { + if (compare(base, partial)) { + matches.add(base); + } + } + } + for (String base: getToggleCompletions(false)) { + if (compare(base, partial)) { + matches.add(base); + } + } + + for (String base: hookRegistry.keySet()) { + if (compare(base, partial)) { + matches.add(base); + } + } + + return matches; + } + + private boolean compare(String base, String partial) { + char[] baseChars = base.toCharArray(); + if (partial.length() > baseChars.length) { + return false; + } + for (int i = 0; i < partial.length(); i++) { + char partialChar = partial.charAt(i); + if (partialChar != baseChars[i]) { + return false; + } + } + return true; + } + + public List getCommandBases(CommandType type) { + return subCommands.getOrDefault(type, Arrays.asList(type.getBase())); + } + + public static enum TimeType { + SECONDS("s", "sec", "second", "seconds"), + MINUTES("m", "min", "minute", "minutes"), + HOURS("h", "hour", "hours"), + DAYS("d", "day", "days"); + + private String[] base; + + private TimeType(String... base) { + this.base = base; + } + + public String[] getBase() { + return base; + } + + public String getCompletion() { + return base[base.length-1]; + } + + public TimeType valueOf(TimeUnit unit) { + return TimeType.valueOf(unit.toString()); + } + } + + public static enum CommandType { + GIVE(CmdGive.class, "give"), + GIVE_ALL(CmdGiveAll.class, "giveall"), + RELOAD(CmdReload.class, "reload"), + REMOVE(CmdRemove.class, "remove"), + SET(CmdSet.class, "set"), + TRAIL_REMOVE(CmdTrailRemove.class, "remove_trail"), + TRAIL_SET(CmdTrailSet.class, "set_trail"), + BYPASS(CmdBypass.class, "bypass"), + FLY(CmdFly.class, "toggle"), + HELP(CmdHelp.class, "help"), + INFINITE(CmdInfinite.class, "infinite"), + PAY(CmdPay.class, "pay"), + SHOP(CmdShop.class, "shop"), + SPEED(CmdSpeed.class, "speed"), + TIME(CmdTime.class, "time"), + TRAILS(CmdTrails.class, "trails"), + MIGRATE(CmdMigrate.class, "migrate"); + + private Class clazz; + private String base; + + private CommandType(Class clazz, String base) { + this.clazz = clazz; + this.base = base; + } + + public boolean isEnabled(TempFly tempfly) { + switch (this) { + case SHOP: + return V.shop; + default: + return true; + } + } + + public String getBase() { + return base; + } + + public Class getDeclaredClass() { + return clazz; + } + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/command/TempFlyCommand.java b/src/com/moneybags/tempfly/command/TempFlyCommand.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/command/TempFlyCommand.java rename to src/com/moneybags/tempfly/command/TempFlyCommand.java index 7f3b288..e11c0b8 100644 --- a/TempFly/src/com/moneybags/tempfly/command/TempFlyCommand.java +++ b/src/com/moneybags/tempfly/command/TempFlyCommand.java @@ -1,71 +1,71 @@ -package com.moneybags.tempfly.command; - -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; - -public abstract class TempFlyCommand { - - protected final TempFly tempfly; - protected final String[] args; - - public TempFlyCommand(TempFly tempfly, String[] args) { - this.tempfly = tempfly; - this.args = args; - } - - public TempFly getTempFly() { - return this.tempfly; - } - - public String[] getArguments() { - return args; - } - - public String[] cleanArgs(String[] arguments, int skip) { - List temp = new ArrayList<>(); - for (int i = 0; i < arguments.length; i++) { - if (i <= skip-1) { - continue; - } - temp.add(arguments[i]); - } - return temp.toArray(new String[temp.size()]); - } - - public List getPlayerArguments(String partial) { - List matches = new ArrayList<>(); - for (Player p: Bukkit.getOnlinePlayers()) { - char[] baseChars = p.getName().toCharArray(); - if (partial.length() > baseChars.length) { - continue; - } - for (int i = 0; i < partial.length(); i++) { - char partialChar = partial.charAt(i); - if (partialChar != baseChars[i]) { - continue; - } - } - matches.add(p.getName()); - } - return matches; - } - - public List getRange(int min, int max) { - List numbers = new ArrayList<>(); - for (int i = min; i <= max; i++) { - numbers.add(String.valueOf(i)); - } - return numbers; - } - - public abstract List getPotentialArguments(CommandSender s); - - public abstract void executeAs(CommandSender s); - -} +package com.moneybags.tempfly.command; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; + +public abstract class TempFlyCommand { + + protected final TempFly tempfly; + protected final String[] args; + + public TempFlyCommand(TempFly tempfly, String[] args) { + this.tempfly = tempfly; + this.args = args; + } + + public TempFly getTempFly() { + return this.tempfly; + } + + public String[] getArguments() { + return args; + } + + public String[] cleanArgs(String[] arguments, int skip) { + List temp = new ArrayList<>(); + for (int i = 0; i < arguments.length; i++) { + if (i <= skip-1) { + continue; + } + temp.add(arguments[i]); + } + return temp.toArray(new String[temp.size()]); + } + + public List getPlayerArguments(String partial) { + List matches = new ArrayList<>(); + for (Player p: Bukkit.getOnlinePlayers()) { + char[] baseChars = p.getName().toCharArray(); + if (partial.length() > baseChars.length) { + continue; + } + for (int i = 0; i < partial.length(); i++) { + char partialChar = partial.charAt(i); + if (partialChar != baseChars[i]) { + continue; + } + } + matches.add(p.getName()); + } + return matches; + } + + public List getRange(int min, int max) { + List numbers = new ArrayList<>(); + for (int i = min; i <= max; i++) { + numbers.add(String.valueOf(i)); + } + return numbers; + } + + public abstract List getPotentialArguments(CommandSender s); + + public abstract void executeAs(CommandSender s); + +} diff --git a/TempFly/src/com/moneybags/tempfly/command/TempFlyExecutor.java b/src/com/moneybags/tempfly/command/TempFlyExecutor.java similarity index 97% rename from TempFly/src/com/moneybags/tempfly/command/TempFlyExecutor.java rename to src/com/moneybags/tempfly/command/TempFlyExecutor.java index 76776e9..eb445d3 100644 --- a/TempFly/src/com/moneybags/tempfly/command/TempFlyExecutor.java +++ b/src/com/moneybags/tempfly/command/TempFlyExecutor.java @@ -1,67 +1,67 @@ -package com.moneybags.tempfly.command; - -import java.util.Arrays; - -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; -import com.moneybags.tempfly.user.FlightUser; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class TempFlyExecutor implements CommandExecutor, Listener { - - private CommandManager manager; - - public TempFlyExecutor(CommandManager manager) { - this.manager = manager; - manager.getTempFly().getServer().getPluginManager().registerEvents(this, manager.getTempFly()); - } - - @Override - public boolean onCommand(CommandSender s, Command cmd, String label, String[] args) { - TempFlyCommand command = manager.getCommand(args); - if (command != null) { - command.executeAs(s); - return true; - } - U.m(s, V.invalidCommand); - return true; - } - - /** - * This handler catches the CommandPreprocessEvent and listens for command /fly. - * If the player has a permission listed under fly_override_permissions in the config - * such as essentials.fly, manager.getTempFly() will not override the flight command, so it returns. - * otherwise we just steal the command base without registering it and run the manager.getTempFly() executor. - * @param e - */ - //TODO test change ignoreCanlled true for AuthMe fly fix. - @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void on(PlayerCommandPreprocessEvent e) { - if (!(e.getPlayer() instanceof Player)) { - return; - } - String[] ls = e.getMessage().split(" "); - Player p = e.getPlayer(); - if (ls[0].equals("/fly")) { - if (ls.length == 1) { - for (String perm : V.overrideFlightPermissions) { - if (p.hasPermission(perm)) { - FlightUser user = manager.getTempFly().getFlightManager().getUser(p); - user.disableFlight(-1, false); - return; - } - } - } - String[] args = Arrays.copyOfRange(ls, 1, ls.length); - e.setCancelled(true); - onCommand(e.getPlayer(), null, "", args); - } - } -} +package com.moneybags.tempfly.command; + +import java.util.Arrays; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import com.moneybags.tempfly.user.FlightUser; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class TempFlyExecutor implements CommandExecutor, Listener { + + private CommandManager manager; + + public TempFlyExecutor(CommandManager manager) { + this.manager = manager; + manager.getTempFly().getServer().getPluginManager().registerEvents(this, manager.getTempFly()); + } + + @Override + public boolean onCommand(CommandSender s, Command cmd, String label, String[] args) { + TempFlyCommand command = manager.getCommand(args); + if (command != null) { + command.executeAs(s); + return true; + } + U.m(s, V.invalidCommand); + return true; + } + + /** + * This handler catches the CommandPreprocessEvent and listens for command /fly. + * If the player has a permission listed under fly_override_permissions in the config + * such as essentials.fly, manager.getTempFly() will not override the flight command, so it returns. + * otherwise we just steal the command base without registering it and run the manager.getTempFly() executor. + * @param e + */ + //TODO test change ignoreCanlled true for AuthMe fly fix. + @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void on(PlayerCommandPreprocessEvent e) { + if (!(e.getPlayer() instanceof Player)) { + return; + } + String[] ls = e.getMessage().split(" "); + Player p = e.getPlayer(); + if (ls[0].equals("/fly")) { + if (ls.length == 1) { + for (String perm : V.overrideFlightPermissions) { + if (p.hasPermission(perm)) { + FlightUser user = manager.getTempFly().getFlightManager().getUser(p); + user.disableFlight(-1, false); + return; + } + } + } + String[] args = Arrays.copyOfRange(ls, 1, ls.length); + e.setCancelled(true); + onCommand(e.getPlayer(), null, "", args); + } + } +} diff --git a/TempFly/src/com/moneybags/tempfly/command/TempFlyTabCompleter.java b/src/com/moneybags/tempfly/command/TempFlyTabCompleter.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/command/TempFlyTabCompleter.java rename to src/com/moneybags/tempfly/command/TempFlyTabCompleter.java index 5dc28d3..9013fcd 100644 --- a/TempFly/src/com/moneybags/tempfly/command/TempFlyTabCompleter.java +++ b/src/com/moneybags/tempfly/command/TempFlyTabCompleter.java @@ -1,63 +1,63 @@ -package com.moneybags.tempfly.command; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.command.TabCompleter; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.server.TabCompleteEvent; - -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class TempFlyTabCompleter implements TabCompleter, Listener { - - private CommandManager manager; - - public TempFlyTabCompleter(CommandManager manager) { - this.manager = manager; - try { - Class.forName("org.bukkit.event.server.TabCompleteEvent"); - Bukkit.getServer().getPluginManager().registerEvents(this, manager.getTempFly()); - } catch (ClassNotFoundException e) {} - } - - @Override - public List onTabComplete(CommandSender s, Command cmd, String label, String[] args) { - if (V.disableTab && !U.hasPermission(s, "tempfly.disable_tab.bypass")) { - return new ArrayList<>(); - } - if (args.length == 0) { - return manager.getAllCommandBases(); - } else if (args.length == 1) { - return manager.getPartialCommandBases(args[0]); - } else { - TempFlyCommand command = manager.getCommand(args); - return command == null ? new ArrayList<>() : command.getPotentialArguments(s); - } - } - - @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void on(TabCompleteEvent e) { - String[] args = e.getBuffer().split(" "); - if (args.length == 0) { - return; - } - if (!args[0].equalsIgnoreCase("/fly")) { - return; - } - - List completions = new ArrayList<>(); - Arrays.asList(U.skipArray(args, 1)).forEach(string -> completions.add(string)); - if (e.getBuffer().endsWith(" ")) { - completions.add(""); - } - e.setCompletions(onTabComplete(e.getSender(), null, "", completions.toArray(new String[completions.size()]))); - } -} +package com.moneybags.tempfly.command; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.server.TabCompleteEvent; + +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class TempFlyTabCompleter implements TabCompleter, Listener { + + private CommandManager manager; + + public TempFlyTabCompleter(CommandManager manager) { + this.manager = manager; + try { + Class.forName("org.bukkit.event.server.TabCompleteEvent"); + Bukkit.getServer().getPluginManager().registerEvents(this, manager.getTempFly()); + } catch (ClassNotFoundException e) {} + } + + @Override + public List onTabComplete(CommandSender s, Command cmd, String label, String[] args) { + if (V.disableTab && !U.hasPermission(s, "tempfly.disable_tab.bypass")) { + return new ArrayList<>(); + } + if (args.length == 0) { + return manager.getAllCommandBases(); + } else if (args.length == 1) { + return manager.getPartialCommandBases(args[0]); + } else { + TempFlyCommand command = manager.getCommand(args); + return command == null ? new ArrayList<>() : command.getPotentialArguments(s); + } + } + + @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void on(TabCompleteEvent e) { + String[] args = e.getBuffer().split(" "); + if (args.length == 0) { + return; + } + if (!args[0].equalsIgnoreCase("/fly")) { + return; + } + + List completions = new ArrayList<>(); + Arrays.asList(U.skipArray(args, 1)).forEach(string -> completions.add(string)); + if (e.getBuffer().endsWith(" ")) { + completions.add(""); + } + e.setCompletions(onTabComplete(e.getSender(), null, "", completions.toArray(new String[completions.size()]))); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/command/TimeCommand.java b/src/com/moneybags/tempfly/command/TimeCommand.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/command/TimeCommand.java rename to src/com/moneybags/tempfly/command/TimeCommand.java index fae8358..c71ee7a 100644 --- a/TempFly/src/com/moneybags/tempfly/command/TimeCommand.java +++ b/src/com/moneybags/tempfly/command/TimeCommand.java @@ -1,140 +1,140 @@ -package com.moneybags.tempfly.command; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import org.bukkit.command.CommandSender; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.time.AsyncTimeExecutor; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public abstract class TimeCommand extends TempFlyCommand implements AsyncTimeExecutor { - - public TimeCommand(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - public List getPartialUnits(String partial, List exclusion) { - if (partial == null || partial.isEmpty()) { - return tempfly.getCommandManager().getTimeCompletions(exclusion); - } - List matches = new ArrayList<>(); - units: - for (String identifier: tempfly.getCommandManager().getTimeCompletions(exclusion)) { - char[] unitChars = identifier.toCharArray(); - if (partial.length() > unitChars.length) { - continue; - } - for (int i = 0; i < partial.length(); i++) { - char partialChar = partial.charAt(i); - if (partialChar != unitChars[i]) { - continue units; - } - } - matches.add(identifier); - } - return matches; - } - - protected boolean isNumeric(String s) { - return regexNumeric(s).length() == 0; - } - - protected String regexNumeric(String s) { - return s.replaceAll("[0-9]", "").replaceAll("\\.", ""); - } - - protected String regexAlphabetical(String s) { - return s.replaceAll("[a-zA-Z]", ""); - } - - protected int lastNumericIndex(String s) { - int fin = 0; - for (int i = 0; i < s.length(); i++) { - if (!String.valueOf(s.charAt(i)).matches("[0-9]") && !String.valueOf(s.charAt(i)).equals(".")) { - return i > 0 ? fin-1 : fin; - } - fin++; - } - return s.length()-1; - } - - public double quantifyArguments(CommandSender s, int skip) { - double seconds = 0; - String[] args = skip > 0 ? cleanArgs(getArguments(), skip) : getArguments(); - for (int i = 0; i < args.length; i++) { - TimeUnit unit; - String parse; - // /tf give -{unit} 1 - if (String.valueOf(args[i].charAt(0)).equals("-")) { - if ((unit = tempfly.getCommandManager().parseUnit(args[i].toLowerCase().replaceAll("\\-", ""))) == null) { - U.m(s, U.cc("&c(" + args[i] + ") is an unknown time argument!")); - return 0; - } - if (args.length >= i+1) { - parse = args[i+1]; - i++; - } else { - U.m(s, U.cc("&c(" + args[i] + ") must be followed by a valid number!")); - return 0; - } - - // /tf give 1{unit} - } else if (lastNumericIndex(args[i]) < args[i].length()-1) { - if ((unit = tempfly.getCommandManager().parseUnit(regexNumeric(args[i]).toLowerCase())) == null) { - U.m(s, U.cc("&c(" + regexNumeric(args[i]) + ") is an unknown time argument!")); - return 0; - } - parse = regexAlphabetical(args[i]); - - // /tf give 60 {unit} | /tf give 60 - } else { - parse = args[i]; - if (args.length-1 > i && (unit = tempfly.getCommandManager().parseUnit(args[i+1])) != null) { - i++; - } else { - unit = TimeUnit.SECONDS; - } - } - try { - double fin = Double.parseDouble(parse); - switch (unit) { - case DAYS: fin *= 24; - case HOURS: fin *= 60; - case MINUTES: fin *= 60; - case SECONDS: seconds += fin; - default: - break; - } - } catch (NumberFormatException e) { - U.m(s, V.invalidNumber.replaceAll("\\{NUMBER}", parse)); - return 0; - } - } - return seconds; - } - - public List getTimeArguments(String[] args) { - if (args == null || args.length == 0 || args.length == 1 && args[0].isEmpty()) { - return getRange(1, 9); - } - List exclusion = new ArrayList<>(); - for (String s : args) { - TimeUnit unit; - if ((unit = tempfly.getCommandManager().parseUnit(s)) != null) { - exclusion.add(unit); - } - } - if (exclusion.size() == 4) { - return new ArrayList<>(); - } - - String lastArg = args[args.length-1]; - // /tf give 1 {unit} - return ((lastArg.isEmpty() || !isNumeric(lastArg)) && args.length > 1 && isNumeric(args[args.length-2])) - ? getPartialUnits(lastArg, exclusion) : getRange(1, 9); - } -} +package com.moneybags.tempfly.command; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import org.bukkit.command.CommandSender; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.time.AsyncTimeExecutor; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public abstract class TimeCommand extends TempFlyCommand implements AsyncTimeExecutor { + + public TimeCommand(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + public List getPartialUnits(String partial, List exclusion) { + if (partial == null || partial.isEmpty()) { + return tempfly.getCommandManager().getTimeCompletions(exclusion); + } + List matches = new ArrayList<>(); + units: + for (String identifier: tempfly.getCommandManager().getTimeCompletions(exclusion)) { + char[] unitChars = identifier.toCharArray(); + if (partial.length() > unitChars.length) { + continue; + } + for (int i = 0; i < partial.length(); i++) { + char partialChar = partial.charAt(i); + if (partialChar != unitChars[i]) { + continue units; + } + } + matches.add(identifier); + } + return matches; + } + + protected boolean isNumeric(String s) { + return regexNumeric(s).length() == 0; + } + + protected String regexNumeric(String s) { + return s.replaceAll("[0-9]", "").replaceAll("\\.", ""); + } + + protected String regexAlphabetical(String s) { + return s.replaceAll("[a-zA-Z]", ""); + } + + protected int lastNumericIndex(String s) { + int fin = 0; + for (int i = 0; i < s.length(); i++) { + if (!String.valueOf(s.charAt(i)).matches("[0-9]") && !String.valueOf(s.charAt(i)).equals(".")) { + return i > 0 ? fin-1 : fin; + } + fin++; + } + return s.length()-1; + } + + public double quantifyArguments(CommandSender s, int skip) { + double seconds = 0; + String[] args = skip > 0 ? cleanArgs(getArguments(), skip) : getArguments(); + for (int i = 0; i < args.length; i++) { + TimeUnit unit; + String parse; + // /tf give -{unit} 1 + if (String.valueOf(args[i].charAt(0)).equals("-")) { + if ((unit = tempfly.getCommandManager().parseUnit(args[i].toLowerCase().replaceAll("\\-", ""))) == null) { + U.m(s, U.cc("&c(" + args[i] + ") is an unknown time argument!")); + return 0; + } + if (args.length >= i+1) { + parse = args[i+1]; + i++; + } else { + U.m(s, U.cc("&c(" + args[i] + ") must be followed by a valid number!")); + return 0; + } + + // /tf give 1{unit} + } else if (lastNumericIndex(args[i]) < args[i].length()-1) { + if ((unit = tempfly.getCommandManager().parseUnit(regexNumeric(args[i]).toLowerCase())) == null) { + U.m(s, U.cc("&c(" + regexNumeric(args[i]) + ") is an unknown time argument!")); + return 0; + } + parse = regexAlphabetical(args[i]); + + // /tf give 60 {unit} | /tf give 60 + } else { + parse = args[i]; + if (args.length-1 > i && (unit = tempfly.getCommandManager().parseUnit(args[i+1])) != null) { + i++; + } else { + unit = TimeUnit.SECONDS; + } + } + try { + double fin = Double.parseDouble(parse); + switch (unit) { + case DAYS: fin *= 24; + case HOURS: fin *= 60; + case MINUTES: fin *= 60; + case SECONDS: seconds += fin; + default: + break; + } + } catch (NumberFormatException e) { + U.m(s, V.invalidNumber.replaceAll("\\{NUMBER}", parse)); + return 0; + } + } + return seconds; + } + + public List getTimeArguments(String[] args) { + if (args == null || args.length == 0 || args.length == 1 && args[0].isEmpty()) { + return getRange(1, 9); + } + List exclusion = new ArrayList<>(); + for (String s : args) { + TimeUnit unit; + if ((unit = tempfly.getCommandManager().parseUnit(s)) != null) { + exclusion.add(unit); + } + } + if (exclusion.size() == 4) { + return new ArrayList<>(); + } + + String lastArg = args[args.length-1]; + // /tf give 1 {unit} + return ((lastArg.isEmpty() || !isNumeric(lastArg)) && args.length > 1 && isNumeric(args[args.length-2])) + ? getPartialUnits(lastArg, exclusion) : getRange(1, 9); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/command/admin/CmdGive.java b/src/com/moneybags/tempfly/command/admin/CmdGive.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/command/admin/CmdGive.java rename to src/com/moneybags/tempfly/command/admin/CmdGive.java index c8af197..82f42de 100644 --- a/TempFly/src/com/moneybags/tempfly/command/admin/CmdGive.java +++ b/src/com/moneybags/tempfly/command/admin/CmdGive.java @@ -1,94 +1,94 @@ -package com.moneybags.tempfly.command.admin; - -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TimeCommand; -import com.moneybags.tempfly.time.AsyncTimeParameters; -import com.moneybags.tempfly.time.TimeManager; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class CmdGive extends TimeCommand { - - public CmdGive(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - @Override - public void executeAs(CommandSender s) { - if (!U.hasPermission(s, "tempfly.give")) { - U.m(s, V.invalidPermission); - return; - } - if (args.length < 3) { - U.m(s, U.cc("&c/tf give [player] [amount]")); - return; - } - - @SuppressWarnings("deprecation") - OfflinePlayer p = Bukkit.getOfflinePlayer(args[1]); - if (p == null || (p != null && !p.isOnline() && !p.hasPlayedBefore())) { - U.m(s, V.invalidPlayer.replaceAll("\\{PLAYER}", args[1])); - return; - } - double amount = quantifyArguments(s, 2); - if (amount <= 0) { - return; - } - new AsyncTimeParameters(tempfly, this, s, p, amount).runAsync(); - } - - @Override - public void execute(AsyncTimeParameters parameters) { - CommandSender s = parameters.getSender(); - double maxTime = parameters.getMaxTime(); - if (maxTime == -999) { - U.m(s, s.isOp() ? V.vaultPermsRequired : V.invalidPlayer); - return; - } - Console.debug(maxTime); - - TimeManager manager = tempfly.getTimeManager(); - OfflinePlayer p = parameters.getTarget(); - double currentTime = parameters.getCurrentTime(); - double amount = parameters.getAmount(); - if (maxTime > -1 && (currentTime + amount > maxTime)) { - U.m(s, manager.regexString(V.timeMaxOther, amount) - .replaceAll("\\{PLAYER}", p.getName())); - U.m(p, V.timeMaxSelf); - - amount = maxTime - currentTime; - if (amount <= 0) { - return; - } - } - manager.addTime(parameters.getTarget().getUniqueId(), parameters); - if (p != s) { - U.m(s, manager.regexString(V.timeGivenOther, amount) - .replaceAll("\\{PLAYER}", p.getName())); - } - if (p.isOnline()) { - U.m((Player)p, manager.regexString(V.timeGivenSelf, amount)); - } - } - - @Override - public List getPotentialArguments(CommandSender s) { - if (!U.hasPermission(s, "tempfly.give")) { - return new ArrayList<>(); - } - if (args.length < 3) { - return getPlayerArguments(args[1]); - } else { - return getTimeArguments(cleanArgs(args, 2)); - } - } -} +package com.moneybags.tempfly.command.admin; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TimeCommand; +import com.moneybags.tempfly.time.AsyncTimeParameters; +import com.moneybags.tempfly.time.TimeManager; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class CmdGive extends TimeCommand { + + public CmdGive(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + @Override + public void executeAs(CommandSender s) { + if (!U.hasPermission(s, "tempfly.give")) { + U.m(s, V.invalidPermission); + return; + } + if (args.length < 3) { + U.m(s, U.cc("&c/tf give [player] [amount]")); + return; + } + + @SuppressWarnings("deprecation") + OfflinePlayer p = Bukkit.getOfflinePlayer(args[1]); + if (p == null || (p != null && !p.isOnline() && !p.hasPlayedBefore())) { + U.m(s, V.invalidPlayer.replaceAll("\\{PLAYER}", args[1])); + return; + } + double amount = quantifyArguments(s, 2); + if (amount <= 0) { + return; + } + new AsyncTimeParameters(tempfly, this, s, p, amount).runAsync(); + } + + @Override + public void execute(AsyncTimeParameters parameters) { + CommandSender s = parameters.getSender(); + double maxTime = parameters.getMaxTime(); + if (maxTime == -999) { + U.m(s, s.isOp() ? V.vaultPermsRequired : V.invalidPlayer); + return; + } + Console.debug(maxTime); + + TimeManager manager = tempfly.getTimeManager(); + OfflinePlayer p = parameters.getTarget(); + double currentTime = parameters.getCurrentTime(); + double amount = parameters.getAmount(); + if (maxTime > -1 && (currentTime + amount > maxTime)) { + U.m(s, manager.regexString(V.timeMaxOther, amount) + .replaceAll("\\{PLAYER}", p.getName())); + U.m(p, V.timeMaxSelf); + + amount = maxTime - currentTime; + if (amount <= 0) { + return; + } + } + manager.addTime(parameters.getTarget().getUniqueId(), parameters); + if (p != s) { + U.m(s, manager.regexString(V.timeGivenOther, amount) + .replaceAll("\\{PLAYER}", p.getName())); + } + if (p.isOnline()) { + U.m((Player)p, manager.regexString(V.timeGivenSelf, amount)); + } + } + + @Override + public List getPotentialArguments(CommandSender s) { + if (!U.hasPermission(s, "tempfly.give")) { + return new ArrayList<>(); + } + if (args.length < 3) { + return getPlayerArguments(args[1]); + } else { + return getTimeArguments(cleanArgs(args, 2)); + } + } +} diff --git a/TempFly/src/com/moneybags/tempfly/command/admin/CmdGiveAll.java b/src/com/moneybags/tempfly/command/admin/CmdGiveAll.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/command/admin/CmdGiveAll.java rename to src/com/moneybags/tempfly/command/admin/CmdGiveAll.java index ea41e19..9ef2218 100644 --- a/TempFly/src/com/moneybags/tempfly/command/admin/CmdGiveAll.java +++ b/src/com/moneybags/tempfly/command/admin/CmdGiveAll.java @@ -1,71 +1,71 @@ -package com.moneybags.tempfly.command.admin; - -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TimeCommand; -import com.moneybags.tempfly.time.AsyncTimeParameters; -import com.moneybags.tempfly.time.TimeManager; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class CmdGiveAll extends TimeCommand { - - public CmdGiveAll(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - @Override - public void executeAs(CommandSender s) { - if (!U.hasPermission(s, "tempfly.giveall")) { - U.m(s, V.invalidPermission); - return; - } - - final double amount = quantifyArguments(s, 1); - if (amount == 0) { - U.m(s, V.invalidNumber.replaceAll("\\{NUMBER}", String.valueOf(amount))); - return; - } - TimeManager manager = tempfly.getTimeManager(); - for (Player p: Bukkit.getOnlinePlayers()) { - //If we were going to check offline player permissions it would need to be an AsyncTimeCommand - double maxTime = tempfly.getTimeManager().getMaxTime(p.getUniqueId()); - double time = manager.getTime(p.getUniqueId()); - double amount2 = amount; - if (maxTime > -1 && (time + amount > maxTime)) { - U.m(s, manager.regexString(V.timeMaxOther, amount) - .replaceAll("\\{PLAYER}", p.getName())); - U.m(p, V.timeMaxSelf); - - amount2 = maxTime - time; - if (amount <= 0) { - continue; - } - } - new AsyncTimeParameters(tempfly, this, s, p, amount2).runAsync(); - U.m((Player)p, manager.regexString(V.timeGivenSelf, amount2)); - } - U.m(s, manager.regexString(V.timeGivenSelf, amount)); - } - - @Override - public List getPotentialArguments(CommandSender s) { - if (!U.hasPermission(s, "tempfly.giveall")) { - return new ArrayList<>(); - } - return getTimeArguments(cleanArgs(args, 1)); - } - - // Im not going to pay all offline players so it doen't need to be async. - @Override - public void execute(AsyncTimeParameters parameters) { - parameters.getTempfly().getTimeManager().addTime(parameters.getTarget().getUniqueId(), parameters); - return; - } -} +package com.moneybags.tempfly.command.admin; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TimeCommand; +import com.moneybags.tempfly.time.AsyncTimeParameters; +import com.moneybags.tempfly.time.TimeManager; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class CmdGiveAll extends TimeCommand { + + public CmdGiveAll(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + @Override + public void executeAs(CommandSender s) { + if (!U.hasPermission(s, "tempfly.giveall")) { + U.m(s, V.invalidPermission); + return; + } + + final double amount = quantifyArguments(s, 1); + if (amount == 0) { + U.m(s, V.invalidNumber.replaceAll("\\{NUMBER}", String.valueOf(amount))); + return; + } + TimeManager manager = tempfly.getTimeManager(); + for (Player p: Bukkit.getOnlinePlayers()) { + //If we were going to check offline player permissions it would need to be an AsyncTimeCommand + double maxTime = tempfly.getTimeManager().getMaxTime(p.getUniqueId()); + double time = manager.getTime(p.getUniqueId()); + double amount2 = amount; + if (maxTime > -1 && (time + amount > maxTime)) { + U.m(s, manager.regexString(V.timeMaxOther, amount) + .replaceAll("\\{PLAYER}", p.getName())); + U.m(p, V.timeMaxSelf); + + amount2 = maxTime - time; + if (amount <= 0) { + continue; + } + } + new AsyncTimeParameters(tempfly, this, s, p, amount2).runAsync(); + U.m((Player)p, manager.regexString(V.timeGivenSelf, amount2)); + } + U.m(s, manager.regexString(V.timeGivenSelf, amount)); + } + + @Override + public List getPotentialArguments(CommandSender s) { + if (!U.hasPermission(s, "tempfly.giveall")) { + return new ArrayList<>(); + } + return getTimeArguments(cleanArgs(args, 1)); + } + + // Im not going to pay all offline players so it doen't need to be async. + @Override + public void execute(AsyncTimeParameters parameters) { + parameters.getTempfly().getTimeManager().addTime(parameters.getTarget().getUniqueId(), parameters); + return; + } +} diff --git a/TempFly/src/com/moneybags/tempfly/command/admin/CmdMigrate.java b/src/com/moneybags/tempfly/command/admin/CmdMigrate.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/command/admin/CmdMigrate.java rename to src/com/moneybags/tempfly/command/admin/CmdMigrate.java index 8e41c8b..3279ef8 100644 --- a/TempFly/src/com/moneybags/tempfly/command/admin/CmdMigrate.java +++ b/src/com/moneybags/tempfly/command/admin/CmdMigrate.java @@ -1,136 +1,136 @@ -package com.moneybags.tempfly.command.admin; - -import java.io.File; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TempFlyCommand; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.data.DataBridge.DataTable; -import com.moneybags.tempfly.util.data.DataBridge.DataValue; - -public class CmdMigrate extends TempFlyCommand{ - - public CmdMigrate(TempFly tempfly, String[] args) { - super(tempfly, args); - - } - - @Override - public List getPotentialArguments(CommandSender s) { - return new ArrayList<>(); - } - - private static boolean sure = false; - - @Override - public void executeAs(CommandSender s) { - if (!(s instanceof ConsoleCommandSender)) { - s.sendMessage("Only the console may use this command!"); - return; - } - - if (!sure) { - s.sendMessage("Warning, Using this command will take all data found in the local tempfly (data.yml) and migrate it to the MySql database defined in the config. If there is any TempFly data already in this database it has the possibility of being overwritten by the migrated data. Please type the command again within the next 5 seconds to continue."); - sure = true; - Bukkit.getScheduler().runTaskLater(tempfly, () -> { - sure = false; - }, 100); - return; - } - - if (!tempfly.getDataBridge().hasSqlEnabled()) { - s.sendMessage("You must enable MySql in the config to migrate your tempfly data..."); - return; - } - - File dataf = new File(tempfly.getDataFolder(), "data.yml"); - if (!dataf.exists()){ - s.sendMessage("There is no datafile to migrate..."); - return; - } - FileConfiguration data = new YamlConfiguration(); - try { data.load(dataf); } catch (Exception e1) { - s.sendMessage("There is a problem inside the data.yml, If you cannot fix the issue, please contact the developer."); - e1.printStackTrace(); - return; - } - - ConfigurationSection csPlayers = data.getConfigurationSection("players"); - if (csPlayers == null) { - s.sendMessage("There is no data to migrate..."); - return; - } - for (String key: csPlayers.getKeys(false)) { - String[] path = new String[] {key}; - - try (PreparedStatement stCreate = tempfly.getDataBridge().prepareStatement("INSERT IGNORE INTO tempfly_data(uuid) VALUES(?)")){ - stCreate.setString(1, key); - stCreate.execute(); - stCreate.close(); - } catch (SQLException e) { - s.sendMessage("Failed to create database entry for (" + key + ")"); - e.printStackTrace(); - continue; - } - - for (DataValue value: DataValue.values()) { - if (value.getTable() != DataTable.TEMPFLY_DATA) { - continue; - } - - int index = 0; - StringBuilder sb = new StringBuilder(); - for (String string: value.getYamlPath()) { - sb.append((sb.length() > 0 ? "." : "") + string); - if (path.length > index) { - sb.append("." + path[index]); - } - index++; - } - Console.debug(sb.toString()); - Object obj = data.get(sb.toString()); - if (obj == null) { - continue; - } - - PreparedStatement st = tempfly.getDataBridge().prepareStatement( - "UPDATE " + value.getTable().getSqlTable() + " SET " + value.getSqlColumn() - + " = ? WHERE " + value.getTable().getPrimaryKey() + " = ?"); - Class type = value.getType(); - try { - if (type.equals(Boolean.TYPE)) { - st.setBoolean(1, (boolean) obj); - } else if (type.equals(Double.TYPE)) { - st.setDouble(1, (double) obj); - }else if (type.equals(String.class)) { - st.setString(1, (String) obj); - } else if (type.equals(Long.TYPE)) { - st.setLong(1, (long) obj); - } - st.setString(2, path[0]); - st.execute(); - st.close(); - } catch (Exception e) { - s.sendMessage("Error while setting data"); - e.printStackTrace(); - continue; - } - } - } - - String statement = "U"; - - } - -} +package com.moneybags.tempfly.command.admin; + +import java.io.File; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TempFlyCommand; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.data.DataBridge.DataTable; +import com.moneybags.tempfly.util.data.DataBridge.DataValue; + +public class CmdMigrate extends TempFlyCommand{ + + public CmdMigrate(TempFly tempfly, String[] args) { + super(tempfly, args); + + } + + @Override + public List getPotentialArguments(CommandSender s) { + return new ArrayList<>(); + } + + private static boolean sure = false; + + @Override + public void executeAs(CommandSender s) { + if (!(s instanceof ConsoleCommandSender)) { + s.sendMessage("Only the console may use this command!"); + return; + } + + if (!sure) { + s.sendMessage("Warning, Using this command will take all data found in the local tempfly (data.yml) and migrate it to the MySql database defined in the config. If there is any TempFly data already in this database it has the possibility of being overwritten by the migrated data. Please type the command again within the next 5 seconds to continue."); + sure = true; + Bukkit.getScheduler().runTaskLater(tempfly, () -> { + sure = false; + }, 100); + return; + } + + if (!tempfly.getDataBridge().hasSqlEnabled()) { + s.sendMessage("You must enable MySql in the config to migrate your tempfly data..."); + return; + } + + File dataf = new File(tempfly.getDataFolder(), "data.yml"); + if (!dataf.exists()){ + s.sendMessage("There is no datafile to migrate..."); + return; + } + FileConfiguration data = new YamlConfiguration(); + try { data.load(dataf); } catch (Exception e1) { + s.sendMessage("There is a problem inside the data.yml, If you cannot fix the issue, please contact the developer."); + e1.printStackTrace(); + return; + } + + ConfigurationSection csPlayers = data.getConfigurationSection("players"); + if (csPlayers == null) { + s.sendMessage("There is no data to migrate..."); + return; + } + for (String key: csPlayers.getKeys(false)) { + String[] path = new String[] {key}; + + try (PreparedStatement stCreate = tempfly.getDataBridge().prepareStatement("INSERT IGNORE INTO tempfly_data(uuid) VALUES(?)")){ + stCreate.setString(1, key); + stCreate.execute(); + stCreate.close(); + } catch (SQLException e) { + s.sendMessage("Failed to create database entry for (" + key + ")"); + e.printStackTrace(); + continue; + } + + for (DataValue value: DataValue.values()) { + if (value.getTable() != DataTable.TEMPFLY_DATA) { + continue; + } + + int index = 0; + StringBuilder sb = new StringBuilder(); + for (String string: value.getYamlPath()) { + sb.append((sb.length() > 0 ? "." : "") + string); + if (path.length > index) { + sb.append("." + path[index]); + } + index++; + } + Console.debug(sb.toString()); + Object obj = data.get(sb.toString()); + if (obj == null) { + continue; + } + + PreparedStatement st = tempfly.getDataBridge().prepareStatement( + "UPDATE " + value.getTable().getSqlTable() + " SET " + value.getSqlColumn() + + " = ? WHERE " + value.getTable().getPrimaryKey() + " = ?"); + Class type = value.getType(); + try { + if (type.equals(Boolean.TYPE)) { + st.setBoolean(1, (boolean) obj); + } else if (type.equals(Double.TYPE)) { + st.setDouble(1, (double) obj); + }else if (type.equals(String.class)) { + st.setString(1, (String) obj); + } else if (type.equals(Long.TYPE)) { + st.setLong(1, (long) obj); + } + st.setString(2, path[0]); + st.execute(); + st.close(); + } catch (Exception e) { + s.sendMessage("Error while setting data"); + e.printStackTrace(); + continue; + } + } + } + + String statement = "U"; + + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/command/admin/CmdReload.java b/src/com/moneybags/tempfly/command/admin/CmdReload.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/command/admin/CmdReload.java rename to src/com/moneybags/tempfly/command/admin/CmdReload.java index d17be1c..a97b1e8 100644 --- a/TempFly/src/com/moneybags/tempfly/command/admin/CmdReload.java +++ b/src/com/moneybags/tempfly/command/admin/CmdReload.java @@ -1,33 +1,33 @@ -package com.moneybags.tempfly.command.admin; - -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.command.CommandSender; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TempFlyCommand; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class CmdReload extends TempFlyCommand { - - public CmdReload(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - @Override - public void executeAs(CommandSender s) { - if (!U.hasPermission(s, "tempfly.reload")) { - U.m(s, V.invalidPermission); - return; - } - tempfly.reloadTempfly(); - U.m(s, V.reload); - } - - @Override - public List getPotentialArguments(CommandSender s) { - return new ArrayList<>(); - } -} +package com.moneybags.tempfly.command.admin; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.command.CommandSender; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TempFlyCommand; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class CmdReload extends TempFlyCommand { + + public CmdReload(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + @Override + public void executeAs(CommandSender s) { + if (!U.hasPermission(s, "tempfly.reload")) { + U.m(s, V.invalidPermission); + return; + } + tempfly.reloadTempfly(); + U.m(s, V.reload); + } + + @Override + public List getPotentialArguments(CommandSender s) { + return new ArrayList<>(); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/command/admin/CmdRemove.java b/src/com/moneybags/tempfly/command/admin/CmdRemove.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/command/admin/CmdRemove.java rename to src/com/moneybags/tempfly/command/admin/CmdRemove.java index 7c3d097..4fbc265 100644 --- a/TempFly/src/com/moneybags/tempfly/command/admin/CmdRemove.java +++ b/src/com/moneybags/tempfly/command/admin/CmdRemove.java @@ -1,82 +1,82 @@ -package com.moneybags.tempfly.command.admin; - -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TimeCommand; -import com.moneybags.tempfly.time.AsyncTimeParameters; -import com.moneybags.tempfly.time.TimeManager; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class CmdRemove extends TimeCommand { - - public CmdRemove(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - @Override @SuppressWarnings("deprecation") - public void executeAs(CommandSender s) { - if (!U.hasPermission(s, "tempfly.remove")) { - U.m(s, V.invalidPermission); - return; - } - if (args.length < 3) { - U.m(s, U.cc("&c/tf remove [player] [amount-> {args=[-s][-m][-h][-d]}]")); - return; - } - - OfflinePlayer p = Bukkit.getOfflinePlayer(args[1]); - if (p == null || (p != null && !p.isOnline() && !p.hasPlayedBefore())) { - U.m(s, V.invalidPlayer.replaceAll("\\{PLAYER}", args[1])); - return; - } - double amount = quantifyArguments(s, 2); - if (amount <= 0) { - U.m(s, V.invalidNumber.replaceAll("\\{NUMBER}", String.valueOf(amount))); - return; - } - new AsyncTimeParameters(tempfly, this, s, p, amount).runAsync(); - } - - @Override - public void execute(AsyncTimeParameters parameters) { - TimeManager manager = tempfly.getTimeManager(); - CommandSender s = parameters.getSender(); - double amount = parameters.getAmount(); - double time = parameters.getCurrentTime(); - OfflinePlayer p = parameters.getTarget(); - if (time == 0) { - U.m(s, V.invalidTimeOther - .replaceAll("\\{PLAYER}", p.getName())); - return; - } - double remove = time-amount < 0 ? time : amount; - manager.removeTime(parameters.getTarget().getUniqueId(), parameters); - if (p != s) { - U.m(s, manager.regexString(V.timeRemovedOther, remove) - .replaceAll("\\{PLAYER}", p.getName())); - } - if (p.isOnline() && time > 0) { - U.m((Player)p, manager.regexString(V.timeRemovedSelf, remove)); - } - } - - @Override - public List getPotentialArguments(CommandSender s) { - if (!U.hasPermission(s, "tempfly.remove")) { - return new ArrayList<>(); - } - if (args.length < 3) { - return getPlayerArguments(args[1]); - } else { - return getTimeArguments(cleanArgs(args, 2)); - } - } -} +package com.moneybags.tempfly.command.admin; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TimeCommand; +import com.moneybags.tempfly.time.AsyncTimeParameters; +import com.moneybags.tempfly.time.TimeManager; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class CmdRemove extends TimeCommand { + + public CmdRemove(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + @Override @SuppressWarnings("deprecation") + public void executeAs(CommandSender s) { + if (!U.hasPermission(s, "tempfly.remove")) { + U.m(s, V.invalidPermission); + return; + } + if (args.length < 3) { + U.m(s, U.cc("&c/tf remove [player] [amount-> {args=[-s][-m][-h][-d]}]")); + return; + } + + OfflinePlayer p = Bukkit.getOfflinePlayer(args[1]); + if (p == null || (p != null && !p.isOnline() && !p.hasPlayedBefore())) { + U.m(s, V.invalidPlayer.replaceAll("\\{PLAYER}", args[1])); + return; + } + double amount = quantifyArguments(s, 2); + if (amount <= 0) { + U.m(s, V.invalidNumber.replaceAll("\\{NUMBER}", String.valueOf(amount))); + return; + } + new AsyncTimeParameters(tempfly, this, s, p, amount).runAsync(); + } + + @Override + public void execute(AsyncTimeParameters parameters) { + TimeManager manager = tempfly.getTimeManager(); + CommandSender s = parameters.getSender(); + double amount = parameters.getAmount(); + double time = parameters.getCurrentTime(); + OfflinePlayer p = parameters.getTarget(); + if (time == 0) { + U.m(s, V.invalidTimeOther + .replaceAll("\\{PLAYER}", p.getName())); + return; + } + double remove = time-amount < 0 ? time : amount; + manager.removeTime(parameters.getTarget().getUniqueId(), parameters); + if (p != s) { + U.m(s, manager.regexString(V.timeRemovedOther, remove) + .replaceAll("\\{PLAYER}", p.getName())); + } + if (p.isOnline() && time > 0) { + U.m((Player)p, manager.regexString(V.timeRemovedSelf, remove)); + } + } + + @Override + public List getPotentialArguments(CommandSender s) { + if (!U.hasPermission(s, "tempfly.remove")) { + return new ArrayList<>(); + } + if (args.length < 3) { + return getPlayerArguments(args[1]); + } else { + return getTimeArguments(cleanArgs(args, 2)); + } + } +} diff --git a/TempFly/src/com/moneybags/tempfly/command/admin/CmdSet.java b/src/com/moneybags/tempfly/command/admin/CmdSet.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/command/admin/CmdSet.java rename to src/com/moneybags/tempfly/command/admin/CmdSet.java index 8db2377..84f5fbe 100644 --- a/TempFly/src/com/moneybags/tempfly/command/admin/CmdSet.java +++ b/src/com/moneybags/tempfly/command/admin/CmdSet.java @@ -1,83 +1,83 @@ -package com.moneybags.tempfly.command.admin; - -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TimeCommand; -import com.moneybags.tempfly.time.AsyncTimeParameters; -import com.moneybags.tempfly.time.TimeManager; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class CmdSet extends TimeCommand { - - public CmdSet(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - @Override @SuppressWarnings("deprecation") - public void executeAs(CommandSender s) { - if (!U.hasPermission(s, "tempfly.set")) { - U.m(s, V.invalidPermission); - return; - } - if (args.length < 3) { - U.m(s, U.cc("&c/time set [player] [amount-> {args=[-s][-m][-h][-d]}]")); - return; - } - - OfflinePlayer p = Bukkit.getOfflinePlayer(args[1]); - if (p == null || (p != null && !p.isOnline() && !p.hasPlayedBefore())) { - U.m(s, V.invalidPlayer.replaceAll("\\{PLAYER}", args[1])); - return; - } - - double amount = quantifyArguments(s, 2); - new AsyncTimeParameters(tempfly, this, s, p, amount).runAsync(); - } - - @Override - public void execute(AsyncTimeParameters parameters) { - CommandSender s = parameters.getSender(); - double maxTime = parameters.getMaxTime(); - if (maxTime == -999) { - U.m(s, s.isOp() ? V.vaultPermsRequired : V.invalidPlayer); - return; - } - - TimeManager manager = tempfly.getTimeManager(); - OfflinePlayer p = parameters.getTarget(); - double amount = parameters.getAmount(); - if ((maxTime > -1) && (amount > maxTime)) { - amount = maxTime; - U.m(s, manager.regexString(V.timeMaxOther, amount) - .replaceAll("\\{PLAYER}", p.getName())); - U.m(p, V.timeMaxSelf); - } - manager.setTime(parameters.getTarget().getUniqueId(), parameters); - U.m(s, manager.regexString(V.timeSetOther, amount) - .replaceAll("\\{PLAYER}", p.getName())); - if (p.isOnline()) { - U.m((Player)p, manager.regexString(V.timeSetSelf, amount)); - } - } - - @Override - public List getPotentialArguments(CommandSender s) { - if (!U.hasPermission(s, "tempfly.set")) { - return new ArrayList<>(); - } - if (args.length < 3) { - return getPlayerArguments(args[1]); - } else { - return getTimeArguments(cleanArgs(args, 2)); - } - } - -} +package com.moneybags.tempfly.command.admin; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TimeCommand; +import com.moneybags.tempfly.time.AsyncTimeParameters; +import com.moneybags.tempfly.time.TimeManager; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class CmdSet extends TimeCommand { + + public CmdSet(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + @Override @SuppressWarnings("deprecation") + public void executeAs(CommandSender s) { + if (!U.hasPermission(s, "tempfly.set")) { + U.m(s, V.invalidPermission); + return; + } + if (args.length < 3) { + U.m(s, U.cc("&c/time set [player] [amount-> {args=[-s][-m][-h][-d]}]")); + return; + } + + OfflinePlayer p = Bukkit.getOfflinePlayer(args[1]); + if (p == null || (p != null && !p.isOnline() && !p.hasPlayedBefore())) { + U.m(s, V.invalidPlayer.replaceAll("\\{PLAYER}", args[1])); + return; + } + + double amount = quantifyArguments(s, 2); + new AsyncTimeParameters(tempfly, this, s, p, amount).runAsync(); + } + + @Override + public void execute(AsyncTimeParameters parameters) { + CommandSender s = parameters.getSender(); + double maxTime = parameters.getMaxTime(); + if (maxTime == -999) { + U.m(s, s.isOp() ? V.vaultPermsRequired : V.invalidPlayer); + return; + } + + TimeManager manager = tempfly.getTimeManager(); + OfflinePlayer p = parameters.getTarget(); + double amount = parameters.getAmount(); + if ((maxTime > -1) && (amount > maxTime)) { + amount = maxTime; + U.m(s, manager.regexString(V.timeMaxOther, amount) + .replaceAll("\\{PLAYER}", p.getName())); + U.m(p, V.timeMaxSelf); + } + manager.setTime(parameters.getTarget().getUniqueId(), parameters); + U.m(s, manager.regexString(V.timeSetOther, amount) + .replaceAll("\\{PLAYER}", p.getName())); + if (p.isOnline()) { + U.m((Player)p, manager.regexString(V.timeSetSelf, amount)); + } + } + + @Override + public List getPotentialArguments(CommandSender s) { + if (!U.hasPermission(s, "tempfly.set")) { + return new ArrayList<>(); + } + if (args.length < 3) { + return getPlayerArguments(args[1]); + } else { + return getTimeArguments(cleanArgs(args, 2)); + } + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/command/admin/CmdTrailRemove.java b/src/com/moneybags/tempfly/command/admin/CmdTrailRemove.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/command/admin/CmdTrailRemove.java rename to src/com/moneybags/tempfly/command/admin/CmdTrailRemove.java index 271032d..e0ab4b4 100644 --- a/TempFly/src/com/moneybags/tempfly/command/admin/CmdTrailRemove.java +++ b/src/com/moneybags/tempfly/command/admin/CmdTrailRemove.java @@ -1,80 +1,80 @@ -package com.moneybags.tempfly.command.admin; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.aesthetic.particle.Particles; -import com.moneybags.tempfly.command.TempFlyCommand; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class CmdTrailRemove extends TempFlyCommand { - - public CmdTrailRemove(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - // Invoked from command - @Override - public void executeAs(CommandSender s) { - Player target = null; - if (args.length == 2 - || ((args.length > 2 && (target = Bukkit.getPlayerExact(args[3])) != null && target == s))) { - if (!(s instanceof Player)) { - U.m(s, V.invalidSender); - return; - } - target = (Player) s; - if (!target.hasPermission("tempfly.trails.remove.self")) { - U.m(target, V.invalidPermission); - return; - } - removeTrail(target); - return; - } - if (!U.hasPermission(s, "tempfly.trails.remove.other")) { - U.m(s, V.invalidPermission); - return; - } - if (args.length < 3) { - U.m(s, U.cc("&c/tf trail remove [player]")); - return; - } - - if (target == null) { - U.m(s, V.invalidPlayer.replaceAll("\\{PLAYER}", args[3])); - return; - } - removeTrail(target); - if (s != target) { - U.m(s, V.trailRemovedOther.replaceAll("\\{PLAYER}", target.getName())); - } - } - - // Invoked from the GUI because it's easier this way - public void executeFromGui(Player target) { - removeTrail(target); - } - - private void removeTrail(Player target) { - Particles.setTrail(target.getUniqueId(), ""); - U.m(target, V.trailRemovedSelf); - } - - @Override - public List getPotentialArguments(CommandSender s) { - if (args.length < 3 && U.hasPermission(s, "tempfly.trails.remove.other")) { - return getPlayerArguments(args[1]); - } else if (args.length < 3 && U.hasPermission(s, "tempfly.trails.remove.self")) { - return Arrays.asList(((Player)s).getName()); - } - return new ArrayList<>(); - } - -} +package com.moneybags.tempfly.command.admin; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.aesthetic.particle.Particles; +import com.moneybags.tempfly.command.TempFlyCommand; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class CmdTrailRemove extends TempFlyCommand { + + public CmdTrailRemove(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + // Invoked from command + @Override + public void executeAs(CommandSender s) { + Player target = null; + if (args.length == 2 + || ((args.length > 2 && (target = Bukkit.getPlayerExact(args[3])) != null && target == s))) { + if (!(s instanceof Player)) { + U.m(s, V.invalidSender); + return; + } + target = (Player) s; + if (!target.hasPermission("tempfly.trails.remove.self")) { + U.m(target, V.invalidPermission); + return; + } + removeTrail(target); + return; + } + if (!U.hasPermission(s, "tempfly.trails.remove.other")) { + U.m(s, V.invalidPermission); + return; + } + if (args.length < 3) { + U.m(s, U.cc("&c/tf trail remove [player]")); + return; + } + + if (target == null) { + U.m(s, V.invalidPlayer.replaceAll("\\{PLAYER}", args[3])); + return; + } + removeTrail(target); + if (s != target) { + U.m(s, V.trailRemovedOther.replaceAll("\\{PLAYER}", target.getName())); + } + } + + // Invoked from the GUI because it's easier this way + public void executeFromGui(Player target) { + removeTrail(target); + } + + private void removeTrail(Player target) { + Particles.setTrail(target.getUniqueId(), ""); + U.m(target, V.trailRemovedSelf); + } + + @Override + public List getPotentialArguments(CommandSender s) { + if (args.length < 3 && U.hasPermission(s, "tempfly.trails.remove.other")) { + return getPlayerArguments(args[1]); + } else if (args.length < 3 && U.hasPermission(s, "tempfly.trails.remove.self")) { + return Arrays.asList(((Player)s).getName()); + } + return new ArrayList<>(); + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/command/admin/CmdTrailSet.java b/src/com/moneybags/tempfly/command/admin/CmdTrailSet.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/command/admin/CmdTrailSet.java rename to src/com/moneybags/tempfly/command/admin/CmdTrailSet.java index 6a0e8d2..6bcba07 100644 --- a/TempFly/src/com/moneybags/tempfly/command/admin/CmdTrailSet.java +++ b/src/com/moneybags/tempfly/command/admin/CmdTrailSet.java @@ -1,100 +1,100 @@ -package com.moneybags.tempfly.command.admin; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.Effect; -import org.bukkit.Particle; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.aesthetic.particle.Particles; -import com.moneybags.tempfly.command.TempFlyCommand; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class CmdTrailSet extends TempFlyCommand { - - public CmdTrailSet(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - // Invoked from command - // /tf trail {player} {trail} - // /tf trail {trail} - @Override - public void executeAs(CommandSender s) { - String particle = args.length > 2 ? args[2].toUpperCase() : - args.length > 1 ? args[1].toUpperCase() : null; - if (particle == null) { - U.m(s, "/tf trail {player} {trail}"); - return; - } - - CommandSender target = args.length > 2 ? Bukkit.getPlayerExact(args[1]) : s; - if (s.equals(target) && !(s instanceof Player)) { - U.m(s, V.invalidSender); - return; - } - if (target == null) { - U.m(s, V.invalidPlayer.replaceAll("\\{PLAYER}", args[1])); - return; - } - - if (s.equals(target) && !s.hasPermission("tempfly.trails.set.self")) { - U.m(target, V.invalidPermission); - return; - } else if (!s.equals(target) && !s.hasPermission("tempfly.trails.set.other")) { - U.m(target, V.invalidPermission); - return; - } - - if (Particles.oldParticles()) { - try {Effect.valueOf(particle);} catch (Exception e) { - U.m(s, V.invalidParticle.replaceAll("\\{PARTICLE}", particle)); - return; - } - } else { - try {Particle.valueOf(particle);} catch (Exception e) { - U.m(s, V.invalidParticle.replaceAll("\\{PARTICLE}", particle)); - return; - } - } - Particles.setTrail(((Player)target).getUniqueId(), particle.toUpperCase()); - U.m(target, V.trailSetSelf - .replaceAll("\\{PARTICLE}", particle)); - if (s != target) { - U.m(s, V.trailSetOther - .replaceAll("\\{PLAYER}", target.getName()) - .replaceAll("\\{PARTICLE}", particle)); - } - return; - } - - @Override - public List getPotentialArguments(CommandSender s) { - Console.debug(U.arrayToString(args, " - ")); - if (args.length <= 2) { - if (U.hasPermission(s, "tempfly.trails.set.other")) { - return getPlayerArguments(args[1]); - } else if (U.hasPermission(s, "tempfly.trails.set.self")) { - return Arrays.asList(((Player)s).getName()); - } - } else if (args.length <= 3) { - List particles = new ArrayList<>(); - if (!Particles.oldParticles()) { - Arrays.asList(Particle.values()).stream().forEach(particle -> particles.add(particle.toString())); - } else { - Arrays.asList(Effect.values()).stream().forEach(particle -> particles.add(particle.toString())); - } - return particles; - } - - return new ArrayList<>(); - } - -} +package com.moneybags.tempfly.command.admin; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.Effect; +import org.bukkit.Particle; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.aesthetic.particle.Particles; +import com.moneybags.tempfly.command.TempFlyCommand; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class CmdTrailSet extends TempFlyCommand { + + public CmdTrailSet(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + // Invoked from command + // /tf trail {player} {trail} + // /tf trail {trail} + @Override + public void executeAs(CommandSender s) { + String particle = args.length > 2 ? args[2].toUpperCase() : + args.length > 1 ? args[1].toUpperCase() : null; + if (particle == null) { + U.m(s, "/tf trail {player} {trail}"); + return; + } + + CommandSender target = args.length > 2 ? Bukkit.getPlayerExact(args[1]) : s; + if (s.equals(target) && !(s instanceof Player)) { + U.m(s, V.invalidSender); + return; + } + if (target == null) { + U.m(s, V.invalidPlayer.replaceAll("\\{PLAYER}", args[1])); + return; + } + + if (s.equals(target) && !s.hasPermission("tempfly.trails.set.self")) { + U.m(target, V.invalidPermission); + return; + } else if (!s.equals(target) && !s.hasPermission("tempfly.trails.set.other")) { + U.m(target, V.invalidPermission); + return; + } + + if (Particles.oldParticles()) { + try {Effect.valueOf(particle);} catch (Exception e) { + U.m(s, V.invalidParticle.replaceAll("\\{PARTICLE}", particle)); + return; + } + } else { + try {Particle.valueOf(particle);} catch (Exception e) { + U.m(s, V.invalidParticle.replaceAll("\\{PARTICLE}", particle)); + return; + } + } + Particles.setTrail(((Player)target).getUniqueId(), particle.toUpperCase()); + U.m(target, V.trailSetSelf + .replaceAll("\\{PARTICLE}", particle)); + if (s != target) { + U.m(s, V.trailSetOther + .replaceAll("\\{PLAYER}", target.getName()) + .replaceAll("\\{PARTICLE}", particle)); + } + return; + } + + @Override + public List getPotentialArguments(CommandSender s) { + Console.debug(U.arrayToString(args, " - ")); + if (args.length <= 2) { + if (U.hasPermission(s, "tempfly.trails.set.other")) { + return getPlayerArguments(args[1]); + } else if (U.hasPermission(s, "tempfly.trails.set.self")) { + return Arrays.asList(((Player)s).getName()); + } + } else if (args.length <= 3) { + List particles = new ArrayList<>(); + if (!Particles.oldParticles()) { + Arrays.asList(Particle.values()).stream().forEach(particle -> particles.add(particle.toString())); + } else { + Arrays.asList(Effect.values()).stream().forEach(particle -> particles.add(particle.toString())); + } + return particles; + } + + return new ArrayList<>(); + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/command/player/CmdBypass.java b/src/com/moneybags/tempfly/command/player/CmdBypass.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/command/player/CmdBypass.java rename to src/com/moneybags/tempfly/command/player/CmdBypass.java index 53bcd1a..bdaa6f9 100644 --- a/TempFly/src/com/moneybags/tempfly/command/player/CmdBypass.java +++ b/src/com/moneybags/tempfly/command/player/CmdBypass.java @@ -1,56 +1,56 @@ -package com.moneybags.tempfly.command.player; - -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TempFlyCommand; -import com.moneybags.tempfly.user.FlightUser; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class CmdBypass extends TempFlyCommand { - - public CmdBypass(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - @Override - public void executeAs(CommandSender s) { - if (!U.hasPermission(s, "tempfly.bypass.toggle")) { - U.m(s, V.invalidPermission); - return; - } - if (!U.isPlayer(s)) { - U.m(s, V.invalidSender); - } - FlightUser user = tempfly.getFlightManager().getUser((Player)s); - boolean toggleVal = false; - if (args.length > 1) { - switch (args[1].toLowerCase()) { - case "on": case "enable": - toggleVal = true; - case "off": case "disable": - break; - default: - U.m(s, "&c/tempfly bypass [on/off]"); - return; - } - } else { - toggleVal = !user.hasRequirementBypass(); - } - U.m(s, toggleVal ? V.flyBypassEnabled : V.flyBypassDisabled); - user.setRequirementBypass(toggleVal); - } - - @Override - public List getPotentialArguments(CommandSender s) { - if (args.length < 3 && U.hasPermission(s, "tempfly.bypass.toggle")) { - return tempfly.getCommandManager().getToggleCompletions(true); - } - return new ArrayList<>(); - } -} +package com.moneybags.tempfly.command.player; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TempFlyCommand; +import com.moneybags.tempfly.user.FlightUser; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class CmdBypass extends TempFlyCommand { + + public CmdBypass(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + @Override + public void executeAs(CommandSender s) { + if (!U.hasPermission(s, "tempfly.bypass.toggle")) { + U.m(s, V.invalidPermission); + return; + } + if (!U.isPlayer(s)) { + U.m(s, V.invalidSender); + } + FlightUser user = tempfly.getFlightManager().getUser((Player)s); + boolean toggleVal = false; + if (args.length > 1) { + switch (args[1].toLowerCase()) { + case "on": case "enable": + toggleVal = true; + case "off": case "disable": + break; + default: + U.m(s, "&c/tempfly bypass [on/off]"); + return; + } + } else { + toggleVal = !user.hasRequirementBypass(); + } + U.m(s, toggleVal ? V.flyBypassEnabled : V.flyBypassDisabled); + user.setRequirementBypass(toggleVal); + } + + @Override + public List getPotentialArguments(CommandSender s) { + if (args.length < 3 && U.hasPermission(s, "tempfly.bypass.toggle")) { + return tempfly.getCommandManager().getToggleCompletions(true); + } + return new ArrayList<>(); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/command/player/CmdFly.java b/src/com/moneybags/tempfly/command/player/CmdFly.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/command/player/CmdFly.java rename to src/com/moneybags/tempfly/command/player/CmdFly.java index d50ef49..b8de012 100644 --- a/TempFly/src/com/moneybags/tempfly/command/player/CmdFly.java +++ b/src/com/moneybags/tempfly/command/player/CmdFly.java @@ -1,144 +1,144 @@ -package com.moneybags.tempfly.command.player; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TempFlyCommand; -import com.moneybags.tempfly.event.FlightEnabledEvent; -import com.moneybags.tempfly.user.FlightUser; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class CmdFly extends TempFlyCommand { - - public CmdFly(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - @Override - public void executeAs(CommandSender s) { - Player p = null; - boolean - manual = false, - toggleVal = false; - if (args.length > 0) { - manual = true; - if (tempfly.getCommandManager().getEnable().contains(args[0])) { - toggleVal = true; - } else if (tempfly.getCommandManager().getDisable().contains(args[0])) { - toggleVal = false; - } else { - U.m(s, U.cc("&c/tf [on/off]")); - return; - } - if (args.length > 1) { - p = Bukkit.getPlayer(args[1]); - if (s.equals(p) && !U.hasPermission(s, "tempfly.toggle.self") - || !s.equals(p) && !U.hasPermission(s, "tempfly.toggle.other")) { - U.m(s, V.invalidPermission); - return; - } - if (p == null) { - U.m(s, V.invalidPlayer.replaceAll("\\{PLAYER}", args[1])); - return; - } - } else { - if (!U.isPlayer(s)) { - U.m(s, V.invalidSender); - return; - } - if (!U.hasPermission(s, "tempfly.toggle.self")) { - U.m(s, V.invalidPermission); - return; - } - } - - - } else { - if (!U.isPlayer(s)) { - U.m(s, V.invalidSender); - return; - } - if (!U.hasPermission(s, "tempfly.toggle.self")) { - U.m(s, V.invalidPermission); - return; - } - } - if (p == null) { - p = (Player)s; - } - - - FlightUser user = tempfly.getFlightManager().getUser(p); - // if command is /fly on and player is not flying || command is base && player is not flying - // try to enable flight - if (manual && toggleVal || !manual && !toggleVal && !user.hasFlightEnabled()) { - if (user.hasFlightEnabled()) { - if (s == p) {U.m(s, V.flyAlreadyEnabled);} - return; - } - // Time check - double time = tempfly.getTimeManager().getTime(p.getUniqueId()); - if ((time <= 0) && (!user.hasInfiniteFlight())) { - U.m(s, s.equals(p) - ? V.invalidTimeSelf - : V.invalidTimeOther.replaceAll("\\{PLAYER}", p.getName())); - return; - } - - // Requirements check - if (!user.evaluateFlightRequirements(p.getLocation(), true) && !user.hasRequirementBypass()) { - if (!user.hasAutoFlyQueued()) { - user.setAutoFly(true); - } - if (s != p) {U.m(s, V.requireFailOther.replaceAll("\\{PLAYER}", p.getName()));} - return; - } - - // Event check - FlightEnabledEvent e = new FlightEnabledEvent(p); - Bukkit.getPluginManager().callEvent(e); - if (e.isCancelled()) { - return; - } - - user.enableFlight(); - U.m(p, V.flyEnabledSelf); - if (!s.equals(p)) { - U.m(s, V.flyEnabledOther.replaceAll("\\{PLAYER}", p.getName())); - } - // if command is /fly off and player is flying || command is base && player is flying - // disable flight - } else if (manual && !toggleVal && user.hasFlightEnabled() || !manual && user.hasFlightEnabled()) { - user.disableFlight(0, !V.damageCommand); - U.m(p, V.flyDisabledSelf); - if (!s.equals(p)) { - U.m(s, V.flyDisabledOther.replaceAll("\\{PLAYER}", p.getName())); - } - } else if (manual && !toggleVal && user.hasAutoFlyQueued()) { - user.setAutoFly(false); - U.m(p, V.flyDisabledSelf); - if (!s.equals(p)) { - U.m(s, V.flyDisabledOther.replaceAll("\\{PLAYER}", p.getName())); - } - } else { - U.m(p, V.flyAlreadyDisabled); - } - } - - @Override - public List getPotentialArguments(CommandSender s) { - if (args.length == 2 && U.hasPermission(s, "tempfly.toggle.other")) { - return getPlayerArguments(args[1]); - } else if (args.length == 2 && U.hasPermission(s, "tempfly.toggle.self")) { - return Arrays.asList(((Player)s).getName()); - } - return new ArrayList<>(); - } -} +package com.moneybags.tempfly.command.player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TempFlyCommand; +import com.moneybags.tempfly.event.FlightEnabledEvent; +import com.moneybags.tempfly.user.FlightUser; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class CmdFly extends TempFlyCommand { + + public CmdFly(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + @Override + public void executeAs(CommandSender s) { + Player p = null; + boolean + manual = false, + toggleVal = false; + if (args.length > 0) { + manual = true; + if (tempfly.getCommandManager().getEnable().contains(args[0])) { + toggleVal = true; + } else if (tempfly.getCommandManager().getDisable().contains(args[0])) { + toggleVal = false; + } else { + U.m(s, U.cc("&c/tf [on/off]")); + return; + } + if (args.length > 1) { + p = Bukkit.getPlayer(args[1]); + if (s.equals(p) && !U.hasPermission(s, "tempfly.toggle.self") + || !s.equals(p) && !U.hasPermission(s, "tempfly.toggle.other")) { + U.m(s, V.invalidPermission); + return; + } + if (p == null) { + U.m(s, V.invalidPlayer.replaceAll("\\{PLAYER}", args[1])); + return; + } + } else { + if (!U.isPlayer(s)) { + U.m(s, V.invalidSender); + return; + } + if (!U.hasPermission(s, "tempfly.toggle.self")) { + U.m(s, V.invalidPermission); + return; + } + } + + + } else { + if (!U.isPlayer(s)) { + U.m(s, V.invalidSender); + return; + } + if (!U.hasPermission(s, "tempfly.toggle.self")) { + U.m(s, V.invalidPermission); + return; + } + } + if (p == null) { + p = (Player)s; + } + + + FlightUser user = tempfly.getFlightManager().getUser(p); + // if command is /fly on and player is not flying || command is base && player is not flying + // try to enable flight + if (manual && toggleVal || !manual && !toggleVal && !user.hasFlightEnabled()) { + if (user.hasFlightEnabled()) { + if (s == p) {U.m(s, V.flyAlreadyEnabled);} + return; + } + // Time check + double time = tempfly.getTimeManager().getTime(p.getUniqueId()); + if ((time <= 0) && (!user.hasInfiniteFlight())) { + U.m(s, s.equals(p) + ? V.invalidTimeSelf + : V.invalidTimeOther.replaceAll("\\{PLAYER}", p.getName())); + return; + } + + // Requirements check + if (!user.evaluateFlightRequirements(p.getLocation(), true) && !user.hasRequirementBypass()) { + if (!user.hasAutoFlyQueued()) { + user.setAutoFly(true); + } + if (s != p) {U.m(s, V.requireFailOther.replaceAll("\\{PLAYER}", p.getName()));} + return; + } + + // Event check + FlightEnabledEvent e = new FlightEnabledEvent(p); + Bukkit.getPluginManager().callEvent(e); + if (e.isCancelled()) { + return; + } + + user.enableFlight(); + U.m(p, V.flyEnabledSelf); + if (!s.equals(p)) { + U.m(s, V.flyEnabledOther.replaceAll("\\{PLAYER}", p.getName())); + } + // if command is /fly off and player is flying || command is base && player is flying + // disable flight + } else if (manual && !toggleVal && user.hasFlightEnabled() || !manual && user.hasFlightEnabled()) { + user.disableFlight(0, !V.damageCommand); + U.m(p, V.flyDisabledSelf); + if (!s.equals(p)) { + U.m(s, V.flyDisabledOther.replaceAll("\\{PLAYER}", p.getName())); + } + } else if (manual && !toggleVal && user.hasAutoFlyQueued()) { + user.setAutoFly(false); + U.m(p, V.flyDisabledSelf); + if (!s.equals(p)) { + U.m(s, V.flyDisabledOther.replaceAll("\\{PLAYER}", p.getName())); + } + } else { + U.m(p, V.flyAlreadyDisabled); + } + } + + @Override + public List getPotentialArguments(CommandSender s) { + if (args.length == 2 && U.hasPermission(s, "tempfly.toggle.other")) { + return getPlayerArguments(args[1]); + } else if (args.length == 2 && U.hasPermission(s, "tempfly.toggle.self")) { + return Arrays.asList(((Player)s).getName()); + } + return new ArrayList<>(); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/command/player/CmdHelp.java b/src/com/moneybags/tempfly/command/player/CmdHelp.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/command/player/CmdHelp.java rename to src/com/moneybags/tempfly/command/player/CmdHelp.java index 2725f81..38e7872 100644 --- a/TempFly/src/com/moneybags/tempfly/command/player/CmdHelp.java +++ b/src/com/moneybags/tempfly/command/player/CmdHelp.java @@ -1,40 +1,40 @@ -package com.moneybags.tempfly.command.player; - -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.command.CommandSender; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TempFlyCommand; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class CmdHelp extends TempFlyCommand { - - public CmdHelp(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - @Override - public void executeAs(CommandSender s) { - if (!U.hasPermission(s, "tempfly.help")) { - U.m(s, V.invalidPermission); - return; - } - for (String line: V.help) { - U.m(s, line); - } - if (U.hasPermission(s, "tempfly.help.admin")) { - for (String line: V.helpExtended) { - U.m(s, line); - } - } - } - - @Override - public List getPotentialArguments(CommandSender s) { - return new ArrayList<>(); - } - -} +package com.moneybags.tempfly.command.player; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.command.CommandSender; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TempFlyCommand; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class CmdHelp extends TempFlyCommand { + + public CmdHelp(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + @Override + public void executeAs(CommandSender s) { + if (!U.hasPermission(s, "tempfly.help")) { + U.m(s, V.invalidPermission); + return; + } + for (String line: V.help) { + U.m(s, line); + } + if (U.hasPermission(s, "tempfly.help.admin")) { + for (String line: V.helpExtended) { + U.m(s, line); + } + } + } + + @Override + public List getPotentialArguments(CommandSender s) { + return new ArrayList<>(); + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/command/player/CmdInfinite.java b/src/com/moneybags/tempfly/command/player/CmdInfinite.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/command/player/CmdInfinite.java rename to src/com/moneybags/tempfly/command/player/CmdInfinite.java index d1340c1..9fcfb74 100644 --- a/TempFly/src/com/moneybags/tempfly/command/player/CmdInfinite.java +++ b/src/com/moneybags/tempfly/command/player/CmdInfinite.java @@ -1,62 +1,62 @@ -package com.moneybags.tempfly.command.player; - -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TempFlyCommand; -import com.moneybags.tempfly.user.FlightUser; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class CmdInfinite extends TempFlyCommand { - - public CmdInfinite(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - @Override - public void executeAs(CommandSender s) { - if (!U.hasPermission(s, "tempfly.infinite.toggle")) { - U.m(s, V.invalidPermission); - return; - } - if (!U.isPlayer(s)) { - U.m(s, V.invalidSender); - return; - } - FlightUser user = tempfly.getFlightManager().getUser((Player)s); - boolean toggleVal = false; - if (args.length > 1) { - switch (args[1].toLowerCase()) { - case "on": case "enable": - toggleVal = true; - case "off": case "disable": - break; - default: - U.m(s, "&c/tempfly infinite [on/off]"); - return; - } - } else { - toggleVal = !user.hasInfiniteFlight(); - } - user.setInfiniteFlight(toggleVal); - // If the player has auto fly queued we will auto enable their flight when they toggle infinite time. - if (toggleVal && user.hasAutoFlyQueued()) { - user.enableFlight(); - } - U.m(s, toggleVal ? V.flyInfiniteEnabled : V.flyInfiniteDisabled); - } - - @Override - public List getPotentialArguments(CommandSender s) { - if (args.length < 3 && U.hasPermission(s, "tempfly.infinite.toggle")) { - return tempfly.getCommandManager().getToggleCompletions(true); - } - return new ArrayList<>(); - } - -} +package com.moneybags.tempfly.command.player; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TempFlyCommand; +import com.moneybags.tempfly.user.FlightUser; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class CmdInfinite extends TempFlyCommand { + + public CmdInfinite(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + @Override + public void executeAs(CommandSender s) { + if (!U.hasPermission(s, "tempfly.infinite.toggle")) { + U.m(s, V.invalidPermission); + return; + } + if (!U.isPlayer(s)) { + U.m(s, V.invalidSender); + return; + } + FlightUser user = tempfly.getFlightManager().getUser((Player)s); + boolean toggleVal = false; + if (args.length > 1) { + switch (args[1].toLowerCase()) { + case "on": case "enable": + toggleVal = true; + case "off": case "disable": + break; + default: + U.m(s, "&c/tempfly infinite [on/off]"); + return; + } + } else { + toggleVal = !user.hasInfiniteFlight(); + } + user.setInfiniteFlight(toggleVal); + // If the player has auto fly queued we will auto enable their flight when they toggle infinite time. + if (toggleVal && user.hasAutoFlyQueued()) { + user.enableFlight(); + } + U.m(s, toggleVal ? V.flyInfiniteEnabled : V.flyInfiniteDisabled); + } + + @Override + public List getPotentialArguments(CommandSender s) { + if (args.length < 3 && U.hasPermission(s, "tempfly.infinite.toggle")) { + return tempfly.getCommandManager().getToggleCompletions(true); + } + return new ArrayList<>(); + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/command/player/CmdPay.java b/src/com/moneybags/tempfly/command/player/CmdPay.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/command/player/CmdPay.java rename to src/com/moneybags/tempfly/command/player/CmdPay.java index 6b0b0c5..c23b91d 100644 --- a/TempFly/src/com/moneybags/tempfly/command/player/CmdPay.java +++ b/src/com/moneybags/tempfly/command/player/CmdPay.java @@ -1,112 +1,112 @@ -package com.moneybags.tempfly.command.player; - -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TimeCommand; -import com.moneybags.tempfly.time.AsyncTimeParameters; -import com.moneybags.tempfly.time.TimeManager; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class CmdPay extends TimeCommand { - - public CmdPay(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - @Override @SuppressWarnings("deprecation") - public void executeAs(CommandSender s) { - if (!V.payable) { - U.m(s, V.invalidCommand); - return; - } - if (!U.isPlayer(s)) { - U.m(s, V.invalidSender); - return; - } - if (!U.hasPermission(s, "tempfly.pay")) { - U.m(s, V.invalidPermission); - return; - } - if (args.length < 3) { - U.m(s, U.cc("&c/tf pay [player] [amount-> {args=[-s][-m][-h][-d]}]")); - return; - } - OfflinePlayer p = Bukkit.getOfflinePlayer(args[1]); - if (p == null || (p != null && !p.isOnline() && !p.hasPlayedBefore())) { - U.m(s, V.invalidPlayer.replaceAll("\\{PLAYER}", args[1])); - return; - } - - if ((Player)s == p) { - U.m(s, V.invalidReciever); - return; - } - double amount = 0; - amount = quantifyArguments(s, 2); - if (amount <= 0) { - U.m(s, V.invalidNumber.replaceAll("\\{NUMBER}", String.valueOf(amount))); - return; - } - amount = Math.floor(amount); - TimeManager manager = tempfly.getTimeManager(); - Player sender = (Player)s; - //This doens't need to be async as the player needs to be online to pay, so their data is already loaded. - double bal = manager.getTime(sender.getUniqueId()); - if (bal < amount) { - U.m(s, V.invalidTimeSelf); - return; - } - new AsyncTimeParameters(tempfly, this, s, p, amount).runAsync(); - } - - @Override - public void execute(AsyncTimeParameters parameters) { - CommandSender s = parameters.getSender(); - double maxTime = parameters.getMaxTime(); - if (maxTime == -999) { - U.m(s, s.isOp() ? V.vaultPermsRequired : V.invalidPlayer); - return; - } - - TimeManager manager = tempfly.getTimeManager(); - OfflinePlayer p = parameters.getTarget(); - double amount = parameters.getAmount(); - if ((maxTime > -1) && (manager.getTime(p.getUniqueId()) + amount >= maxTime)) { - U.m(s, manager.regexString(V.timeMaxOther, amount) - .replaceAll("\\{PLAYER}", p.getName())); - U.m(p, V.timeMaxSelf); - return; - } - - manager.removeTime(((Player)s).getUniqueId(), parameters); - manager.addTime(p.getUniqueId(), parameters); - U.m(s, manager.regexString(V.timeSentOther, amount) - .replaceAll("\\{PLAYER}", p.getName())); - if (p.isOnline()) { - U.m((Player)p, manager.regexString(V.timeSentSelf, amount) - .replaceAll("\\{PLAYER}", s.getName())); - } - } - - @Override - public List getPotentialArguments(CommandSender s) { - if (!U.hasPermission(s, "tempfly.pay") || !V.payable) { - return new ArrayList<>(); - } - if (args.length < 3) { - return getPlayerArguments(args[1]); - } else { - return getTimeArguments(cleanArgs(args, 2)); - } - } - - -} +package com.moneybags.tempfly.command.player; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TimeCommand; +import com.moneybags.tempfly.time.AsyncTimeParameters; +import com.moneybags.tempfly.time.TimeManager; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class CmdPay extends TimeCommand { + + public CmdPay(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + @Override @SuppressWarnings("deprecation") + public void executeAs(CommandSender s) { + if (!V.payable) { + U.m(s, V.invalidCommand); + return; + } + if (!U.isPlayer(s)) { + U.m(s, V.invalidSender); + return; + } + if (!U.hasPermission(s, "tempfly.pay")) { + U.m(s, V.invalidPermission); + return; + } + if (args.length < 3) { + U.m(s, U.cc("&c/tf pay [player] [amount-> {args=[-s][-m][-h][-d]}]")); + return; + } + OfflinePlayer p = Bukkit.getOfflinePlayer(args[1]); + if (p == null || (p != null && !p.isOnline() && !p.hasPlayedBefore())) { + U.m(s, V.invalidPlayer.replaceAll("\\{PLAYER}", args[1])); + return; + } + + if ((Player)s == p) { + U.m(s, V.invalidReciever); + return; + } + double amount = 0; + amount = quantifyArguments(s, 2); + if (amount <= 0) { + U.m(s, V.invalidNumber.replaceAll("\\{NUMBER}", String.valueOf(amount))); + return; + } + amount = Math.floor(amount); + TimeManager manager = tempfly.getTimeManager(); + Player sender = (Player)s; + //This doens't need to be async as the player needs to be online to pay, so their data is already loaded. + double bal = manager.getTime(sender.getUniqueId()); + if (bal < amount) { + U.m(s, V.invalidTimeSelf); + return; + } + new AsyncTimeParameters(tempfly, this, s, p, amount).runAsync(); + } + + @Override + public void execute(AsyncTimeParameters parameters) { + CommandSender s = parameters.getSender(); + double maxTime = parameters.getMaxTime(); + if (maxTime == -999) { + U.m(s, s.isOp() ? V.vaultPermsRequired : V.invalidPlayer); + return; + } + + TimeManager manager = tempfly.getTimeManager(); + OfflinePlayer p = parameters.getTarget(); + double amount = parameters.getAmount(); + if ((maxTime > -1) && (manager.getTime(p.getUniqueId()) + amount >= maxTime)) { + U.m(s, manager.regexString(V.timeMaxOther, amount) + .replaceAll("\\{PLAYER}", p.getName())); + U.m(p, V.timeMaxSelf); + return; + } + + manager.removeTime(((Player)s).getUniqueId(), parameters); + manager.addTime(p.getUniqueId(), parameters); + U.m(s, manager.regexString(V.timeSentOther, amount) + .replaceAll("\\{PLAYER}", p.getName())); + if (p.isOnline()) { + U.m((Player)p, manager.regexString(V.timeSentSelf, amount) + .replaceAll("\\{PLAYER}", s.getName())); + } + } + + @Override + public List getPotentialArguments(CommandSender s) { + if (!U.hasPermission(s, "tempfly.pay") || !V.payable) { + return new ArrayList<>(); + } + if (args.length < 3) { + return getPlayerArguments(args[1]); + } else { + return getTimeArguments(cleanArgs(args, 2)); + } + } + + +} diff --git a/TempFly/src/com/moneybags/tempfly/command/player/CmdShop.java b/src/com/moneybags/tempfly/command/player/CmdShop.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/command/player/CmdShop.java rename to src/com/moneybags/tempfly/command/player/CmdShop.java index 65f87fb..200f2d7 100644 --- a/TempFly/src/com/moneybags/tempfly/command/player/CmdShop.java +++ b/src/com/moneybags/tempfly/command/player/CmdShop.java @@ -1,46 +1,46 @@ -package com.moneybags.tempfly.command.player; - -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TempFlyCommand; -import com.moneybags.tempfly.gui.pages.PageShop; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class CmdShop extends TempFlyCommand { - - public CmdShop(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - @Override - public void executeAs(CommandSender s) { - if (!V.shop) { - U.m(s, V.invalidCommand); - return; - } - if (tempfly.getHookManager().getEconomy() == null) { - U.m(s, V.invalidEconomy); - return; - } - if (!U.isPlayer(s)) { - U.m(s, V.invalidSender); - return; - } - if (!U.hasPermission(s, "tempfly.shop")) { - U.m(s, V.invalidPermission); - return; - } - new PageShop(tempfly.getGuiManager().createSession((Player)s), 0); - } - - @Override - public List getPotentialArguments(CommandSender s) { - return new ArrayList<>(); - } -} +package com.moneybags.tempfly.command.player; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TempFlyCommand; +import com.moneybags.tempfly.gui.pages.PageShop; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class CmdShop extends TempFlyCommand { + + public CmdShop(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + @Override + public void executeAs(CommandSender s) { + if (!V.shop) { + U.m(s, V.invalidCommand); + return; + } + if (tempfly.getHookManager().getEconomy() == null) { + U.m(s, V.invalidEconomy); + return; + } + if (!U.isPlayer(s)) { + U.m(s, V.invalidSender); + return; + } + if (!U.hasPermission(s, "tempfly.shop")) { + U.m(s, V.invalidPermission); + return; + } + new PageShop(tempfly.getGuiManager().createSession((Player)s), 0); + } + + @Override + public List getPotentialArguments(CommandSender s) { + return new ArrayList<>(); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/command/player/CmdSpeed.java b/src/com/moneybags/tempfly/command/player/CmdSpeed.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/command/player/CmdSpeed.java rename to src/com/moneybags/tempfly/command/player/CmdSpeed.java index f460b74..119e2ac 100644 --- a/TempFly/src/com/moneybags/tempfly/command/player/CmdSpeed.java +++ b/src/com/moneybags/tempfly/command/player/CmdSpeed.java @@ -1,120 +1,120 @@ -package com.moneybags.tempfly.command.player; - -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TempFlyCommand; -import com.moneybags.tempfly.user.FlightUser; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class CmdSpeed extends TempFlyCommand { - - public CmdSpeed(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - @Override - public void executeAs(CommandSender s) { - Player p = null; - float speed = 1; - - if (args.length > 2) { - if (!U.hasPermission(s, "tempfly.speed.other")) { - U.m(s, V.invalidPermission); - return; - } - p = Bukkit.getPlayer(args[2]); - if (p == null) { - U.m(s, V.invalidPlayer.replaceAll("\\{PLAYER}", args[2])); - return; - } - } - - if (args.length > 1) { - if (p == null && !U.isPlayer(s)) { - U.m(s, V.invalidSender); - return; - } - if (!U.hasPermission(s, "tempfly.speed.self")) { - U.m(s, V.invalidPermission); - return; - } - if (p == null) { - p = (Player) s; - } - - if (args[1].equalsIgnoreCase("reset")) { - speed = -999; - } else { - try { - speed = Float.parseFloat(args[1]); - } catch (Exception e) { - U.m(s, V.invalidNumber); - return; - } - } - } else { - U.m(s, U.cc("/tf speed [speed / reset]")); - return; - } - - FlightUser user = tempfly.getFlightManager().getUser(p); - user.setSpeedPreference(speed); - float old = user.getPlayer().getFlySpeed(); - float fin = user.applySpeedCorrect(false, 0); - String result = new DecimalFormat("#.##").format(fin * 10); - - if (fin < (speed / 10) && p.equals(s)) { - U.m(p, V.flySpeedLimitSelf.replaceAll("\\{SPEED}", result)); - if (old == (speed / 10)) { - return; - } - } - U.m(p, V.flySpeedSelf - .replaceAll("\\{SPEED}", speed == -999 ? "DEFAULT" : result)); - if (!s.equals(p)) { - if (fin < speed) { - U.m(s, V.flySpeedLimitOther - .replaceAll("\\{SPEED}", result) - .replaceAll("\\{PLAYER}", p.getName())); - if (old == (speed / 10)) { - return; - } - } - U.m(s, V.flySpeedOther - .replaceAll("\\{SPEED}", speed == -999 ? "DEFAULT" : result) - .replaceAll("\\{PLAYER}", p.getName())); - } - - } - - @Override - public List getPotentialArguments(CommandSender s) { - if (args.length > 3) { - return new ArrayList<>(); - } - if (args.length == 3) { - return U.hasPermission(s, "tempfly.speed.other") ? getPlayerArguments(args[2]) - : U.hasPermission(s, "tempfly.speed.self") ? Arrays.asList(((Player)s).getName()) : new ArrayList<>(); - } - if (args.length >= 2 && !U.hasPermission(s, "tempfly.speed.self") || (s instanceof Player)) { - return new ArrayList<>(); - } - if (s instanceof Player) { - FlightUser user = tempfly.getFlightManager().getUser((Player)s); - Console.debug(user.getMaxSpeed()); - return getRange(1, (int)Math.floor(user.getMaxSpeed())); - } else { - return getRange(0, 10); - } - } -} +package com.moneybags.tempfly.command.player; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TempFlyCommand; +import com.moneybags.tempfly.user.FlightUser; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class CmdSpeed extends TempFlyCommand { + + public CmdSpeed(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + @Override + public void executeAs(CommandSender s) { + Player p = null; + float speed = 1; + + if (args.length > 2) { + if (!U.hasPermission(s, "tempfly.speed.other")) { + U.m(s, V.invalidPermission); + return; + } + p = Bukkit.getPlayer(args[2]); + if (p == null) { + U.m(s, V.invalidPlayer.replaceAll("\\{PLAYER}", args[2])); + return; + } + } + + if (args.length > 1) { + if (p == null && !U.isPlayer(s)) { + U.m(s, V.invalidSender); + return; + } + if (!U.hasPermission(s, "tempfly.speed.self")) { + U.m(s, V.invalidPermission); + return; + } + if (p == null) { + p = (Player) s; + } + + if (args[1].equalsIgnoreCase("reset")) { + speed = -999; + } else { + try { + speed = Float.parseFloat(args[1]); + } catch (Exception e) { + U.m(s, V.invalidNumber); + return; + } + } + } else { + U.m(s, U.cc("/tf speed [speed / reset]")); + return; + } + + FlightUser user = tempfly.getFlightManager().getUser(p); + user.setSpeedPreference(speed); + float old = user.getPlayer().getFlySpeed(); + float fin = user.applySpeedCorrect(false, 0); + String result = new DecimalFormat("#.##").format(fin * 10); + + if (fin < (speed / 10) && p.equals(s)) { + U.m(p, V.flySpeedLimitSelf.replaceAll("\\{SPEED}", result)); + if (old == (speed / 10)) { + return; + } + } + U.m(p, V.flySpeedSelf + .replaceAll("\\{SPEED}", speed == -999 ? "DEFAULT" : result)); + if (!s.equals(p)) { + if (fin < speed) { + U.m(s, V.flySpeedLimitOther + .replaceAll("\\{SPEED}", result) + .replaceAll("\\{PLAYER}", p.getName())); + if (old == (speed / 10)) { + return; + } + } + U.m(s, V.flySpeedOther + .replaceAll("\\{SPEED}", speed == -999 ? "DEFAULT" : result) + .replaceAll("\\{PLAYER}", p.getName())); + } + + } + + @Override + public List getPotentialArguments(CommandSender s) { + if (args.length > 3) { + return new ArrayList<>(); + } + if (args.length == 3) { + return U.hasPermission(s, "tempfly.speed.other") ? getPlayerArguments(args[2]) + : U.hasPermission(s, "tempfly.speed.self") ? Arrays.asList(((Player)s).getName()) : new ArrayList<>(); + } + if (args.length >= 2 && !U.hasPermission(s, "tempfly.speed.self") || (s instanceof Player)) { + return new ArrayList<>(); + } + if (s instanceof Player) { + FlightUser user = tempfly.getFlightManager().getUser((Player)s); + Console.debug(user.getMaxSpeed()); + return getRange(1, (int)Math.floor(user.getMaxSpeed())); + } else { + return getRange(0, 10); + } + } +} diff --git a/TempFly/src/com/moneybags/tempfly/command/player/CmdTime.java b/src/com/moneybags/tempfly/command/player/CmdTime.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/command/player/CmdTime.java rename to src/com/moneybags/tempfly/command/player/CmdTime.java index dac1bed..cd59ea2 100644 --- a/TempFly/src/com/moneybags/tempfly/command/player/CmdTime.java +++ b/src/com/moneybags/tempfly/command/player/CmdTime.java @@ -1,96 +1,96 @@ -package com.moneybags.tempfly.command.player; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TimeCommand; -import com.moneybags.tempfly.time.AsyncTimeParameters; -import com.moneybags.tempfly.time.TimeManager; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class CmdTime extends TimeCommand { - - public CmdTime(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - @SuppressWarnings("deprecation") - public void executeAs(CommandSender s) { - if (args.length > 1) { - if (!U.hasPermission(s, "tempfly.time.other")) { - U.m(s, V.invalidPermission); - return; - } - OfflinePlayer p = Bukkit.getOfflinePlayer(args[1]); - if (p == null || (p != null && !p.isOnline() && !p.hasPlayedBefore())) { - U.m(s, V.invalidPlayer); - return; - } - new AsyncTimeParameters(tempfly, this, s, p, 0).runAsync(); - } else { - if (!U.hasPermission(s, "tempfly.time.self")) { - U.m(s, V.invalidPermission); - return; - } - if (!U.isPlayer(s)) { - U.m(s, V.invalidSender); - return; - } - new AsyncTimeParameters(tempfly, this, s, (Player)s, 0).runAsync(); - } - } - - public void execute(AsyncTimeParameters parameters) { - CommandSender s = parameters.getSender(); - OfflinePlayer p = parameters.getTarget(); - - TimeManager manager = tempfly.getTimeManager(); - double time = parameters.getCurrentTime(); - U.m(s, manager.regexString(V.infoHeader, time)); - U.m(s, manager.regexString(V.infoPlayer, time).replaceAll("\\{PLAYER}", p.getName())); - final boolean infinite = p.isOnline() && tempfly.getFlightManager().getUser((Player)p).hasInfiniteFlight(); - if (infinite) { - U.m(s, V.infoInfinite); - } - long days = manager.formatTime(TimeUnit.DAYS, time); - if (days > 0) { - U.m(s, manager.regexString(V.infoDays, time)); - } - - double hours = manager.formatTime(TimeUnit.HOURS, time); - if (hours > 0) { - U.m(s, manager.regexString(V.infoHours, time)); - } - - double minutes = manager.formatTime(TimeUnit.MINUTES, time); - if (minutes > 0) { - U.m(s, manager.regexString(V.infoMinutes, time)); - } - - double seconds = manager.formatTime(TimeUnit.SECONDS, time); - if (seconds > 0 || (seconds == 0 && days == 0 && hours == 0 && minutes == 0 && !infinite)) { - U.m(s, manager.regexString(V.infoSeconds, time)); - } - U.m(s, manager.regexString(V.infoFooter, time)); - } - - @Override - public List getPotentialArguments(CommandSender s) { - if (args.length < 3 && U.hasPermission(s, "tempfly.time.other")) { - return getPlayerArguments(args[1]); - } else if (args.length < 3 && U.hasPermission(s, "tempfly.time.self")) { - return Arrays.asList(((Player)s).getName()); - } - return new ArrayList<>(); - - } -} +package com.moneybags.tempfly.command.player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TimeCommand; +import com.moneybags.tempfly.time.AsyncTimeParameters; +import com.moneybags.tempfly.time.TimeManager; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class CmdTime extends TimeCommand { + + public CmdTime(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + @SuppressWarnings("deprecation") + public void executeAs(CommandSender s) { + if (args.length > 1) { + if (!U.hasPermission(s, "tempfly.time.other")) { + U.m(s, V.invalidPermission); + return; + } + OfflinePlayer p = Bukkit.getOfflinePlayer(args[1]); + if (p == null || (p != null && !p.isOnline() && !p.hasPlayedBefore())) { + U.m(s, V.invalidPlayer); + return; + } + new AsyncTimeParameters(tempfly, this, s, p, 0).runAsync(); + } else { + if (!U.hasPermission(s, "tempfly.time.self")) { + U.m(s, V.invalidPermission); + return; + } + if (!U.isPlayer(s)) { + U.m(s, V.invalidSender); + return; + } + new AsyncTimeParameters(tempfly, this, s, (Player)s, 0).runAsync(); + } + } + + public void execute(AsyncTimeParameters parameters) { + CommandSender s = parameters.getSender(); + OfflinePlayer p = parameters.getTarget(); + + TimeManager manager = tempfly.getTimeManager(); + double time = parameters.getCurrentTime(); + U.m(s, manager.regexString(V.infoHeader, time)); + U.m(s, manager.regexString(V.infoPlayer, time).replaceAll("\\{PLAYER}", p.getName())); + final boolean infinite = p.isOnline() && tempfly.getFlightManager().getUser((Player)p).hasInfiniteFlight(); + if (infinite) { + U.m(s, V.infoInfinite); + } + long days = manager.formatTime(TimeUnit.DAYS, time); + if (days > 0) { + U.m(s, manager.regexString(V.infoDays, time)); + } + + double hours = manager.formatTime(TimeUnit.HOURS, time); + if (hours > 0) { + U.m(s, manager.regexString(V.infoHours, time)); + } + + double minutes = manager.formatTime(TimeUnit.MINUTES, time); + if (minutes > 0) { + U.m(s, manager.regexString(V.infoMinutes, time)); + } + + double seconds = manager.formatTime(TimeUnit.SECONDS, time); + if (seconds > 0 || (seconds == 0 && days == 0 && hours == 0 && minutes == 0 && !infinite)) { + U.m(s, manager.regexString(V.infoSeconds, time)); + } + U.m(s, manager.regexString(V.infoFooter, time)); + } + + @Override + public List getPotentialArguments(CommandSender s) { + if (args.length < 3 && U.hasPermission(s, "tempfly.time.other")) { + return getPlayerArguments(args[1]); + } else if (args.length < 3 && U.hasPermission(s, "tempfly.time.self")) { + return Arrays.asList(((Player)s).getName()); + } + return new ArrayList<>(); + + } +} diff --git a/TempFly/src/com/moneybags/tempfly/command/player/CmdTrails.java b/src/com/moneybags/tempfly/command/player/CmdTrails.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/command/player/CmdTrails.java rename to src/com/moneybags/tempfly/command/player/CmdTrails.java index 5ea2799..5843108 100644 --- a/TempFly/src/com/moneybags/tempfly/command/player/CmdTrails.java +++ b/src/com/moneybags/tempfly/command/player/CmdTrails.java @@ -1,38 +1,38 @@ -package com.moneybags.tempfly.command.player; - -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TempFlyCommand; -import com.moneybags.tempfly.gui.pages.PageTrails; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class CmdTrails extends TempFlyCommand { - - public CmdTrails(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - @Override - public void executeAs(CommandSender s) { - if (!U.isPlayer(s)) { - U.m(s, V.invalidSender); - return; - } - if (!U.hasPermission(s, "tempfly.trails")) { - U.m(s, V.invalidPermission); - return; - } - new PageTrails(tempfly.getGuiManager().createSession((Player)s), 0, true); - } - - @Override - public List getPotentialArguments(CommandSender s) { - return new ArrayList<>(); - } -} +package com.moneybags.tempfly.command.player; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TempFlyCommand; +import com.moneybags.tempfly.gui.pages.PageTrails; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class CmdTrails extends TempFlyCommand { + + public CmdTrails(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + @Override + public void executeAs(CommandSender s) { + if (!U.isPlayer(s)) { + U.m(s, V.invalidSender); + return; + } + if (!U.hasPermission(s, "tempfly.trails")) { + U.m(s, V.invalidPermission); + return; + } + new PageTrails(tempfly.getGuiManager().createSession((Player)s), 0, true); + } + + @Override + public List getPotentialArguments(CommandSender s) { + return new ArrayList<>(); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/environment/FlightEnvironment.java b/src/com/moneybags/tempfly/environment/FlightEnvironment.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/environment/FlightEnvironment.java rename to src/com/moneybags/tempfly/environment/FlightEnvironment.java index 301ede4..d234b60 100644 --- a/TempFly/src/com/moneybags/tempfly/environment/FlightEnvironment.java +++ b/src/com/moneybags/tempfly/environment/FlightEnvironment.java @@ -1,348 +1,348 @@ -package com.moneybags.tempfly.environment; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.configuration.ConfigurationSection; - -import com.moneybags.tempfly.fly.FlightManager; -import com.moneybags.tempfly.fly.RequirementProvider; -import com.moneybags.tempfly.fly.result.FlightResult; -import com.moneybags.tempfly.fly.result.FlightResult.DenyReason; -import com.moneybags.tempfly.fly.result.ResultAllow; -import com.moneybags.tempfly.fly.result.ResultDeny; -import com.moneybags.tempfly.hook.region.CompatRegion; -import com.moneybags.tempfly.user.FlightUser; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.V; -import com.moneybags.tempfly.util.data.Files; - -public class FlightEnvironment implements RequirementProvider { - - private FlightManager manager; - - private Map rtRegions = new HashMap<>(); - private Map rtWorlds = new HashMap<>(); - - private List blackRegions = new ArrayList<>(); - private List blackWorlds = new ArrayList<>(); - - private List whiteRegions = new ArrayList<>(); - private List whiteWorlds = new ArrayList<>(); - - private List freeRegions = new ArrayList<>(); - private List freeWorlds = new ArrayList<>(); - - - - private float speedGlobal = 1; - private boolean allowPreferredSpeed; - private Map speedWorlds = new HashMap<>(); - private Map speedRegions = new HashMap<>(); - - - public FlightEnvironment(FlightManager manager) { - this.manager = manager; - onTempflyReload(); - } - - public FlightManager getFlightManager() { - return manager; - } - - - - /** - * - * --=-------------=-- - * Relative Time - * --=-------------=-- - * - */ - - - - public RelativeTimeRegion[] getRelativeTimeRegions() { - return rtRegions.values().toArray(new RelativeTimeRegion[rtRegions.size()]); - } - - public RelativeTimeRegion[] getRelativeTimeWorlds() { - return rtWorlds.values().toArray(new RelativeTimeRegion[rtWorlds.size()]); - } - - public boolean hasRelativeTime(World world) { - return rtWorlds.containsKey(world.getName()); - } - - public boolean hasRelativeTime(CompatRegion region) { - return rtRegions.containsKey(region.getId()); - } - - public RelativeTimeRegion getRelativeTime(World world) { - return rtWorlds.get(world.getName()); - } - - public RelativeTimeRegion getRelativeTime(CompatRegion region) { - return rtRegions.get(region.getId()); - } - - - - /** - * - * --=--------=-- - * Disabled - * --=--------=-- - * - */ - - - - public boolean isDisabled(World world) { - return blackWorlds.contains(world.getName()); - } - - public boolean isDisabled(CompatRegion region) { - return blackRegions.contains(region.getId()); - } - - - - /** - * - * --=---------=-- - * whitelist - * --=---------=-- - * - */ - - public boolean isWhitelisted(World world) { - return whiteWorlds.size() == 0 || whiteWorlds.contains(world.getName()); - } - - public boolean isWhitelisted(CompatRegion region) { - return whiteRegions.size() == 0 || whiteRegions.contains(region.getId()); - } - - - - /** - * - * --=---------=-- - * infinite - * --=---------=-- - * - */ - - public boolean isInfinite(World world) { - return freeWorlds.contains(world.getName()); - } - - public boolean isInfinite(CompatRegion region) { - return freeRegions.contains(region.getId()); - } - - - /** - * - * --=---------=-- - * Speed - * --=---------=-- - * - */ - - - - public boolean hasMaxSpeed(World world) { - return speedWorlds.containsKey(world.getName()); - } - - public boolean hasMaxSpeed(CompatRegion region) { - //Console.debug(region.getId(), speedRegions.containsKey(region.getId())); - return speedRegions.containsKey(region.getId()); - } - - public boolean hasMaxSpeed(CompatRegion[] regions) { - for (CompatRegion region: regions) { - if (hasMaxSpeed(region)) { - return true; - } - } - return false; - } - - public float getDefaultSpeed() { - return speedGlobal; - } - - public float getMaxSpeed(World world) { - return speedWorlds.getOrDefault(world.getName(), getDefaultSpeed()); - } - - public float getMaxSpeed(CompatRegion region) { - //Console.debug(region.getId(), speedRegions.get(region.getId())); - return speedRegions.getOrDefault(region.getId(), getDefaultSpeed()); - } - - public float getMaxSpeed(CompatRegion[] regions) { - float highest = -999; - for (CompatRegion region: regions) { - if (hasMaxSpeed(region)) { - float speed = getMaxSpeed(region); - if (highest == -999 || highest < speed) { - highest = speed; - } - } - } - return highest == -999 ? getDefaultSpeed() : highest; - } - - public boolean allowSpeedPreference() { - return allowPreferredSpeed; - } - - - - /** - * - * --=--------------------=-- - * Requirement Provider - * --=--------------------=-- - * - */ - - - - /** - * Deprecated as of TempFly 3.0, This method will only check for blacklisted regions and worlds. - * I left it in because the api needs this method for legacy support. - * Check if flight is allowed at a given location. - * @param loc the location in question. - * @return - */ - @Deprecated - public boolean flyAllowed(Location loc) { - if (manager.getTempFly().getHookManager().hasRegionProvider()) { - for (CompatRegion r: manager.getTempFly().getHookManager().getRegionProvider().getApplicableRegions(loc)) { - if (blackRegions.contains(r.getId())) { - return false; - } - } - } - return !V.disabledWorlds.contains(loc.getWorld().getName()); - } - - /** - * disabled regions - */ - @Override - public FlightResult handleFlightInquiry(FlightUser user, CompatRegion[] regions) { - for (CompatRegion region: regions) { - FlightResult result = handleFlightInquiry(user, region); - if (!result.isAllowed()) { - return result; - } - } - return new ResultAllow(this, InquiryType.REGION, V.requirePassDefault); - } - - /** - * disabled region - */ - @Override - public FlightResult handleFlightInquiry(FlightUser user, CompatRegion r) { - return isDisabled(r) || !isWhitelisted(r) ? new ResultDeny(DenyReason.DISABLED_REGION, this, InquiryType.REGION, V.requireFailRegion, !V.damageRegion) - : new ResultAllow(this, InquiryType.REGION, V.requirePassDefault); - } - - /** - * disabled worlds - */ - @Override - public FlightResult handleFlightInquiry(FlightUser user, World world) { - return isDisabled(world) || !isWhitelisted(world) ? new ResultDeny(DenyReason.DISABLED_WORLD, this, InquiryType.WORLD, V.requireFailWorld, !V.damageWorld) - : new ResultAllow(this, InquiryType.WORLD, V.requirePassDefault); - } - - /** - * max y - */ - @Override - public FlightResult handleFlightInquiry(FlightUser user, Location loc) { - if (user.hasFlightRequirement(this, InquiryType.LOCATION)) { - return loc.getBlockY() <= V.maxY-5 ? new ResultAllow(this, InquiryType.LOCATION, V.requirePassDefault) : - new ResultDeny(DenyReason.OTHER, this, InquiryType.LOCATION, - V.requireFailHeight.replaceAll("\\{MAX_Y}", String.valueOf(V.maxY)), false); - } - return loc.getBlockY() > V.maxY ? new ResultDeny(DenyReason.OTHER, this, InquiryType.LOCATION, - V.requireFailHeight.replaceAll("\\{MAX_Y}", String.valueOf(V.maxY)), false) - : new ResultAllow(this, InquiryType.LOCATION, V.requirePassDefault); - } - - @Override - public boolean handles(InquiryType type) { - return false; - } - - @Override - public void onTempflyReload() { - blackRegions = Files.config.contains("general.disabled.regions") ? Files.config.getStringList("general.disabled.regions") : new ArrayList<>(); - blackWorlds = Files.config.contains("general.disabled.worlds") ? Files.config.getStringList("general.disabled.worlds") : new ArrayList<>(); - - whiteRegions = Files.config.contains("general.whitelist.regions") ? Files.config.getStringList("general.whitelist.regions") : new ArrayList<>(); - whiteWorlds = Files.config.contains("general.whitelist.worlds") ? Files.config.getStringList("general.whitelist.worlds") : new ArrayList<>(); - - whiteRegions = Files.config.contains("general.whitelist.regions") ? Files.config.getStringList("general.whitelist.regions") : new ArrayList<>(); - whiteWorlds = Files.config.contains("general.whitelist.worlds") ? Files.config.getStringList("general.whitelist.worlds") : new ArrayList<>(); - - freeRegions = Files.config.contains("general.time.infinite.regions") ? Files.config.getStringList("general.time.infinite.regions") : new ArrayList<>(); - freeWorlds = Files.config.contains("general.time.infinite.worlds") ? Files.config.getStringList("general.time.infinite.worlds") : new ArrayList<>(); - - ConfigurationSection csRtW = Files.config.getConfigurationSection("other.relative_time.worlds"); - if (csRtW != null) { - for (String s : csRtW.getKeys(false)) { - rtWorlds.put(s, new RelativeTimeRegion( - Files.config.getDouble("other.relative_time.worlds." + s, 1), true, s)); - } - } - ConfigurationSection csRtR = Files.config.getConfigurationSection("other.relative_time.regions"); - if (csRtW != null) { - for (String s : csRtR.getKeys(false)) { - rtRegions.put(s, new RelativeTimeRegion( - Files.config.getDouble("other.relative_time.regions." + s, 1), false, s)); - } - } - - ConfigurationSection csSpeedW = Files.config.getConfigurationSection("general.flight.speed.worlds"); - if (csSpeedW != null) { - for (String s : csSpeedW.getKeys(false)) { - speedWorlds.put(s, (float) Files.config.getDouble("general.flight.speed.worlds." + s, 1)); - } - } - ConfigurationSection csSpeedR = Files.config.getConfigurationSection("general.flight.speed.regions"); - if (csSpeedR != null) { - for (String s : csSpeedR.getKeys(false)) { - Console.debug(s, Files.config.getDouble("general.flight.speed.regions." + s)); - - speedRegions.put(s, (float) Files.config.getDouble("general.flight.speed.regions." + s, 1)); - } - } - - // legacy default speed. - speedGlobal = (float) Files.config.getDouble("general.flight.default_speed"); - // new default speed. - if (speedGlobal == 0) { - speedGlobal = (float) Files.config.getDouble("general.flight.speed.default", 1); - } - - allowPreferredSpeed = Files.config.getBoolean("general.flight.speed.user_preference", true); - - - } - - -} +package com.moneybags.tempfly.environment; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.configuration.ConfigurationSection; + +import com.moneybags.tempfly.fly.FlightManager; +import com.moneybags.tempfly.fly.RequirementProvider; +import com.moneybags.tempfly.fly.result.FlightResult; +import com.moneybags.tempfly.fly.result.FlightResult.DenyReason; +import com.moneybags.tempfly.fly.result.ResultAllow; +import com.moneybags.tempfly.fly.result.ResultDeny; +import com.moneybags.tempfly.hook.region.CompatRegion; +import com.moneybags.tempfly.user.FlightUser; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.V; +import com.moneybags.tempfly.util.data.Files; + +public class FlightEnvironment implements RequirementProvider { + + private FlightManager manager; + + private Map rtRegions = new HashMap<>(); + private Map rtWorlds = new HashMap<>(); + + private List blackRegions = new ArrayList<>(); + private List blackWorlds = new ArrayList<>(); + + private List whiteRegions = new ArrayList<>(); + private List whiteWorlds = new ArrayList<>(); + + private List freeRegions = new ArrayList<>(); + private List freeWorlds = new ArrayList<>(); + + + + private float speedGlobal = 1; + private boolean allowPreferredSpeed; + private Map speedWorlds = new HashMap<>(); + private Map speedRegions = new HashMap<>(); + + + public FlightEnvironment(FlightManager manager) { + this.manager = manager; + onTempflyReload(); + } + + public FlightManager getFlightManager() { + return manager; + } + + + + /** + * + * --=-------------=-- + * Relative Time + * --=-------------=-- + * + */ + + + + public RelativeTimeRegion[] getRelativeTimeRegions() { + return rtRegions.values().toArray(new RelativeTimeRegion[rtRegions.size()]); + } + + public RelativeTimeRegion[] getRelativeTimeWorlds() { + return rtWorlds.values().toArray(new RelativeTimeRegion[rtWorlds.size()]); + } + + public boolean hasRelativeTime(World world) { + return rtWorlds.containsKey(world.getName()); + } + + public boolean hasRelativeTime(CompatRegion region) { + return rtRegions.containsKey(region.getId()); + } + + public RelativeTimeRegion getRelativeTime(World world) { + return rtWorlds.get(world.getName()); + } + + public RelativeTimeRegion getRelativeTime(CompatRegion region) { + return rtRegions.get(region.getId()); + } + + + + /** + * + * --=--------=-- + * Disabled + * --=--------=-- + * + */ + + + + public boolean isDisabled(World world) { + return blackWorlds.contains(world.getName()); + } + + public boolean isDisabled(CompatRegion region) { + return blackRegions.contains(region.getId()); + } + + + + /** + * + * --=---------=-- + * whitelist + * --=---------=-- + * + */ + + public boolean isWhitelisted(World world) { + return whiteWorlds.size() == 0 || whiteWorlds.contains(world.getName()); + } + + public boolean isWhitelisted(CompatRegion region) { + return whiteRegions.size() == 0 || whiteRegions.contains(region.getId()); + } + + + + /** + * + * --=---------=-- + * infinite + * --=---------=-- + * + */ + + public boolean isInfinite(World world) { + return freeWorlds.contains(world.getName()); + } + + public boolean isInfinite(CompatRegion region) { + return freeRegions.contains(region.getId()); + } + + + /** + * + * --=---------=-- + * Speed + * --=---------=-- + * + */ + + + + public boolean hasMaxSpeed(World world) { + return speedWorlds.containsKey(world.getName()); + } + + public boolean hasMaxSpeed(CompatRegion region) { + //Console.debug(region.getId(), speedRegions.containsKey(region.getId())); + return speedRegions.containsKey(region.getId()); + } + + public boolean hasMaxSpeed(CompatRegion[] regions) { + for (CompatRegion region: regions) { + if (hasMaxSpeed(region)) { + return true; + } + } + return false; + } + + public float getDefaultSpeed() { + return speedGlobal; + } + + public float getMaxSpeed(World world) { + return speedWorlds.getOrDefault(world.getName(), getDefaultSpeed()); + } + + public float getMaxSpeed(CompatRegion region) { + //Console.debug(region.getId(), speedRegions.get(region.getId())); + return speedRegions.getOrDefault(region.getId(), getDefaultSpeed()); + } + + public float getMaxSpeed(CompatRegion[] regions) { + float highest = -999; + for (CompatRegion region: regions) { + if (hasMaxSpeed(region)) { + float speed = getMaxSpeed(region); + if (highest == -999 || highest < speed) { + highest = speed; + } + } + } + return highest == -999 ? getDefaultSpeed() : highest; + } + + public boolean allowSpeedPreference() { + return allowPreferredSpeed; + } + + + + /** + * + * --=--------------------=-- + * Requirement Provider + * --=--------------------=-- + * + */ + + + + /** + * Deprecated as of TempFly 3.0, This method will only check for blacklisted regions and worlds. + * I left it in because the api needs this method for legacy support. + * Check if flight is allowed at a given location. + * @param loc the location in question. + * @return + */ + @Deprecated + public boolean flyAllowed(Location loc) { + if (manager.getTempFly().getHookManager().hasRegionProvider()) { + for (CompatRegion r: manager.getTempFly().getHookManager().getRegionProvider().getApplicableRegions(loc)) { + if (blackRegions.contains(r.getId())) { + return false; + } + } + } + return !V.disabledWorlds.contains(loc.getWorld().getName()); + } + + /** + * disabled regions + */ + @Override + public FlightResult handleFlightInquiry(FlightUser user, CompatRegion[] regions) { + for (CompatRegion region: regions) { + FlightResult result = handleFlightInquiry(user, region); + if (!result.isAllowed()) { + return result; + } + } + return new ResultAllow(this, InquiryType.REGION, V.requirePassDefault); + } + + /** + * disabled region + */ + @Override + public FlightResult handleFlightInquiry(FlightUser user, CompatRegion r) { + return isDisabled(r) || !isWhitelisted(r) ? new ResultDeny(DenyReason.DISABLED_REGION, this, InquiryType.REGION, V.requireFailRegion, !V.damageRegion) + : new ResultAllow(this, InquiryType.REGION, V.requirePassDefault); + } + + /** + * disabled worlds + */ + @Override + public FlightResult handleFlightInquiry(FlightUser user, World world) { + return isDisabled(world) || !isWhitelisted(world) ? new ResultDeny(DenyReason.DISABLED_WORLD, this, InquiryType.WORLD, V.requireFailWorld, !V.damageWorld) + : new ResultAllow(this, InquiryType.WORLD, V.requirePassDefault); + } + + /** + * max y + */ + @Override + public FlightResult handleFlightInquiry(FlightUser user, Location loc) { + if (user.hasFlightRequirement(this, InquiryType.LOCATION)) { + return loc.getBlockY() <= V.maxY-5 ? new ResultAllow(this, InquiryType.LOCATION, V.requirePassDefault) : + new ResultDeny(DenyReason.OTHER, this, InquiryType.LOCATION, + V.requireFailHeight.replaceAll("\\{MAX_Y}", String.valueOf(V.maxY)), false); + } + return loc.getBlockY() > V.maxY ? new ResultDeny(DenyReason.OTHER, this, InquiryType.LOCATION, + V.requireFailHeight.replaceAll("\\{MAX_Y}", String.valueOf(V.maxY)), false) + : new ResultAllow(this, InquiryType.LOCATION, V.requirePassDefault); + } + + @Override + public boolean handles(InquiryType type) { + return false; + } + + @Override + public void onTempflyReload() { + blackRegions = Files.config.contains("general.disabled.regions") ? Files.config.getStringList("general.disabled.regions") : new ArrayList<>(); + blackWorlds = Files.config.contains("general.disabled.worlds") ? Files.config.getStringList("general.disabled.worlds") : new ArrayList<>(); + + whiteRegions = Files.config.contains("general.whitelist.regions") ? Files.config.getStringList("general.whitelist.regions") : new ArrayList<>(); + whiteWorlds = Files.config.contains("general.whitelist.worlds") ? Files.config.getStringList("general.whitelist.worlds") : new ArrayList<>(); + + whiteRegions = Files.config.contains("general.whitelist.regions") ? Files.config.getStringList("general.whitelist.regions") : new ArrayList<>(); + whiteWorlds = Files.config.contains("general.whitelist.worlds") ? Files.config.getStringList("general.whitelist.worlds") : new ArrayList<>(); + + freeRegions = Files.config.contains("general.time.infinite.regions") ? Files.config.getStringList("general.time.infinite.regions") : new ArrayList<>(); + freeWorlds = Files.config.contains("general.time.infinite.worlds") ? Files.config.getStringList("general.time.infinite.worlds") : new ArrayList<>(); + + ConfigurationSection csRtW = Files.config.getConfigurationSection("other.relative_time.worlds"); + if (csRtW != null) { + for (String s : csRtW.getKeys(false)) { + rtWorlds.put(s, new RelativeTimeRegion( + Files.config.getDouble("other.relative_time.worlds." + s, 1), true, s)); + } + } + ConfigurationSection csRtR = Files.config.getConfigurationSection("other.relative_time.regions"); + if (csRtW != null) { + for (String s : csRtR.getKeys(false)) { + rtRegions.put(s, new RelativeTimeRegion( + Files.config.getDouble("other.relative_time.regions." + s, 1), false, s)); + } + } + + ConfigurationSection csSpeedW = Files.config.getConfigurationSection("general.flight.speed.worlds"); + if (csSpeedW != null) { + for (String s : csSpeedW.getKeys(false)) { + speedWorlds.put(s, (float) Files.config.getDouble("general.flight.speed.worlds." + s, 1)); + } + } + ConfigurationSection csSpeedR = Files.config.getConfigurationSection("general.flight.speed.regions"); + if (csSpeedR != null) { + for (String s : csSpeedR.getKeys(false)) { + Console.debug(s, Files.config.getDouble("general.flight.speed.regions." + s)); + + speedRegions.put(s, (float) Files.config.getDouble("general.flight.speed.regions." + s, 1)); + } + } + + // legacy default speed. + speedGlobal = (float) Files.config.getDouble("general.flight.default_speed"); + // new default speed. + if (speedGlobal == 0) { + speedGlobal = (float) Files.config.getDouble("general.flight.speed.default", 1); + } + + allowPreferredSpeed = Files.config.getBoolean("general.flight.speed.user_preference", true); + + + } + + +} diff --git a/TempFly/src/com/moneybags/tempfly/environment/RelativeTimeRegion.java b/src/com/moneybags/tempfly/environment/RelativeTimeRegion.java similarity index 94% rename from TempFly/src/com/moneybags/tempfly/environment/RelativeTimeRegion.java rename to src/com/moneybags/tempfly/environment/RelativeTimeRegion.java index 6e5c749..fbbd256 100644 --- a/TempFly/src/com/moneybags/tempfly/environment/RelativeTimeRegion.java +++ b/src/com/moneybags/tempfly/environment/RelativeTimeRegion.java @@ -1,26 +1,26 @@ -package com.moneybags.tempfly.environment; - -public class RelativeTimeRegion { - - private double factor; - private boolean isWorld; - private String name; - - public RelativeTimeRegion(double factor, boolean isWorld, String name) { - this.factor = factor; - this.isWorld = isWorld; - this.name = name; - } - - public double getFactor() { - return factor; - } - - public boolean isWorld() { - return isWorld; - } - - public String getName() { - return name; - } -} +package com.moneybags.tempfly.environment; + +public class RelativeTimeRegion { + + private double factor; + private boolean isWorld; + private String name; + + public RelativeTimeRegion(double factor, boolean isWorld, String name) { + this.factor = factor; + this.isWorld = isWorld; + this.name = name; + } + + public double getFactor() { + return factor; + } + + public boolean isWorld() { + return isWorld; + } + + public String getName() { + return name; + } +} diff --git a/TempFly/src/com/moneybags/tempfly/environment/StructureProximity.java b/src/com/moneybags/tempfly/environment/StructureProximity.java similarity index 97% rename from TempFly/src/com/moneybags/tempfly/environment/StructureProximity.java rename to src/com/moneybags/tempfly/environment/StructureProximity.java index 70662fe..778e60e 100644 --- a/TempFly/src/com/moneybags/tempfly/environment/StructureProximity.java +++ b/src/com/moneybags/tempfly/environment/StructureProximity.java @@ -1,80 +1,80 @@ -package com.moneybags.tempfly.environment; - -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.StructureType; -import org.bukkit.World; -import org.bukkit.configuration.ConfigurationSection; - -import com.moneybags.tempfly.fly.FlightManager; -import com.moneybags.tempfly.fly.RequirementProvider; -import com.moneybags.tempfly.fly.result.FlightResult; -import com.moneybags.tempfly.fly.result.ResultAllow; -import com.moneybags.tempfly.fly.result.ResultDeny; -import com.moneybags.tempfly.fly.result.FlightResult.DenyReason; -import com.moneybags.tempfly.user.FlightUser; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.V; -import com.moneybags.tempfly.util.data.Files; - -public class StructureProximity implements RequirementProvider { - - private FlightManager manager; - - private Map structs = new HashMap<>(); - - public StructureProximity(FlightManager manager) throws NoSuchMethodException, SecurityException, ClassNotFoundException { - this.manager = manager; - Class.forName("org.bukkit.World").getMethod("locateNearestStructure", Location.class, StructureType.class, Integer.TYPE, Boolean.TYPE); - onTempflyReload(); - } - - public FlightManager getFlightManager() { - return this.manager; - } - - @Override - public FlightResult handleFlightInquiry(FlightUser user, Location loc) { - World world = loc.getWorld(); - for (Entry entry: structs.entrySet()) { - Location closest = world.locateNearestStructure(loc, entry.getKey(), entry.getValue(), false); - if (closest != null) { - Bukkit.broadcastMessage(String.valueOf(closest.distanceSquared(loc))); - return new ResultDeny(DenyReason.OTHER, this, InquiryType.LOCATION, - V.requireFailStruct - .replaceAll("\\{STRUCTURE}", entry.getKey().getName()), !V.damageStruct); - } - } - return new ResultAllow(this, InquiryType.LOCATION, V.requirePassDefault); - } - - @Override - public boolean handles(InquiryType type) { - return type != InquiryType.LOCATION; - } - - @Override - public void onTempflyReload() { - ConfigurationSection csStruct = Files.config.getConfigurationSection("general.structure_proximity"); - if (csStruct == null) { - return; - } - Map registered = StructureType.getStructureTypes(); - Console.debug(registered); - for (String key: csStruct.getKeys(false)) { - if (!registered.containsKey(key)) { - Console.warn("An invalid structure type is defined in the config! (" + key + ")"); - continue; - } - int range = Files.config.getInt("general.structure_proximity." + key, -1); - StructureType struct = registered.get(key); - this.structs.put(struct, range); - } - } - - -} +package com.moneybags.tempfly.environment; + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.StructureType; +import org.bukkit.World; +import org.bukkit.configuration.ConfigurationSection; + +import com.moneybags.tempfly.fly.FlightManager; +import com.moneybags.tempfly.fly.RequirementProvider; +import com.moneybags.tempfly.fly.result.FlightResult; +import com.moneybags.tempfly.fly.result.ResultAllow; +import com.moneybags.tempfly.fly.result.ResultDeny; +import com.moneybags.tempfly.fly.result.FlightResult.DenyReason; +import com.moneybags.tempfly.user.FlightUser; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.V; +import com.moneybags.tempfly.util.data.Files; + +public class StructureProximity implements RequirementProvider { + + private FlightManager manager; + + private Map structs = new HashMap<>(); + + public StructureProximity(FlightManager manager) throws NoSuchMethodException, SecurityException, ClassNotFoundException { + this.manager = manager; + Class.forName("org.bukkit.World").getMethod("locateNearestStructure", Location.class, StructureType.class, Integer.TYPE, Boolean.TYPE); + onTempflyReload(); + } + + public FlightManager getFlightManager() { + return this.manager; + } + + @Override + public FlightResult handleFlightInquiry(FlightUser user, Location loc) { + World world = loc.getWorld(); + for (Entry entry: structs.entrySet()) { + Location closest = world.locateNearestStructure(loc, entry.getKey(), entry.getValue(), false); + if (closest != null) { + Bukkit.broadcastMessage(String.valueOf(closest.distanceSquared(loc))); + return new ResultDeny(DenyReason.OTHER, this, InquiryType.LOCATION, + V.requireFailStruct + .replaceAll("\\{STRUCTURE}", entry.getKey().getName()), !V.damageStruct); + } + } + return new ResultAllow(this, InquiryType.LOCATION, V.requirePassDefault); + } + + @Override + public boolean handles(InquiryType type) { + return type != InquiryType.LOCATION; + } + + @Override + public void onTempflyReload() { + ConfigurationSection csStruct = Files.config.getConfigurationSection("general.structure_proximity"); + if (csStruct == null) { + return; + } + Map registered = StructureType.getStructureTypes(); + Console.debug(registered); + for (String key: csStruct.getKeys(false)) { + if (!registered.containsKey(key)) { + Console.warn("An invalid structure type is defined in the config! (" + key + ")"); + continue; + } + int range = Files.config.getInt("general.structure_proximity." + key, -1); + StructureType struct = registered.get(key); + this.structs.put(struct, range); + } + } + + +} diff --git a/TempFly/src/com/moneybags/tempfly/event/ActionBarSendEvent.java b/src/com/moneybags/tempfly/event/ActionBarSendEvent.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/event/ActionBarSendEvent.java rename to src/com/moneybags/tempfly/event/ActionBarSendEvent.java index 77456de..5339477 100644 --- a/TempFly/src/com/moneybags/tempfly/event/ActionBarSendEvent.java +++ b/src/com/moneybags/tempfly/event/ActionBarSendEvent.java @@ -1,57 +1,57 @@ -package com.moneybags.tempfly.event; - -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -/** - * This event will not be fired as of tempfly 2.0.3 due to a complication with async threads and the EventApi - * If you wish to cancel the action bar you can disable it in the tempfly config. Alteratively you can set V.actionBar false - * @author Kevin - * - */ -@Deprecated -public class ActionBarSendEvent extends Event implements Cancellable { - - private final HandlerList handlers = new HandlerList(); - private final Player player; - private String message; - private boolean cancelled = false; - - public ActionBarSendEvent(Player player, String message) { - this.player = player; - this.message = message; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - public HandlerList getHandlerList() { - return handlers; - } - - public Player getPlayer() { - return player; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } -} +package com.moneybags.tempfly.event; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * This event will not be fired as of tempfly 2.0.3 due to a complication with async threads and the EventApi + * If you wish to cancel the action bar you can disable it in the tempfly config. Alteratively you can set V.actionBar false + * @author Kevin + * + */ +@Deprecated +public class ActionBarSendEvent extends Event implements Cancellable { + + private final HandlerList handlers = new HandlerList(); + private final Player player; + private String message; + private boolean cancelled = false; + + public ActionBarSendEvent(Player player, String message) { + this.player = player; + this.message = message; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public HandlerList getHandlerList() { + return handlers; + } + + public Player getPlayer() { + return player; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } +} diff --git a/TempFly/src/com/moneybags/tempfly/event/FlightEnabledEvent.java b/src/com/moneybags/tempfly/event/FlightEnabledEvent.java similarity index 94% rename from TempFly/src/com/moneybags/tempfly/event/FlightEnabledEvent.java rename to src/com/moneybags/tempfly/event/FlightEnabledEvent.java index 05321eb..9133693 100644 --- a/TempFly/src/com/moneybags/tempfly/event/FlightEnabledEvent.java +++ b/src/com/moneybags/tempfly/event/FlightEnabledEvent.java @@ -1,40 +1,40 @@ -package com.moneybags.tempfly.event; - -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -public class FlightEnabledEvent extends Event implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private Player p; - private boolean cancelled; - - public FlightEnabledEvent(Player p) { - this.p = p; - } - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - public Player getPlayer() { - return p; - } - -} +package com.moneybags.tempfly.event; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class FlightEnabledEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private Player p; + private boolean cancelled; + + public FlightEnabledEvent(Player p) { + this.p = p; + } + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public Player getPlayer() { + return p; + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/event/FlightUserInitializedEvent.java b/src/com/moneybags/tempfly/event/FlightUserInitializedEvent.java similarity index 94% rename from TempFly/src/com/moneybags/tempfly/event/FlightUserInitializedEvent.java rename to src/com/moneybags/tempfly/event/FlightUserInitializedEvent.java index 608f0b2..0ac012b 100644 --- a/TempFly/src/com/moneybags/tempfly/event/FlightUserInitializedEvent.java +++ b/src/com/moneybags/tempfly/event/FlightUserInitializedEvent.java @@ -1,31 +1,31 @@ -package com.moneybags.tempfly.event; - -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import com.moneybags.tempfly.user.FlightUser; - -public class FlightUserInitializedEvent extends Event { - - private static final HandlerList handlers = new HandlerList(); - - private FlightUser user; - - public FlightUserInitializedEvent(FlightUser user) { - this.user = user; - } - - public FlightUser getUser() { - return user; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } - -} +package com.moneybags.tempfly.event; + +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import com.moneybags.tempfly.user.FlightUser; + +public class FlightUserInitializedEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + + private FlightUser user; + + public FlightUserInitializedEvent(FlightUser user) { + this.user = user; + } + + public FlightUser getUser() { + return user; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/event/TitleSendEvent.java b/src/com/moneybags/tempfly/event/TitleSendEvent.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/event/TitleSendEvent.java rename to src/com/moneybags/tempfly/event/TitleSendEvent.java index 9ea6432..328f452 100644 --- a/TempFly/src/com/moneybags/tempfly/event/TitleSendEvent.java +++ b/src/com/moneybags/tempfly/event/TitleSendEvent.java @@ -1,59 +1,59 @@ -package com.moneybags.tempfly.event; - -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -public class TitleSendEvent extends Event implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private final Player player; - private String - title, subtitle; - private boolean cancelled = false; - - public TitleSendEvent(Player player, String title, String subtitle) { - this.player = player; - this.title = title; - this.subtitle = subtitle; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - public Player getPlayer() { - return player; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getSubtitle() { - return subtitle; - } - - public void setSubtitle(String subtitle) { - this.subtitle = subtitle; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } -} +package com.moneybags.tempfly.event; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class TitleSendEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Player player; + private String + title, subtitle; + private boolean cancelled = false; + + public TitleSendEvent(Player player, String title, String subtitle) { + this.player = player; + this.title = title; + this.subtitle = subtitle; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public Player getPlayer() { + return player; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getSubtitle() { + return subtitle; + } + + public void setSubtitle(String subtitle) { + this.subtitle = subtitle; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } +} diff --git a/TempFly/src/com/moneybags/tempfly/fly/FlightManager.java b/src/com/moneybags/tempfly/fly/FlightManager.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/fly/FlightManager.java rename to src/com/moneybags/tempfly/fly/FlightManager.java index 9fc7bdf..394ef81 100644 --- a/TempFly/src/com/moneybags/tempfly/fly/FlightManager.java +++ b/src/com/moneybags/tempfly/fly/FlightManager.java @@ -1,652 +1,652 @@ -package com.moneybags.tempfly.fly; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.entity.EntityDamageEvent.DamageCause; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.player.AsyncPlayerChatEvent; -import org.bukkit.event.player.AsyncPlayerPreLoginEvent; -import org.bukkit.event.player.AsyncPlayerPreLoginEvent.Result; -import org.bukkit.event.player.PlayerChangedWorldEvent; -import org.bukkit.event.player.PlayerGameModeChangeEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.player.PlayerRespawnEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.event.player.PlayerToggleFlightEvent; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.combat.CombatHandler; -import com.moneybags.tempfly.environment.FlightEnvironment; -import com.moneybags.tempfly.event.FlightUserInitializedEvent; -import com.moneybags.tempfly.fly.RequirementProvider.InquiryType; -import com.moneybags.tempfly.fly.result.FlightResult; -import com.moneybags.tempfly.hook.TempFlyHook; -import com.moneybags.tempfly.hook.region.CompatRegion; -import com.moneybags.tempfly.user.FlightUser; -import com.moneybags.tempfly.user.UserLoader; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.V; -import com.moneybags.tempfly.util.data.Reloadable; - -public class FlightManager implements Listener, Reloadable { - - private final TempFly tempfly; - private final FlightEnvironment environment; - //private StructureProximity structures; - private final CombatHandler combat; - - private final List providers = new LinkedList<>(); - - public FlightManager(final TempFly tempfly) { - this.tempfly = tempfly; - - providers.add(this.environment = new FlightEnvironment(this)); - providers.add(this.combat = new CombatHandler(this)); - //try { providers.add(this.structures = new StructureProximity(this)); } catch (Exception e) { - // e.printStackTrace(); - //} - - tempfly.getServer().getPluginManager().registerEvents(this, tempfly); - }// /tf give 1m - - public TempFly getTempFly() { - return tempfly; - } - - public FlightEnvironment getFlightEnvironment() { - return environment; - } - - public CombatHandler getCombatHandler() { - return combat; - } - - /** - public StructureProximity getStructureProximity() { - return this.structures; - } - */ - - @Override - public void onTempflyReload() { - for (RequirementProvider provider : providers) { - if (provider instanceof TempFlyHook) { - continue; - } - provider.onTempflyReload(); - } - - for (FlightUser user : getUsers()) { - user.evaluateFlightRequirements(user.getPlayer().getLocation(), user.hasFlightEnabled()); - user.applySpeedCorrect(true, 0); - } - - } - - /** - * - * --=------------=-- User Control --=------------=-- - * - */ - - private final Map users = new HashMap<>(); - private final Map loaders = new HashMap<>(); - - public synchronized boolean hasUser(Player p) { - return ((p != null) && users.containsKey(p.getUniqueId())) - || ((p != null) && loaders.containsKey(p.getUniqueId()) && loaders.get(p.getUniqueId()).isReady()); - } - - public synchronized FlightUser getUser(UUID u) { - if (!users.containsKey(u) && loaders.containsKey(u) && loaders.get(u).isReady()) { - UserLoader loader = loaders.get(u); - loaders.remove(u); - users.put(u, loader.buildUser()); - } - return users.containsKey(u) ? users.get(u) : null; - } - - public synchronized FlightUser getUser(Player p) { - if (p == null) { - return null; - } - - UUID u = p.getUniqueId(); - if (!users.containsKey(u) && loaders.containsKey(u) && loaders.get(u).isReady()) { - UserLoader loader = loaders.get(u); - loaders.remove(u); - users.put(u, loader.buildUser(p)); - } - return users.containsKey(u) ? users.get(u) : null; - } - - public synchronized FlightUser[] getUsers() { - return users.values().toArray(new FlightUser[users.size()]); - } - - /** - * Should be called asyncrounously - * - * @param u - */ - public synchronized void addUser(UUID u, boolean async) { - Console.debug("------Add User UUID------"); - if (!users.containsKey(u) && !loaders.containsKey(u)) { - Console.debug("--| Starting to load player data..."); - UserLoader loader = new UserLoader(u, this, async); - loaders.put(u, loader); - if (async) { - Bukkit.getScheduler().runTaskAsynchronously(tempfly, loader); - } else { - loader.run(); - } - } - } - - public synchronized void addUser(Player p) { - Console.debug("------Add User Player------"); - UUID u = p.getUniqueId(); - if (p != null && users.containsKey(p.getUniqueId())) { - Console.debug("--|> User is already registered!"); - return; - } - UserLoader loader = loaders.get(u); - if (loader == null) { - Console.debug( - "--|> User has not been loaded! Starting loader async, This may cause NullPointers on player join event..."); - addUser(u, true); - return; - } - loaders.remove(u); - if (!p.isOnline()) { - Console.debug("--| Player is no longer online..."); - if (users.containsKey(u)) { - users.get(u).onQuit(false); - users.remove(u); - } - return; - } - if (!users.containsKey(u)) { - Console.debug("--| Building and registering the FlightUser..."); - FlightUser user = loader.buildUser(); - users.put(u, user); - Bukkit.getScheduler().runTask(tempfly, () -> { - // TODO change the order in which this occurs to prevent any indiscrepencies in - // the requirementproviders if the time gets changed by time manager on user - // join. - for (RequirementProvider provider : providers) { - provider.onUserInitialized(user); - } - Bukkit.getServer().getPluginManager().callEvent(new FlightUserInitializedEvent(user)); - }); - } - } - - public synchronized void removeUser(Player p, boolean reload) { - removeUser(p.getUniqueId(), reload); - } - - public synchronized void removeUser(UUID u, boolean reload) { - if (users.containsKey(u)) { - users.get(u).onQuit(reload); - users.remove(u); - } - if (loaders.containsKey(u)) { - loaders.remove(u); - } - } - - /** - * Called on plugin disable, saves users and cleans up. - */ - public void onDisable() { - for (FlightUser user : getUsers()) { - removeUser(user.getPlayer(), true); - } - } - - /** - * - * --=------------=-- Requirements --=------------=-- - * - * The flight inquiry methods in the FlightManager will process the requirements - * from every RequirementProvider available. All of the hooks, the environment - * tracker for disabled regions etc... - * - * --=------------=-- - */ - - /** - * Register a new requirement provider with tempfly. All users will - * automatically be updated with the new requirements. - * - * @param provider - * The new requirements - */ - public void registerRequirementProvider(RequirementProvider provider) { - if (providers.contains(provider)) { - throw new IllegalArgumentException("A requirement provider can only be registered once!"); - } - providers.add(provider); - for (FlightUser user : getUsers()) { - user.evaluateFlightRequirement(provider, user.getPlayer().getLocation()); - } - } - - /** - * unregister an existing requirement provider in tempfly. All users will - * automatically be updated and the requirements removed. - * - * @param provider - * The new requirements - */ - public void unregisterRequirementProvider(RequirementProvider provider) { - if (providers.remove(provider)) { - for (FlightUser user : getUsers()) { - if (user.removeFlightRequirement(provider)) { - user.updateRequirements(V.requirePassDefault); - } - } - } - } - - /** - * Check if a player can fly in a set of given regions. - * - * @param user - * @param regions - * @param invokeHooks - * @return - */ - public List inquireFlight(FlightUser user, CompatRegion[] regions) { - List results = new ArrayList<>(); - for (RequirementProvider requirement : providers) { - if (requirement.handles(InquiryType.REGION)) { - continue; - } - results.add(requirement.handleFlightInquiry(user, regions)); - } - return results; - } - - /** - * Check if a player can fly in a single region. - * - * @param user - * @param r - * @param invokeHooks - * @return - */ - public List inquireFlight(FlightUser user, CompatRegion region) { - List results = new ArrayList<>(); - for (RequirementProvider requirement : providers) { - if (requirement.handles(InquiryType.REGION)) { - continue; - } - results.add(requirement.handleFlightInquiry(user, region)); - } - return results; - } - - /** - * Check if a player can fly in a world. - * - * @param user - * @param world - * @param invokeHooks - * @return - */ - public List inquireFlight(FlightUser user, World world) { - List results = new ArrayList<>(); - for (RequirementProvider requirement : providers) { - if (requirement.handles(InquiryType.WORLD)) { - continue; - } - results.add(requirement.handleFlightInquiry(user, world)); - } - return results; - } - - /** - * Check if a player can fly at a given location and process all requirements - * for said location. Does not check regions and worlds, you need to use the - * specified methods for regions and worlds. - * - * @param user - * @param loc - * @param invokeHooks - * @return - */ - public List inquireFlight(FlightUser user, Location loc) { - List results = new ArrayList<>(); - for (RequirementProvider requirement : providers) { - if (requirement.handles(InquiryType.LOCATION)) { - continue; - } - results.add(requirement.handleFlightInquiry(user, loc)); - } - return results; - } - - public List inquireFlightBeyondScope(FlightUser user) { - List results = new ArrayList<>(); - for (RequirementProvider requirement : providers) { - results.add(requirement.handleFlightInquiry(user)); - } - return results; - } - - /** - * - * --=--------------=-- Event Handling --=--------------=-- - * - * General event handling for users. - * - * Provides location tracking for users and handles flight inquiries based on - * location. - * - * --=--------------=-- - * - */ - - /** - * Method to tie in with the EventHandlers. Responsible for all location - * tracking in the plugin. Takes in a player and their new location. Proceeds to - * process the information for all RequirementProviders and handles flight - * restrictions. - * - * This method will probably be the bulk of tempfly's resource usage, it looks - * like its doing alot but realistically it wont do much unless some server goes - * way overboard with stacking up features from the config. like adding hundreds - * of ReletiveTimeRegions and having multiple hooks enabled. - * - * @param p - * The player to process - * @param to - * The new location - */ - public void updateLocation(FlightUser user, Location from, Location to, boolean forceWorld, boolean forceRegion) { - if (V.bugInfiniteA) { - if (user.getPlayer().isFlying() - && !user.hasTimer() - && !user.getPlayer().hasPermission("tempfly.workaround.infinite.bypass.fix_a")) { - user.enforce(0); - } - } else if (V.bugInfiniteB) { - Console.debug(0); - if (user.getPlayer().isFlying() - && !user.hasTimer() - && !user.getPlayer().hasPermission("tempfly.workaround.infinite.bypass.fix_b")) { - if (!user.enableFlight()) { - user.enforce(0); - } - } - } - - final List results = new ArrayList<>(); - - if (getTempFly().getHookManager().hasRegionProvider()) { - List regions = Arrays - .asList(getTempFly().getHookManager().getRegionProvider().getApplicableRegions(to)); - if (forceRegion || !user.getEnvironment().checkIdenticalRegions(regions)) { - // Process regions - results.addAll(inquireFlight(user, regions.toArray(new CompatRegion[regions.size()]))); - // Update the users current regions. - user.getEnvironment().updateCurrentRegionSet(regions.toArray(new CompatRegion[regions.size()])); - - if (user.hasFlightEnabled()) { - user.applySpeedCorrect(true, 0); - } - } - } - - // Check flight requirements if player entered a new world. - // Process world - if (!from.getWorld().equals(to.getWorld()) || forceWorld) { - results.addAll((inquireFlight(user, to.getWorld()))); - user.getEnvironment().asessRtWorld(); - user.getEnvironment().asessInfiniteFlight(); - } - // Check flight requirements at player location. Doesn't really do anything if - // no hooks are enabled. - // Used mainly for things like islands in skyblock, faction land, etc... - // Process location - results.addAll(inquireFlight(user, user.getPlayer().getLocation())); - - // Submit the flight results and see if auto fly can be enabled. - user.submitFlightResults(results, user.hasFlightEnabled()); - } - - /** - * Evaluate flight requirements on teleport - */ - @EventHandler(priority = EventPriority.MONITOR) - public void onTeleport(PlayerTeleportEvent e) { - Console.debug("------on teleport------", "--|> " + e.getPlayer().getUniqueId()); - if (!hasUser(e.getPlayer())) { - return; - } - FlightUser user = getUser(e.getPlayer()); - if (user == null) { - return; - } - user.resetIdleTimer(); - if (!e.getFrom().getBlock().equals(e.getTo().getBlock())) { - updateLocation(user, e.getFrom(), e.getTo(), false, false); - } - user.applyFlightCorrect(); - } - - /** - * Evaluate flight requirements on respawn - */ - @EventHandler(priority = EventPriority.MONITOR) - public void onRespawn(PlayerRespawnEvent e) { - if (!hasUser(e.getPlayer())) { - return; - } - FlightUser user = getUser(e.getPlayer()); - if (user == null) { - return; - } - user.resetIdleTimer(); - updateLocation(user, e.getPlayer().getLocation(), e.getRespawnLocation(), false, false); - // If the user has flight enabled, we need to correct their speed so it doesnt - // reset to 1. - if (user.hasFlightEnabled()) { - user.applyFlightCorrect(); - user.applySpeedCorrect(false, 1); - } - user.enforce(1); - } - - /** - * Evaluate flight requirements on changing worlds. - */ - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onChangedWorld(PlayerChangedWorldEvent e) { - if (!hasUser(e.getPlayer())) { - return; - } - FlightUser user = getUser(e.getPlayer()); - if (user == null) { - return; - } - user.resetIdleTimer(); - // The from coordinate really doesn't matter here, just the world. - updateLocation(user, new Location(e.getFrom(), 0, 0, 0), user.getPlayer().getLocation(), true, false); - // If the user has flight enabled, we need to correct their speed so it doesnt - // reset to 1. - if (user.hasFlightEnabled()) { - user.applyFlightCorrect(); - user.applySpeedCorrect(true, 10); - - } - // TODO flight cannot just be enforced on every world change as it will break - // essentials fly compatibility. Must be enforced - // when something happens to actually disable the flight, impossible to check if - // it should be disabled here... - - // else if (!user.hasFlightEnabled() && user.getPlayer().getAllowFlight()){ - // user.enforce(1); - // } - } - - /** - * Fix the players flight when they change gamemodes. - */ - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onChangedGamemode(PlayerGameModeChangeEvent e) { - if (!hasUser(e.getPlayer())) { - return; - } - FlightUser user = getUser(e.getPlayer()); - if (user == null) { - return; - } - user.resetIdleTimer(); - user.applyFlightCorrect(); - if (e.getNewGameMode() == GameMode.CREATIVE && V.creativeTimer) { - if (!user.hasFlightEnabled() && !user.enableFlight()) { - user.enforce(1); - } - } - } - - /** - * Handles removal of damage protection. - * - * @param e - */ - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onEntityDamage(EntityDamageEvent e) { - Entity vic = e.getEntity(); - if (!e.getCause().equals(DamageCause.FALL) || !(vic instanceof Player)) { - return; - } - FlightUser user = getUser((Player) vic); - if (user == null) { - return; - } - user.resetIdleTimer(); - if (!user.hasDamageProtection()) { - return; - } - e.setCancelled(true); - user.removeDamageProtection(); - } - - /** - * I will listen to player join on lowest priority so that i can initialize the - * flight user before other plugins try to access it on higher priorities. - */ - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false) - public void onJoin(PlayerJoinEvent e) { - Console.debug("------------ On PlayerjOIN event ------------"); - addUser(e.getPlayer()); - } - - /** - * @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = false) - * public void onSpawn(PlayerSpawnLocationEvent e) { - * e.setSpawnLocation(new Location(e.getPlayer().getWorld(), 100, - * 200, 100)); Console.debug("------------ On PlayerSpawn event - * ------------"); Console.debug("--------------->>>>>>>>> " + - * String.valueOf(Bukkit.getPlayer(e.getPlayer().getUniqueId()))); - * //e.getPlayer().teleport(new Location(e.getPlayer().getWorld(), - * 100, 200, 100)); e.getPlayer().setGameMode(GameMode.SPECTATOR); - * - * } - */ - - @EventHandler(priority = EventPriority.LOWEST) - public void onAsyncPreLogin(AsyncPlayerPreLoginEvent e) { - Console.debug("------------ On AsyncPlayerPreLogin event ------------"); - addUser(e.getUniqueId(), false); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onAsyncPreLoginMonitor(AsyncPlayerPreLoginEvent e) { - UUID u = e.getUniqueId(); - if (e.getLoginResult() != Result.ALLOWED) { - users.get(u); - removeUser(u, false); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) - public void onQuit(PlayerQuitEvent e) { - Player p = e.getPlayer(); - removeUser(p, false); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(PlayerMoveEvent e) { - if (!e.getFrom().getBlock().equals(e.getTo().getBlock())) { - FlightUser user = getUser(e.getPlayer()); - if (user == null) { - return; - } - user.resetIdleTimer(); - updateLocation(user, e.getFrom(), e.getTo(), false, false); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) - public void onInteract(PlayerInteractEvent e) { - FlightUser user = getUser(e.getPlayer()); - if (user == null) { - return; - } - user.resetIdleTimer(); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) - public void onAsyncChat(AsyncPlayerChatEvent e) { - FlightUser user = getUser(e.getPlayer()); - if (user == null) { - return; - } - user.resetIdleTimer(); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) - public void onInventoryClick(InventoryClickEvent e) { - if (e.getWhoClicked() instanceof Player) { - FlightUser user = getUser((Player) e.getWhoClicked()); - if (user == null) { - return; - } - user.resetIdleTimer(); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) - public void onFlyMonitor(PlayerToggleFlightEvent e) { - Console.debug("----------- Monitor ------------", e.getPlayer().getName() + " toggled flight!", "Cancelled: " + e.isCancelled(), "Flying: " + e.isFlying()); - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = false) - public void onFly(PlayerToggleFlightEvent e) { - Console.debug("----------- Normal ------------", e.getPlayer().getName() + " toggled flight!", "Cancelled: " + e.isCancelled(), "Flying: " + e.isFlying()); - } -} +package com.moneybags.tempfly.fly; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.AsyncPlayerPreLoginEvent; +import org.bukkit.event.player.AsyncPlayerPreLoginEvent.Result; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerGameModeChangeEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.event.player.PlayerToggleFlightEvent; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.combat.CombatHandler; +import com.moneybags.tempfly.environment.FlightEnvironment; +import com.moneybags.tempfly.event.FlightUserInitializedEvent; +import com.moneybags.tempfly.fly.RequirementProvider.InquiryType; +import com.moneybags.tempfly.fly.result.FlightResult; +import com.moneybags.tempfly.hook.TempFlyHook; +import com.moneybags.tempfly.hook.region.CompatRegion; +import com.moneybags.tempfly.user.FlightUser; +import com.moneybags.tempfly.user.UserLoader; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.V; +import com.moneybags.tempfly.util.data.Reloadable; + +public class FlightManager implements Listener, Reloadable { + + private final TempFly tempfly; + private final FlightEnvironment environment; + //private StructureProximity structures; + private final CombatHandler combat; + + private final List providers = new LinkedList<>(); + + public FlightManager(final TempFly tempfly) { + this.tempfly = tempfly; + + providers.add(this.environment = new FlightEnvironment(this)); + providers.add(this.combat = new CombatHandler(this)); + //try { providers.add(this.structures = new StructureProximity(this)); } catch (Exception e) { + // e.printStackTrace(); + //} + + tempfly.getServer().getPluginManager().registerEvents(this, tempfly); + }// /tf give 1m + + public TempFly getTempFly() { + return tempfly; + } + + public FlightEnvironment getFlightEnvironment() { + return environment; + } + + public CombatHandler getCombatHandler() { + return combat; + } + + /** + public StructureProximity getStructureProximity() { + return this.structures; + } + */ + + @Override + public void onTempflyReload() { + for (RequirementProvider provider : providers) { + if (provider instanceof TempFlyHook) { + continue; + } + provider.onTempflyReload(); + } + + for (FlightUser user : getUsers()) { + user.evaluateFlightRequirements(user.getPlayer().getLocation(), user.hasFlightEnabled()); + user.applySpeedCorrect(true, 0); + } + + } + + /** + * + * --=------------=-- User Control --=------------=-- + * + */ + + private final Map users = new HashMap<>(); + private final Map loaders = new HashMap<>(); + + public synchronized boolean hasUser(Player p) { + return ((p != null) && users.containsKey(p.getUniqueId())) + || ((p != null) && loaders.containsKey(p.getUniqueId()) && loaders.get(p.getUniqueId()).isReady()); + } + + public synchronized FlightUser getUser(UUID u) { + if (!users.containsKey(u) && loaders.containsKey(u) && loaders.get(u).isReady()) { + UserLoader loader = loaders.get(u); + loaders.remove(u); + users.put(u, loader.buildUser()); + } + return users.containsKey(u) ? users.get(u) : null; + } + + public synchronized FlightUser getUser(Player p) { + if (p == null) { + return null; + } + + UUID u = p.getUniqueId(); + if (!users.containsKey(u) && loaders.containsKey(u) && loaders.get(u).isReady()) { + UserLoader loader = loaders.get(u); + loaders.remove(u); + users.put(u, loader.buildUser(p)); + } + return users.containsKey(u) ? users.get(u) : null; + } + + public synchronized FlightUser[] getUsers() { + return users.values().toArray(new FlightUser[users.size()]); + } + + /** + * Should be called asyncrounously + * + * @param u + */ + public synchronized void addUser(UUID u, boolean async) { + Console.debug("------Add User UUID------"); + if (!users.containsKey(u) && !loaders.containsKey(u)) { + Console.debug("--| Starting to load player data..."); + UserLoader loader = new UserLoader(u, this, async); + loaders.put(u, loader); + if (async) { + Bukkit.getScheduler().runTaskAsynchronously(tempfly, loader); + } else { + loader.run(); + } + } + } + + public synchronized void addUser(Player p) { + Console.debug("------Add User Player------"); + UUID u = p.getUniqueId(); + if (p != null && users.containsKey(p.getUniqueId())) { + Console.debug("--|> User is already registered!"); + return; + } + UserLoader loader = loaders.get(u); + if (loader == null) { + Console.debug( + "--|> User has not been loaded! Starting loader async, This may cause NullPointers on player join event..."); + addUser(u, true); + return; + } + loaders.remove(u); + if (!p.isOnline()) { + Console.debug("--| Player is no longer online..."); + if (users.containsKey(u)) { + users.get(u).onQuit(false); + users.remove(u); + } + return; + } + if (!users.containsKey(u)) { + Console.debug("--| Building and registering the FlightUser..."); + FlightUser user = loader.buildUser(); + users.put(u, user); + Bukkit.getScheduler().runTask(tempfly, () -> { + // TODO change the order in which this occurs to prevent any indiscrepencies in + // the requirementproviders if the time gets changed by time manager on user + // join. + for (RequirementProvider provider : providers) { + provider.onUserInitialized(user); + } + Bukkit.getServer().getPluginManager().callEvent(new FlightUserInitializedEvent(user)); + }); + } + } + + public synchronized void removeUser(Player p, boolean reload) { + removeUser(p.getUniqueId(), reload); + } + + public synchronized void removeUser(UUID u, boolean reload) { + if (users.containsKey(u)) { + users.get(u).onQuit(reload); + users.remove(u); + } + if (loaders.containsKey(u)) { + loaders.remove(u); + } + } + + /** + * Called on plugin disable, saves users and cleans up. + */ + public void onDisable() { + for (FlightUser user : getUsers()) { + removeUser(user.getPlayer(), true); + } + } + + /** + * + * --=------------=-- Requirements --=------------=-- + * + * The flight inquiry methods in the FlightManager will process the requirements + * from every RequirementProvider available. All of the hooks, the environment + * tracker for disabled regions etc... + * + * --=------------=-- + */ + + /** + * Register a new requirement provider with tempfly. All users will + * automatically be updated with the new requirements. + * + * @param provider + * The new requirements + */ + public void registerRequirementProvider(RequirementProvider provider) { + if (providers.contains(provider)) { + throw new IllegalArgumentException("A requirement provider can only be registered once!"); + } + providers.add(provider); + for (FlightUser user : getUsers()) { + user.evaluateFlightRequirement(provider, user.getPlayer().getLocation()); + } + } + + /** + * unregister an existing requirement provider in tempfly. All users will + * automatically be updated and the requirements removed. + * + * @param provider + * The new requirements + */ + public void unregisterRequirementProvider(RequirementProvider provider) { + if (providers.remove(provider)) { + for (FlightUser user : getUsers()) { + if (user.removeFlightRequirement(provider)) { + user.updateRequirements(V.requirePassDefault); + } + } + } + } + + /** + * Check if a player can fly in a set of given regions. + * + * @param user + * @param regions + * @param invokeHooks + * @return + */ + public List inquireFlight(FlightUser user, CompatRegion[] regions) { + List results = new ArrayList<>(); + for (RequirementProvider requirement : providers) { + if (requirement.handles(InquiryType.REGION)) { + continue; + } + results.add(requirement.handleFlightInquiry(user, regions)); + } + return results; + } + + /** + * Check if a player can fly in a single region. + * + * @param user + * @param r + * @param invokeHooks + * @return + */ + public List inquireFlight(FlightUser user, CompatRegion region) { + List results = new ArrayList<>(); + for (RequirementProvider requirement : providers) { + if (requirement.handles(InquiryType.REGION)) { + continue; + } + results.add(requirement.handleFlightInquiry(user, region)); + } + return results; + } + + /** + * Check if a player can fly in a world. + * + * @param user + * @param world + * @param invokeHooks + * @return + */ + public List inquireFlight(FlightUser user, World world) { + List results = new ArrayList<>(); + for (RequirementProvider requirement : providers) { + if (requirement.handles(InquiryType.WORLD)) { + continue; + } + results.add(requirement.handleFlightInquiry(user, world)); + } + return results; + } + + /** + * Check if a player can fly at a given location and process all requirements + * for said location. Does not check regions and worlds, you need to use the + * specified methods for regions and worlds. + * + * @param user + * @param loc + * @param invokeHooks + * @return + */ + public List inquireFlight(FlightUser user, Location loc) { + List results = new ArrayList<>(); + for (RequirementProvider requirement : providers) { + if (requirement.handles(InquiryType.LOCATION)) { + continue; + } + results.add(requirement.handleFlightInquiry(user, loc)); + } + return results; + } + + public List inquireFlightBeyondScope(FlightUser user) { + List results = new ArrayList<>(); + for (RequirementProvider requirement : providers) { + results.add(requirement.handleFlightInquiry(user)); + } + return results; + } + + /** + * + * --=--------------=-- Event Handling --=--------------=-- + * + * General event handling for users. + * + * Provides location tracking for users and handles flight inquiries based on + * location. + * + * --=--------------=-- + * + */ + + /** + * Method to tie in with the EventHandlers. Responsible for all location + * tracking in the plugin. Takes in a player and their new location. Proceeds to + * process the information for all RequirementProviders and handles flight + * restrictions. + * + * This method will probably be the bulk of tempfly's resource usage, it looks + * like its doing alot but realistically it wont do much unless some server goes + * way overboard with stacking up features from the config. like adding hundreds + * of ReletiveTimeRegions and having multiple hooks enabled. + * + * @param p + * The player to process + * @param to + * The new location + */ + public void updateLocation(FlightUser user, Location from, Location to, boolean forceWorld, boolean forceRegion) { + if (V.bugInfiniteA) { + if (user.getPlayer().isFlying() + && !user.hasTimer() + && !user.getPlayer().hasPermission("tempfly.workaround.infinite.bypass.fix_a")) { + user.enforce(0); + } + } else if (V.bugInfiniteB) { + Console.debug(0); + if (user.getPlayer().isFlying() + && !user.hasTimer() + && !user.getPlayer().hasPermission("tempfly.workaround.infinite.bypass.fix_b")) { + if (!user.enableFlight()) { + user.enforce(0); + } + } + } + + final List results = new ArrayList<>(); + + if (getTempFly().getHookManager().hasRegionProvider()) { + List regions = Arrays + .asList(getTempFly().getHookManager().getRegionProvider().getApplicableRegions(to)); + if (forceRegion || !user.getEnvironment().checkIdenticalRegions(regions)) { + // Process regions + results.addAll(inquireFlight(user, regions.toArray(new CompatRegion[regions.size()]))); + // Update the users current regions. + user.getEnvironment().updateCurrentRegionSet(regions.toArray(new CompatRegion[regions.size()])); + + if (user.hasFlightEnabled()) { + user.applySpeedCorrect(true, 0); + } + } + } + + // Check flight requirements if player entered a new world. + // Process world + if (!from.getWorld().equals(to.getWorld()) || forceWorld) { + results.addAll((inquireFlight(user, to.getWorld()))); + user.getEnvironment().asessRtWorld(); + user.getEnvironment().asessInfiniteFlight(); + } + // Check flight requirements at player location. Doesn't really do anything if + // no hooks are enabled. + // Used mainly for things like islands in skyblock, faction land, etc... + // Process location + results.addAll(inquireFlight(user, user.getPlayer().getLocation())); + + // Submit the flight results and see if auto fly can be enabled. + user.submitFlightResults(results, user.hasFlightEnabled()); + } + + /** + * Evaluate flight requirements on teleport + */ + @EventHandler(priority = EventPriority.MONITOR) + public void onTeleport(PlayerTeleportEvent e) { + Console.debug("------on teleport------", "--|> " + e.getPlayer().getUniqueId()); + if (!hasUser(e.getPlayer())) { + return; + } + FlightUser user = getUser(e.getPlayer()); + if (user == null) { + return; + } + user.resetIdleTimer(); + if (!e.getFrom().getBlock().equals(e.getTo().getBlock())) { + updateLocation(user, e.getFrom(), e.getTo(), false, false); + } + user.applyFlightCorrect(); + } + + /** + * Evaluate flight requirements on respawn + */ + @EventHandler(priority = EventPriority.MONITOR) + public void onRespawn(PlayerRespawnEvent e) { + if (!hasUser(e.getPlayer())) { + return; + } + FlightUser user = getUser(e.getPlayer()); + if (user == null) { + return; + } + user.resetIdleTimer(); + updateLocation(user, e.getPlayer().getLocation(), e.getRespawnLocation(), false, false); + // If the user has flight enabled, we need to correct their speed so it doesnt + // reset to 1. + if (user.hasFlightEnabled()) { + user.applyFlightCorrect(); + user.applySpeedCorrect(false, 1); + } + user.enforce(1); + } + + /** + * Evaluate flight requirements on changing worlds. + */ + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onChangedWorld(PlayerChangedWorldEvent e) { + if (!hasUser(e.getPlayer())) { + return; + } + FlightUser user = getUser(e.getPlayer()); + if (user == null) { + return; + } + user.resetIdleTimer(); + // The from coordinate really doesn't matter here, just the world. + updateLocation(user, new Location(e.getFrom(), 0, 0, 0), user.getPlayer().getLocation(), true, false); + // If the user has flight enabled, we need to correct their speed so it doesnt + // reset to 1. + if (user.hasFlightEnabled()) { + user.applyFlightCorrect(); + user.applySpeedCorrect(true, 10); + + } + // TODO flight cannot just be enforced on every world change as it will break + // essentials fly compatibility. Must be enforced + // when something happens to actually disable the flight, impossible to check if + // it should be disabled here... + + // else if (!user.hasFlightEnabled() && user.getPlayer().getAllowFlight()){ + // user.enforce(1); + // } + } + + /** + * Fix the players flight when they change gamemodes. + */ + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onChangedGamemode(PlayerGameModeChangeEvent e) { + if (!hasUser(e.getPlayer())) { + return; + } + FlightUser user = getUser(e.getPlayer()); + if (user == null) { + return; + } + user.resetIdleTimer(); + user.applyFlightCorrect(); + if (e.getNewGameMode() == GameMode.CREATIVE && V.creativeTimer) { + if (!user.hasFlightEnabled() && !user.enableFlight()) { + user.enforce(1); + } + } + } + + /** + * Handles removal of damage protection. + * + * @param e + */ + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onEntityDamage(EntityDamageEvent e) { + Entity vic = e.getEntity(); + if (!e.getCause().equals(DamageCause.FALL) || !(vic instanceof Player)) { + return; + } + FlightUser user = getUser((Player) vic); + if (user == null) { + return; + } + user.resetIdleTimer(); + if (!user.hasDamageProtection()) { + return; + } + e.setCancelled(true); + user.removeDamageProtection(); + } + + /** + * I will listen to player join on lowest priority so that i can initialize the + * flight user before other plugins try to access it on higher priorities. + */ + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false) + public void onJoin(PlayerJoinEvent e) { + Console.debug("------------ On PlayerjOIN event ------------"); + addUser(e.getPlayer()); + } + + /** + * @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled = false) + * public void onSpawn(PlayerSpawnLocationEvent e) { + * e.setSpawnLocation(new Location(e.getPlayer().getWorld(), 100, + * 200, 100)); Console.debug("------------ On PlayerSpawn event + * ------------"); Console.debug("--------------->>>>>>>>> " + + * String.valueOf(Bukkit.getPlayer(e.getPlayer().getUniqueId()))); + * //e.getPlayer().teleport(new Location(e.getPlayer().getWorld(), + * 100, 200, 100)); e.getPlayer().setGameMode(GameMode.SPECTATOR); + * + * } + */ + + @EventHandler(priority = EventPriority.LOWEST) + public void onAsyncPreLogin(AsyncPlayerPreLoginEvent e) { + Console.debug("------------ On AsyncPlayerPreLogin event ------------"); + addUser(e.getUniqueId(), false); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onAsyncPreLoginMonitor(AsyncPlayerPreLoginEvent e) { + UUID u = e.getUniqueId(); + if (e.getLoginResult() != Result.ALLOWED) { + users.get(u); + removeUser(u, false); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) + public void onQuit(PlayerQuitEvent e) { + Player p = e.getPlayer(); + removeUser(p, false); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(PlayerMoveEvent e) { + if (!e.getFrom().getBlock().equals(e.getTo().getBlock())) { + FlightUser user = getUser(e.getPlayer()); + if (user == null) { + return; + } + user.resetIdleTimer(); + updateLocation(user, e.getFrom(), e.getTo(), false, false); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) + public void onInteract(PlayerInteractEvent e) { + FlightUser user = getUser(e.getPlayer()); + if (user == null) { + return; + } + user.resetIdleTimer(); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) + public void onAsyncChat(AsyncPlayerChatEvent e) { + FlightUser user = getUser(e.getPlayer()); + if (user == null) { + return; + } + user.resetIdleTimer(); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) + public void onInventoryClick(InventoryClickEvent e) { + if (e.getWhoClicked() instanceof Player) { + FlightUser user = getUser((Player) e.getWhoClicked()); + if (user == null) { + return; + } + user.resetIdleTimer(); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) + public void onFlyMonitor(PlayerToggleFlightEvent e) { + Console.debug("----------- Monitor ------------", e.getPlayer().getName() + " toggled flight!", "Cancelled: " + e.isCancelled(), "Flying: " + e.isFlying()); + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = false) + public void onFly(PlayerToggleFlightEvent e) { + Console.debug("----------- Normal ------------", e.getPlayer().getName() + " toggled flight!", "Cancelled: " + e.isCancelled(), "Flying: " + e.isFlying()); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/fly/Flyer.java b/src/com/moneybags/tempfly/fly/Flyer.java similarity index 94% rename from TempFly/src/com/moneybags/tempfly/fly/Flyer.java rename to src/com/moneybags/tempfly/fly/Flyer.java index 0968941..5c68c34 100644 --- a/TempFly/src/com/moneybags/tempfly/fly/Flyer.java +++ b/src/com/moneybags/tempfly/fly/Flyer.java @@ -1,90 +1,90 @@ -package com.moneybags.tempfly.fly; - -import org.bukkit.entity.Player; -import com.moneybags.tempfly.environment.RelativeTimeRegion; -import com.moneybags.tempfly.user.FlightUser; - -@Deprecated -public class Flyer { - - private FlightUser user; - - @Deprecated - public Flyer(FlightUser user) { - this.user = user; - } - - @Deprecated - public boolean isFlying() { - return user.getPlayer().isFlying(); - } - @Deprecated - public boolean isIdle() { - return user.isIdle(); - } - @Deprecated - public void resetIdleTimer() { - user.resetIdleTimer(); - } - @Deprecated - public RelativeTimeRegion[] getRtEncompassing() { - return user.getEnvironment().getRelativeTimeRegions(); - } - @Deprecated - public Player getPlayer() { - return user.getPlayer(); - } - @Deprecated - public double getTime() { - return user.getTime(); - } - @Deprecated - public void setTime(double time) { - user.setTime(time); - } - - /* - * - * - */ - - @Deprecated - public void asessRtWorlds() { - return; - } - - @Deprecated - public void asessRtRegions() { - return; - } - - @Deprecated - public void removeFlyer() { - //TODO - user.disableFlight(1, true); - } - - /** - * This method returns a string to keep the plugin compatible through versions. - * @return The enum string representation of the particle - */ - @Deprecated - public String getTrail() { - return user.getTrail(); - } - - /** - * This method requires a string to keep the plugin compatible through versions. - * The enum value of the particle as a string - * @param particle - */ - @Deprecated - public void setTrail(String particle) { - user.setTrail(particle); - } - - @Deprecated - public void playTrail() { - user.playTrail(); - } -} +package com.moneybags.tempfly.fly; + +import org.bukkit.entity.Player; +import com.moneybags.tempfly.environment.RelativeTimeRegion; +import com.moneybags.tempfly.user.FlightUser; + +@Deprecated +public class Flyer { + + private FlightUser user; + + @Deprecated + public Flyer(FlightUser user) { + this.user = user; + } + + @Deprecated + public boolean isFlying() { + return user.getPlayer().isFlying(); + } + @Deprecated + public boolean isIdle() { + return user.isIdle(); + } + @Deprecated + public void resetIdleTimer() { + user.resetIdleTimer(); + } + @Deprecated + public RelativeTimeRegion[] getRtEncompassing() { + return user.getEnvironment().getRelativeTimeRegions(); + } + @Deprecated + public Player getPlayer() { + return user.getPlayer(); + } + @Deprecated + public double getTime() { + return user.getTime(); + } + @Deprecated + public void setTime(double time) { + user.setTime(time); + } + + /* + * + * + */ + + @Deprecated + public void asessRtWorlds() { + return; + } + + @Deprecated + public void asessRtRegions() { + return; + } + + @Deprecated + public void removeFlyer() { + //TODO + user.disableFlight(1, true); + } + + /** + * This method returns a string to keep the plugin compatible through versions. + * @return The enum string representation of the particle + */ + @Deprecated + public String getTrail() { + return user.getTrail(); + } + + /** + * This method requires a string to keep the plugin compatible through versions. + * The enum value of the particle as a string + * @param particle + */ + @Deprecated + public void setTrail(String particle) { + user.setTrail(particle); + } + + @Deprecated + public void playTrail() { + user.playTrail(); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/fly/RequirementProvider.java b/src/com/moneybags/tempfly/fly/RequirementProvider.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/fly/RequirementProvider.java rename to src/com/moneybags/tempfly/fly/RequirementProvider.java index 918d5e5..065e13d 100644 --- a/TempFly/src/com/moneybags/tempfly/fly/RequirementProvider.java +++ b/src/com/moneybags/tempfly/fly/RequirementProvider.java @@ -1,109 +1,109 @@ -package com.moneybags.tempfly.fly; - -import org.bukkit.Location; -import org.bukkit.World; - -import com.moneybags.tempfly.fly.result.FlightResult; -import com.moneybags.tempfly.fly.result.ResultAllow; -import com.moneybags.tempfly.hook.region.CompatRegion; -import com.moneybags.tempfly.user.FlightUser; -import com.moneybags.tempfly.util.V; -import com.moneybags.tempfly.util.data.Reloadable; - -public interface RequirementProvider extends Reloadable { - - /** - * Inquire whether a player can fly within a set of given regions. - * @param p - * @param regions - * @return - */ - public default FlightResult handleFlightInquiry(FlightUser user, CompatRegion[] regions) { - return new ResultAllow(this, InquiryType.REGION, V.requirePassDefault); - } - - /** - * Inquire whether a player can fly within a specific regions. - * @param p - * @param regions - * @return - */ - public default FlightResult handleFlightInquiry(FlightUser user, CompatRegion r) { - return new ResultAllow(this, InquiryType.REGION, V.requirePassDefault); - } - - /** - * Inquire whether a player can fly within a given world. - * @param p - * @param regions - * @return - */ - public default FlightResult handleFlightInquiry(FlightUser user, World world) { - return new ResultAllow(this, InquiryType.WORLD, V.requirePassDefault); - } - - /** - * Inquire whether a player can fly at a given location. - * @param p - * @param regions - * @return - */ - public default FlightResult handleFlightInquiry(FlightUser user, Location loc) { - return new ResultAllow(this, InquiryType.LOCATION, V.requirePassDefault); - } - - public default FlightResult handleFlightInquiry(FlightUser user) { - return new ResultAllow(this, InquiryType.UNDEFINED, V.requirePassDefault); - } - - /** - * Called when a player joins the server and their flight user is done being initialized. - * @param user The new user. - */ - public default void onUserInitialized(FlightUser user) {} - - /** - * Called when the user leaves the server and their user object is about to be destroyed. - * @param user The user who quit. - */ - public default void onUserQuit(FlightUser user) {} - - /** - * Should tempfly inquire flight for the players location or will the provider handle it. - * Useful to save on unnecessary checks if the provider does not need it. - * - * For example, why check if flight is allowed when a player enters a region in the combat manager, - * it has nothing to do with combat. - * @return true if tempfly should let the RequirementProvider handle its own location. - */ - public default boolean handles(InquiryType type) { - return true; - } - - /** - * - * Defines the types of inquiry. Mainly used to track where a FlightResult originated. - * - */ - public static enum InquiryType { - /** - * Location Inquiry - */ - LOCATION, - /** - * World Inquiry - */ - WORLD, - /** - * Region Inquiry - */ - REGION, - /** - * Inquiry is not within the scope of the base tempfly plugin, for instance - * island plots in the skyblock hook cannot be processed by the FlightManager, they are out_of_scope. - */ - OUT_OF_SCOPE, - UNDEFINED; - } - -} +package com.moneybags.tempfly.fly; + +import org.bukkit.Location; +import org.bukkit.World; + +import com.moneybags.tempfly.fly.result.FlightResult; +import com.moneybags.tempfly.fly.result.ResultAllow; +import com.moneybags.tempfly.hook.region.CompatRegion; +import com.moneybags.tempfly.user.FlightUser; +import com.moneybags.tempfly.util.V; +import com.moneybags.tempfly.util.data.Reloadable; + +public interface RequirementProvider extends Reloadable { + + /** + * Inquire whether a player can fly within a set of given regions. + * @param p + * @param regions + * @return + */ + public default FlightResult handleFlightInquiry(FlightUser user, CompatRegion[] regions) { + return new ResultAllow(this, InquiryType.REGION, V.requirePassDefault); + } + + /** + * Inquire whether a player can fly within a specific regions. + * @param p + * @param regions + * @return + */ + public default FlightResult handleFlightInquiry(FlightUser user, CompatRegion r) { + return new ResultAllow(this, InquiryType.REGION, V.requirePassDefault); + } + + /** + * Inquire whether a player can fly within a given world. + * @param p + * @param regions + * @return + */ + public default FlightResult handleFlightInquiry(FlightUser user, World world) { + return new ResultAllow(this, InquiryType.WORLD, V.requirePassDefault); + } + + /** + * Inquire whether a player can fly at a given location. + * @param p + * @param regions + * @return + */ + public default FlightResult handleFlightInquiry(FlightUser user, Location loc) { + return new ResultAllow(this, InquiryType.LOCATION, V.requirePassDefault); + } + + public default FlightResult handleFlightInquiry(FlightUser user) { + return new ResultAllow(this, InquiryType.UNDEFINED, V.requirePassDefault); + } + + /** + * Called when a player joins the server and their flight user is done being initialized. + * @param user The new user. + */ + public default void onUserInitialized(FlightUser user) {} + + /** + * Called when the user leaves the server and their user object is about to be destroyed. + * @param user The user who quit. + */ + public default void onUserQuit(FlightUser user) {} + + /** + * Should tempfly inquire flight for the players location or will the provider handle it. + * Useful to save on unnecessary checks if the provider does not need it. + * + * For example, why check if flight is allowed when a player enters a region in the combat manager, + * it has nothing to do with combat. + * @return true if tempfly should let the RequirementProvider handle its own location. + */ + public default boolean handles(InquiryType type) { + return true; + } + + /** + * + * Defines the types of inquiry. Mainly used to track where a FlightResult originated. + * + */ + public static enum InquiryType { + /** + * Location Inquiry + */ + LOCATION, + /** + * World Inquiry + */ + WORLD, + /** + * Region Inquiry + */ + REGION, + /** + * Inquiry is not within the scope of the base tempfly plugin, for instance + * island plots in the skyblock hook cannot be processed by the FlightManager, they are out_of_scope. + */ + OUT_OF_SCOPE, + UNDEFINED; + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/fly/result/FlightResult.java b/src/com/moneybags/tempfly/fly/result/FlightResult.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/fly/result/FlightResult.java rename to src/com/moneybags/tempfly/fly/result/FlightResult.java index 3239c38..7a9420f 100644 --- a/TempFly/src/com/moneybags/tempfly/fly/result/FlightResult.java +++ b/src/com/moneybags/tempfly/fly/result/FlightResult.java @@ -1,61 +1,61 @@ -package com.moneybags.tempfly.fly.result; - -import com.moneybags.tempfly.fly.RequirementProvider; -import com.moneybags.tempfly.fly.RequirementProvider.InquiryType; -import com.moneybags.tempfly.util.V; - -public abstract class FlightResult { - - private boolean allowed; - private DenyReason reason; - private InquiryType type; - private String message; - private RequirementProvider requirement; - private boolean fallSafely; - - public FlightResult(boolean allowed, DenyReason reason, InquiryType type, String message, RequirementProvider requirement, boolean fallSafely) { - this.allowed = allowed; - this.reason = reason; - this.type = type; - this.message = message; - this.requirement = requirement; - this.fallSafely = fallSafely; - } - - public boolean isAllowed() { - return allowed; - } - - public DenyReason getDenyReason() { - return reason; - } - - public InquiryType getInquiryType() { - return type; - } - - public FlightResult setInquiryType(InquiryType type) { - this.type = type; - return this; - } - - public String getMessage() { - return message == null ? (allowed ? V.requirePassDefault : V.requireFailDefault) : message; - } - - public RequirementProvider getRequirement() { - return requirement; - } - - public boolean hasDamageProtection() { - return fallSafely; - } - public static enum DenyReason { - COMBAT, - DISABLED_WORLD, - DISABLED_REGION, - REQUIREMENT, - OTHER; - } - -} +package com.moneybags.tempfly.fly.result; + +import com.moneybags.tempfly.fly.RequirementProvider; +import com.moneybags.tempfly.fly.RequirementProvider.InquiryType; +import com.moneybags.tempfly.util.V; + +public abstract class FlightResult { + + private boolean allowed; + private DenyReason reason; + private InquiryType type; + private String message; + private RequirementProvider requirement; + private boolean fallSafely; + + public FlightResult(boolean allowed, DenyReason reason, InquiryType type, String message, RequirementProvider requirement, boolean fallSafely) { + this.allowed = allowed; + this.reason = reason; + this.type = type; + this.message = message; + this.requirement = requirement; + this.fallSafely = fallSafely; + } + + public boolean isAllowed() { + return allowed; + } + + public DenyReason getDenyReason() { + return reason; + } + + public InquiryType getInquiryType() { + return type; + } + + public FlightResult setInquiryType(InquiryType type) { + this.type = type; + return this; + } + + public String getMessage() { + return message == null ? (allowed ? V.requirePassDefault : V.requireFailDefault) : message; + } + + public RequirementProvider getRequirement() { + return requirement; + } + + public boolean hasDamageProtection() { + return fallSafely; + } + public static enum DenyReason { + COMBAT, + DISABLED_WORLD, + DISABLED_REGION, + REQUIREMENT, + OTHER; + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/fly/result/ResultAllow.java b/src/com/moneybags/tempfly/fly/result/ResultAllow.java similarity index 97% rename from TempFly/src/com/moneybags/tempfly/fly/result/ResultAllow.java rename to src/com/moneybags/tempfly/fly/result/ResultAllow.java index 130d222..7499012 100644 --- a/TempFly/src/com/moneybags/tempfly/fly/result/ResultAllow.java +++ b/src/com/moneybags/tempfly/fly/result/ResultAllow.java @@ -1,17 +1,17 @@ -package com.moneybags.tempfly.fly.result; - -import com.moneybags.tempfly.fly.RequirementProvider; -import com.moneybags.tempfly.fly.RequirementProvider.InquiryType; - -/** - * I know it looks kinda stupid but I made these 2 flight result classes seperate to help avoid consfusion - * when people are using the API. They used to just be 2 seperate constructors in FlightResult. - * I could forsee people using the wrong constructor and causing nullpointers in the plugin - */ -public class ResultAllow extends FlightResult { - - public ResultAllow(RequirementProvider requirement, InquiryType type, String allowMessage) { - super(true, null, type, allowMessage, requirement, true); - } - -} +package com.moneybags.tempfly.fly.result; + +import com.moneybags.tempfly.fly.RequirementProvider; +import com.moneybags.tempfly.fly.RequirementProvider.InquiryType; + +/** + * I know it looks kinda stupid but I made these 2 flight result classes seperate to help avoid consfusion + * when people are using the API. They used to just be 2 seperate constructors in FlightResult. + * I could forsee people using the wrong constructor and causing nullpointers in the plugin + */ +public class ResultAllow extends FlightResult { + + public ResultAllow(RequirementProvider requirement, InquiryType type, String allowMessage) { + super(true, null, type, allowMessage, requirement, true); + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/fly/result/ResultDeny.java b/src/com/moneybags/tempfly/fly/result/ResultDeny.java similarity index 97% rename from TempFly/src/com/moneybags/tempfly/fly/result/ResultDeny.java rename to src/com/moneybags/tempfly/fly/result/ResultDeny.java index 3f14388..e9b2cf6 100644 --- a/TempFly/src/com/moneybags/tempfly/fly/result/ResultDeny.java +++ b/src/com/moneybags/tempfly/fly/result/ResultDeny.java @@ -1,17 +1,17 @@ -package com.moneybags.tempfly.fly.result; - -import com.moneybags.tempfly.fly.RequirementProvider; -import com.moneybags.tempfly.fly.RequirementProvider.InquiryType; - -/** - * I know it looks kinda stupid but I made these 2 flight result classes seperate to help avoid consfusion - * when people are using the API. They used to just be 2 seperate constructors in FlightResult. - * I could forsee people using the wrong constructor and causing nullpointers in the plugin - */ -public class ResultDeny extends FlightResult { - - public ResultDeny(DenyReason reason, RequirementProvider requirement, InquiryType type, String denyMessage, boolean fallSafely) { - super(false, reason, type, denyMessage, requirement, fallSafely); - } - -} +package com.moneybags.tempfly.fly.result; + +import com.moneybags.tempfly.fly.RequirementProvider; +import com.moneybags.tempfly.fly.RequirementProvider.InquiryType; + +/** + * I know it looks kinda stupid but I made these 2 flight result classes seperate to help avoid consfusion + * when people are using the API. They used to just be 2 seperate constructors in FlightResult. + * I could forsee people using the wrong constructor and causing nullpointers in the plugin + */ +public class ResultDeny extends FlightResult { + + public ResultDeny(DenyReason reason, RequirementProvider requirement, InquiryType type, String denyMessage, boolean fallSafely) { + super(false, reason, type, denyMessage, requirement, fallSafely); + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/gui/GuiManager.java b/src/com/moneybags/tempfly/gui/GuiManager.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/gui/GuiManager.java rename to src/com/moneybags/tempfly/gui/GuiManager.java index 6c0a366..96207dc 100644 --- a/TempFly/src/com/moneybags/tempfly/gui/GuiManager.java +++ b/src/com/moneybags/tempfly/gui/GuiManager.java @@ -1,113 +1,113 @@ -package com.moneybags.tempfly.gui; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.event.inventory.InventoryDragEvent; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.gui.abstraction.Page; - -public class GuiManager implements Listener { - - private TempFly tempfly; - - public GuiManager(TempFly tempfly) { - this.tempfly = tempfly; - tempfly.getServer().getPluginManager().registerEvents(this, tempfly); - } - - private Map sessions = new HashMap<>(); - - public TempFly getTempFly() { - return tempfly; - } - - public Collection getSessions() { - return sessions.values(); - } - - public void endAllSessions() { - for (GuiSession session: sessions.values()) { - session.endSession(); - } - } - - public GuiSession getSession(Player p) { - return sessions.containsKey(p) ? sessions.get(p) : null; - } - - public GuiSession createSession(Player p) { - if (sessions.containsKey(p)) { - sessions.get(p).endSession(); - } - GuiSession session = new GuiSession(p); - sessions.put(p, session); - return session; - } - - - - /** - * -------------- - * Event Handling - * -------------- - */ - - - - @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void on(InventoryCloseEvent e) { - if (!(e.getPlayer() instanceof Player)) { - return; - } - if (sessions.containsKey(e.getPlayer())) { - GuiSession session = sessions.get(e.getPlayer()); - Page page = session.getPage(); - if (page != null) { - page.onClose(e); - } - if (!session.saveSession()) { - sessions.remove(e.getPlayer()); - } - } - } - - @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void on(InventoryClickEvent e) { - if (!(e.getWhoClicked() instanceof Player)) { - return; - } - Player p = (Player)e.getWhoClicked(); - if (!sessions.containsKey(p)) { - return; - } - GuiSession session = sessions.get(p); - e.setCancelled(true); - if (e.getClickedInventory() == null) { - return; - } - int slot = e.getRawSlot(); - session.getPage().runPage(slot, e); - } - - @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void on(InventoryDragEvent e) { - if (!(e.getWhoClicked() instanceof Player)) { - return; - } - Player p = (Player)e.getWhoClicked(); - if (!sessions.containsKey(p)) { - return; - } - e.setCancelled(true); - } - -} +package com.moneybags.tempfly.gui; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.inventory.InventoryDragEvent; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.gui.abstraction.Page; + +public class GuiManager implements Listener { + + private TempFly tempfly; + + public GuiManager(TempFly tempfly) { + this.tempfly = tempfly; + tempfly.getServer().getPluginManager().registerEvents(this, tempfly); + } + + private Map sessions = new HashMap<>(); + + public TempFly getTempFly() { + return tempfly; + } + + public Collection getSessions() { + return sessions.values(); + } + + public void endAllSessions() { + for (GuiSession session: sessions.values()) { + session.endSession(); + } + } + + public GuiSession getSession(Player p) { + return sessions.containsKey(p) ? sessions.get(p) : null; + } + + public GuiSession createSession(Player p) { + if (sessions.containsKey(p)) { + sessions.get(p).endSession(); + } + GuiSession session = new GuiSession(p); + sessions.put(p, session); + return session; + } + + + + /** + * -------------- + * Event Handling + * -------------- + */ + + + + @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void on(InventoryCloseEvent e) { + if (!(e.getPlayer() instanceof Player)) { + return; + } + if (sessions.containsKey(e.getPlayer())) { + GuiSession session = sessions.get(e.getPlayer()); + Page page = session.getPage(); + if (page != null) { + page.onClose(e); + } + if (!session.saveSession()) { + sessions.remove(e.getPlayer()); + } + } + } + + @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void on(InventoryClickEvent e) { + if (!(e.getWhoClicked() instanceof Player)) { + return; + } + Player p = (Player)e.getWhoClicked(); + if (!sessions.containsKey(p)) { + return; + } + GuiSession session = sessions.get(p); + e.setCancelled(true); + if (e.getClickedInventory() == null) { + return; + } + int slot = e.getRawSlot(); + session.getPage().runPage(slot, e); + } + + @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void on(InventoryDragEvent e) { + if (!(e.getWhoClicked() instanceof Player)) { + return; + } + Player p = (Player)e.getWhoClicked(); + if (!sessions.containsKey(p)) { + return; + } + e.setCancelled(true); + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/gui/GuiSession.java b/src/com/moneybags/tempfly/gui/GuiSession.java similarity index 94% rename from TempFly/src/com/moneybags/tempfly/gui/GuiSession.java rename to src/com/moneybags/tempfly/gui/GuiSession.java index 35bfd38..f13c344 100644 --- a/TempFly/src/com/moneybags/tempfly/gui/GuiSession.java +++ b/src/com/moneybags/tempfly/gui/GuiSession.java @@ -1,53 +1,53 @@ -package com.moneybags.tempfly.gui; - -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; - -import com.moneybags.tempfly.gui.abstraction.Page; - - -public class GuiSession { - - private Page page; - private Player p; - private boolean safety; - private boolean save; - - public GuiSession(Player p) { - this.p = p; - } - - public void setSaveSession(boolean save) { - this.save = save; - } - - public boolean saveSession() { - return save; - } - - public Player getPlayer() { - return p; - } - - public Page getPage() { - return page; - } - - public void newPage(Page page, Inventory inv) { - setSaveSession(true); - p.openInventory(inv); - setSaveSession(false); - this.page = page; - } - public void setPage(Page page) { - this.page = page; - } - - public boolean safetyLock() { - return safety; - } - - public void endSession() { - p.closeInventory(); - } -} +package com.moneybags.tempfly.gui; + +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; + +import com.moneybags.tempfly.gui.abstraction.Page; + + +public class GuiSession { + + private Page page; + private Player p; + private boolean safety; + private boolean save; + + public GuiSession(Player p) { + this.p = p; + } + + public void setSaveSession(boolean save) { + this.save = save; + } + + public boolean saveSession() { + return save; + } + + public Player getPlayer() { + return p; + } + + public Page getPage() { + return page; + } + + public void newPage(Page page, Inventory inv) { + setSaveSession(true); + p.openInventory(inv); + setSaveSession(false); + this.page = page; + } + public void setPage(Page page) { + this.page = page; + } + + public boolean safetyLock() { + return safety; + } + + public void endSession() { + p.closeInventory(); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/gui/abstraction/DynamicPage.java b/src/com/moneybags/tempfly/gui/abstraction/DynamicPage.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/gui/abstraction/DynamicPage.java rename to src/com/moneybags/tempfly/gui/abstraction/DynamicPage.java index 6b9a310..7cd7ce4 100644 --- a/TempFly/src/com/moneybags/tempfly/gui/abstraction/DynamicPage.java +++ b/src/com/moneybags/tempfly/gui/abstraction/DynamicPage.java @@ -1,85 +1,85 @@ -package com.moneybags.tempfly.gui.abstraction; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import com.moneybags.tempfly.gui.GuiSession; - -public abstract class DynamicPage extends Page { - - //Page number - private int num; - private List open = new ArrayList<>(); - private int rows = 3; - - public DynamicPage(GuiSession session) { - super(session); - } - - public void calculateSlots(int num, int items) { - this.num = num; - - int skip = 21 * num; - int pageItems = items-skip > 21 ? 21 : items-skip; - final List sides = Arrays.asList(17, 18, 26, 27, 35); - int rowIndex = 0; - for (int i = 10; i < 35; i++) { - if (sides.contains(i)) { - continue; - } - if ((i == 10) || (i == 19) || (i == 28)) { - rowIndex++; - int rowItems = pageItems - ((rowIndex-1) * 7) < 7 ? pageItems - ((rowIndex-1) * 7) : 7; - if (rowItems < 7 && rowItems > 0) { - Iterator it = getPageLayout(pageItems % 7).iterator(); - while (it.hasNext()) { - open.add(it.next() + (9 * (rowIndex))); - } - break; - } else if (rowItems <= 0) { - rowIndex--; - break; - } - } - open.add(i); - } - rows = rows+rowIndex; - } - - public static List getPageLayout(int remainder) { - switch (remainder) { - case 1: - return Arrays.asList(4); - case 2: - return Arrays.asList(3, 5); - case 3: - return Arrays.asList(3, 4, 5); - case 4: - return Arrays.asList(2, 3, 5, 6); - case 5: - return Arrays.asList(2, 3, 4, 5, 6); - case 6: - return Arrays.asList(1, 2, 3, 5, 6, 7); - default: - return Arrays.asList(); - } - } - - public int getPageNumber() { - return num; - } - - public void setPageNumber(int num) { - this.num = num; - } - - public List getOpenSlots() { - return open; - } - - public int getRows() { - return rows; - } -} +package com.moneybags.tempfly.gui.abstraction; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import com.moneybags.tempfly.gui.GuiSession; + +public abstract class DynamicPage extends Page { + + //Page number + private int num; + private List open = new ArrayList<>(); + private int rows = 3; + + public DynamicPage(GuiSession session) { + super(session); + } + + public void calculateSlots(int num, int items) { + this.num = num; + + int skip = 21 * num; + int pageItems = items-skip > 21 ? 21 : items-skip; + final List sides = Arrays.asList(17, 18, 26, 27, 35); + int rowIndex = 0; + for (int i = 10; i < 35; i++) { + if (sides.contains(i)) { + continue; + } + if ((i == 10) || (i == 19) || (i == 28)) { + rowIndex++; + int rowItems = pageItems - ((rowIndex-1) * 7) < 7 ? pageItems - ((rowIndex-1) * 7) : 7; + if (rowItems < 7 && rowItems > 0) { + Iterator it = getPageLayout(pageItems % 7).iterator(); + while (it.hasNext()) { + open.add(it.next() + (9 * (rowIndex))); + } + break; + } else if (rowItems <= 0) { + rowIndex--; + break; + } + } + open.add(i); + } + rows = rows+rowIndex; + } + + public static List getPageLayout(int remainder) { + switch (remainder) { + case 1: + return Arrays.asList(4); + case 2: + return Arrays.asList(3, 5); + case 3: + return Arrays.asList(3, 4, 5); + case 4: + return Arrays.asList(2, 3, 5, 6); + case 5: + return Arrays.asList(2, 3, 4, 5, 6); + case 6: + return Arrays.asList(1, 2, 3, 5, 6, 7); + default: + return Arrays.asList(); + } + } + + public int getPageNumber() { + return num; + } + + public void setPageNumber(int num) { + this.num = num; + } + + public List getOpenSlots() { + return open; + } + + public int getRows() { + return rows; + } +} diff --git a/TempFly/src/com/moneybags/tempfly/gui/abstraction/Page.java b/src/com/moneybags/tempfly/gui/abstraction/Page.java similarity index 94% rename from TempFly/src/com/moneybags/tempfly/gui/abstraction/Page.java rename to src/com/moneybags/tempfly/gui/abstraction/Page.java index e29efa4..56852b6 100644 --- a/TempFly/src/com/moneybags/tempfly/gui/abstraction/Page.java +++ b/src/com/moneybags/tempfly/gui/abstraction/Page.java @@ -1,37 +1,37 @@ -package com.moneybags.tempfly.gui.abstraction; - -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryCloseEvent; - -import com.moneybags.tempfly.gui.GuiSession; - - -public abstract class Page { - - private int num; - protected GuiSession session; - - public Page(GuiSession session, int num) { - this.session = session; - this.num = num; - } - - public Page(GuiSession session) { - this.session = session; - } - - public GuiSession getSession() { - return session; - } - - public int getPageNumber() { - return num; - } - - public void onClose(InventoryCloseEvent e) { - return; - } - - public abstract void runPage(int slot, InventoryClickEvent e); - -} +package com.moneybags.tempfly.gui.abstraction; + +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; + +import com.moneybags.tempfly.gui.GuiSession; + + +public abstract class Page { + + private int num; + protected GuiSession session; + + public Page(GuiSession session, int num) { + this.session = session; + this.num = num; + } + + public Page(GuiSession session) { + this.session = session; + } + + public GuiSession getSession() { + return session; + } + + public int getPageNumber() { + return num; + } + + public void onClose(InventoryCloseEvent e) { + return; + } + + public abstract void runPage(int slot, InventoryClickEvent e); + +} diff --git a/TempFly/src/com/moneybags/tempfly/gui/pages/PageShop.java b/src/com/moneybags/tempfly/gui/pages/PageShop.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/gui/pages/PageShop.java rename to src/com/moneybags/tempfly/gui/pages/PageShop.java index ee39c24..2047484 100644 --- a/TempFly/src/com/moneybags/tempfly/gui/pages/PageShop.java +++ b/src/com/moneybags/tempfly/gui/pages/PageShop.java @@ -1,187 +1,187 @@ -package com.moneybags.tempfly.gui.pages; - -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.gui.GuiSession; -import com.moneybags.tempfly.gui.abstraction.DynamicPage; -import com.moneybags.tempfly.time.AsyncTimeParameters; -import com.moneybags.tempfly.time.TimeManager; -import com.moneybags.tempfly.util.CompatMaterial; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; -import com.moneybags.tempfly.util.data.Files; - -import net.milkbowl.vault.economy.Economy; - -public class PageShop extends DynamicPage { - - private static TempFly tempfly; - private static List allOptions = new ArrayList<>(); - - private static String title; - private static ItemStack background, toolbar, next, prev; - - public static void initialize(TempFly plugin) { - FileConfiguration config = Files.page; - String path = "page.shop"; - tempfly = plugin; - title = U.cc(config.getString(path + ".title", "&dParticle Trails")); - background = U.getConfigItem(config, path + ".background"); - toolbar = U.getConfigItem(config, path + ".toolbar"); - next = U.getConfigItem(config, path + ".next"); - prev = U.getConfigItem(config, path + ".prev"); - - CompatMaterial.setType(background, CompatMaterial.GRAY_STAINED_GLASS_PANE); - CompatMaterial.setType(toolbar, CompatMaterial.BLACK_STAINED_GLASS_PANE); - CompatMaterial.setType(next, CompatMaterial.REDSTONE_TORCH); - CompatMaterial.setType(prev, CompatMaterial.REDSTONE_TORCH); - - allOptions.clear(); - ConfigurationSection csOptons = Files.config.getConfigurationSection("shop.options"); - if (csOptons != null) { - for (String s: csOptons.getKeys(false)) { - path = "shop.options." + s; - allOptions.add(new ShopOption(Files.config.getInt(path + ".time", 0), Files.config.getDouble(path + ".cost", 1000000))); - } - } - } - - private Inventory inv; - private Map layout = new HashMap<>(); - - public PageShop(GuiSession session, int num) { - super(session); - - this.inv = Bukkit.createInventory(null, 54, title); - - for (int i = 0; i < 45; i++) { - inv.setItem(i, background); - } - for (int i = 45; i < 54; i++) { - inv.setItem(i, toolbar); - } - - super.calculateSlots(num, allOptions.size()); - if (allOptions.size() < 21*num) { - num = 0; - } - List options = new ArrayList<>(); - options.addAll(allOptions); - options = options.subList(21 * num, options.size()); - Iterator ito = options.iterator(); - Iterator its = super.getOpenSlots().iterator(); - while (its.hasNext() && ito.hasNext()) { - int slot = its.next(); - ShopOption option = ito.next(); - layout.put(slot, option); - inv.setItem(slot, option.getDisplay()); - } - if (allOptions.size() > (getPageNumber()+1)*21) { - inv.setItem(53, next); - } - if (getPageNumber() > 0) { - inv.setItem(45, prev); - } - - session.newPage(this, inv); - } - - @Override - public void runPage(int slot, InventoryClickEvent e) { - if (layout.containsKey(slot)) { - Player p = session.getPlayer(); - ShopOption option = layout.get(slot); - TimeManager manager = tempfly.getTimeManager(); - double maxTime = manager.getMaxTime(p.getUniqueId()); - if (maxTime == -999) { - U.m(p, "&cAn internal error occured. please contact the developer!"); - return; - } - - if (manager.getMaxTime(p.getUniqueId()) > -1 && - manager.getTime(p.getUniqueId()) + option.getTime() > maxTime) { - U.m(p, V.timeMaxSelf); - return; - } - Economy eco = tempfly.getHookManager().getEconomy(); - double balance = eco.getBalance(p); - if (option.getCost() > balance) { - U.m(p, manager.regexString(V.invalidFunds, option.getTime()) - .replaceAll("\\{COST}", String.valueOf(option.getCost()))); - } else { - eco.withdrawPlayer(p, option.getCost()); - U.m(p, manager.regexString(V.timePurchased, option.getTime()) - .replaceAll("\\{COST}", String.valueOf(option.getCost()))); - new AsyncTimeParameters(tempfly, (AsyncTimeParameters parameters) -> { - parameters.getTempfly().getTimeManager().addTime(p.getUniqueId(), parameters); - }, p, p, option.getTime()).run(); - } - } else if (slot == 53 && allOptions.size() > (getPageNumber()+1)*21) { - new PageShop(session, getPageNumber()+1); - } else if (slot == 45 && getPageNumber() > 0) { - new PageShop(session, getPageNumber()-1); - } - } - - public static class ShopOption { - - private int time; - private double cost; - private ItemStack item; - - private ShopOption(int time, double cost) { - this.time = time; - this.cost = cost; - item = CompatMaterial.get(CompatMaterial.FEATHER); - ItemMeta meta = item.getItemMeta(); - - String name = U.cc( - tempfly.getTimeManager().regexString( - Files.page.getString("page.shop.option.name", "{FORMATTED_TIME}"), time) - .replaceAll("\\{COST}", String.valueOf(cost)) - ); - meta.setDisplayName(name); - - List l = Files.page.getStringList("page.shop.option.lore"); - List lore = new ArrayList<>(); - if (l != null) { - DecimalFormat df = new DecimalFormat("##.##"); - for (String s: l) { - lore.add(U.cc( - tempfly.getTimeManager().regexString(s, time) - .replaceAll("\\{COST}", df.format(cost)) - )); - } - } - meta.setLore(lore); - item.setItemMeta(meta); - } - public int getTime() { - return time; - } - - public double getCost() { - return cost; - } - - public ItemStack getDisplay() { - return item; - } - } - -} +package com.moneybags.tempfly.gui.pages; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.bukkit.Bukkit; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.gui.GuiSession; +import com.moneybags.tempfly.gui.abstraction.DynamicPage; +import com.moneybags.tempfly.time.AsyncTimeParameters; +import com.moneybags.tempfly.time.TimeManager; +import com.moneybags.tempfly.util.CompatMaterial; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; +import com.moneybags.tempfly.util.data.Files; + +import net.milkbowl.vault.economy.Economy; + +public class PageShop extends DynamicPage { + + private static TempFly tempfly; + private static List allOptions = new ArrayList<>(); + + private static String title; + private static ItemStack background, toolbar, next, prev; + + public static void initialize(TempFly plugin) { + FileConfiguration config = Files.page; + String path = "page.shop"; + tempfly = plugin; + title = U.cc(config.getString(path + ".title", "&dParticle Trails")); + background = U.getConfigItem(config, path + ".background"); + toolbar = U.getConfigItem(config, path + ".toolbar"); + next = U.getConfigItem(config, path + ".next"); + prev = U.getConfigItem(config, path + ".prev"); + + CompatMaterial.setType(background, CompatMaterial.GRAY_STAINED_GLASS_PANE); + CompatMaterial.setType(toolbar, CompatMaterial.BLACK_STAINED_GLASS_PANE); + CompatMaterial.setType(next, CompatMaterial.REDSTONE_TORCH); + CompatMaterial.setType(prev, CompatMaterial.REDSTONE_TORCH); + + allOptions.clear(); + ConfigurationSection csOptons = Files.config.getConfigurationSection("shop.options"); + if (csOptons != null) { + for (String s: csOptons.getKeys(false)) { + path = "shop.options." + s; + allOptions.add(new ShopOption(Files.config.getInt(path + ".time", 0), Files.config.getDouble(path + ".cost", 1000000))); + } + } + } + + private Inventory inv; + private Map layout = new HashMap<>(); + + public PageShop(GuiSession session, int num) { + super(session); + + this.inv = Bukkit.createInventory(null, 54, title); + + for (int i = 0; i < 45; i++) { + inv.setItem(i, background); + } + for (int i = 45; i < 54; i++) { + inv.setItem(i, toolbar); + } + + super.calculateSlots(num, allOptions.size()); + if (allOptions.size() < 21*num) { + num = 0; + } + List options = new ArrayList<>(); + options.addAll(allOptions); + options = options.subList(21 * num, options.size()); + Iterator ito = options.iterator(); + Iterator its = super.getOpenSlots().iterator(); + while (its.hasNext() && ito.hasNext()) { + int slot = its.next(); + ShopOption option = ito.next(); + layout.put(slot, option); + inv.setItem(slot, option.getDisplay()); + } + if (allOptions.size() > (getPageNumber()+1)*21) { + inv.setItem(53, next); + } + if (getPageNumber() > 0) { + inv.setItem(45, prev); + } + + session.newPage(this, inv); + } + + @Override + public void runPage(int slot, InventoryClickEvent e) { + if (layout.containsKey(slot)) { + Player p = session.getPlayer(); + ShopOption option = layout.get(slot); + TimeManager manager = tempfly.getTimeManager(); + double maxTime = manager.getMaxTime(p.getUniqueId()); + if (maxTime == -999) { + U.m(p, "&cAn internal error occured. please contact the developer!"); + return; + } + + if (manager.getMaxTime(p.getUniqueId()) > -1 && + manager.getTime(p.getUniqueId()) + option.getTime() > maxTime) { + U.m(p, V.timeMaxSelf); + return; + } + Economy eco = tempfly.getHookManager().getEconomy(); + double balance = eco.getBalance(p); + if (option.getCost() > balance) { + U.m(p, manager.regexString(V.invalidFunds, option.getTime()) + .replaceAll("\\{COST}", String.valueOf(option.getCost()))); + } else { + eco.withdrawPlayer(p, option.getCost()); + U.m(p, manager.regexString(V.timePurchased, option.getTime()) + .replaceAll("\\{COST}", String.valueOf(option.getCost()))); + new AsyncTimeParameters(tempfly, (AsyncTimeParameters parameters) -> { + parameters.getTempfly().getTimeManager().addTime(p.getUniqueId(), parameters); + }, p, p, option.getTime()).run(); + } + } else if (slot == 53 && allOptions.size() > (getPageNumber()+1)*21) { + new PageShop(session, getPageNumber()+1); + } else if (slot == 45 && getPageNumber() > 0) { + new PageShop(session, getPageNumber()-1); + } + } + + public static class ShopOption { + + private int time; + private double cost; + private ItemStack item; + + private ShopOption(int time, double cost) { + this.time = time; + this.cost = cost; + item = CompatMaterial.get(CompatMaterial.FEATHER); + ItemMeta meta = item.getItemMeta(); + + String name = U.cc( + tempfly.getTimeManager().regexString( + Files.page.getString("page.shop.option.name", "{FORMATTED_TIME}"), time) + .replaceAll("\\{COST}", String.valueOf(cost)) + ); + meta.setDisplayName(name); + + List l = Files.page.getStringList("page.shop.option.lore"); + List lore = new ArrayList<>(); + if (l != null) { + DecimalFormat df = new DecimalFormat("##.##"); + for (String s: l) { + lore.add(U.cc( + tempfly.getTimeManager().regexString(s, time) + .replaceAll("\\{COST}", df.format(cost)) + )); + } + } + meta.setLore(lore); + item.setItemMeta(meta); + } + public int getTime() { + return time; + } + + public double getCost() { + return cost; + } + + public ItemStack getDisplay() { + return item; + } + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/gui/pages/PageTrails.java b/src/com/moneybags/tempfly/gui/pages/PageTrails.java similarity index 97% rename from TempFly/src/com/moneybags/tempfly/gui/pages/PageTrails.java rename to src/com/moneybags/tempfly/gui/pages/PageTrails.java index 0787d65..efe8e89 100644 --- a/TempFly/src/com/moneybags/tempfly/gui/pages/PageTrails.java +++ b/src/com/moneybags/tempfly/gui/pages/PageTrails.java @@ -1,155 +1,155 @@ -package com.moneybags.tempfly.gui.pages; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.bukkit.Bukkit; -import org.bukkit.Effect; -import org.bukkit.Particle; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.aesthetic.particle.Particles; -import com.moneybags.tempfly.command.admin.CmdTrailRemove; -import com.moneybags.tempfly.gui.GuiSession; -import com.moneybags.tempfly.gui.abstraction.DynamicPage; -import com.moneybags.tempfly.util.CompatMaterial; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.data.Files; - -public class PageTrails extends DynamicPage { - - private static TempFly tempfly; - private static String title; - private static ItemStack - background, - toolbar, - next, - prev, - remove; - - public static void initialize(TempFly plugin) { - tempfly = plugin; - FileConfiguration config = Files.page; - String path = "page.trails"; - title = U.cc(config.getString(path + ".title", "&dParticle Trails")); - background = U.getConfigItem(config, path + ".background"); - toolbar = U.getConfigItem(config, path + ".toolbar"); - next = U.getConfigItem(config, path + ".next"); - prev = U.getConfigItem(config, path + ".prev"); - remove = U.getConfigItem(config, path + ".remove"); - - CompatMaterial.setType(background, CompatMaterial.GRAY_STAINED_GLASS_PANE); - CompatMaterial.setType(toolbar, CompatMaterial.BLACK_STAINED_GLASS_PANE); - CompatMaterial.setType(next, CompatMaterial.REDSTONE_TORCH); - CompatMaterial.setType(prev, CompatMaterial.REDSTONE_TORCH); - CompatMaterial.setType(remove, CompatMaterial.LAVA_BUCKET); - - } - - private Inventory inv; - private Map layout = new HashMap<>(); - private List allParticles; - - public PageTrails(GuiSession session, int num, boolean bookmark) { - super(session); - - this.inv = Bukkit.createInventory(null, 54, title); - - for (int i = 0; i < 45; i++) { - inv.setItem(i, background); - } - for (int i = 45; i < 54; i++) { - inv.setItem(i, toolbar); - } - - Player p = session.getPlayer(); - List particles = new ArrayList<>(); - if (Particles.oldParticles()) { - for (Effect e: Effect.values()) { - if (e.toString().equalsIgnoreCase("ITEM_BREAK")) { - continue; - } - if (p.hasPermission("tempfly.trail." + e.toString())) { - particles.add(e.toString()); - } - } - } else { - for (Particle particle: Particle.values()) { - if (particle.toString().contains("LEGACY")) { - continue; - } - if (p.hasPermission("tempfly.trail." + particle.toString())) { - particles.add(particle.toString()); - } - } - } - allParticles = particles; - String current = Particles.loadTrail(session.getPlayer().getUniqueId()); - if (bookmark && particles.contains(current)) { - num = (int) Math.floor(particles.indexOf(current) / 21); - } - super.calculateSlots(num, particles.size()); - if (particles.size() < 21*num) { - num = 0; - } - - particles = particles.subList(21 * num, particles.size()); - Iterator itp = particles.iterator(); - Iterator its = super.getOpenSlots().iterator(); - while (its.hasNext() && itp.hasNext()) { - int slot = its.next(); - String particle = itp.next(); - layout.put(slot, particle); - ItemStack display; - if (particle.equalsIgnoreCase(current)) { - display = CompatMaterial.get(CompatMaterial.LIME_STAINED_GLASS); - } else { - display = CompatMaterial.get(CompatMaterial.WHITE_STAINED_GLASS); - } - ItemMeta meta = display.getItemMeta(); - meta.setDisplayName(U.cc("&a" + particle.toLowerCase().replaceAll("\\_", " "))); - if (p.isOp()) { - meta.setLore(Arrays.asList(U.cc("&fPermission: &etempfly.trail." + particle))); - } - display.setItemMeta(meta); - inv.setItem(slot, display); - } - if (allParticles.size() > (getPageNumber()+1)*21) { - inv.setItem(53, next); - } - if (getPageNumber() > 0) { - inv.setItem(45, prev); - } - if (p.hasPermission("tempfly.trails.remove.self")) { - inv.setItem(49, remove); - } - - session.newPage(this, inv); - } - - @Override - public void runPage(int slot, InventoryClickEvent e) { - if (layout.containsKey(slot)) { - String s = layout.get(slot); - Particles.setTrail(session.getPlayer().getUniqueId(), s); - new PageTrails(session, getPageNumber(), false); - } else if (slot == 53 && allParticles.size() > (getPageNumber()+1)*21) { - new PageTrails(session, getPageNumber()+1, false); - } else if (slot == 45 && getPageNumber() > 0) { - new PageTrails(session, getPageNumber()-1, false); - } else if (slot == 49 && session.getPlayer().hasPermission("tempfly.trails.remove.self")) { - new CmdTrailRemove(tempfly, null).executeFromGui(session.getPlayer()); - new PageTrails(session, getPageNumber(), false); - } - } -} +package com.moneybags.tempfly.gui.pages; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.bukkit.Bukkit; +import org.bukkit.Effect; +import org.bukkit.Particle; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.aesthetic.particle.Particles; +import com.moneybags.tempfly.command.admin.CmdTrailRemove; +import com.moneybags.tempfly.gui.GuiSession; +import com.moneybags.tempfly.gui.abstraction.DynamicPage; +import com.moneybags.tempfly.util.CompatMaterial; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.data.Files; + +public class PageTrails extends DynamicPage { + + private static TempFly tempfly; + private static String title; + private static ItemStack + background, + toolbar, + next, + prev, + remove; + + public static void initialize(TempFly plugin) { + tempfly = plugin; + FileConfiguration config = Files.page; + String path = "page.trails"; + title = U.cc(config.getString(path + ".title", "&dParticle Trails")); + background = U.getConfigItem(config, path + ".background"); + toolbar = U.getConfigItem(config, path + ".toolbar"); + next = U.getConfigItem(config, path + ".next"); + prev = U.getConfigItem(config, path + ".prev"); + remove = U.getConfigItem(config, path + ".remove"); + + CompatMaterial.setType(background, CompatMaterial.GRAY_STAINED_GLASS_PANE); + CompatMaterial.setType(toolbar, CompatMaterial.BLACK_STAINED_GLASS_PANE); + CompatMaterial.setType(next, CompatMaterial.REDSTONE_TORCH); + CompatMaterial.setType(prev, CompatMaterial.REDSTONE_TORCH); + CompatMaterial.setType(remove, CompatMaterial.LAVA_BUCKET); + + } + + private Inventory inv; + private Map layout = new HashMap<>(); + private List allParticles; + + public PageTrails(GuiSession session, int num, boolean bookmark) { + super(session); + + this.inv = Bukkit.createInventory(null, 54, title); + + for (int i = 0; i < 45; i++) { + inv.setItem(i, background); + } + for (int i = 45; i < 54; i++) { + inv.setItem(i, toolbar); + } + + Player p = session.getPlayer(); + List particles = new ArrayList<>(); + if (Particles.oldParticles()) { + for (Effect e: Effect.values()) { + if (e.toString().equalsIgnoreCase("ITEM_BREAK")) { + continue; + } + if (p.hasPermission("tempfly.trail." + e.toString())) { + particles.add(e.toString()); + } + } + } else { + for (Particle particle: Particle.values()) { + if (particle.toString().contains("LEGACY")) { + continue; + } + if (p.hasPermission("tempfly.trail." + particle.toString())) { + particles.add(particle.toString()); + } + } + } + allParticles = particles; + String current = Particles.loadTrail(session.getPlayer().getUniqueId()); + if (bookmark && particles.contains(current)) { + num = (int) Math.floor(particles.indexOf(current) / 21); + } + super.calculateSlots(num, particles.size()); + if (particles.size() < 21*num) { + num = 0; + } + + particles = particles.subList(21 * num, particles.size()); + Iterator itp = particles.iterator(); + Iterator its = super.getOpenSlots().iterator(); + while (its.hasNext() && itp.hasNext()) { + int slot = its.next(); + String particle = itp.next(); + layout.put(slot, particle); + ItemStack display; + if (particle.equalsIgnoreCase(current)) { + display = CompatMaterial.get(CompatMaterial.LIME_STAINED_GLASS); + } else { + display = CompatMaterial.get(CompatMaterial.WHITE_STAINED_GLASS); + } + ItemMeta meta = display.getItemMeta(); + meta.setDisplayName(U.cc("&a" + particle.toLowerCase().replaceAll("\\_", " "))); + if (p.isOp()) { + meta.setLore(Arrays.asList(U.cc("&fPermission: &etempfly.trail." + particle))); + } + display.setItemMeta(meta); + inv.setItem(slot, display); + } + if (allParticles.size() > (getPageNumber()+1)*21) { + inv.setItem(53, next); + } + if (getPageNumber() > 0) { + inv.setItem(45, prev); + } + if (p.hasPermission("tempfly.trails.remove.self")) { + inv.setItem(49, remove); + } + + session.newPage(this, inv); + } + + @Override + public void runPage(int slot, InventoryClickEvent e) { + if (layout.containsKey(slot)) { + String s = layout.get(slot); + Particles.setTrail(session.getPlayer().getUniqueId(), s); + new PageTrails(session, getPageNumber(), false); + } else if (slot == 53 && allParticles.size() > (getPageNumber()+1)*21) { + new PageTrails(session, getPageNumber()+1, false); + } else if (slot == 45 && getPageNumber() > 0) { + new PageTrails(session, getPageNumber()-1, false); + } else if (slot == 49 && session.getPlayer().hasPermission("tempfly.trails.remove.self")) { + new CmdTrailRemove(tempfly, null).executeFromGui(session.getPlayer()); + new PageTrails(session, getPageNumber(), false); + } + } +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/HookManager.java b/src/com/moneybags/tempfly/hook/HookManager.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/hook/HookManager.java rename to src/com/moneybags/tempfly/hook/HookManager.java index 7ad741b..29d152d 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/HookManager.java +++ b/src/com/moneybags/tempfly/hook/HookManager.java @@ -1,252 +1,252 @@ -package com.moneybags.tempfly.hook; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.bukkit.plugin.RegisteredServiceProvider; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.hook.factions.plugins.FactionsUUIDHook; -import com.moneybags.tempfly.hook.region.RegionProvider; -import com.moneybags.tempfly.hook.region.plugins.WorldGuardHook; -import com.moneybags.tempfly.hook.skyblock.plugins.AskyblockHook; -import com.moneybags.tempfly.hook.skyblock.plugins.BskyblockHook; -import com.moneybags.tempfly.hook.skyblock.plugins.IridiumHook; -import com.moneybags.tempfly.hook.skyblock.plugins.SuperiorHook; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.V; -import com.moneybags.tempfly.util.data.Reloadable; - -import net.milkbowl.vault.economy.Economy; -import net.milkbowl.vault.permission.Permission; - -public class HookManager implements Reloadable { - - public static final Class[] REGIONS = new Class[] {WorldGuardHook.class}; - - private TempFly plugin; - private Economy eco = null; - private Permission perms = null; - private RegionProvider regions; - - private Map> hooks = new HashMap<>(); - - public HookManager(TempFly plugin) { - this.plugin = plugin; - - loadRegionProvider(); - if (setupEconomy()) { - setupPermissions(); - } - } - - public boolean registerHook(TempFlyHook hook) throws IllegalArgumentException { - if (getHook(hook.getClass()) != null) { - throw new IllegalArgumentException("You may only register a hook once within tempfly!"); - } - List loaded = hooks.getOrDefault(hook.getGenre(), new ArrayList<>()); - loaded.add(hook); - hooks.put(hook.getGenre(), loaded); - plugin.getFlightManager().registerRequirementProvider(hook); - return true; - } - - public void unregisterHook(TempFlyHook hook) { - if (getHook(hook.getClass()) == null) { - return; - } - List loaded = hooks.get(hook.getGenre()); - loaded.remove(hook); - plugin.getFlightManager().unregisterRequirementProvider(hook); - if (loaded.size() < 1) { - hooks.remove(hook.getGenre()); - return; - } - hooks.put(hook.getGenre(), loaded); - } - - - - /** - * - * Initialization - * - */ - - private void loadRegionProvider() { - RegionProvider hook; - for (Class clazz: REGIONS) { - try { - hook = (RegionProvider) clazz.getConstructor(TempFly.class).newInstance(plugin); - if (hook.isEnabled()) { - regions = hook; - break; - } - } catch (Exception e) {e.printStackTrace();} - } - } - - /** - * Manually set tempfly's region provider. - * @param provider The regbion provider - */ - public void setRegionProvider(RegionProvider provider) { - this.regions = provider; - } - - public boolean hasRegionProvider() { - return !V.disableTracker && regions != null && regions.isEnabled(); - } - - public RegionProvider getRegionProvider() { - return regions; - } - - public boolean hasPermissions() { - return perms != null; - } - - private boolean setupEconomy() { - if (plugin.getServer().getPluginManager().getPlugin("Vault") == null) { - return false; - } - RegisteredServiceProvider rsp = plugin.getServer().getServicesManager().getRegistration(Economy.class); - if (rsp == null) { - return false; - } - eco = rsp.getProvider(); - return eco != null; - } - - private boolean setupPermissions() { - RegisteredServiceProvider rsp = plugin.getServer().getServicesManager().getRegistration(Permission.class); - perms = rsp.getProvider(); - return perms != null; - } - - - public void loadInternalGenres() { - Console.debug("", "----------Loading Genre Hooks----------"); - TempFlyHook hook; - for (Genre genre: Genre.values()) { - Console.debug("", "--< Loading: " + genre.toString()); - for (Class clazz: genre.getInternalClasses()) { - Console.debug("", "----< Class: " + clazz.getName()); - try { - hook = (TempFlyHook) clazz.getConstructor(TempFly.class).newInstance(plugin); - Console.debug("----< Enabled: " + hook.isEnabled()); - } catch (Exception e) { - e.printStackTrace(); - } catch (Error e) { - if (V.debug) { - e.printStackTrace(); - } - } - } - } - Console.debug("--------Loading Genre Hooks End--------", ""); - } - - /** - * - * Getters - * - */ - - public Economy getEconomy() { - return eco; - } - - public Permission getPermissions() { - return perms; - } - - public TempFlyHook getHook(String plugin) { - for (List list: hooks.values()) { - for (TempFlyHook hook: list) { - if (hook.getPluginName().equals(plugin)) { - return hook; - } - } - } - return null; - } - - public TempFlyHook getHook(Class clazz) { - for (List list: hooks.values()) { - for (TempFlyHook hook: list) { - if (hook.getClass().equals(clazz)) { - return hook; - } - } - } - return null; - } - - public TempFlyHook[] getGenre(Genre genre) { - List list; - return (list = hooks.getOrDefault(genre, new ArrayList<>())).toArray(new TempFlyHook[list.size()]); - } - - public TempFlyHook[] getEnabled() { - List enabled = new ArrayList<>(); - for (List genre: hooks.values()) { - for (TempFlyHook hook: genre) { - if (hook.isEnabled()) { - enabled.add(hook); - } - } - } - return enabled.toArray(new TempFlyHook[enabled.size()]); - } - - - - - /* - * Represents the GameMode type of a hook - */ - public static enum Genre { - SKYBLOCK("SkyBlock", AskyblockHook.class, IridiumHook.class, BskyblockHook.class, SuperiorHook.class), - LANDS("Lands"), - FACTIONS("Factions", FactionsUUIDHook.class), - OTHER("Other"); - - private String folder; - private final Class[] classes; - - private Genre(String folder, Class... classes) { - this.folder = folder; - this.classes = classes; - } - - public String getDirectory() { - return "hooks" + File.separator + folder; - } - - /** - * - * @return An array of built in TempFly classes that represent this genre. You can still add your own that - * aren't on this list, i just use it internally for ease of access. - */ - public Class[] getInternalClasses() { - return classes; - } - } - - @Override - public void onTempflyReload() { - for (Entry> entry: hooks.entrySet()) { - for (TempFlyHook hook: entry.getValue()) { - Console.debug("Preparing to reload hook: " + hook.getHookName()); - ((Reloadable)hook).onTempflyReload(); - } - } - - } - -} +package com.moneybags.tempfly.hook; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.bukkit.plugin.RegisteredServiceProvider; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.hook.factions.plugins.FactionsUUIDHook; +import com.moneybags.tempfly.hook.region.RegionProvider; +import com.moneybags.tempfly.hook.region.plugins.WorldGuardHook; +import com.moneybags.tempfly.hook.skyblock.plugins.AskyblockHook; +import com.moneybags.tempfly.hook.skyblock.plugins.BskyblockHook; +import com.moneybags.tempfly.hook.skyblock.plugins.IridiumHook; +import com.moneybags.tempfly.hook.skyblock.plugins.SuperiorHook; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.V; +import com.moneybags.tempfly.util.data.Reloadable; + +import net.milkbowl.vault.economy.Economy; +import net.milkbowl.vault.permission.Permission; + +public class HookManager implements Reloadable { + + public static final Class[] REGIONS = new Class[] {WorldGuardHook.class}; + + private TempFly plugin; + private Economy eco = null; + private Permission perms = null; + private RegionProvider regions; + + private Map> hooks = new HashMap<>(); + + public HookManager(TempFly plugin) { + this.plugin = plugin; + + loadRegionProvider(); + if (setupEconomy()) { + setupPermissions(); + } + } + + public boolean registerHook(TempFlyHook hook) throws IllegalArgumentException { + if (getHook(hook.getClass()) != null) { + throw new IllegalArgumentException("You may only register a hook once within tempfly!"); + } + List loaded = hooks.getOrDefault(hook.getGenre(), new ArrayList<>()); + loaded.add(hook); + hooks.put(hook.getGenre(), loaded); + plugin.getFlightManager().registerRequirementProvider(hook); + return true; + } + + public void unregisterHook(TempFlyHook hook) { + if (getHook(hook.getClass()) == null) { + return; + } + List loaded = hooks.get(hook.getGenre()); + loaded.remove(hook); + plugin.getFlightManager().unregisterRequirementProvider(hook); + if (loaded.size() < 1) { + hooks.remove(hook.getGenre()); + return; + } + hooks.put(hook.getGenre(), loaded); + } + + + + /** + * + * Initialization + * + */ + + private void loadRegionProvider() { + RegionProvider hook; + for (Class clazz: REGIONS) { + try { + hook = (RegionProvider) clazz.getConstructor(TempFly.class).newInstance(plugin); + if (hook.isEnabled()) { + regions = hook; + break; + } + } catch (Exception e) {e.printStackTrace();} + } + } + + /** + * Manually set tempfly's region provider. + * @param provider The regbion provider + */ + public void setRegionProvider(RegionProvider provider) { + this.regions = provider; + } + + public boolean hasRegionProvider() { + return !V.disableTracker && regions != null && regions.isEnabled(); + } + + public RegionProvider getRegionProvider() { + return regions; + } + + public boolean hasPermissions() { + return perms != null; + } + + private boolean setupEconomy() { + if (plugin.getServer().getPluginManager().getPlugin("Vault") == null) { + return false; + } + RegisteredServiceProvider rsp = plugin.getServer().getServicesManager().getRegistration(Economy.class); + if (rsp == null) { + return false; + } + eco = rsp.getProvider(); + return eco != null; + } + + private boolean setupPermissions() { + RegisteredServiceProvider rsp = plugin.getServer().getServicesManager().getRegistration(Permission.class); + perms = rsp.getProvider(); + return perms != null; + } + + + public void loadInternalGenres() { + Console.debug("", "----------Loading Genre Hooks----------"); + TempFlyHook hook; + for (Genre genre: Genre.values()) { + Console.debug("", "--< Loading: " + genre.toString()); + for (Class clazz: genre.getInternalClasses()) { + Console.debug("", "----< Class: " + clazz.getName()); + try { + hook = (TempFlyHook) clazz.getConstructor(TempFly.class).newInstance(plugin); + Console.debug("----< Enabled: " + hook.isEnabled()); + } catch (Exception e) { + e.printStackTrace(); + } catch (Error e) { + if (V.debug) { + e.printStackTrace(); + } + } + } + } + Console.debug("--------Loading Genre Hooks End--------", ""); + } + + /** + * + * Getters + * + */ + + public Economy getEconomy() { + return eco; + } + + public Permission getPermissions() { + return perms; + } + + public TempFlyHook getHook(String plugin) { + for (List list: hooks.values()) { + for (TempFlyHook hook: list) { + if (hook.getPluginName().equals(plugin)) { + return hook; + } + } + } + return null; + } + + public TempFlyHook getHook(Class clazz) { + for (List list: hooks.values()) { + for (TempFlyHook hook: list) { + if (hook.getClass().equals(clazz)) { + return hook; + } + } + } + return null; + } + + public TempFlyHook[] getGenre(Genre genre) { + List list; + return (list = hooks.getOrDefault(genre, new ArrayList<>())).toArray(new TempFlyHook[list.size()]); + } + + public TempFlyHook[] getEnabled() { + List enabled = new ArrayList<>(); + for (List genre: hooks.values()) { + for (TempFlyHook hook: genre) { + if (hook.isEnabled()) { + enabled.add(hook); + } + } + } + return enabled.toArray(new TempFlyHook[enabled.size()]); + } + + + + + /* + * Represents the GameMode type of a hook + */ + public static enum Genre { + SKYBLOCK("SkyBlock", AskyblockHook.class, IridiumHook.class, BskyblockHook.class, SuperiorHook.class), + LANDS("Lands"), + FACTIONS("Factions", FactionsUUIDHook.class), + OTHER("Other"); + + private String folder; + private final Class[] classes; + + private Genre(String folder, Class... classes) { + this.folder = folder; + this.classes = classes; + } + + public String getDirectory() { + return "hooks" + File.separator + folder; + } + + /** + * + * @return An array of built in TempFly classes that represent this genre. You can still add your own that + * aren't on this list, i just use it internally for ease of access. + */ + public Class[] getInternalClasses() { + return classes; + } + } + + @Override + public void onTempflyReload() { + for (Entry> entry: hooks.entrySet()) { + for (TempFlyHook hook: entry.getValue()) { + Console.debug("Preparing to reload hook: " + hook.getHookName()); + ((Reloadable)hook).onTempflyReload(); + } + } + + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/IslandSettings.java b/src/com/moneybags/tempfly/hook/IslandSettings.java similarity index 97% rename from TempFly/src/com/moneybags/tempfly/hook/IslandSettings.java rename to src/com/moneybags/tempfly/hook/IslandSettings.java index 5b7aac1..d8b77eb 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/IslandSettings.java +++ b/src/com/moneybags/tempfly/hook/IslandSettings.java @@ -1,104 +1,104 @@ -package com.moneybags.tempfly.hook; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.zip.DataFormatException; - -import com.moneybags.tempfly.hook.skyblock.IslandWrapper; -import com.moneybags.tempfly.hook.skyblock.SkyblockHook; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.V; -import com.moneybags.tempfly.util.data.DataBridge; -import com.moneybags.tempfly.util.data.DataBridge.DataTable; -import com.moneybags.tempfly.util.data.DataBridge.DataValue; -import com.moneybags.tempfly.util.data.DataPointer; - -public class IslandSettings { - - private SkyblockHook hook; - private IslandWrapper island; - private Map settings = new HashMap<>(); - - public IslandSettings(IslandWrapper island, SkyblockHook hook) { - this.hook = hook; - this.island = island; - String id = hook.getIslandIdentifier(island.getRawIsland()); - DataBridge bridge = hook.getTempFly().getDataBridge(); - - Map values = bridge.getValues(DataTable.ISLAND_SETTINGS, hook, "islands", id, "settings"); - for (Entry entry: values.entrySet()) { - if (entry.getKey().equalsIgnoreCase("OWNER")) { - continue; - } - if (!(entry.getValue() instanceof Boolean)) { - try { throw new DataFormatException("A data value in Island Settings is not properly formatted, Expected boolean got (" + entry.getValue().getClass() + ")! island=(" + id + ") key=(" + entry.getKey() + ")");} - catch (DataFormatException e) { - e.printStackTrace(); - continue; - } - } - settings.put(entry.getKey(), (Boolean)entry.getValue()); - } - } - - public boolean canFly(String role) { - role = role.toUpperCase(); - return role.equalsIgnoreCase("OWNER") ? true : settings.getOrDefault(role, hook.getDefaults().getOrDefault(role, false)); - } - - public void setCanFly(String role, boolean canFly) { - role = role.toUpperCase(); - if (role.equals("OWNER")) { - return; - } - Console.debug("-- Set flight for: " + role, - "currently: " + canFly(role), - "mapped settings contains: " + settings.containsKey(role)); - settings.put(role, canFly); - hook.evaluate(island); - hook.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.ISLAND_SETTING, hook.getIslandIdentifier(island), role), canFly, hook); - } - - public void toggleCanFly(String role) { - role = role.toUpperCase(); - if (role.equals("OWNER")) { - return; - } - if (V.debug) {Console.debug("-- Set flight for: " + role, "--| currently: " + canFly(role), "--| mapped settings contains: " + settings.containsKey(role));} - boolean canFly = !canFly(role); - settings.put(role, canFly); - hook.evaluate(island); - hook.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.ISLAND_SETTING, hook.getIslandIdentifier(island.getRawIsland()), role), canFly, hook); - } - - public List> getCurrentState() { - Map state = new HashMap<>(); - state.putAll(settings); - for (String role: hook.getRoles()) { - role = role.toUpperCase(); - if (!role.equalsIgnoreCase("OWNER") && !state.containsKey(role)) { - state.put(role, hook.getDefaults().getOrDefault(role, false)); - } - } - - Comparator> comp = new Comparator>() { - @Override - public int compare(Entry e0, Entry e1) { - return e0.getKey().compareTo(e1.getKey()); - } - }; - List> sorted = new ArrayList>(state.entrySet()); - Collections.sort(sorted, comp); - return sorted; - } - - public IslandWrapper getIsland() { - return island; - } - -} +package com.moneybags.tempfly.hook; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.zip.DataFormatException; + +import com.moneybags.tempfly.hook.skyblock.IslandWrapper; +import com.moneybags.tempfly.hook.skyblock.SkyblockHook; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.V; +import com.moneybags.tempfly.util.data.DataBridge; +import com.moneybags.tempfly.util.data.DataBridge.DataTable; +import com.moneybags.tempfly.util.data.DataBridge.DataValue; +import com.moneybags.tempfly.util.data.DataPointer; + +public class IslandSettings { + + private SkyblockHook hook; + private IslandWrapper island; + private Map settings = new HashMap<>(); + + public IslandSettings(IslandWrapper island, SkyblockHook hook) { + this.hook = hook; + this.island = island; + String id = hook.getIslandIdentifier(island.getRawIsland()); + DataBridge bridge = hook.getTempFly().getDataBridge(); + + Map values = bridge.getValues(DataTable.ISLAND_SETTINGS, hook, "islands", id, "settings"); + for (Entry entry: values.entrySet()) { + if (entry.getKey().equalsIgnoreCase("OWNER")) { + continue; + } + if (!(entry.getValue() instanceof Boolean)) { + try { throw new DataFormatException("A data value in Island Settings is not properly formatted, Expected boolean got (" + entry.getValue().getClass() + ")! island=(" + id + ") key=(" + entry.getKey() + ")");} + catch (DataFormatException e) { + e.printStackTrace(); + continue; + } + } + settings.put(entry.getKey(), (Boolean)entry.getValue()); + } + } + + public boolean canFly(String role) { + role = role.toUpperCase(); + return role.equalsIgnoreCase("OWNER") ? true : settings.getOrDefault(role, hook.getDefaults().getOrDefault(role, false)); + } + + public void setCanFly(String role, boolean canFly) { + role = role.toUpperCase(); + if (role.equals("OWNER")) { + return; + } + Console.debug("-- Set flight for: " + role, + "currently: " + canFly(role), + "mapped settings contains: " + settings.containsKey(role)); + settings.put(role, canFly); + hook.evaluate(island); + hook.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.ISLAND_SETTING, hook.getIslandIdentifier(island), role), canFly, hook); + } + + public void toggleCanFly(String role) { + role = role.toUpperCase(); + if (role.equals("OWNER")) { + return; + } + if (V.debug) {Console.debug("-- Set flight for: " + role, "--| currently: " + canFly(role), "--| mapped settings contains: " + settings.containsKey(role));} + boolean canFly = !canFly(role); + settings.put(role, canFly); + hook.evaluate(island); + hook.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.ISLAND_SETTING, hook.getIslandIdentifier(island.getRawIsland()), role), canFly, hook); + } + + public List> getCurrentState() { + Map state = new HashMap<>(); + state.putAll(settings); + for (String role: hook.getRoles()) { + role = role.toUpperCase(); + if (!role.equalsIgnoreCase("OWNER") && !state.containsKey(role)) { + state.put(role, hook.getDefaults().getOrDefault(role, false)); + } + } + + Comparator> comp = new Comparator>() { + @Override + public int compare(Entry e0, Entry e1) { + return e0.getKey().compareTo(e1.getKey()); + } + }; + List> sorted = new ArrayList>(state.entrySet()); + Collections.sort(sorted, comp); + return sorted; + } + + public IslandWrapper getIsland() { + return island; + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/TempFlyHook.java b/src/com/moneybags/tempfly/hook/TempFlyHook.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/hook/TempFlyHook.java rename to src/com/moneybags/tempfly/hook/TempFlyHook.java index 9e85ca7..83f28a0 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/TempFlyHook.java +++ b/src/com/moneybags/tempfly/hook/TempFlyHook.java @@ -1,246 +1,246 @@ -package com.moneybags.tempfly.hook; - -import java.io.File; -import java.io.IOException; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.SQLException; -import java.util.Map; -import java.util.Map.Entry; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.CommandManager; -import com.moneybags.tempfly.command.TempFlyCommand; -import com.moneybags.tempfly.fly.RequirementProvider; -import com.moneybags.tempfly.hook.HookManager.Genre; -import com.moneybags.tempfly.user.FlightUser; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.data.Files; -import com.moneybags.tempfly.util.data.Reloadable; -import com.moneybags.tempfly.util.data.DataFileHolder; - -public abstract class TempFlyHook implements RequirementProvider, Reloadable, DataFileHolder { - - protected final TempFly tempfly; - private String target; - private boolean enabled; - - private File dataf; - private FileConfiguration data; - - private FileConfiguration hookConfig; - - @SuppressWarnings("unchecked") - public TempFlyHook(TempFly tempfly) { - this.target = getPluginName(); - this.tempfly = tempfly; - - Console.debug("--| Trying to load hook: " + getHookName()); - - if (getTargetClass() != null) { - Console.debug("--| Using plugins declared class as a target...", "--| Class: " + getTargetClass()); - try { - Class clazz = Class.forName(getTargetClass()); - Console.debug("--| Found class..."); - if (!JavaPlugin.class.isAssignableFrom(clazz)) { - Console.debug("--| Target class is not a JavaPlugin..."); - return; - } - if (JavaPlugin.getPlugin((Class) clazz) == null) { - Console.debug("--| Target plugin is not present..."); - return; - } - } catch (ClassNotFoundException e) { - return; - } - } else if (Bukkit.getPluginManager().getPlugin(target) == null) { - Console.debug("--| Plugin (" + target + ") is not present..."); - return; - } - - Console.info("Attempting to initialize (" + getHookName() + ") hook..."); - try { if (!initializeFiles()) { return; } } catch (Exception e) { - Console.severe("An error occured while trying to initilize the (" + getHookName() + ") hook."); - e.printStackTrace(); - return; - } - if (initializeHook()) { - setEnabled(true); - } - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - CommandManager commands = tempfly.getCommandManager(); - if (enabled) { - try {tempfly.getHookManager().registerHook(this);} catch (IllegalArgumentException e) { - e.printStackTrace(); - setEnabled(false); - } - for (Entry> entry: getCommands().entrySet()) { - try {commands.registerHookCommand(entry.getKey(), entry.getValue());} catch (IllegalArgumentException e) { - e.printStackTrace(); - setEnabled(false); - break; - } - } - return; - } - tempfly.getHookManager().unregisterHook(this); - for (String base: getCommands().keySet()) { - commands.unregisterHookCommand(base); - } - } - - - - protected boolean initializeFiles() throws Exception { - Console.debug("--<[ Initializing hook files..."); - File hookConfigf = new File(tempfly.getDataFolder() + File.separator + getGenre().getDirectory(), getConfigName() + ".yml"); - if (!hookConfigf.exists()) { - Console.info("Config for ("+ getHookName() + ") hook does not exist, creating..."); - hookConfigf.getParentFile().mkdirs(); - Files.createConfig(tempfly.getResource(getEmbeddedConfigName() + ".yml"), hookConfigf); - } - - Console.debug("--<[ loading config into memory..."); - hookConfig = new YamlConfiguration(); - hookConfig.load(hookConfigf); - if (!hookConfig.getBoolean("enable_hook")) { - Console.info("(" + getHookName() + ") hook is disabled, skipping..."); - return false; - } - initializeData(); - return true; - } - - public void initializeData() throws IOException, InvalidConfigurationException, SQLException { - Console.debug("--<[ Initializing hook data..."); - if (!needsDataFile()) { - Console.debug("--| This hook does not require a data file."); - return; - } - File hookDataf = new File(tempfly.getDataFolder() + File.separator + getGenre().getDirectory() + File.separator + getDataName() + "_data.yml"); - Console.debug("--<[ Sql connection null, using YAML: " + hookDataf.getName()); - Console.debug("--<[ Path: " + hookDataf.getAbsolutePath()); - Console.debug("--<[ Exists?: " + hookDataf.exists()); - if (!hookDataf.exists()) { - Console.debug("--<[ Creating new file: " + hookDataf.getName()); - hookDataf.getParentFile().mkdirs(); - hookDataf.createNewFile(); - } - FileConfiguration hookData = new YamlConfiguration(); - hookData.load(hookDataf); - - setDataFile(hookDataf); - setDataConfiguration(hookData); - } - - public TempFly getTempFly() { - return tempfly; - } - - public FlightUser getUser(Player p) { - return getTempFly().getFlightManager().getUser(p); - } - - public String getHookedPlugin() { - return target; - } - - public FileConfiguration getConfig() { - return hookConfig; - } - - public abstract boolean needsDataFile(); - - @Override - public void onTempflyReload() { - try { - if (!initializeFiles()) { - if (enabled) { - setEnabled(false); - } - return; - } - } catch (Exception e) { - - Console.severe("An error occured while trying to initilize the (" + target + ") hook. Disabling hook"); - enabled = false; - e.printStackTrace(); - return; - } - enabled = true; - } - - public abstract Genre getGenre(); - - public abstract String getPluginName(); - - public String getHookName() { - return getPluginName(); - } - - public abstract String getConfigName(); - - public String getDataName() { - return getConfigName(); - } - - public abstract String getEmbeddedConfigName(); - - public abstract Map> getCommands(); - - /** - * Called from within the TempFlyHook constructor as a means of constructing the class structure in - * a reversed mannor allowing the child classes to finish their initialization first. - * This will not be called if there is an error while setting up the tempfly hook. - * - * @return false if there is a problem while initializing the hook. - */ - public abstract boolean initializeHook(); - - @Override - public File getDataFile() { - return dataf; - } - - @Override - public FileConfiguration getDataConfiguration() { - return data; - } - - @Override - public void setDataFile(File file) { - this.dataf = file; - } - - @Override - public void setDataConfiguration(FileConfiguration data) { - this.data = data; - } - - @Override - public void saveData() { - try { data.save(dataf); } catch (Exception e) {e.printStackTrace();} - } - - /** - * Needed to differentiate between plugins that have identical names. - * @return - */ - public String getTargetClass() { - return null; - } -} +package com.moneybags.tempfly.hook; + +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.util.Map; +import java.util.Map.Entry; + +import org.bukkit.Bukkit; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.CommandManager; +import com.moneybags.tempfly.command.TempFlyCommand; +import com.moneybags.tempfly.fly.RequirementProvider; +import com.moneybags.tempfly.hook.HookManager.Genre; +import com.moneybags.tempfly.user.FlightUser; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.data.Files; +import com.moneybags.tempfly.util.data.Reloadable; +import com.moneybags.tempfly.util.data.DataFileHolder; + +public abstract class TempFlyHook implements RequirementProvider, Reloadable, DataFileHolder { + + protected final TempFly tempfly; + private String target; + private boolean enabled; + + private File dataf; + private FileConfiguration data; + + private FileConfiguration hookConfig; + + @SuppressWarnings("unchecked") + public TempFlyHook(TempFly tempfly) { + this.target = getPluginName(); + this.tempfly = tempfly; + + Console.debug("--| Trying to load hook: " + getHookName()); + + if (getTargetClass() != null) { + Console.debug("--| Using plugins declared class as a target...", "--| Class: " + getTargetClass()); + try { + Class clazz = Class.forName(getTargetClass()); + Console.debug("--| Found class..."); + if (!JavaPlugin.class.isAssignableFrom(clazz)) { + Console.debug("--| Target class is not a JavaPlugin..."); + return; + } + if (JavaPlugin.getPlugin((Class) clazz) == null) { + Console.debug("--| Target plugin is not present..."); + return; + } + } catch (ClassNotFoundException e) { + return; + } + } else if (Bukkit.getPluginManager().getPlugin(target) == null) { + Console.debug("--| Plugin (" + target + ") is not present..."); + return; + } + + Console.info("Attempting to initialize (" + getHookName() + ") hook..."); + try { if (!initializeFiles()) { return; } } catch (Exception e) { + Console.severe("An error occured while trying to initilize the (" + getHookName() + ") hook."); + e.printStackTrace(); + return; + } + if (initializeHook()) { + setEnabled(true); + } + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + CommandManager commands = tempfly.getCommandManager(); + if (enabled) { + try {tempfly.getHookManager().registerHook(this);} catch (IllegalArgumentException e) { + e.printStackTrace(); + setEnabled(false); + } + for (Entry> entry: getCommands().entrySet()) { + try {commands.registerHookCommand(entry.getKey(), entry.getValue());} catch (IllegalArgumentException e) { + e.printStackTrace(); + setEnabled(false); + break; + } + } + return; + } + tempfly.getHookManager().unregisterHook(this); + for (String base: getCommands().keySet()) { + commands.unregisterHookCommand(base); + } + } + + + + protected boolean initializeFiles() throws Exception { + Console.debug("--<[ Initializing hook files..."); + File hookConfigf = new File(tempfly.getDataFolder() + File.separator + getGenre().getDirectory(), getConfigName() + ".yml"); + if (!hookConfigf.exists()) { + Console.info("Config for ("+ getHookName() + ") hook does not exist, creating..."); + hookConfigf.getParentFile().mkdirs(); + Files.createConfig(tempfly.getResource(getEmbeddedConfigName() + ".yml"), hookConfigf); + } + + Console.debug("--<[ loading config into memory..."); + hookConfig = new YamlConfiguration(); + hookConfig.load(hookConfigf); + if (!hookConfig.getBoolean("enable_hook")) { + Console.info("(" + getHookName() + ") hook is disabled, skipping..."); + return false; + } + initializeData(); + return true; + } + + public void initializeData() throws IOException, InvalidConfigurationException, SQLException { + Console.debug("--<[ Initializing hook data..."); + if (!needsDataFile()) { + Console.debug("--| This hook does not require a data file."); + return; + } + File hookDataf = new File(tempfly.getDataFolder() + File.separator + getGenre().getDirectory() + File.separator + getDataName() + "_data.yml"); + Console.debug("--<[ Sql connection null, using YAML: " + hookDataf.getName()); + Console.debug("--<[ Path: " + hookDataf.getAbsolutePath()); + Console.debug("--<[ Exists?: " + hookDataf.exists()); + if (!hookDataf.exists()) { + Console.debug("--<[ Creating new file: " + hookDataf.getName()); + hookDataf.getParentFile().mkdirs(); + hookDataf.createNewFile(); + } + FileConfiguration hookData = new YamlConfiguration(); + hookData.load(hookDataf); + + setDataFile(hookDataf); + setDataConfiguration(hookData); + } + + public TempFly getTempFly() { + return tempfly; + } + + public FlightUser getUser(Player p) { + return getTempFly().getFlightManager().getUser(p); + } + + public String getHookedPlugin() { + return target; + } + + public FileConfiguration getConfig() { + return hookConfig; + } + + public abstract boolean needsDataFile(); + + @Override + public void onTempflyReload() { + try { + if (!initializeFiles()) { + if (enabled) { + setEnabled(false); + } + return; + } + } catch (Exception e) { + + Console.severe("An error occured while trying to initilize the (" + target + ") hook. Disabling hook"); + enabled = false; + e.printStackTrace(); + return; + } + enabled = true; + } + + public abstract Genre getGenre(); + + public abstract String getPluginName(); + + public String getHookName() { + return getPluginName(); + } + + public abstract String getConfigName(); + + public String getDataName() { + return getConfigName(); + } + + public abstract String getEmbeddedConfigName(); + + public abstract Map> getCommands(); + + /** + * Called from within the TempFlyHook constructor as a means of constructing the class structure in + * a reversed mannor allowing the child classes to finish their initialization first. + * This will not be called if there is an error while setting up the tempfly hook. + * + * @return false if there is a problem while initializing the hook. + */ + public abstract boolean initializeHook(); + + @Override + public File getDataFile() { + return dataf; + } + + @Override + public FileConfiguration getDataConfiguration() { + return data; + } + + @Override + public void setDataFile(File file) { + this.dataf = file; + } + + @Override + public void setDataConfiguration(FileConfiguration data) { + this.data = data; + } + + @Override + public void saveData() { + try { data.save(dataf); } catch (Exception e) {e.printStackTrace();} + } + + /** + * Needed to differentiate between plugins that have identical names. + * @return + */ + public String getTargetClass() { + return null; + } +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/TerritoryHook.java b/src/com/moneybags/tempfly/hook/TerritoryHook.java similarity index 97% rename from TempFly/src/com/moneybags/tempfly/hook/TerritoryHook.java rename to src/com/moneybags/tempfly/hook/TerritoryHook.java index 4f864a3..bd780ac 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/TerritoryHook.java +++ b/src/com/moneybags/tempfly/hook/TerritoryHook.java @@ -1,298 +1,298 @@ -package com.moneybags.tempfly.hook; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerChangedWorldEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.player.PlayerRespawnEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.scheduler.BukkitRunnable; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.fly.RequirementProvider; -import com.moneybags.tempfly.fly.result.FlightResult; -import com.moneybags.tempfly.fly.result.ResultAllow; -import com.moneybags.tempfly.user.FlightUser; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.V; - -public abstract class TerritoryHook extends TempFlyHook { - - public TerritoryHook(TempFly tempfly) { - super(tempfly); - } - - @Override - public void onTempflyReload() { - super.onTempflyReload(); - /** - for (FlightUser user: getTempFly().getFlightManager().getUsers()) { - user.submitFlightResult(checkFlightRequirements(user.getPlayer().getUniqueId(), user.getPlayer().getLocation())); - } - */ - } - - - private TerritoryTracker manualTracker = null; - private Map locationCache = new HashMap<>(); - private Map wrapperCache = new HashMap<>(); - - public void startManualTracking() { - Console.debug("---> (" + getHookName() + ") Started manual territory tracking"); - if (manualTracker == null) { - manualTracker = new TerritoryTracker(this); - } - } - - public void stopManualTracking() { - Console.debug("---> (" + getHookName() + ") Stopped manual territory tracking"); - if (manualTracker != null) { - manualTracker.unregister(); - manualTracker = null; - } - } - - /** - * This method is called by the children of SkyblockHook when a player enters an island. - * It will track the island each player is on and handle flight requirements for the player. - * - * @param p The player who entered the island. - * @param rawTerritory The raw object representing the island. A wrapper will be created for it. - * @param loc Nullable, The location where the player entered the island. - */ - public void onTerritoryEnter(Player p, Object rawTerritory, Location loc) { - if (V.debug) { - Console.debug("", "------ On Territory Enter ------", "--| Player: " + p.getName(), rawTerritory); - } - if (rawTerritory instanceof TerritoryWrapper) { - rawTerritory = ((TerritoryWrapper)rawTerritory).getRawTerritory(); - } - if (locationCache.containsKey(p)) { - // Player already being tracked. - if (locationCache.get(p).getRawTerritory().equals(rawTerritory)) { - // Player is already on this island... - return; - } - // Player is now on 2 islands at once, this is a bug. - Console.severe("If you are seeing this message there may be a bug. Please contact the tempfly dev with this info: TerritoryHook | onTerritoeyEnter()"); - TerritoryWrapper territory = locationCache.get(p); - locationCache.remove(p); - if(!locationCache.containsValue(territory)) { - wrapperCache.remove(getTerritoryIdentifier(rawTerritory)); - } - } - - TerritoryWrapper territory = getTerritoryWrapper(rawTerritory); - if (V.debug) {Console.debug("--|> Island Identifier: " + getTerritoryIdentifier(rawTerritory), "------ End Territory Enter ------", "");} - - locationCache.put(p, territory); - FlightUser user = tempfly.getFlightManager().getUser(p); - if (user == null) { - return; - } - user.submitFlightResult(checkFlightRequirements(p.getUniqueId(), territory)); - } - - public void evaluate(Player p) { - getUser(p).submitFlightResult(checkFlightRequirements(p.getUniqueId(), p.getLocation())); - } - - public abstract FlightResult checkFlightRequirements(UUID playerId, Location loc); - - public abstract FlightResult checkFlightRequirements(UUID playerId, TerritoryWrapper territory); - - /** - * This method is called by the children of SkyblockHook when a player enters an island. - * It will track the island each player is on and handle flight requirements for the player. - * - * @param p The player who entered the island. - */ - public void onTerritoryExit(final Player p) { - if (V.debug) { - Console.debug("", "------ On territory Exit ------", "--| Player: " + p.getName()); - } - if (locationCache.containsKey(p)) { - TerritoryWrapper currentTerritory = locationCache.get(p); - locationCache.remove(p); - if(!locationCache.containsValue(currentTerritory)) { - Console.debug("----------------- removing wrapper from cache"); - wrapperCache.remove(getTerritoryIdentifier(currentTerritory.getRawTerritory())); - } - if (V.debug) {Console.debug("--|> Territory Identifier: " + getTerritoryIdentifier(currentTerritory.getRawTerritory()), "------ End Territory Exit ------", "");} - } - // On island exit i will wait 1 tick then check if the player still has this requirement. - // If they are no longer in a territory it will be removed. - final RequirementProvider provider = this; - new BukkitRunnable() { - @Override - public void run() { - if (!p.isOnline()) { - return; - } - FlightUser user = tempfly.getFlightManager().getUser(p); - if (user == null) { - return; - } - if (user.hasFlightRequirement(provider, InquiryType.OUT_OF_SCOPE) && !locationCache.containsKey(user.getPlayer())) { - user.submitFlightResult(new ResultAllow(provider, InquiryType.OUT_OF_SCOPE, V.requirePassDefault)); - } - } - }.runTaskLater(tempfly, 1); - } - - public TerritoryWrapper getTerritoryWrapper(Object rawTerritory) { - if (rawTerritory == null) { - return null; - } - TerritoryWrapper wrapper; - if (!wrapperCache.containsKey(getTerritoryIdentifier(rawTerritory))) { - wrapper = createTerritoryWrapper(rawTerritory, this); - wrapperCache.put(getTerritoryIdentifier(rawTerritory), wrapper); - } else { - wrapper = wrapperCache.get(getTerritoryIdentifier(rawTerritory)); - } - return wrapper; - } - - public abstract TerritoryWrapper createTerritoryWrapper(Object rawTerritory, TerritoryHook hook); - - public abstract String getTerritoryIdentifier(Object rawTerritory); - - /** - * Get all the players that are currently being tracked on an island. - * @param island The island in question - * @return All the players currently on the island. - */ - public Player[] getPlayersOn(TerritoryWrapper territory) { - List players = new ArrayList<>(); - for (Map.Entry entry: locationCache.entrySet()) { - if (entry.getValue().equals(territory)) { - players.add(entry.getKey()); - } - } - return players.toArray(new Player[players.size()]); - } - - /** - * @return true if the player is currently being tracked on an island - */ - public boolean isCurrentlyTracking(Player p) { - return locationCache.containsKey(p); - } - - /** - * @return The island the player is currently being tracked on. - */ - public TerritoryWrapper getTrackedTerritory(Player p) { - return locationCache.get(p); - } - - @Override - public void onUserInitialized(FlightUser user) { - Console.debug("", "-- on user initialized --"); - new BukkitRunnable() { - @Override - public void run() { - if (!isCurrentlyTracking(user.getPlayer())) { - TerritoryWrapper territory = getTerritoryAt(user.getPlayer().getLocation()); - if (territory != null) { - onTerritoryEnter(user.getPlayer(), territory.getRawTerritory(), user.getPlayer().getLocation()); - } - } - } - }.runTaskLater(getTempFly(), 5); - } - - - - @Override - public void onUserQuit(FlightUser user) { - Player p = user.getPlayer(); - TerritoryWrapper territory = getTerritoryAt(p.getLocation()); - if (territory != null) { - onTerritoryExit(p); - } - } - - /** - * This method is used for plugins that do not have internal island tracking or events - * such as IridiumSkyblock where we will need to process the player locations ourselves. Onn player teleport, player respawn etc. - * @param p The player to update. - * @param loc The new location of the player. - */ - public void updateLocation(Player p, Location loc) { - if (isCurrentlyTracking(p)) { - Console.debug("--| Player is being tracked"); - TerritoryWrapper territory = getTrackedTerritory(p); - if (!isInTerritory(territory, loc)) { - Console.debug("--|> Player is no longer in the same territory"); - onTerritoryExit(p); - } - } - TerritoryWrapper territory = getTerritoryAt(loc); - - if (territory == null) { - Console.debug("--| Player is not in a territory"); - return; - } - if (!isCurrentlyTracking(p)) { - Console.debug("--|> Player is in a new territory!"); - onTerritoryEnter(p, territory.getRawTerritory(), loc); - } - } - - public abstract TerritoryWrapper getTerritoryAt(Location loc); - - public abstract boolean isInTerritory(TerritoryWrapper territory, Location loc); - - private class TerritoryTracker implements Listener { - private TerritoryHook hook; - - public TerritoryTracker(TerritoryHook hook) { - this.hook = hook; - hook.getTempFly().getServer().getPluginManager().registerEvents(this, hook.getTempFly()); - } - - public void unregister() { - PlayerMoveEvent.getHandlerList().unregister(this); - PlayerRespawnEvent.getHandlerList().unregister(this); - PlayerTeleportEvent.getHandlerList().unregister(this); - PlayerChangedWorldEvent.getHandlerList().unregister(this); - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void on(PlayerMoveEvent e) { - Location to = e.getTo(); - if (e.getFrom().getBlock().equals(to.getBlock())) { - return; - } - hook.updateLocation(e.getPlayer(), e.getTo()); - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void on(PlayerRespawnEvent e) { - hook.updateLocation(e.getPlayer(), e.getRespawnLocation()); - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void on(PlayerTeleportEvent e) { - hook.updateLocation(e.getPlayer(), e.getTo()); - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void on(PlayerChangedWorldEvent e) { - hook.updateLocation(e.getPlayer(), e.getPlayer().getLocation()); - } - } - - -} +package com.moneybags.tempfly.hook; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.scheduler.BukkitRunnable; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.fly.RequirementProvider; +import com.moneybags.tempfly.fly.result.FlightResult; +import com.moneybags.tempfly.fly.result.ResultAllow; +import com.moneybags.tempfly.user.FlightUser; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.V; + +public abstract class TerritoryHook extends TempFlyHook { + + public TerritoryHook(TempFly tempfly) { + super(tempfly); + } + + @Override + public void onTempflyReload() { + super.onTempflyReload(); + /** + for (FlightUser user: getTempFly().getFlightManager().getUsers()) { + user.submitFlightResult(checkFlightRequirements(user.getPlayer().getUniqueId(), user.getPlayer().getLocation())); + } + */ + } + + + private TerritoryTracker manualTracker = null; + private Map locationCache = new HashMap<>(); + private Map wrapperCache = new HashMap<>(); + + public void startManualTracking() { + Console.debug("---> (" + getHookName() + ") Started manual territory tracking"); + if (manualTracker == null) { + manualTracker = new TerritoryTracker(this); + } + } + + public void stopManualTracking() { + Console.debug("---> (" + getHookName() + ") Stopped manual territory tracking"); + if (manualTracker != null) { + manualTracker.unregister(); + manualTracker = null; + } + } + + /** + * This method is called by the children of SkyblockHook when a player enters an island. + * It will track the island each player is on and handle flight requirements for the player. + * + * @param p The player who entered the island. + * @param rawTerritory The raw object representing the island. A wrapper will be created for it. + * @param loc Nullable, The location where the player entered the island. + */ + public void onTerritoryEnter(Player p, Object rawTerritory, Location loc) { + if (V.debug) { + Console.debug("", "------ On Territory Enter ------", "--| Player: " + p.getName(), rawTerritory); + } + if (rawTerritory instanceof TerritoryWrapper) { + rawTerritory = ((TerritoryWrapper)rawTerritory).getRawTerritory(); + } + if (locationCache.containsKey(p)) { + // Player already being tracked. + if (locationCache.get(p).getRawTerritory().equals(rawTerritory)) { + // Player is already on this island... + return; + } + // Player is now on 2 islands at once, this is a bug. + Console.severe("If you are seeing this message there may be a bug. Please contact the tempfly dev with this info: TerritoryHook | onTerritoeyEnter()"); + TerritoryWrapper territory = locationCache.get(p); + locationCache.remove(p); + if(!locationCache.containsValue(territory)) { + wrapperCache.remove(getTerritoryIdentifier(rawTerritory)); + } + } + + TerritoryWrapper territory = getTerritoryWrapper(rawTerritory); + if (V.debug) {Console.debug("--|> Island Identifier: " + getTerritoryIdentifier(rawTerritory), "------ End Territory Enter ------", "");} + + locationCache.put(p, territory); + FlightUser user = tempfly.getFlightManager().getUser(p); + if (user == null) { + return; + } + user.submitFlightResult(checkFlightRequirements(p.getUniqueId(), territory)); + } + + public void evaluate(Player p) { + getUser(p).submitFlightResult(checkFlightRequirements(p.getUniqueId(), p.getLocation())); + } + + public abstract FlightResult checkFlightRequirements(UUID playerId, Location loc); + + public abstract FlightResult checkFlightRequirements(UUID playerId, TerritoryWrapper territory); + + /** + * This method is called by the children of SkyblockHook when a player enters an island. + * It will track the island each player is on and handle flight requirements for the player. + * + * @param p The player who entered the island. + */ + public void onTerritoryExit(final Player p) { + if (V.debug) { + Console.debug("", "------ On territory Exit ------", "--| Player: " + p.getName()); + } + if (locationCache.containsKey(p)) { + TerritoryWrapper currentTerritory = locationCache.get(p); + locationCache.remove(p); + if(!locationCache.containsValue(currentTerritory)) { + Console.debug("----------------- removing wrapper from cache"); + wrapperCache.remove(getTerritoryIdentifier(currentTerritory.getRawTerritory())); + } + if (V.debug) {Console.debug("--|> Territory Identifier: " + getTerritoryIdentifier(currentTerritory.getRawTerritory()), "------ End Territory Exit ------", "");} + } + // On island exit i will wait 1 tick then check if the player still has this requirement. + // If they are no longer in a territory it will be removed. + final RequirementProvider provider = this; + new BukkitRunnable() { + @Override + public void run() { + if (!p.isOnline()) { + return; + } + FlightUser user = tempfly.getFlightManager().getUser(p); + if (user == null) { + return; + } + if (user.hasFlightRequirement(provider, InquiryType.OUT_OF_SCOPE) && !locationCache.containsKey(user.getPlayer())) { + user.submitFlightResult(new ResultAllow(provider, InquiryType.OUT_OF_SCOPE, V.requirePassDefault)); + } + } + }.runTaskLater(tempfly, 1); + } + + public TerritoryWrapper getTerritoryWrapper(Object rawTerritory) { + if (rawTerritory == null) { + return null; + } + TerritoryWrapper wrapper; + if (!wrapperCache.containsKey(getTerritoryIdentifier(rawTerritory))) { + wrapper = createTerritoryWrapper(rawTerritory, this); + wrapperCache.put(getTerritoryIdentifier(rawTerritory), wrapper); + } else { + wrapper = wrapperCache.get(getTerritoryIdentifier(rawTerritory)); + } + return wrapper; + } + + public abstract TerritoryWrapper createTerritoryWrapper(Object rawTerritory, TerritoryHook hook); + + public abstract String getTerritoryIdentifier(Object rawTerritory); + + /** + * Get all the players that are currently being tracked on an island. + * @param island The island in question + * @return All the players currently on the island. + */ + public Player[] getPlayersOn(TerritoryWrapper territory) { + List players = new ArrayList<>(); + for (Map.Entry entry: locationCache.entrySet()) { + if (entry.getValue().equals(territory)) { + players.add(entry.getKey()); + } + } + return players.toArray(new Player[players.size()]); + } + + /** + * @return true if the player is currently being tracked on an island + */ + public boolean isCurrentlyTracking(Player p) { + return locationCache.containsKey(p); + } + + /** + * @return The island the player is currently being tracked on. + */ + public TerritoryWrapper getTrackedTerritory(Player p) { + return locationCache.get(p); + } + + @Override + public void onUserInitialized(FlightUser user) { + Console.debug("", "-- on user initialized --"); + new BukkitRunnable() { + @Override + public void run() { + if (!isCurrentlyTracking(user.getPlayer())) { + TerritoryWrapper territory = getTerritoryAt(user.getPlayer().getLocation()); + if (territory != null) { + onTerritoryEnter(user.getPlayer(), territory.getRawTerritory(), user.getPlayer().getLocation()); + } + } + } + }.runTaskLater(getTempFly(), 5); + } + + + + @Override + public void onUserQuit(FlightUser user) { + Player p = user.getPlayer(); + TerritoryWrapper territory = getTerritoryAt(p.getLocation()); + if (territory != null) { + onTerritoryExit(p); + } + } + + /** + * This method is used for plugins that do not have internal island tracking or events + * such as IridiumSkyblock where we will need to process the player locations ourselves. Onn player teleport, player respawn etc. + * @param p The player to update. + * @param loc The new location of the player. + */ + public void updateLocation(Player p, Location loc) { + if (isCurrentlyTracking(p)) { + Console.debug("--| Player is being tracked"); + TerritoryWrapper territory = getTrackedTerritory(p); + if (!isInTerritory(territory, loc)) { + Console.debug("--|> Player is no longer in the same territory"); + onTerritoryExit(p); + } + } + TerritoryWrapper territory = getTerritoryAt(loc); + + if (territory == null) { + Console.debug("--| Player is not in a territory"); + return; + } + if (!isCurrentlyTracking(p)) { + Console.debug("--|> Player is in a new territory!"); + onTerritoryEnter(p, territory.getRawTerritory(), loc); + } + } + + public abstract TerritoryWrapper getTerritoryAt(Location loc); + + public abstract boolean isInTerritory(TerritoryWrapper territory, Location loc); + + private class TerritoryTracker implements Listener { + private TerritoryHook hook; + + public TerritoryTracker(TerritoryHook hook) { + this.hook = hook; + hook.getTempFly().getServer().getPluginManager().registerEvents(this, hook.getTempFly()); + } + + public void unregister() { + PlayerMoveEvent.getHandlerList().unregister(this); + PlayerRespawnEvent.getHandlerList().unregister(this); + PlayerTeleportEvent.getHandlerList().unregister(this); + PlayerChangedWorldEvent.getHandlerList().unregister(this); + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void on(PlayerMoveEvent e) { + Location to = e.getTo(); + if (e.getFrom().getBlock().equals(to.getBlock())) { + return; + } + hook.updateLocation(e.getPlayer(), e.getTo()); + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void on(PlayerRespawnEvent e) { + hook.updateLocation(e.getPlayer(), e.getRespawnLocation()); + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void on(PlayerTeleportEvent e) { + hook.updateLocation(e.getPlayer(), e.getTo()); + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void on(PlayerChangedWorldEvent e) { + hook.updateLocation(e.getPlayer(), e.getPlayer().getLocation()); + } + } + + +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/TerritoryWrapper.java b/src/com/moneybags/tempfly/hook/TerritoryWrapper.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/hook/TerritoryWrapper.java rename to src/com/moneybags/tempfly/hook/TerritoryWrapper.java index f940ddb..b21c9fd 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/TerritoryWrapper.java +++ b/src/com/moneybags/tempfly/hook/TerritoryWrapper.java @@ -1,12 +1,12 @@ -package com.moneybags.tempfly.hook; - -public interface TerritoryWrapper { - - /** - * Get the raw territory this object is safely wrapping. - * Example A Faction / Island object. - * @return The raw territory object from the plugin being hooked into. - */ - abstract Object getRawTerritory(); - -} +package com.moneybags.tempfly.hook; + +public interface TerritoryWrapper { + + /** + * Get the raw territory this object is safely wrapping. + * Example A Faction / Island object. + * @return The raw territory object from the plugin being hooked into. + */ + abstract Object getRawTerritory(); + +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/factions/FactionRequirement.java b/src/com/moneybags/tempfly/hook/factions/FactionRequirement.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/hook/factions/FactionRequirement.java rename to src/com/moneybags/tempfly/hook/factions/FactionRequirement.java index 273d6b5..fbb6285 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/factions/FactionRequirement.java +++ b/src/com/moneybags/tempfly/hook/factions/FactionRequirement.java @@ -1,219 +1,219 @@ -package com.moneybags.tempfly.hook.factions; - -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.function.Predicate; - -import org.bukkit.configuration.ConfigurationSection; - -import com.moneybags.tempfly.hook.factions.FactionsHook.FactionRelation; -import com.moneybags.tempfly.util.Console; - -public class FactionRequirement { - - private FactionsHook hook; - private FactionRelation relation; - private boolean allowed; - private Map powerRequirements = new HashMap<>(); - - /** - * Loads a faction requirement from the config. - * @param hook - * @param relation - * @param section - */ - public FactionRequirement(FactionsHook hook, FactionRelation relation, ConfigurationSection section, boolean enforceDefaults) { - this.hook = hook; - this.relation = relation; - loadValues(section, enforceDefaults); - } - - /** - * Creates a default faction requirement with no restrictions. - * @param hook - * @param relation - */ - public FactionRequirement(FactionsHook hook, FactionRelation relation) { - this.hook = hook; - this.relation = relation; - allowed = true; - powerRequirements.put(PowerContext.HOME_POWER_PERCENTAGE, 0d); - - if (relation.getPowerContext() != PowerContext.SELF) { - powerRequirements.put(PowerContext.FOREIGN_POWER_PERCENTAGE, 100d); - } - } - - private void loadValues(ConfigurationSection section, boolean enforceDefaults) { - Console.debug("--| Loading settings for faction relation: " + relation); - if (section == null) { - Console.debug("--| Configuration section is null, loading defaults if applicable."); - if (enforceDefaults) { - powerRequirements.put(PowerContext.HOME_POWER_PERCENTAGE, 0d); - if (relation == FactionRelation.ALLIED) { - powerRequirements.put(PowerContext.ALLIED_POWER_PERCENTAGE, 0d); - } else { - powerRequirements.put(PowerContext.FOREIGN_POWER_PERCENTAGE, 100d); - } - allowed = true; - } - return; - } - - allowed = section.getBoolean("allowed", enforceDefaults ? true : hook.getBaseRequirement(relation).isAllowed()); - - boolean - self = false, - foreign = false; - - for (String key: section.getKeys(false)) { - PowerContext context; - try { context = PowerContext.valueOf(key.toUpperCase()); } catch (IllegalArgumentException e) { - continue; - } - if (powerRequirements.keySet().stream().anyMatch(definedContext -> definedContext.getContext() == context.getContext())) { - Console.warn("You cannot set more than one power requirement under the context of (" + context.getContext() + ") power. | (" + context + ")"); - continue; - } - - if (context.getContext() == PowerContext.SELF) { - self = true; - } else { - foreign = true; - } - Console.debug("--| Loading " + key, "--| Value: " + String.valueOf(section.getDouble(key))); - powerRequirements.put(context, section.getDouble(key)); - } - - if (enforceDefaults) { - if (!self) { - Console.debug("--| No self requirement defined, loading default."); - powerRequirements.put(PowerContext.HOME_POWER_PERCENTAGE, 0d); - } - if (!foreign) { - Console.debug("--| No foreign requirement defined, loading default."); - if (relation == FactionRelation.ALLIED) { - powerRequirements.put(PowerContext.ALLIED_POWER_PERCENTAGE, 0d); - } else { - powerRequirements.put(PowerContext.FOREIGN_POWER_PERCENTAGE, 100d); - } - } - } - Console.debug(powerRequirements); - } - - public boolean isThresholdMet(PowerContext context, double currentPower, double maxPower) { - for (Entry entry: powerRequirements.entrySet()) { - if (entry.getKey() != context && entry.getKey().getContext() != context) { - continue; - } - Console.debug("--| Found a power requirement for the role...", "--| PowerContext: " + context, "--| DefinedContext: " + entry.getKey()); - PowerPackage pack = new PowerPackage(); - pack.defined = entry.getValue(); - pack.current = currentPower; - pack.max = Math.max(maxPower, 1); - Console.debug("--| value defined in config: " + pack.defined); - return entry.getKey().meetsThreshold(pack); - } - Console.debug("--| power requirement does not exist for this role, using default requirement."); - return hook.getBaseRequirement(relation).isThresholdMet(context, currentPower, maxPower); - } - - public double getPowerThreshold(PowerContext context, double currentPower, double maxPower) { - for (Entry entry: powerRequirements.entrySet()) { - if (entry.getKey() != context && entry.getKey().getContext() != context) { - continue; - } - return entry.getValue(); - } - return hook.getBaseRequirement(relation).getPowerThreshold(context, currentPower, maxPower); - } - - public String getPowerFormatted(PowerContext context, double currentPower, double maxPower) { - for (Entry entry: powerRequirements.entrySet()) { - if (entry.getKey() != context && entry.getKey().getContext() != context) { - continue; - } - PowerPackage pack = new PowerPackage(); - pack.defined = entry.getValue(); - pack.current = currentPower; - pack.max = Math.max(maxPower, 1); - return entry.getKey().getFormatted(pack); - } - return hook.getBaseRequirement(relation).getPowerFormatted(context, currentPower, maxPower); - } - - public boolean isAllowed() { - return allowed; - } - - - - - private static class PowerPackage { - double defined, current, max; - } - - public static enum PowerContext { - SELF(), - HOME_POWER_PERCENTAGE(SELF, true, - pack -> { - return (pack.current / pack.max) * 100 >= pack.defined; - }), - HOME_POWER_ABSOLUTE(SELF, false, - pack -> { - return pack.current >= pack.defined; - }), - - FOREIGN(), - FOREIGN_POWER_PERCENTAGE(FOREIGN, true, - pack -> { - return (pack.current / pack.max) * 100 <= pack.defined; - }), - FOREIGN_POWER_ABSOLUTE(FOREIGN, false, - pack -> { - return pack.current <= pack.defined; - }), - - - ALLIED_POWER_PERCENTAGE(FOREIGN, true, - pack -> { - return (pack.current / pack.max) * 100 >= pack.defined; - }), - ALLIED_POWER_ABSOLUTE(FOREIGN, false, - pack -> { - return pack.current >= pack.defined; - }); - - private PowerContext context; - private boolean percentage; - private Predicate predicate; - - private PowerContext(PowerContext context, boolean percentage, Predicate predicate) { - this.context = context; - this.percentage = percentage; - this.predicate = predicate; - } - - private PowerContext() { - this.context = null; - this.predicate = null; - } - - - public PowerContext getContext() { - return context; - } - - private boolean meetsThreshold(PowerPackage pack) { - return predicate.test(pack); - } - - private String getFormatted(PowerPackage pack) { - return percentage ? String.valueOf(pack.defined) + "%" : String.valueOf(pack.defined); - } - - } - -} +package com.moneybags.tempfly.hook.factions; + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.Predicate; + +import org.bukkit.configuration.ConfigurationSection; + +import com.moneybags.tempfly.hook.factions.FactionsHook.FactionRelation; +import com.moneybags.tempfly.util.Console; + +public class FactionRequirement { + + private FactionsHook hook; + private FactionRelation relation; + private boolean allowed; + private Map powerRequirements = new HashMap<>(); + + /** + * Loads a faction requirement from the config. + * @param hook + * @param relation + * @param section + */ + public FactionRequirement(FactionsHook hook, FactionRelation relation, ConfigurationSection section, boolean enforceDefaults) { + this.hook = hook; + this.relation = relation; + loadValues(section, enforceDefaults); + } + + /** + * Creates a default faction requirement with no restrictions. + * @param hook + * @param relation + */ + public FactionRequirement(FactionsHook hook, FactionRelation relation) { + this.hook = hook; + this.relation = relation; + allowed = true; + powerRequirements.put(PowerContext.HOME_POWER_PERCENTAGE, 0d); + + if (relation.getPowerContext() != PowerContext.SELF) { + powerRequirements.put(PowerContext.FOREIGN_POWER_PERCENTAGE, 100d); + } + } + + private void loadValues(ConfigurationSection section, boolean enforceDefaults) { + Console.debug("--| Loading settings for faction relation: " + relation); + if (section == null) { + Console.debug("--| Configuration section is null, loading defaults if applicable."); + if (enforceDefaults) { + powerRequirements.put(PowerContext.HOME_POWER_PERCENTAGE, 0d); + if (relation == FactionRelation.ALLIED) { + powerRequirements.put(PowerContext.ALLIED_POWER_PERCENTAGE, 0d); + } else { + powerRequirements.put(PowerContext.FOREIGN_POWER_PERCENTAGE, 100d); + } + allowed = true; + } + return; + } + + allowed = section.getBoolean("allowed", enforceDefaults ? true : hook.getBaseRequirement(relation).isAllowed()); + + boolean + self = false, + foreign = false; + + for (String key: section.getKeys(false)) { + PowerContext context; + try { context = PowerContext.valueOf(key.toUpperCase()); } catch (IllegalArgumentException e) { + continue; + } + if (powerRequirements.keySet().stream().anyMatch(definedContext -> definedContext.getContext() == context.getContext())) { + Console.warn("You cannot set more than one power requirement under the context of (" + context.getContext() + ") power. | (" + context + ")"); + continue; + } + + if (context.getContext() == PowerContext.SELF) { + self = true; + } else { + foreign = true; + } + Console.debug("--| Loading " + key, "--| Value: " + String.valueOf(section.getDouble(key))); + powerRequirements.put(context, section.getDouble(key)); + } + + if (enforceDefaults) { + if (!self) { + Console.debug("--| No self requirement defined, loading default."); + powerRequirements.put(PowerContext.HOME_POWER_PERCENTAGE, 0d); + } + if (!foreign) { + Console.debug("--| No foreign requirement defined, loading default."); + if (relation == FactionRelation.ALLIED) { + powerRequirements.put(PowerContext.ALLIED_POWER_PERCENTAGE, 0d); + } else { + powerRequirements.put(PowerContext.FOREIGN_POWER_PERCENTAGE, 100d); + } + } + } + Console.debug(powerRequirements); + } + + public boolean isThresholdMet(PowerContext context, double currentPower, double maxPower) { + for (Entry entry: powerRequirements.entrySet()) { + if (entry.getKey() != context && entry.getKey().getContext() != context) { + continue; + } + Console.debug("--| Found a power requirement for the role...", "--| PowerContext: " + context, "--| DefinedContext: " + entry.getKey()); + PowerPackage pack = new PowerPackage(); + pack.defined = entry.getValue(); + pack.current = currentPower; + pack.max = Math.max(maxPower, 1); + Console.debug("--| value defined in config: " + pack.defined); + return entry.getKey().meetsThreshold(pack); + } + Console.debug("--| power requirement does not exist for this role, using default requirement."); + return hook.getBaseRequirement(relation).isThresholdMet(context, currentPower, maxPower); + } + + public double getPowerThreshold(PowerContext context, double currentPower, double maxPower) { + for (Entry entry: powerRequirements.entrySet()) { + if (entry.getKey() != context && entry.getKey().getContext() != context) { + continue; + } + return entry.getValue(); + } + return hook.getBaseRequirement(relation).getPowerThreshold(context, currentPower, maxPower); + } + + public String getPowerFormatted(PowerContext context, double currentPower, double maxPower) { + for (Entry entry: powerRequirements.entrySet()) { + if (entry.getKey() != context && entry.getKey().getContext() != context) { + continue; + } + PowerPackage pack = new PowerPackage(); + pack.defined = entry.getValue(); + pack.current = currentPower; + pack.max = Math.max(maxPower, 1); + return entry.getKey().getFormatted(pack); + } + return hook.getBaseRequirement(relation).getPowerFormatted(context, currentPower, maxPower); + } + + public boolean isAllowed() { + return allowed; + } + + + + + private static class PowerPackage { + double defined, current, max; + } + + public static enum PowerContext { + SELF(), + HOME_POWER_PERCENTAGE(SELF, true, + pack -> { + return (pack.current / pack.max) * 100 >= pack.defined; + }), + HOME_POWER_ABSOLUTE(SELF, false, + pack -> { + return pack.current >= pack.defined; + }), + + FOREIGN(), + FOREIGN_POWER_PERCENTAGE(FOREIGN, true, + pack -> { + return (pack.current / pack.max) * 100 <= pack.defined; + }), + FOREIGN_POWER_ABSOLUTE(FOREIGN, false, + pack -> { + return pack.current <= pack.defined; + }), + + + ALLIED_POWER_PERCENTAGE(FOREIGN, true, + pack -> { + return (pack.current / pack.max) * 100 >= pack.defined; + }), + ALLIED_POWER_ABSOLUTE(FOREIGN, false, + pack -> { + return pack.current >= pack.defined; + }); + + private PowerContext context; + private boolean percentage; + private Predicate predicate; + + private PowerContext(PowerContext context, boolean percentage, Predicate predicate) { + this.context = context; + this.percentage = percentage; + this.predicate = predicate; + } + + private PowerContext() { + this.context = null; + this.predicate = null; + } + + + public PowerContext getContext() { + return context; + } + + private boolean meetsThreshold(PowerPackage pack) { + return predicate.test(pack); + } + + private String getFormatted(PowerPackage pack) { + return percentage ? String.valueOf(pack.defined) + "%" : String.valueOf(pack.defined); + } + + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/factions/FactionRoleSettings.java b/src/com/moneybags/tempfly/hook/factions/FactionRoleSettings.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/hook/factions/FactionRoleSettings.java rename to src/com/moneybags/tempfly/hook/factions/FactionRoleSettings.java index 03cd19d..f37fba0 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/factions/FactionRoleSettings.java +++ b/src/com/moneybags/tempfly/hook/factions/FactionRoleSettings.java @@ -1,48 +1,48 @@ -package com.moneybags.tempfly.hook.factions; - -import java.util.HashMap; -import java.util.Map; - -import org.bukkit.configuration.ConfigurationSection; - -import com.moneybags.tempfly.hook.factions.FactionsHook.FactionRelation; -import com.moneybags.tempfly.util.Console; - -public class FactionRoleSettings { - - private FactionsHook hook; - private String role; - private Map requirements = new HashMap<>(); - - public FactionRoleSettings(FactionsHook hook, String role, ConfigurationSection section) { - this.hook = hook; - this.role = role; - loadValues(section); - } - - private void loadValues(ConfigurationSection section) { - if (section == null) { - return; - } - for (String key: section.getKeys(false)) { - FactionRelation relation; - try { relation = FactionRelation.valueOf(key.toUpperCase()); } catch (IllegalArgumentException e) { - Console.warn("A faction relationship defined in the config does not exist: (" + key + ")"); - continue; - } - requirements.put(relation, new FactionRequirement(hook, relation, section.getConfigurationSection(key), false)); - } - } - - public String getRole() { - return role; - } - - public FactionsHook getHook() { - return hook; - } - - public FactionRequirement getRequirement(FactionRelation relation) { - return requirements.getOrDefault(relation, hook.getBaseRequirement(relation)); - } -} +package com.moneybags.tempfly.hook.factions; + +import java.util.HashMap; +import java.util.Map; + +import org.bukkit.configuration.ConfigurationSection; + +import com.moneybags.tempfly.hook.factions.FactionsHook.FactionRelation; +import com.moneybags.tempfly.util.Console; + +public class FactionRoleSettings { + + private FactionsHook hook; + private String role; + private Map requirements = new HashMap<>(); + + public FactionRoleSettings(FactionsHook hook, String role, ConfigurationSection section) { + this.hook = hook; + this.role = role; + loadValues(section); + } + + private void loadValues(ConfigurationSection section) { + if (section == null) { + return; + } + for (String key: section.getKeys(false)) { + FactionRelation relation; + try { relation = FactionRelation.valueOf(key.toUpperCase()); } catch (IllegalArgumentException e) { + Console.warn("A faction relationship defined in the config does not exist: (" + key + ")"); + continue; + } + requirements.put(relation, new FactionRequirement(hook, relation, section.getConfigurationSection(key), false)); + } + } + + public String getRole() { + return role; + } + + public FactionsHook getHook() { + return hook; + } + + public FactionRequirement getRequirement(FactionRelation relation) { + return requirements.getOrDefault(relation, hook.getBaseRequirement(relation)); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/factions/FactionWrapper.java b/src/com/moneybags/tempfly/hook/factions/FactionWrapper.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/hook/factions/FactionWrapper.java rename to src/com/moneybags/tempfly/hook/factions/FactionWrapper.java index e1fbd45..e4429b0 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/factions/FactionWrapper.java +++ b/src/com/moneybags/tempfly/hook/factions/FactionWrapper.java @@ -1,18 +1,18 @@ -package com.moneybags.tempfly.hook.factions; - -import com.moneybags.tempfly.hook.TerritoryWrapper; - -public class FactionWrapper implements TerritoryWrapper { - - private Object rawFaction; - - public FactionWrapper(Object rawFaction) { - this.rawFaction = rawFaction; - } - - @Override - public Object getRawTerritory() { - return rawFaction; - } - -} +package com.moneybags.tempfly.hook.factions; + +import com.moneybags.tempfly.hook.TerritoryWrapper; + +public class FactionWrapper implements TerritoryWrapper { + + private Object rawFaction; + + public FactionWrapper(Object rawFaction) { + this.rawFaction = rawFaction; + } + + @Override + public Object getRawTerritory() { + return rawFaction; + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/factions/FactionsHook.java b/src/com/moneybags/tempfly/hook/factions/FactionsHook.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/hook/factions/FactionsHook.java rename to src/com/moneybags/tempfly/hook/factions/FactionsHook.java index 43f3b4f..ce551d1 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/factions/FactionsHook.java +++ b/src/com/moneybags/tempfly/hook/factions/FactionsHook.java @@ -1,712 +1,712 @@ -package com.moneybags.tempfly.hook.factions; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.player.PlayerRespawnEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TempFlyCommand; -import com.moneybags.tempfly.fly.result.FlightResult; -import com.moneybags.tempfly.fly.result.ResultAllow; -import com.moneybags.tempfly.fly.result.ResultDeny; -import com.moneybags.tempfly.fly.result.FlightResult.DenyReason; -import com.moneybags.tempfly.hook.HookManager.Genre; -import com.moneybags.tempfly.hook.skyblock.CmdIslandSettings; -import com.moneybags.tempfly.user.FlightUser; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.V; -import com.moneybags.tempfly.hook.TerritoryHook; -import com.moneybags.tempfly.hook.TerritoryWrapper; -import com.moneybags.tempfly.hook.factions.FactionRequirement.PowerContext; - -public abstract class FactionsHook extends TerritoryHook implements Listener { - - private Set damagePower; - private Set damageIllegal; - private String - requireIllegalTerritory, - requirePowerSelf, - requirePowerForeign, - requirePowerAllied, - requireFactionSelf; - - private Map baseRequirements; - private Map roleRequirements; - - public static enum FactionRelation { - HOME(PowerContext.SELF), - ENEMY(PowerContext.FOREIGN), - NEUTRAL(PowerContext.FOREIGN), - ALLIED(PowerContext.FOREIGN), - WILDERNESS(PowerContext.FOREIGN); - - private PowerContext context; - - private FactionRelation(PowerContext context) { - this.context = context; - } - - public PowerContext getPowerContext() { - return context; - } - - } - - - - public FactionsHook(TempFly tempfly) { - super(tempfly); - } - - - public void loadValues() { - Console.debug("", "---- Loading Factions Settings ----"); - FileConfiguration config = getConfig(); - - damagePower = new HashSet<>(); - damageIllegal = new HashSet<>(); - baseRequirements = new HashMap<>(); - roleRequirements = new HashMap<>(); - - ConfigurationSection csFallPower = config.getConfigurationSection("fall_damage.power"); - if (csFallPower != null) { - for (String key: csFallPower.getKeys(false)) { - FactionRelation relation; - try { relation = FactionRelation.valueOf(key.toUpperCase()); } catch (IllegalArgumentException e) { - Console.warn("A faction relationship defined in the config does not exist: (" + key + ")"); - continue; - } - if (csFallPower.getBoolean(key)) { - damagePower.add(relation); - } - } - } - - ConfigurationSection csFallDisabled = config.getConfigurationSection("fall_damage.disabled"); - if (csFallDisabled != null) { - for (String key: csFallDisabled.getKeys(false)) { - FactionRelation relation; - try { relation = FactionRelation.valueOf(key.toUpperCase()); } catch (IllegalArgumentException e) { - Console.warn("A faction relationship defined in the config does not exist: (" + key + ")"); - continue; - } - if (csFallDisabled.getBoolean(key)) { - damageIllegal.add(relation); - } - } - } - - String name = getConfigName(); - requireIllegalTerritory = V.st(config, "language.requirements.illegal_territory", name); - requirePowerSelf = V.st(config, "language.requirements.power_self", name); - requirePowerForeign = V.st(config, "language.requirements.power_foreign", name); - requirePowerAllied = V.st(config, "language.requirements.power_allied", name); - requireFactionSelf = V.st(config, "language.requirements.faction_self", name); - - // Load base faction requirements from the config. - ConfigurationSection csBase = config.getConfigurationSection("base_requirements"); - if (csBase != null) { - for (String key: csBase.getKeys(false)) { - FactionRelation relation; - try { relation = FactionRelation.valueOf(key.toUpperCase()); } catch (IllegalArgumentException e) { - Console.warn("A faction relationship defined in the config does not exist: (" + key + ")"); - continue; - } - baseRequirements.put(relation, new FactionRequirement(this, relation, csBase.getConfigurationSection(key), true)); - } - } - - // Add default unrestricted faction requirements if they are not in the config. - for (FactionRelation relation: FactionRelation.values()) { - if (!baseRequirements.containsKey(relation)) { - Console.debug("--! Base requirements does not contain settings for: " + relation); - baseRequirements.put(relation, new FactionRequirement(this, relation)); - } - } - - ConfigurationSection csRole = config.getConfigurationSection("role_requirements"); - if (csRole != null) { - for (String key: csRole.getKeys(false)) { - roleRequirements.put(key.toUpperCase(), new FactionRoleSettings(this, key.toUpperCase(), csRole.getConfigurationSection(key))); - } - } - Console.debug("---- Done Factions Settings ----"); - } - - public FactionRequirement getBaseRequirement(FactionRelation relation) { - return baseRequirements.get(relation); - } - - - - - /** - * -------------- - * Event Handling - * -------------- - */ - - - - /** - * - * - */ - @EventHandler - public void onJoin(PlayerJoinEvent e) { - FactionWrapper to = getFactionAt(e.getPlayer().getLocation()); - if (to == null) { - return; - } - onFactionEnter(e.getPlayer(), to, null); - } - - @EventHandler - public void onTeleport(PlayerTeleportEvent e) { - if (e.getFrom().getChunk().equals(e.getTo().getChunk())) { - return; - } - FactionWrapper from = getFactionAt(e.getFrom()); - FactionWrapper to = getFactionAt(e.getTo()); - if (from.equals(to)) { - return; - } - - onFactionExit(e.getPlayer()); - onFactionEnter(e.getPlayer(), to, null); - } - - @EventHandler - public void onRespawn(PlayerRespawnEvent e) { - if (e.getPlayer().getLocation().getChunk().equals(e.getRespawnLocation().getChunk())) { - return; - } - FactionWrapper from = getFactionAt(e.getPlayer().getLocation()); - FactionWrapper to = getFactionAt(e.getRespawnLocation()); - if (from.equals(to)) { - return; - } - - onFactionExit(e.getPlayer()); - onFactionEnter(e.getPlayer(), to, null); - } - - @EventHandler - public void onMove(PlayerMoveEvent e) { - if (e.getFrom().getChunk().equals(e.getTo().getChunk())) { - return; - } - FactionWrapper from = getFactionAt(e.getFrom()); - FactionWrapper to = getFactionAt(e.getTo()); - if (from.equals(to)) { - return; - } - - onFactionExit(e.getPlayer()); - onFactionEnter(e.getPlayer(), to, null); - } - - - - /** - * -------------------- - * Super Event Handling - * -------------------- - */ - - - - /** - * - * @param chunk - * @param faction - */ - public void onLandClaimed(Chunk chunk, FactionWrapper faction) { - Console.debug("--| Claimed land"); - for (Entity ent: chunk.getEntities()) { - if (!(ent instanceof Player)) { - continue; - } - onFactionEnter((Player) ent, faction.getRawTerritory(), ent.getLocation()); - } - } - - public void onLandOverClaimed(Chunk chunk, FactionWrapper victim, FactionWrapper agressor) { - Console.debug("--| Land overclaimed from (" + getFactionName(victim)); - for (Entity ent: chunk.getEntities()) { - if (!(ent instanceof Player)) { - continue; - } - onFactionExit((Player) ent); - onFactionEnter((Player) ent, agressor.getRawTerritory(), ent.getLocation()); - } - } - - public void onLandUnclaimed(Chunk chunk) { - Console.debug("--| Unclaimed land"); - for (Entity ent: chunk.getEntities()) { - if (!(ent instanceof Player)) { - continue; - } - onFactionExit((Player) ent); - onFactionEnter((Player) ent, getFactionAt(ent.getLocation()).getRawTerritory(), ent.getLocation()); - } - } - - public void onPlayerJoinFaction(Player p, FactionWrapper faction) { - for (Player player: getOnlineMembers(faction)) { - if (p.equals(player)) { - continue; - } - evaluate(player); - } - evaluate(p); - } - - public List getOnlineMembers(FactionWrapper faction) { - List players = new ArrayList<>(); - for (UUID playerId: getAllMembers(faction)) { - Player p = Bukkit.getPlayer(playerId); - if (p == null) { - continue; - } - players.add(p); - } - return players; - } - - /** - * - * @param p - * @param faction - */ - public void onPlayerLeaveFaction(Player p, FactionWrapper faction) { - for (Player player: getOnlineMembers(faction)) { - if (p.equals(player)) { - continue; - } - evaluate(player); - } - evaluate(p); - } - - public void onFactionDisband(FactionWrapper faction) { - List players = Arrays.asList(getAllMembers(faction)); - - Bukkit.getScheduler().runTask(tempfly, () -> { - for (UUID playerId: players) { - Player p = Bukkit.getPlayer(playerId); - if (p == null) { - continue; - } - evaluate(p); - } - for (Player p: getPlayersOn(faction)) { - if (!p.isOnline() || players.contains(p.getUniqueId())) { - continue; - } - evaluate(p); - onTerritoryExit(p); - } - }); - } - - /** - * Invoked when a players power changes. - * @param p The player - */ - public void onPlayerPowerChange(Player p) { - FactionWrapper faction = getFaction(p.getUniqueId()); - // Check faction requirements. - for (UUID id: getAllMembers(faction)) { - Player player = Bukkit.getPlayer(id); - if (player != null) { - evaluate(player); - } - } - // Check requirements for foreign players in the factions land. - for (Player player: getPlayersOn(faction)) { - if (isMember(player.getUniqueId(), faction)) { - continue; - } - evaluate(player); - } - } - - /** - * Invoked when the relationship between two factions changes. - * @param faction Faction A - * @param target Faction B - */ - public void onFactionRelationshipChange(FactionWrapper faction, FactionWrapper target) { - for (UUID id: getAllMembers(faction)) { - Player p = Bukkit.getPlayer(id); - if (p != null) { - evaluate(p); - } - } - - for (UUID id: getAllMembers(target)) { - Player p = Bukkit.getPlayer(id); - if (p != null) { - evaluate(p); - } - } - } - - /** - * This method is called by the children of FactionHook when a player enters faction land. - * It will track the island each player is on and handle flight requirements for the player. - * - * @param p The player who entered the land. - * @param rawIsland The raw object representing the faction. A wrapper will be created for it. - * @param loc Nullable, The location where the player entered the land. - */ - public void onFactionEnter(Player p, Object rawFaction, Location loc) { - super.onTerritoryEnter(p, rawFaction, loc); - } - - /** - * This method is called by the children of FactionHook when a player enters a factions land. - * It will track the faction land each player is in and handle flight requirements for the player. - * - * @param p The player who entered the land. - */ - public void onFactionExit(Player p) { - super.onTerritoryExit(p); - } - - - - /** - * ----------------- - * Requirement Logic - * ----------------- - */ - - - - /** - * - * @param playerId - * @param faction - * @return - */ - public FactionRelation getRelation(UUID playerId, FactionWrapper faction) { - if (faction == null || isWilderness(faction)) { - return FactionRelation.WILDERNESS; - } - if (isMember(playerId, faction)) { - return FactionRelation.HOME; - } - if (isEnemy(playerId, faction)) { - return FactionRelation.ENEMY; - } - if (isAllied(playerId, faction)) { - return FactionRelation.ALLIED; - } - return FactionRelation.NEUTRAL; - } - - @Override - public FlightResult handleFlightInquiry(FlightUser user) { - return checkFlightRequirements(user.getPlayer().getUniqueId(), user.getPlayer().getLocation()); - } - - @Override - public FlightResult checkFlightRequirements(UUID playerId, Location loc) { - return checkFlightRequirements(playerId, getFactionAt(loc)); - } - - @Override - public FlightResult checkFlightRequirements(UUID playerId, TerritoryWrapper territory) { - return checkFlightRequirements(playerId, (FactionWrapper) territory); - } - - public FlightResult checkFlightRequirements(UUID playerId, FactionWrapper faction) { - Console.debug("", "--- FactionsHook Check Flight Requirements A ---"); - if (!isEnabled()) { - Console.debug("--|!!!> Hook is not enabled. Returning allowed flight!"); - return new ResultAllow(this, InquiryType.OUT_OF_SCOPE, V.requirePassDefault); - } - return checkRoleRequirements(playerId, faction); - } - - public FlightResult checkRoleRequirements(UUID playerId, FactionWrapper faction) { - String role = getRole(playerId, faction); - if (V.debug) { - Console.debug("", "--- FactionHook check role requirements ---", "--| Players Role: " + role); - } - FactionWrapper home = getFaction(playerId); - if (home == null || isWilderness(home)) { - return new ResultDeny(DenyReason.REQUIREMENT, this, InquiryType.OUT_OF_SCOPE, requireFactionSelf - .replaceAll("\\{FACTION_NAME}", getFactionName(faction)), - false); - } - FactionRelation relation = getRelation(playerId, faction); - Console.debug("--| Players relation to faction: " + relation); - FactionRoleSettings roleSettings = roleRequirements.get(role.toUpperCase()); - Console.debug("--| role settings result: " + roleSettings); - FactionRequirement requirement = roleSettings == null ? baseRequirements.get(relation) : roleSettings.getRequirement(relation); - if (requirement == null) { - Console.debug("requirement is null"); - return new ResultAllow(this, InquiryType.OUT_OF_SCOPE, V.requirePassDefault); - } - - if (!requirement.isAllowed()) { - return new ResultDeny(DenyReason.DISABLED_REGION, this, InquiryType.OUT_OF_SCOPE, requireIllegalTerritory - .replaceAll("\\{FACTION_NAME}", getFactionName(faction)) - .replaceAll("\\{ROLE}", role), - !damageIllegal.contains(relation)); - } - Console.debug("--| flight is allowed in the land."); - - - if (!requirement.isThresholdMet(PowerContext.SELF, getCurrentPower(home), getMaxPower(home))) { - Console.debug("--| Power threshold for flight is not met A."); - return new ResultDeny(DenyReason.REQUIREMENT, this, InquiryType.OUT_OF_SCOPE, requirePowerSelf - .replaceAll("\\{POWER}", String.valueOf(requirement.getPowerFormatted(PowerContext.SELF, getCurrentPower(home), getMaxPower(home)))) - .replaceAll("\\{FACTION_NAME}", getFactionName(faction)) - , !damagePower.contains(relation)); - } - - boolean allied = isAllied(playerId, faction); - - if (!requirement.isThresholdMet(PowerContext.FOREIGN, getCurrentPower(faction), getMaxPower(faction))) { - Console.debug("--| Power threshold for flight is not met B."); - - return new ResultDeny(DenyReason.REQUIREMENT, this, InquiryType.OUT_OF_SCOPE, - (allied ? requirePowerAllied : requirePowerForeign) - .replaceAll("\\{POWER}", String.valueOf(requirement.getPowerFormatted(PowerContext.FOREIGN, getCurrentPower(faction), getMaxPower(faction)))) - .replaceAll("\\{FACTION_NAME}", getFactionName(faction)) - , !damagePower.contains(relation)); - } - - - Console.debug("--| Power threshold for flight is met."); - return new ResultAllow(this, InquiryType.OUT_OF_SCOPE, V.requirePassDefault); - - } - - - /** - * ------------- - * Abstraction - * ------------- - */ - - - - /** - * Get all players that are members of the given faction. Includes all faction roles. - * @param faction The faction to check - * @return The UUIDs of all faction members. - */ - public abstract UUID[] getAllMembers(FactionWrapper faction); - - /** - * - */ - public abstract boolean isWilderness(FactionWrapper faction); - - /** - * Get the current power of an individual player. - * @param playerId The player to check. - * @return The players power. - */ - public abstract double getCurrentPower(UUID playerId); - - /** - * Get the maximum power of an individual player. - * @param playerId The player to check. - * @return The players maximum power. - */ - public abstract double getMaxPower(UUID playerId); - - /** - * Get the current power of a faction. - * @param faction The faction to check. - * @return The factions power. - */ - public abstract double getCurrentPower(FactionWrapper faction); - - /** - * get the maximum power of a faction. - * @param faction The faction to check. - * @return the maximum power of the faction. - */ - public abstract double getMaxPower(FactionWrapper faction); - - /** - * Get the faction a player is associated with. - * @param playerId The player to check. - * @return The faction this player is a member of. - */ - public abstract FactionWrapper getFaction(UUID playerId); - - /** - * Get if a player is currently a member of the given faction. - * @return true if this player is a member of the faction; - */ - public abstract boolean isMember(UUID playerId, FactionWrapper faction); - - /** - * Get the UUID belonging to the player who owns a faction. - * @param faction The faction in question. - * @return The UUID of the owning player. - */ - public abstract UUID getFactionOwner(FactionWrapper faction); - - /** - * Get the role a player assumes in a specific faction. - * @param playerId The player to check. - * @param faction The faction in question. - * @return The players role in that faction. - */ - public abstract String getRole(UUID playerId, FactionWrapper faction); - - /** - * Check if the given faction is an enemy of the specified player. - * @param playerId The player to check. - * @param faction The faction in question. - * @return true if this faction is enemies with the player. - */ - public abstract boolean isEnemy(UUID playerId, FactionWrapper faction); - - /** - * Check if the given faction is an ally of the specified player. - * @param playerId The player to check. - * @param faction The faction in question. - * @return true if this faction is allies with the player. - */ - public abstract boolean isAllied(UUID playerId, FactionWrapper faction); - - /** - * Get the unique identifier of a given faction. - * @param faction The faction to check - * @return The identifier for this faction. - */ - public abstract String getFactionIdentifier(Object rawFaction); - - /** - * Get the name of the given faction. Return should not be null and must contain wilderness as an option. - * @param faction The faction. - * @return The name of the faction. - */ - public abstract String getFactionName(FactionWrapper faction); - - @Override - public String getTerritoryIdentifier(Object rawTerritory) { - return getFactionIdentifier(rawTerritory); - } - - /** - * Get the faction present at a specific location. - * @param loc The location to check - * @return The faction that occupies this location, null if there isn't one. - */ - public abstract FactionWrapper getFactionAt(Location loc); - - @Override - public TerritoryWrapper getTerritoryAt(Location loc) { - return getFactionAt(loc); - } - - /** - * Check if the given location is inside of a factions claimed territory. - * @param faction The location in question. - * @param loc The location to check. - * @return true if the location is in the faction land. - */ - public abstract boolean isInFactionLand(FactionWrapper faction, Location loc); - - - - /** - * ----------- - * Inherited - * ----------- - */ - - - - @Override - public boolean isInTerritory(TerritoryWrapper territory, Location loc) { - return isInFactionLand((FactionWrapper) territory, loc); - } - - @Override - public void onTempflyReload() { - super.onTempflyReload(); - - baseRequirements.clear(); - roleRequirements.clear(); - loadValues(); - for (Player player: Bukkit.getOnlinePlayers()) { - evaluate(player); - } - } - - @Override - public boolean initializeHook() { - loadValues(); - getTempFly().getServer().getPluginManager().registerEvents(this, getTempFly()); - - return true; - } - - @Override - public boolean needsDataFile() { - return false; - } - - @Override - public boolean forceYaml() { - return true; - } - - @Override - public Genre getGenre() { - return Genre.FACTIONS; - } - - @Override - public String getEmbeddedConfigName() { - return "factions_preset_generic"; - } - - @SuppressWarnings("serial") - @Override - public Map> getCommands() { - return new HashMap>() {{ - put("faction", CmdIslandSettings.class); - }}; - } - - public FactionWrapper getFactionWrapper(Object rawFaction) { - return (FactionWrapper) super.getTerritoryWrapper(rawFaction); - } - - @Override - public TerritoryWrapper createTerritoryWrapper(Object rawTerritory, TerritoryHook hook) { - return new FactionWrapper(rawTerritory); - } -} +package com.moneybags.tempfly.hook.factions; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TempFlyCommand; +import com.moneybags.tempfly.fly.result.FlightResult; +import com.moneybags.tempfly.fly.result.ResultAllow; +import com.moneybags.tempfly.fly.result.ResultDeny; +import com.moneybags.tempfly.fly.result.FlightResult.DenyReason; +import com.moneybags.tempfly.hook.HookManager.Genre; +import com.moneybags.tempfly.hook.skyblock.CmdIslandSettings; +import com.moneybags.tempfly.user.FlightUser; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.V; +import com.moneybags.tempfly.hook.TerritoryHook; +import com.moneybags.tempfly.hook.TerritoryWrapper; +import com.moneybags.tempfly.hook.factions.FactionRequirement.PowerContext; + +public abstract class FactionsHook extends TerritoryHook implements Listener { + + private Set damagePower; + private Set damageIllegal; + private String + requireIllegalTerritory, + requirePowerSelf, + requirePowerForeign, + requirePowerAllied, + requireFactionSelf; + + private Map baseRequirements; + private Map roleRequirements; + + public static enum FactionRelation { + HOME(PowerContext.SELF), + ENEMY(PowerContext.FOREIGN), + NEUTRAL(PowerContext.FOREIGN), + ALLIED(PowerContext.FOREIGN), + WILDERNESS(PowerContext.FOREIGN); + + private PowerContext context; + + private FactionRelation(PowerContext context) { + this.context = context; + } + + public PowerContext getPowerContext() { + return context; + } + + } + + + + public FactionsHook(TempFly tempfly) { + super(tempfly); + } + + + public void loadValues() { + Console.debug("", "---- Loading Factions Settings ----"); + FileConfiguration config = getConfig(); + + damagePower = new HashSet<>(); + damageIllegal = new HashSet<>(); + baseRequirements = new HashMap<>(); + roleRequirements = new HashMap<>(); + + ConfigurationSection csFallPower = config.getConfigurationSection("fall_damage.power"); + if (csFallPower != null) { + for (String key: csFallPower.getKeys(false)) { + FactionRelation relation; + try { relation = FactionRelation.valueOf(key.toUpperCase()); } catch (IllegalArgumentException e) { + Console.warn("A faction relationship defined in the config does not exist: (" + key + ")"); + continue; + } + if (csFallPower.getBoolean(key)) { + damagePower.add(relation); + } + } + } + + ConfigurationSection csFallDisabled = config.getConfigurationSection("fall_damage.disabled"); + if (csFallDisabled != null) { + for (String key: csFallDisabled.getKeys(false)) { + FactionRelation relation; + try { relation = FactionRelation.valueOf(key.toUpperCase()); } catch (IllegalArgumentException e) { + Console.warn("A faction relationship defined in the config does not exist: (" + key + ")"); + continue; + } + if (csFallDisabled.getBoolean(key)) { + damageIllegal.add(relation); + } + } + } + + String name = getConfigName(); + requireIllegalTerritory = V.st(config, "language.requirements.illegal_territory", name); + requirePowerSelf = V.st(config, "language.requirements.power_self", name); + requirePowerForeign = V.st(config, "language.requirements.power_foreign", name); + requirePowerAllied = V.st(config, "language.requirements.power_allied", name); + requireFactionSelf = V.st(config, "language.requirements.faction_self", name); + + // Load base faction requirements from the config. + ConfigurationSection csBase = config.getConfigurationSection("base_requirements"); + if (csBase != null) { + for (String key: csBase.getKeys(false)) { + FactionRelation relation; + try { relation = FactionRelation.valueOf(key.toUpperCase()); } catch (IllegalArgumentException e) { + Console.warn("A faction relationship defined in the config does not exist: (" + key + ")"); + continue; + } + baseRequirements.put(relation, new FactionRequirement(this, relation, csBase.getConfigurationSection(key), true)); + } + } + + // Add default unrestricted faction requirements if they are not in the config. + for (FactionRelation relation: FactionRelation.values()) { + if (!baseRequirements.containsKey(relation)) { + Console.debug("--! Base requirements does not contain settings for: " + relation); + baseRequirements.put(relation, new FactionRequirement(this, relation)); + } + } + + ConfigurationSection csRole = config.getConfigurationSection("role_requirements"); + if (csRole != null) { + for (String key: csRole.getKeys(false)) { + roleRequirements.put(key.toUpperCase(), new FactionRoleSettings(this, key.toUpperCase(), csRole.getConfigurationSection(key))); + } + } + Console.debug("---- Done Factions Settings ----"); + } + + public FactionRequirement getBaseRequirement(FactionRelation relation) { + return baseRequirements.get(relation); + } + + + + + /** + * -------------- + * Event Handling + * -------------- + */ + + + + /** + * + * + */ + @EventHandler + public void onJoin(PlayerJoinEvent e) { + FactionWrapper to = getFactionAt(e.getPlayer().getLocation()); + if (to == null) { + return; + } + onFactionEnter(e.getPlayer(), to, null); + } + + @EventHandler + public void onTeleport(PlayerTeleportEvent e) { + if (e.getFrom().getChunk().equals(e.getTo().getChunk())) { + return; + } + FactionWrapper from = getFactionAt(e.getFrom()); + FactionWrapper to = getFactionAt(e.getTo()); + if (from.equals(to)) { + return; + } + + onFactionExit(e.getPlayer()); + onFactionEnter(e.getPlayer(), to, null); + } + + @EventHandler + public void onRespawn(PlayerRespawnEvent e) { + if (e.getPlayer().getLocation().getChunk().equals(e.getRespawnLocation().getChunk())) { + return; + } + FactionWrapper from = getFactionAt(e.getPlayer().getLocation()); + FactionWrapper to = getFactionAt(e.getRespawnLocation()); + if (from.equals(to)) { + return; + } + + onFactionExit(e.getPlayer()); + onFactionEnter(e.getPlayer(), to, null); + } + + @EventHandler + public void onMove(PlayerMoveEvent e) { + if (e.getFrom().getChunk().equals(e.getTo().getChunk())) { + return; + } + FactionWrapper from = getFactionAt(e.getFrom()); + FactionWrapper to = getFactionAt(e.getTo()); + if (from.equals(to)) { + return; + } + + onFactionExit(e.getPlayer()); + onFactionEnter(e.getPlayer(), to, null); + } + + + + /** + * -------------------- + * Super Event Handling + * -------------------- + */ + + + + /** + * + * @param chunk + * @param faction + */ + public void onLandClaimed(Chunk chunk, FactionWrapper faction) { + Console.debug("--| Claimed land"); + for (Entity ent: chunk.getEntities()) { + if (!(ent instanceof Player)) { + continue; + } + onFactionEnter((Player) ent, faction.getRawTerritory(), ent.getLocation()); + } + } + + public void onLandOverClaimed(Chunk chunk, FactionWrapper victim, FactionWrapper agressor) { + Console.debug("--| Land overclaimed from (" + getFactionName(victim)); + for (Entity ent: chunk.getEntities()) { + if (!(ent instanceof Player)) { + continue; + } + onFactionExit((Player) ent); + onFactionEnter((Player) ent, agressor.getRawTerritory(), ent.getLocation()); + } + } + + public void onLandUnclaimed(Chunk chunk) { + Console.debug("--| Unclaimed land"); + for (Entity ent: chunk.getEntities()) { + if (!(ent instanceof Player)) { + continue; + } + onFactionExit((Player) ent); + onFactionEnter((Player) ent, getFactionAt(ent.getLocation()).getRawTerritory(), ent.getLocation()); + } + } + + public void onPlayerJoinFaction(Player p, FactionWrapper faction) { + for (Player player: getOnlineMembers(faction)) { + if (p.equals(player)) { + continue; + } + evaluate(player); + } + evaluate(p); + } + + public List getOnlineMembers(FactionWrapper faction) { + List players = new ArrayList<>(); + for (UUID playerId: getAllMembers(faction)) { + Player p = Bukkit.getPlayer(playerId); + if (p == null) { + continue; + } + players.add(p); + } + return players; + } + + /** + * + * @param p + * @param faction + */ + public void onPlayerLeaveFaction(Player p, FactionWrapper faction) { + for (Player player: getOnlineMembers(faction)) { + if (p.equals(player)) { + continue; + } + evaluate(player); + } + evaluate(p); + } + + public void onFactionDisband(FactionWrapper faction) { + List players = Arrays.asList(getAllMembers(faction)); + + Bukkit.getScheduler().runTask(tempfly, () -> { + for (UUID playerId: players) { + Player p = Bukkit.getPlayer(playerId); + if (p == null) { + continue; + } + evaluate(p); + } + for (Player p: getPlayersOn(faction)) { + if (!p.isOnline() || players.contains(p.getUniqueId())) { + continue; + } + evaluate(p); + onTerritoryExit(p); + } + }); + } + + /** + * Invoked when a players power changes. + * @param p The player + */ + public void onPlayerPowerChange(Player p) { + FactionWrapper faction = getFaction(p.getUniqueId()); + // Check faction requirements. + for (UUID id: getAllMembers(faction)) { + Player player = Bukkit.getPlayer(id); + if (player != null) { + evaluate(player); + } + } + // Check requirements for foreign players in the factions land. + for (Player player: getPlayersOn(faction)) { + if (isMember(player.getUniqueId(), faction)) { + continue; + } + evaluate(player); + } + } + + /** + * Invoked when the relationship between two factions changes. + * @param faction Faction A + * @param target Faction B + */ + public void onFactionRelationshipChange(FactionWrapper faction, FactionWrapper target) { + for (UUID id: getAllMembers(faction)) { + Player p = Bukkit.getPlayer(id); + if (p != null) { + evaluate(p); + } + } + + for (UUID id: getAllMembers(target)) { + Player p = Bukkit.getPlayer(id); + if (p != null) { + evaluate(p); + } + } + } + + /** + * This method is called by the children of FactionHook when a player enters faction land. + * It will track the island each player is on and handle flight requirements for the player. + * + * @param p The player who entered the land. + * @param rawIsland The raw object representing the faction. A wrapper will be created for it. + * @param loc Nullable, The location where the player entered the land. + */ + public void onFactionEnter(Player p, Object rawFaction, Location loc) { + super.onTerritoryEnter(p, rawFaction, loc); + } + + /** + * This method is called by the children of FactionHook when a player enters a factions land. + * It will track the faction land each player is in and handle flight requirements for the player. + * + * @param p The player who entered the land. + */ + public void onFactionExit(Player p) { + super.onTerritoryExit(p); + } + + + + /** + * ----------------- + * Requirement Logic + * ----------------- + */ + + + + /** + * + * @param playerId + * @param faction + * @return + */ + public FactionRelation getRelation(UUID playerId, FactionWrapper faction) { + if (faction == null || isWilderness(faction)) { + return FactionRelation.WILDERNESS; + } + if (isMember(playerId, faction)) { + return FactionRelation.HOME; + } + if (isEnemy(playerId, faction)) { + return FactionRelation.ENEMY; + } + if (isAllied(playerId, faction)) { + return FactionRelation.ALLIED; + } + return FactionRelation.NEUTRAL; + } + + @Override + public FlightResult handleFlightInquiry(FlightUser user) { + return checkFlightRequirements(user.getPlayer().getUniqueId(), user.getPlayer().getLocation()); + } + + @Override + public FlightResult checkFlightRequirements(UUID playerId, Location loc) { + return checkFlightRequirements(playerId, getFactionAt(loc)); + } + + @Override + public FlightResult checkFlightRequirements(UUID playerId, TerritoryWrapper territory) { + return checkFlightRequirements(playerId, (FactionWrapper) territory); + } + + public FlightResult checkFlightRequirements(UUID playerId, FactionWrapper faction) { + Console.debug("", "--- FactionsHook Check Flight Requirements A ---"); + if (!isEnabled()) { + Console.debug("--|!!!> Hook is not enabled. Returning allowed flight!"); + return new ResultAllow(this, InquiryType.OUT_OF_SCOPE, V.requirePassDefault); + } + return checkRoleRequirements(playerId, faction); + } + + public FlightResult checkRoleRequirements(UUID playerId, FactionWrapper faction) { + String role = getRole(playerId, faction); + if (V.debug) { + Console.debug("", "--- FactionHook check role requirements ---", "--| Players Role: " + role); + } + FactionWrapper home = getFaction(playerId); + if (home == null || isWilderness(home)) { + return new ResultDeny(DenyReason.REQUIREMENT, this, InquiryType.OUT_OF_SCOPE, requireFactionSelf + .replaceAll("\\{FACTION_NAME}", getFactionName(faction)), + false); + } + FactionRelation relation = getRelation(playerId, faction); + Console.debug("--| Players relation to faction: " + relation); + FactionRoleSettings roleSettings = roleRequirements.get(role.toUpperCase()); + Console.debug("--| role settings result: " + roleSettings); + FactionRequirement requirement = roleSettings == null ? baseRequirements.get(relation) : roleSettings.getRequirement(relation); + if (requirement == null) { + Console.debug("requirement is null"); + return new ResultAllow(this, InquiryType.OUT_OF_SCOPE, V.requirePassDefault); + } + + if (!requirement.isAllowed()) { + return new ResultDeny(DenyReason.DISABLED_REGION, this, InquiryType.OUT_OF_SCOPE, requireIllegalTerritory + .replaceAll("\\{FACTION_NAME}", getFactionName(faction)) + .replaceAll("\\{ROLE}", role), + !damageIllegal.contains(relation)); + } + Console.debug("--| flight is allowed in the land."); + + + if (!requirement.isThresholdMet(PowerContext.SELF, getCurrentPower(home), getMaxPower(home))) { + Console.debug("--| Power threshold for flight is not met A."); + return new ResultDeny(DenyReason.REQUIREMENT, this, InquiryType.OUT_OF_SCOPE, requirePowerSelf + .replaceAll("\\{POWER}", String.valueOf(requirement.getPowerFormatted(PowerContext.SELF, getCurrentPower(home), getMaxPower(home)))) + .replaceAll("\\{FACTION_NAME}", getFactionName(faction)) + , !damagePower.contains(relation)); + } + + boolean allied = isAllied(playerId, faction); + + if (!requirement.isThresholdMet(PowerContext.FOREIGN, getCurrentPower(faction), getMaxPower(faction))) { + Console.debug("--| Power threshold for flight is not met B."); + + return new ResultDeny(DenyReason.REQUIREMENT, this, InquiryType.OUT_OF_SCOPE, + (allied ? requirePowerAllied : requirePowerForeign) + .replaceAll("\\{POWER}", String.valueOf(requirement.getPowerFormatted(PowerContext.FOREIGN, getCurrentPower(faction), getMaxPower(faction)))) + .replaceAll("\\{FACTION_NAME}", getFactionName(faction)) + , !damagePower.contains(relation)); + } + + + Console.debug("--| Power threshold for flight is met."); + return new ResultAllow(this, InquiryType.OUT_OF_SCOPE, V.requirePassDefault); + + } + + + /** + * ------------- + * Abstraction + * ------------- + */ + + + + /** + * Get all players that are members of the given faction. Includes all faction roles. + * @param faction The faction to check + * @return The UUIDs of all faction members. + */ + public abstract UUID[] getAllMembers(FactionWrapper faction); + + /** + * + */ + public abstract boolean isWilderness(FactionWrapper faction); + + /** + * Get the current power of an individual player. + * @param playerId The player to check. + * @return The players power. + */ + public abstract double getCurrentPower(UUID playerId); + + /** + * Get the maximum power of an individual player. + * @param playerId The player to check. + * @return The players maximum power. + */ + public abstract double getMaxPower(UUID playerId); + + /** + * Get the current power of a faction. + * @param faction The faction to check. + * @return The factions power. + */ + public abstract double getCurrentPower(FactionWrapper faction); + + /** + * get the maximum power of a faction. + * @param faction The faction to check. + * @return the maximum power of the faction. + */ + public abstract double getMaxPower(FactionWrapper faction); + + /** + * Get the faction a player is associated with. + * @param playerId The player to check. + * @return The faction this player is a member of. + */ + public abstract FactionWrapper getFaction(UUID playerId); + + /** + * Get if a player is currently a member of the given faction. + * @return true if this player is a member of the faction; + */ + public abstract boolean isMember(UUID playerId, FactionWrapper faction); + + /** + * Get the UUID belonging to the player who owns a faction. + * @param faction The faction in question. + * @return The UUID of the owning player. + */ + public abstract UUID getFactionOwner(FactionWrapper faction); + + /** + * Get the role a player assumes in a specific faction. + * @param playerId The player to check. + * @param faction The faction in question. + * @return The players role in that faction. + */ + public abstract String getRole(UUID playerId, FactionWrapper faction); + + /** + * Check if the given faction is an enemy of the specified player. + * @param playerId The player to check. + * @param faction The faction in question. + * @return true if this faction is enemies with the player. + */ + public abstract boolean isEnemy(UUID playerId, FactionWrapper faction); + + /** + * Check if the given faction is an ally of the specified player. + * @param playerId The player to check. + * @param faction The faction in question. + * @return true if this faction is allies with the player. + */ + public abstract boolean isAllied(UUID playerId, FactionWrapper faction); + + /** + * Get the unique identifier of a given faction. + * @param faction The faction to check + * @return The identifier for this faction. + */ + public abstract String getFactionIdentifier(Object rawFaction); + + /** + * Get the name of the given faction. Return should not be null and must contain wilderness as an option. + * @param faction The faction. + * @return The name of the faction. + */ + public abstract String getFactionName(FactionWrapper faction); + + @Override + public String getTerritoryIdentifier(Object rawTerritory) { + return getFactionIdentifier(rawTerritory); + } + + /** + * Get the faction present at a specific location. + * @param loc The location to check + * @return The faction that occupies this location, null if there isn't one. + */ + public abstract FactionWrapper getFactionAt(Location loc); + + @Override + public TerritoryWrapper getTerritoryAt(Location loc) { + return getFactionAt(loc); + } + + /** + * Check if the given location is inside of a factions claimed territory. + * @param faction The location in question. + * @param loc The location to check. + * @return true if the location is in the faction land. + */ + public abstract boolean isInFactionLand(FactionWrapper faction, Location loc); + + + + /** + * ----------- + * Inherited + * ----------- + */ + + + + @Override + public boolean isInTerritory(TerritoryWrapper territory, Location loc) { + return isInFactionLand((FactionWrapper) territory, loc); + } + + @Override + public void onTempflyReload() { + super.onTempflyReload(); + + baseRequirements.clear(); + roleRequirements.clear(); + loadValues(); + for (Player player: Bukkit.getOnlinePlayers()) { + evaluate(player); + } + } + + @Override + public boolean initializeHook() { + loadValues(); + getTempFly().getServer().getPluginManager().registerEvents(this, getTempFly()); + + return true; + } + + @Override + public boolean needsDataFile() { + return false; + } + + @Override + public boolean forceYaml() { + return true; + } + + @Override + public Genre getGenre() { + return Genre.FACTIONS; + } + + @Override + public String getEmbeddedConfigName() { + return "factions_preset_generic"; + } + + @SuppressWarnings("serial") + @Override + public Map> getCommands() { + return new HashMap>() {{ + put("faction", CmdIslandSettings.class); + }}; + } + + public FactionWrapper getFactionWrapper(Object rawFaction) { + return (FactionWrapper) super.getTerritoryWrapper(rawFaction); + } + + @Override + public TerritoryWrapper createTerritoryWrapper(Object rawTerritory, TerritoryHook hook) { + return new FactionWrapper(rawTerritory); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/factions/plugins/FactionsUUIDHook.java b/src/com/moneybags/tempfly/hook/factions/plugins/FactionsUUIDHook.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/hook/factions/plugins/FactionsUUIDHook.java rename to src/com/moneybags/tempfly/hook/factions/plugins/FactionsUUIDHook.java index a973ecb..d716db9 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/factions/plugins/FactionsUUIDHook.java +++ b/src/com/moneybags/tempfly/hook/factions/plugins/FactionsUUIDHook.java @@ -1,231 +1,231 @@ -package com.moneybags.tempfly.hook.factions.plugins; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import com.massivecraft.factions.Board; -import com.massivecraft.factions.FLocation; -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.event.FPlayerJoinEvent; -import com.massivecraft.factions.event.FPlayerLeaveEvent; -import com.massivecraft.factions.event.FactionDisbandEvent; -import com.massivecraft.factions.event.FactionRelationEvent; -import com.massivecraft.factions.event.LandClaimEvent; -import com.massivecraft.factions.event.LandUnclaimAllEvent; -import com.massivecraft.factions.event.LandUnclaimEvent; -import com.massivecraft.factions.event.PowerLossEvent; -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.hook.factions.FactionWrapper; -import com.moneybags.tempfly.hook.factions.FactionsHook; - -public class FactionsUUIDHook extends FactionsHook implements Listener { - - public FactionsUUIDHook(TempFly tempfly) { - super(tempfly); - } - - @Override - public boolean initializeHook() { - getTempFly().getServer().getPluginManager().registerEvents(this, tempfly); - return super.initializeHook(); - } - - @Override - public String getTargetClass() { - return "com.massivecraft.factions.FactionsPlugin"; - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onClaim(LandClaimEvent e) { - FLocation loc = e.getLocation(); - Faction current = Board.getInstance().getFactionAt(loc); - Bukkit.getScheduler().runTask(tempfly, () -> { - Faction claimer = e.getFaction(); - if (!claimer.equals(current)) { - super.onLandOverClaimed(loc.getChunk(), getFactionWrapper(current), getFactionWrapper(claimer)); - } else { - super.onLandClaimed(loc.getChunk(), getFactionWrapper(claimer)); - } - }); - } - - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUnclaim(LandUnclaimEvent e) { - Bukkit.getScheduler().runTask(tempfly, () -> { - super.onLandUnclaimed(e.getLocation().getChunk()); - }); - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUnclaimAll(LandUnclaimAllEvent e) { - Set claims = new HashSet<>(e.getFaction().getAllClaims()); - Bukkit.getScheduler().runTask(tempfly, () -> { - for (FLocation loc: claims) { - super.onLandUnclaimed(loc.getChunk()); - } - }); - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPower(PowerLossEvent e) { - Bukkit.getScheduler().runTask(tempfly, () -> { - super.onPlayerPowerChange(e.getfPlayer().getPlayer()); - }); - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onRelation(FactionRelationEvent e) { - super.onFactionRelationshipChange(getFactionWrapper(e.getFaction()), getFactionWrapper(e.getTargetFaction())); - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDisband(FactionDisbandEvent e) { - super.onFactionDisband(getFactionWrapper(e.getFaction())); - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onFactionJoin(FPlayerJoinEvent e) { - Bukkit.getScheduler().runTask(tempfly, () -> { - if (e.getfPlayer().getPlayer().isOnline()) { - super.onPlayerJoinFaction(e.getfPlayer().getPlayer(), getFactionWrapper(e.getFaction())); - } - }); - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onFactionLeave(FPlayerLeaveEvent e) { - Bukkit.getScheduler().runTask(tempfly, () -> { - if (e.getfPlayer().getPlayer().isOnline()) { - super.onPlayerLeaveFaction(e.getfPlayer().getPlayer(), getFactionWrapper(e.getFaction())); - } - }); - } - - - - - - - public FPlayer getFPlayer(UUID playerId) { - return FPlayers.getInstance().getById(playerId.toString()); - } - - @Override - public double getCurrentPower(UUID playerId) { - return getFPlayer(playerId).getPower(); - } - - @Override - public double getMaxPower(UUID playerId) { - return getFPlayer(playerId).getPowerMax(); - } - - @Override - public double getCurrentPower(FactionWrapper faction) { - return ((Faction) faction.getRawTerritory()).getPower(); - } - - @Override - public double getMaxPower(FactionWrapper faction) { - return ((Faction) faction.getRawTerritory()).getPowerMax(); - } - - @Override - public FactionWrapper getFaction(UUID playerId) { - return getFactionWrapper(getFPlayer(playerId).getFaction()); - } - - @Override - public boolean isMember(UUID playerId, FactionWrapper faction) { - if (((Faction) faction.getRawTerritory()).isWilderness()) { - return false; - } - return getFPlayer(playerId).getFaction().equals(faction.getRawTerritory()); - } - - @Override - public UUID getFactionOwner(FactionWrapper faction) { - return UUID.fromString(((Faction) faction.getRawTerritory()).getFPlayerAdmin().getId()); - } - - @Override - public String getRole(UUID playerId, FactionWrapper faction) { - return getFPlayer(playerId).getRole().toString(); - } - - @Override - public boolean isEnemy(UUID playerId, FactionWrapper faction) { - return getFPlayer(playerId).getFaction().getRelationTo((Faction) faction.getRawTerritory()).isEnemy(); - } - - @Override - public boolean isAllied(UUID playerId, FactionWrapper faction) { - return getFPlayer(playerId).getFaction().getRelationTo((Faction) faction.getRawTerritory()).isAlly(); - } - - @Override - public String getFactionIdentifier(Object rawFaction) { - return ((Faction) rawFaction).getId(); - } - - @Override - public String getFactionName(FactionWrapper faction) { - return ((Faction) faction.getRawTerritory()).getTag(); - } - - @Override - public FactionWrapper getFactionAt(Location loc) { - return getFactionWrapper(Board.getInstance().getFactionAt(new FLocation(loc))); - } - - @Override - public boolean isInFactionLand(FactionWrapper faction, Location loc) { - Faction rawFaction = Board.getInstance().getFactionAt(new FLocation(loc)); - if (rawFaction == null) { - return false; - } - return rawFaction.equals(faction.getRawTerritory()); - } - - @Override - public UUID[] getAllMembers(FactionWrapper faction) { - List ids = new ArrayList<>(); - for (FPlayer player: ((Faction) faction.getRawTerritory()).getFPlayers()) { - ids.add(UUID.fromString(player.getId())); - } - return ids.toArray(new UUID[ids.size()]); - } - - - @Override - public String getPluginName() { - return "Factions"; - } - - @Override - public String getConfigName() { - return "FactionsUUID"; - } - - @Override - public String getEmbeddedConfigName() { - return "factions_preset_uuid"; - } - - @Override - public boolean isWilderness(FactionWrapper faction) { - return ((Faction) faction.getRawTerritory()).isWilderness(); - } - -} +package com.moneybags.tempfly.hook.factions.plugins; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import com.massivecraft.factions.Board; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.event.FPlayerJoinEvent; +import com.massivecraft.factions.event.FPlayerLeaveEvent; +import com.massivecraft.factions.event.FactionDisbandEvent; +import com.massivecraft.factions.event.FactionRelationEvent; +import com.massivecraft.factions.event.LandClaimEvent; +import com.massivecraft.factions.event.LandUnclaimAllEvent; +import com.massivecraft.factions.event.LandUnclaimEvent; +import com.massivecraft.factions.event.PowerLossEvent; +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.hook.factions.FactionWrapper; +import com.moneybags.tempfly.hook.factions.FactionsHook; + +public class FactionsUUIDHook extends FactionsHook implements Listener { + + public FactionsUUIDHook(TempFly tempfly) { + super(tempfly); + } + + @Override + public boolean initializeHook() { + getTempFly().getServer().getPluginManager().registerEvents(this, tempfly); + return super.initializeHook(); + } + + @Override + public String getTargetClass() { + return "com.massivecraft.factions.FactionsPlugin"; + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onClaim(LandClaimEvent e) { + FLocation loc = e.getLocation(); + Faction current = Board.getInstance().getFactionAt(loc); + Bukkit.getScheduler().runTask(tempfly, () -> { + Faction claimer = e.getFaction(); + if (!claimer.equals(current)) { + super.onLandOverClaimed(loc.getChunk(), getFactionWrapper(current), getFactionWrapper(claimer)); + } else { + super.onLandClaimed(loc.getChunk(), getFactionWrapper(claimer)); + } + }); + } + + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onUnclaim(LandUnclaimEvent e) { + Bukkit.getScheduler().runTask(tempfly, () -> { + super.onLandUnclaimed(e.getLocation().getChunk()); + }); + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onUnclaimAll(LandUnclaimAllEvent e) { + Set claims = new HashSet<>(e.getFaction().getAllClaims()); + Bukkit.getScheduler().runTask(tempfly, () -> { + for (FLocation loc: claims) { + super.onLandUnclaimed(loc.getChunk()); + } + }); + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPower(PowerLossEvent e) { + Bukkit.getScheduler().runTask(tempfly, () -> { + super.onPlayerPowerChange(e.getfPlayer().getPlayer()); + }); + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onRelation(FactionRelationEvent e) { + super.onFactionRelationshipChange(getFactionWrapper(e.getFaction()), getFactionWrapper(e.getTargetFaction())); + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDisband(FactionDisbandEvent e) { + super.onFactionDisband(getFactionWrapper(e.getFaction())); + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onFactionJoin(FPlayerJoinEvent e) { + Bukkit.getScheduler().runTask(tempfly, () -> { + if (e.getfPlayer().getPlayer().isOnline()) { + super.onPlayerJoinFaction(e.getfPlayer().getPlayer(), getFactionWrapper(e.getFaction())); + } + }); + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onFactionLeave(FPlayerLeaveEvent e) { + Bukkit.getScheduler().runTask(tempfly, () -> { + if (e.getfPlayer().getPlayer().isOnline()) { + super.onPlayerLeaveFaction(e.getfPlayer().getPlayer(), getFactionWrapper(e.getFaction())); + } + }); + } + + + + + + + public FPlayer getFPlayer(UUID playerId) { + return FPlayers.getInstance().getById(playerId.toString()); + } + + @Override + public double getCurrentPower(UUID playerId) { + return getFPlayer(playerId).getPower(); + } + + @Override + public double getMaxPower(UUID playerId) { + return getFPlayer(playerId).getPowerMax(); + } + + @Override + public double getCurrentPower(FactionWrapper faction) { + return ((Faction) faction.getRawTerritory()).getPower(); + } + + @Override + public double getMaxPower(FactionWrapper faction) { + return ((Faction) faction.getRawTerritory()).getPowerMax(); + } + + @Override + public FactionWrapper getFaction(UUID playerId) { + return getFactionWrapper(getFPlayer(playerId).getFaction()); + } + + @Override + public boolean isMember(UUID playerId, FactionWrapper faction) { + if (((Faction) faction.getRawTerritory()).isWilderness()) { + return false; + } + return getFPlayer(playerId).getFaction().equals(faction.getRawTerritory()); + } + + @Override + public UUID getFactionOwner(FactionWrapper faction) { + return UUID.fromString(((Faction) faction.getRawTerritory()).getFPlayerAdmin().getId()); + } + + @Override + public String getRole(UUID playerId, FactionWrapper faction) { + return getFPlayer(playerId).getRole().toString(); + } + + @Override + public boolean isEnemy(UUID playerId, FactionWrapper faction) { + return getFPlayer(playerId).getFaction().getRelationTo((Faction) faction.getRawTerritory()).isEnemy(); + } + + @Override + public boolean isAllied(UUID playerId, FactionWrapper faction) { + return getFPlayer(playerId).getFaction().getRelationTo((Faction) faction.getRawTerritory()).isAlly(); + } + + @Override + public String getFactionIdentifier(Object rawFaction) { + return ((Faction) rawFaction).getId(); + } + + @Override + public String getFactionName(FactionWrapper faction) { + return ((Faction) faction.getRawTerritory()).getTag(); + } + + @Override + public FactionWrapper getFactionAt(Location loc) { + return getFactionWrapper(Board.getInstance().getFactionAt(new FLocation(loc))); + } + + @Override + public boolean isInFactionLand(FactionWrapper faction, Location loc) { + Faction rawFaction = Board.getInstance().getFactionAt(new FLocation(loc)); + if (rawFaction == null) { + return false; + } + return rawFaction.equals(faction.getRawTerritory()); + } + + @Override + public UUID[] getAllMembers(FactionWrapper faction) { + List ids = new ArrayList<>(); + for (FPlayer player: ((Faction) faction.getRawTerritory()).getFPlayers()) { + ids.add(UUID.fromString(player.getId())); + } + return ids.toArray(new UUID[ids.size()]); + } + + + @Override + public String getPluginName() { + return "Factions"; + } + + @Override + public String getConfigName() { + return "FactionsUUID"; + } + + @Override + public String getEmbeddedConfigName() { + return "factions_preset_uuid"; + } + + @Override + public boolean isWilderness(FactionWrapper faction) { + return ((Faction) faction.getRawTerritory()).isWilderness(); + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/region/CompatRegion.java b/src/com/moneybags/tempfly/hook/region/CompatRegion.java similarity index 94% rename from TempFly/src/com/moneybags/tempfly/hook/region/CompatRegion.java rename to src/com/moneybags/tempfly/hook/region/CompatRegion.java index 0d91a61..21e11ba 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/region/CompatRegion.java +++ b/src/com/moneybags/tempfly/hook/region/CompatRegion.java @@ -1,41 +1,41 @@ -package com.moneybags.tempfly.hook.region; - -import org.bukkit.util.Vector; - -public class CompatRegion { - - private String id; - private Vector min, max; - - public CompatRegion(String id, Vector min, Vector max) { - this.id = id; - this.min = min; - this.max = max; - } - - public CompatRegion(String id) { - this.id = id; - this.min = new Vector(0, 0, 0); - this.max = new Vector(0, 0, 0); - } - - public String getId() { - return id; - } - - public Vector getMin() { - return min; - } - - public Vector getMax() { - return max; - } - - @Override - public boolean equals(Object o) { - return (o instanceof CompatRegion) && super.equals(o) - || ((CompatRegion)o).getId().equals(id) - && this.min.equals(((CompatRegion)o).getMin()) - && this.max.equals(((CompatRegion)o).getMax()); - } -} +package com.moneybags.tempfly.hook.region; + +import org.bukkit.util.Vector; + +public class CompatRegion { + + private String id; + private Vector min, max; + + public CompatRegion(String id, Vector min, Vector max) { + this.id = id; + this.min = min; + this.max = max; + } + + public CompatRegion(String id) { + this.id = id; + this.min = new Vector(0, 0, 0); + this.max = new Vector(0, 0, 0); + } + + public String getId() { + return id; + } + + public Vector getMin() { + return min; + } + + public Vector getMax() { + return max; + } + + @Override + public boolean equals(Object o) { + return (o instanceof CompatRegion) && super.equals(o) + || ((CompatRegion)o).getId().equals(id) + && this.min.equals(((CompatRegion)o).getMin()) + && this.max.equals(((CompatRegion)o).getMax()); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/region/RegionProvider.java b/src/com/moneybags/tempfly/hook/region/RegionProvider.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/hook/region/RegionProvider.java rename to src/com/moneybags/tempfly/hook/region/RegionProvider.java index 2e83fe7..c784708 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/region/RegionProvider.java +++ b/src/com/moneybags/tempfly/hook/region/RegionProvider.java @@ -1,22 +1,22 @@ -package com.moneybags.tempfly.hook.region; - -import org.bukkit.Location; - -public interface RegionProvider { - - - /** - * - * @return Whether or not this RegionProvider is currently active and accepting inquiries. - */ - public default boolean isEnabled() { - return true; - } - - /** - * Called when tempfly wants to know about the regions that encompass this location. - * @param loc The location in question. - * @return - */ - public abstract CompatRegion[] getApplicableRegions(Location loc); -} +package com.moneybags.tempfly.hook.region; + +import org.bukkit.Location; + +public interface RegionProvider { + + + /** + * + * @return Whether or not this RegionProvider is currently active and accepting inquiries. + */ + public default boolean isEnabled() { + return true; + } + + /** + * Called when tempfly wants to know about the regions that encompass this location. + * @param loc The location in question. + * @return + */ + public abstract CompatRegion[] getApplicableRegions(Location loc); +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/region/plugins/WorldGuardHook.java b/src/com/moneybags/tempfly/hook/region/plugins/WorldGuardHook.java similarity index 97% rename from TempFly/src/com/moneybags/tempfly/hook/region/plugins/WorldGuardHook.java rename to src/com/moneybags/tempfly/hook/region/plugins/WorldGuardHook.java index ca946c4..1d84ce0 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/region/plugins/WorldGuardHook.java +++ b/src/com/moneybags/tempfly/hook/region/plugins/WorldGuardHook.java @@ -1,134 +1,134 @@ -package com.moneybags.tempfly.hook.region.plugins; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.plugin.Plugin; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.hook.region.CompatRegion; -import com.moneybags.tempfly.hook.region.RegionProvider; -import com.sk89q.worldguard.bukkit.WorldGuardPlugin; -import com.sk89q.worldguard.protection.ApplicableRegionSet; -import com.sk89q.worldguard.protection.managers.RegionManager; -import com.sk89q.worldguard.protection.regions.ProtectedRegion; - -public class WorldGuardHook implements RegionProvider { - - private boolean enabled; - - private static Object worldGuard = null; - private static Object worldGuardPlugin = null; - private static Object regionContainer = null; - private static Method regionContainerGetMethod = null; - private static Method worldAdaptMethod = null; - private static Method regionManagerGetMethod = null; - private static Constructor vectorConstructor = null; - private static Method vectorConstructorMethod = null; - - public WorldGuardHook(TempFly tempfly) { - try { - Class worldGuardClass = Class.forName("com.sk89q.worldguard.WorldGuard"); - Method getInstanceMethod = worldGuardClass.getMethod("getInstance"); - worldGuard = getInstanceMethod.invoke(null); - } catch (Exception ex) { - Plugin plugin = tempfly.getServer().getPluginManager().getPlugin("WorldGuard"); - if (plugin == null || !(plugin instanceof WorldGuardPlugin)) { - return; - } - worldGuardPlugin = (WorldGuardPlugin) plugin; - } - if (worldGuard != null) { - try { - Method getPlatFormMethod = worldGuard.getClass().getMethod("getPlatform"); - Object platform = getPlatFormMethod.invoke(worldGuard); - Method getRegionContainerMethod = platform.getClass().getMethod("getRegionContainer"); - regionContainer = getRegionContainerMethod.invoke(platform); - - Class worldEditWorldClass = Class.forName("com.sk89q.worldedit.world.World"); - Class worldEditAdapterClass = Class.forName("com.sk89q.worldedit.bukkit.BukkitAdapter"); - worldAdaptMethod = worldEditAdapterClass.getMethod("adapt", World.class); - regionContainerGetMethod = regionContainer.getClass().getMethod("get", worldEditWorldClass); - } catch (Exception ex) { - regionContainer = null; - return; - } - } else { - try { - regionContainer = ((WorldGuardPlugin) worldGuardPlugin).getClass().getMethod("getRegionContainer").invoke(((WorldGuardPlugin) worldGuardPlugin)); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException - | NoSuchMethodException | SecurityException e) { - e.printStackTrace(); - return; - } - try { - regionContainerGetMethod = regionContainer.getClass().getMethod("get", World.class); - } catch (Exception ex) { - regionContainer = null; - return; - } - } - try { - Class vectorClass = Class.forName("com.sk89q.worldedit.Vector"); - vectorConstructor = vectorClass.getConstructor(Double.TYPE, Double.TYPE, Double.TYPE); - regionManagerGetMethod = RegionManager.class.getMethod("getApplicableRegions", vectorClass); - } catch (Exception ex) { - try { - Class vectorClass = Class.forName("com.sk89q.worldedit.math.BlockVector3"); - vectorConstructorMethod = vectorClass.getMethod("at", Double.TYPE, Double.TYPE, Double.TYPE); - regionManagerGetMethod = RegionManager.class.getMethod("getApplicableRegions", vectorClass); - } catch (Exception sodonewiththis) { - regionContainer = null; - return; - } - } - enabled = worldGuardPlugin != null || worldGuard != null; - } - - public RegionManager getRegionManager(World world) { - if (regionContainer == null || regionContainerGetMethod == null) return null; - RegionManager regionManager = null; - try { - if (worldAdaptMethod != null) { - Object worldEditWorld = worldAdaptMethod.invoke(null, world); - regionManager = (RegionManager)regionContainerGetMethod.invoke(regionContainer, worldEditWorld); - } else { - regionManager = (RegionManager)regionContainerGetMethod.invoke(regionContainer, world); - } - } catch (Exception e) {} - return regionManager; - } - - public ApplicableRegionSet getRegionSet(Location location) { - RegionManager regionManager = getRegionManager(location.getWorld()); - if (regionManager == null) return null; - try { - Object vector = vectorConstructorMethod == null - ? vectorConstructor.newInstance(location.getX(), location.getY(), location.getZ()) - : vectorConstructorMethod.invoke(null, location.getX(), location.getY(), location.getZ()); - return (ApplicableRegionSet)regionManagerGetMethod.invoke(regionManager, vector); - } catch (Exception ex) { - - } - return null; - } - - @Override - public CompatRegion[] getApplicableRegions(Location loc) { - List list = new ArrayList<>(); - for (ProtectedRegion r: getRegionSet(loc)) { - list.add(new CompatRegion(r.getId())); - } - return list.toArray(new CompatRegion[list.size()]); - } - - @Override - public boolean isEnabled() { - return enabled; - } -} +package com.moneybags.tempfly.hook.region.plugins; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.plugin.Plugin; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.hook.region.CompatRegion; +import com.moneybags.tempfly.hook.region.RegionProvider; +import com.sk89q.worldguard.bukkit.WorldGuardPlugin; +import com.sk89q.worldguard.protection.ApplicableRegionSet; +import com.sk89q.worldguard.protection.managers.RegionManager; +import com.sk89q.worldguard.protection.regions.ProtectedRegion; + +public class WorldGuardHook implements RegionProvider { + + private boolean enabled; + + private static Object worldGuard = null; + private static Object worldGuardPlugin = null; + private static Object regionContainer = null; + private static Method regionContainerGetMethod = null; + private static Method worldAdaptMethod = null; + private static Method regionManagerGetMethod = null; + private static Constructor vectorConstructor = null; + private static Method vectorConstructorMethod = null; + + public WorldGuardHook(TempFly tempfly) { + try { + Class worldGuardClass = Class.forName("com.sk89q.worldguard.WorldGuard"); + Method getInstanceMethod = worldGuardClass.getMethod("getInstance"); + worldGuard = getInstanceMethod.invoke(null); + } catch (Exception ex) { + Plugin plugin = tempfly.getServer().getPluginManager().getPlugin("WorldGuard"); + if (plugin == null || !(plugin instanceof WorldGuardPlugin)) { + return; + } + worldGuardPlugin = (WorldGuardPlugin) plugin; + } + if (worldGuard != null) { + try { + Method getPlatFormMethod = worldGuard.getClass().getMethod("getPlatform"); + Object platform = getPlatFormMethod.invoke(worldGuard); + Method getRegionContainerMethod = platform.getClass().getMethod("getRegionContainer"); + regionContainer = getRegionContainerMethod.invoke(platform); + + Class worldEditWorldClass = Class.forName("com.sk89q.worldedit.world.World"); + Class worldEditAdapterClass = Class.forName("com.sk89q.worldedit.bukkit.BukkitAdapter"); + worldAdaptMethod = worldEditAdapterClass.getMethod("adapt", World.class); + regionContainerGetMethod = regionContainer.getClass().getMethod("get", worldEditWorldClass); + } catch (Exception ex) { + regionContainer = null; + return; + } + } else { + try { + regionContainer = ((WorldGuardPlugin) worldGuardPlugin).getClass().getMethod("getRegionContainer").invoke(((WorldGuardPlugin) worldGuardPlugin)); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException + | NoSuchMethodException | SecurityException e) { + e.printStackTrace(); + return; + } + try { + regionContainerGetMethod = regionContainer.getClass().getMethod("get", World.class); + } catch (Exception ex) { + regionContainer = null; + return; + } + } + try { + Class vectorClass = Class.forName("com.sk89q.worldedit.Vector"); + vectorConstructor = vectorClass.getConstructor(Double.TYPE, Double.TYPE, Double.TYPE); + regionManagerGetMethod = RegionManager.class.getMethod("getApplicableRegions", vectorClass); + } catch (Exception ex) { + try { + Class vectorClass = Class.forName("com.sk89q.worldedit.math.BlockVector3"); + vectorConstructorMethod = vectorClass.getMethod("at", Double.TYPE, Double.TYPE, Double.TYPE); + regionManagerGetMethod = RegionManager.class.getMethod("getApplicableRegions", vectorClass); + } catch (Exception sodonewiththis) { + regionContainer = null; + return; + } + } + enabled = worldGuardPlugin != null || worldGuard != null; + } + + public RegionManager getRegionManager(World world) { + if (regionContainer == null || regionContainerGetMethod == null) return null; + RegionManager regionManager = null; + try { + if (worldAdaptMethod != null) { + Object worldEditWorld = worldAdaptMethod.invoke(null, world); + regionManager = (RegionManager)regionContainerGetMethod.invoke(regionContainer, worldEditWorld); + } else { + regionManager = (RegionManager)regionContainerGetMethod.invoke(regionContainer, world); + } + } catch (Exception e) {} + return regionManager; + } + + public ApplicableRegionSet getRegionSet(Location location) { + RegionManager regionManager = getRegionManager(location.getWorld()); + if (regionManager == null) return null; + try { + Object vector = vectorConstructorMethod == null + ? vectorConstructor.newInstance(location.getX(), location.getY(), location.getZ()) + : vectorConstructorMethod.invoke(null, location.getX(), location.getY(), location.getZ()); + return (ApplicableRegionSet)regionManagerGetMethod.invoke(regionManager, vector); + } catch (Exception ex) { + + } + return null; + } + + @Override + public CompatRegion[] getApplicableRegions(Location loc) { + List list = new ArrayList<>(); + for (ProtectedRegion r: getRegionSet(loc)) { + list.add(new CompatRegion(r.getId())); + } + return list.toArray(new CompatRegion[list.size()]); + } + + @Override + public boolean isEnabled() { + return enabled; + } +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/skyblock/CmdIslandSettings.java b/src/com/moneybags/tempfly/hook/skyblock/CmdIslandSettings.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/hook/skyblock/CmdIslandSettings.java rename to src/com/moneybags/tempfly/hook/skyblock/CmdIslandSettings.java index 08d62d2..4f66d83 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/skyblock/CmdIslandSettings.java +++ b/src/com/moneybags/tempfly/hook/skyblock/CmdIslandSettings.java @@ -1,38 +1,38 @@ -package com.moneybags.tempfly.hook.skyblock; - -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TempFlyCommand; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class CmdIslandSettings extends TempFlyCommand { - - public CmdIslandSettings(TempFly tempfly, String[] args) { - super(tempfly, args); - } - - public void executeAs(CommandSender s) { - if (!U.isPlayer(s)) { - U.m(s, V.invalidSender); - return; - } - Player p = (Player) s; - if (!p.hasPermission("tempfly.skyblock.island.settings")) { - U.m(s, V.invalidPermission); - return; - } - new PageIslandSettings(tempfly.getGuiManager().createSession(p)); - } - - @Override - public List getPotentialArguments(CommandSender s) { - // TODO Auto-generated method stub - return null; - } - -} +package com.moneybags.tempfly.hook.skyblock; + +import java.util.List; + +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TempFlyCommand; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class CmdIslandSettings extends TempFlyCommand { + + public CmdIslandSettings(TempFly tempfly, String[] args) { + super(tempfly, args); + } + + public void executeAs(CommandSender s) { + if (!U.isPlayer(s)) { + U.m(s, V.invalidSender); + return; + } + Player p = (Player) s; + if (!p.hasPermission("tempfly.skyblock.island.settings")) { + U.m(s, V.invalidPermission); + return; + } + new PageIslandSettings(tempfly.getGuiManager().createSession(p)); + } + + @Override + public List getPotentialArguments(CommandSender s) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/skyblock/IslandWrapper.java b/src/com/moneybags/tempfly/hook/skyblock/IslandWrapper.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/hook/skyblock/IslandWrapper.java rename to src/com/moneybags/tempfly/hook/skyblock/IslandWrapper.java index 45e2b83..35b0006 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/skyblock/IslandWrapper.java +++ b/src/com/moneybags/tempfly/hook/skyblock/IslandWrapper.java @@ -1,38 +1,38 @@ -package com.moneybags.tempfly.hook.skyblock; - -import com.moneybags.tempfly.hook.IslandSettings; -import com.moneybags.tempfly.hook.TerritoryWrapper; - -public class IslandWrapper implements TerritoryWrapper { - - private SkyblockHook hook; - private Object island; - private IslandSettings settings; - - public IslandWrapper(Object island, SkyblockHook hook) { - this.island = island; - this.hook = hook; - this.settings = new IslandSettings(this, hook); - } - - @Override - public Object getRawTerritory() { - return island; - } - - /** - * Retain compatibility with versions before TerritoryHook was added - * @return The raw island Object from the respective skyblock plugin. - */ - public Object getRawIsland() { - return getRawTerritory(); - } - - public SkyblockHook getHook() { - return hook; - } - - public IslandSettings getSettings() { - return settings; - } -} +package com.moneybags.tempfly.hook.skyblock; + +import com.moneybags.tempfly.hook.IslandSettings; +import com.moneybags.tempfly.hook.TerritoryWrapper; + +public class IslandWrapper implements TerritoryWrapper { + + private SkyblockHook hook; + private Object island; + private IslandSettings settings; + + public IslandWrapper(Object island, SkyblockHook hook) { + this.island = island; + this.hook = hook; + this.settings = new IslandSettings(this, hook); + } + + @Override + public Object getRawTerritory() { + return island; + } + + /** + * Retain compatibility with versions before TerritoryHook was added + * @return The raw island Object from the respective skyblock plugin. + */ + public Object getRawIsland() { + return getRawTerritory(); + } + + public SkyblockHook getHook() { + return hook; + } + + public IslandSettings getSettings() { + return settings; + } +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/skyblock/PageIslandSettings.java b/src/com/moneybags/tempfly/hook/skyblock/PageIslandSettings.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/hook/skyblock/PageIslandSettings.java rename to src/com/moneybags/tempfly/hook/skyblock/PageIslandSettings.java index 24d4a78..5aa9d02 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/skyblock/PageIslandSettings.java +++ b/src/com/moneybags/tempfly/hook/skyblock/PageIslandSettings.java @@ -1,134 +1,134 @@ -package com.moneybags.tempfly.hook.skyblock; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import com.moneybags.tempfly.gui.GuiSession; -import com.moneybags.tempfly.gui.abstraction.DynamicPage; -import com.moneybags.tempfly.hook.IslandSettings; -import com.moneybags.tempfly.util.CompatMaterial; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.U; - -public class PageIslandSettings extends DynamicPage { - - /** - * - * Static values - * - */ - - private static SkyblockHook hook; - - private static String - title, - allowLore, - disallowLore; - - private static ItemStack - background, - toolbar, - allowed, - disallowed; - - public static void initialize(SkyblockHook skyblockHook) { - hook = skyblockHook; - - FileConfiguration config = hook.getConfig(); - String path = "gui.page.settings"; - - title = U.cc(config.getString(path + ".title", "&dFlight Settings")); - title = U.cc(config.getString(path + ".title", "&dFlight Settings")); - background = U.getConfigItem(config, path + ".background"); - toolbar = U.getConfigItem(config, path + ".toolbar"); - allowed = U.getConfigItem(config, path + ".allowed"); - disallowed = U.getConfigItem(config, path + ".disallowed"); - - CompatMaterial.setType(background, CompatMaterial.GRAY_STAINED_GLASS_PANE); - CompatMaterial.setType(toolbar, CompatMaterial.BLACK_STAINED_GLASS_PANE); - CompatMaterial.setType(allowed, CompatMaterial.LIME_WOOL); - CompatMaterial.setType(disallowed, CompatMaterial.RED_WOOL); - } - - - /** - * - * - * Object - * - * - */ - private Inventory inv; - private Map layout = new HashMap<>(); - - public PageIslandSettings(GuiSession session) { - super(session); - IslandSettings settings = hook.getIslandOwnedBy(session.getPlayer().getUniqueId()).getSettings(); - - this.inv = Bukkit.createInventory(null, 45, U.cc(title)); - - for (int i = 0; i < 36; i++) { - inv.setItem(i, background); - } - for (int i = 36; i < 45; i++) { - inv.setItem(i, toolbar); - } - List> perms = settings.getCurrentState(); - calculateSlots(0, perms.size()); - Iterator itInt = getOpenSlots().iterator(); - Iterator> itPerms = perms.iterator(); - while (itInt.hasNext() && itPerms.hasNext()) { - int slot = itInt.next(); - Entry perm = itPerms.next(); - ItemStack item = perm.getValue() ? allowed.clone() : disallowed.clone(); - ItemMeta meta = item.getItemMeta(); - meta.setDisplayName(meta.getDisplayName().replaceAll("\\{ROLE}", perm.getKey()) - .replaceAll("\\{STATUS}", perm.getValue() ? allowLore : disallowLore)); - if (meta.hasLore()) { - List lore = new ArrayList<>(); - for (String line: meta.getLore()) { - lore.add(line.replaceAll("\\{ROLE}", perm.getKey()) - .replaceAll("\\{STATUS}", perm.getValue() ? allowLore : disallowLore)); - } - meta.setLore(lore); - } - item.setItemMeta(meta); - inv.setItem(slot, item); - Console.debug("putting: " + slot + " : " + perm.getKey()); - layout.put(slot, perm.getKey()); - } - - session.newPage(this, inv); - } - - @Override - public void runPage(int slot, InventoryClickEvent e) { - if (!layout.containsKey(slot)) { - return; - } - Player p = session.getPlayer(); - IslandWrapper island = hook.getIslandOwnedBy(p.getUniqueId()); - if (island == null) { - U.m(p, hook.requireIsland); - session.endSession(); - return; - } - Console.debug("clicked: " + slot); - Console.debug("oi: " + layout.get(slot)); - IslandSettings settings = island.getSettings(); - String rank = layout.get(slot); - settings.toggleCanFly(rank); - new PageIslandSettings(session); - } -} +package com.moneybags.tempfly.hook.skyblock; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import com.moneybags.tempfly.gui.GuiSession; +import com.moneybags.tempfly.gui.abstraction.DynamicPage; +import com.moneybags.tempfly.hook.IslandSettings; +import com.moneybags.tempfly.util.CompatMaterial; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.U; + +public class PageIslandSettings extends DynamicPage { + + /** + * + * Static values + * + */ + + private static SkyblockHook hook; + + private static String + title, + allowLore, + disallowLore; + + private static ItemStack + background, + toolbar, + allowed, + disallowed; + + public static void initialize(SkyblockHook skyblockHook) { + hook = skyblockHook; + + FileConfiguration config = hook.getConfig(); + String path = "gui.page.settings"; + + title = U.cc(config.getString(path + ".title", "&dFlight Settings")); + title = U.cc(config.getString(path + ".title", "&dFlight Settings")); + background = U.getConfigItem(config, path + ".background"); + toolbar = U.getConfigItem(config, path + ".toolbar"); + allowed = U.getConfigItem(config, path + ".allowed"); + disallowed = U.getConfigItem(config, path + ".disallowed"); + + CompatMaterial.setType(background, CompatMaterial.GRAY_STAINED_GLASS_PANE); + CompatMaterial.setType(toolbar, CompatMaterial.BLACK_STAINED_GLASS_PANE); + CompatMaterial.setType(allowed, CompatMaterial.LIME_WOOL); + CompatMaterial.setType(disallowed, CompatMaterial.RED_WOOL); + } + + + /** + * + * + * Object + * + * + */ + private Inventory inv; + private Map layout = new HashMap<>(); + + public PageIslandSettings(GuiSession session) { + super(session); + IslandSettings settings = hook.getIslandOwnedBy(session.getPlayer().getUniqueId()).getSettings(); + + this.inv = Bukkit.createInventory(null, 45, U.cc(title)); + + for (int i = 0; i < 36; i++) { + inv.setItem(i, background); + } + for (int i = 36; i < 45; i++) { + inv.setItem(i, toolbar); + } + List> perms = settings.getCurrentState(); + calculateSlots(0, perms.size()); + Iterator itInt = getOpenSlots().iterator(); + Iterator> itPerms = perms.iterator(); + while (itInt.hasNext() && itPerms.hasNext()) { + int slot = itInt.next(); + Entry perm = itPerms.next(); + ItemStack item = perm.getValue() ? allowed.clone() : disallowed.clone(); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(meta.getDisplayName().replaceAll("\\{ROLE}", perm.getKey()) + .replaceAll("\\{STATUS}", perm.getValue() ? allowLore : disallowLore)); + if (meta.hasLore()) { + List lore = new ArrayList<>(); + for (String line: meta.getLore()) { + lore.add(line.replaceAll("\\{ROLE}", perm.getKey()) + .replaceAll("\\{STATUS}", perm.getValue() ? allowLore : disallowLore)); + } + meta.setLore(lore); + } + item.setItemMeta(meta); + inv.setItem(slot, item); + Console.debug("putting: " + slot + " : " + perm.getKey()); + layout.put(slot, perm.getKey()); + } + + session.newPage(this, inv); + } + + @Override + public void runPage(int slot, InventoryClickEvent e) { + if (!layout.containsKey(slot)) { + return; + } + Player p = session.getPlayer(); + IslandWrapper island = hook.getIslandOwnedBy(p.getUniqueId()); + if (island == null) { + U.m(p, hook.requireIsland); + session.endSession(); + return; + } + Console.debug("clicked: " + slot); + Console.debug("oi: " + layout.get(slot)); + IslandSettings settings = island.getSettings(); + String rank = layout.get(slot); + settings.toggleCanFly(rank); + new PageIslandSettings(session); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/skyblock/SettingsProvider.java b/src/com/moneybags/tempfly/hook/skyblock/SettingsProvider.java similarity index 94% rename from TempFly/src/com/moneybags/tempfly/hook/skyblock/SettingsProvider.java rename to src/com/moneybags/tempfly/hook/skyblock/SettingsProvider.java index 0ac9f88..6009527 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/skyblock/SettingsProvider.java +++ b/src/com/moneybags/tempfly/hook/skyblock/SettingsProvider.java @@ -1,7 +1,7 @@ -package com.moneybags.tempfly.hook.skyblock; - -public interface SettingsProvider { - - public boolean canFly(String role); - -} +package com.moneybags.tempfly.hook.skyblock; + +public interface SettingsProvider { + + public boolean canFly(String role); + +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/skyblock/SkyblockChallenge.java b/src/com/moneybags/tempfly/hook/skyblock/SkyblockChallenge.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/hook/skyblock/SkyblockChallenge.java rename to src/com/moneybags/tempfly/hook/skyblock/SkyblockChallenge.java index dc4496a..ee66b67 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/skyblock/SkyblockChallenge.java +++ b/src/com/moneybags/tempfly/hook/skyblock/SkyblockChallenge.java @@ -1,32 +1,32 @@ -package com.moneybags.tempfly.hook.skyblock; - -public class SkyblockChallenge { - - private String name; - private int progress; - private int completed; - - public SkyblockChallenge(String name, int progress, int completed) { - this.name = name; - this.progress = progress; - this.completed = completed; - } - - public String getName() { - return name; - } - - public int getRequiredProgress() { - return progress; - } - - public int getRequiredCompletions() { - return completed; - } - - @Override - public String toString() { - return "[SkyblockChallenge] Name: (" + name + ") | RequiredProgress: (" + progress + ") | RequiredCompletions: (" + completed + ")"; - } - -} +package com.moneybags.tempfly.hook.skyblock; + +public class SkyblockChallenge { + + private String name; + private int progress; + private int completed; + + public SkyblockChallenge(String name, int progress, int completed) { + this.name = name; + this.progress = progress; + this.completed = completed; + } + + public String getName() { + return name; + } + + public int getRequiredProgress() { + return progress; + } + + public int getRequiredCompletions() { + return completed; + } + + @Override + public String toString() { + return "[SkyblockChallenge] Name: (" + name + ") | RequiredProgress: (" + progress + ") | RequiredCompletions: (" + completed + ")"; + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/skyblock/SkyblockHook.java b/src/com/moneybags/tempfly/hook/skyblock/SkyblockHook.java similarity index 97% rename from TempFly/src/com/moneybags/tempfly/hook/skyblock/SkyblockHook.java rename to src/com/moneybags/tempfly/hook/skyblock/SkyblockHook.java index 791cfc8..9e8d656 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/skyblock/SkyblockHook.java +++ b/src/com/moneybags/tempfly/hook/skyblock/SkyblockHook.java @@ -1,790 +1,790 @@ -package com.moneybags.tempfly.hook.skyblock; - -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.command.TempFlyCommand; -import com.moneybags.tempfly.fly.result.FlightResult; -import com.moneybags.tempfly.fly.result.FlightResult.DenyReason; -import com.moneybags.tempfly.fly.result.ResultAllow; -import com.moneybags.tempfly.fly.result.ResultDeny; -import com.moneybags.tempfly.hook.IslandSettings; -import com.moneybags.tempfly.hook.TerritoryHook; -import com.moneybags.tempfly.hook.TerritoryWrapper; -import com.moneybags.tempfly.hook.HookManager.Genre; -import com.moneybags.tempfly.hook.region.CompatRegion; -import com.moneybags.tempfly.user.FlightUser; -import com.moneybags.tempfly.util.CompatMaterial; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -/** - * SkyblockHook is a class that represents an object who's purpose is to introduce - * flight requirements centered around a skyblock plugin. The logic, config, data and requirements - * are all taken care of for you. simply extend the class and do the following; - * - * 1) Fill in the abstract methods introduced by this class, do not return null unless it is otherwise specified you may do so. - * 2) Invoke the super methods onIslandEnter and onIslandExit when players enter and leave islands as well as onIslandLevelChange and onChallengeComplete. - * 3) Profit? - */ -public abstract class SkyblockHook extends TerritoryHook { - - private Map basePerms; - private boolean wilderness, settingsHook; - private ItemStack settingsButton; - public String - requireIsland, - requireLevelSelf, - requireLevelOther, - requireChallengeSelf, - requireChallengeOther, - roleDenied; - - - private Map requirements; - - public SkyblockHook(TempFly plugin) { - super(plugin); - } - - @Override - public void onTempflyReload() { - super.onTempflyReload(); - - loadValues(); - for (Player player: Bukkit.getOnlinePlayers()) { - evaluate(player); - } - } - - - - @Override - public boolean needsDataFile() { - return true; - } - - @Override - public boolean forceYaml() { - return true; - } - - @Override - public boolean initializeFiles() throws Exception { - if (!super.initializeFiles()) { - return false; - } - //tempfly.getDataBridge().initializeHookData(this, DataTable.ISLAND_SETTINGS); - return true; - } - - @Override - public boolean initializeHook() { - loadValues(); - return true; - } - - - public void loadValues() { - Console.debug("", "----Loading Skyblock Settings----"); - FileConfiguration config = getConfig(); - basePerms = new HashMap<>(); - requirements = new HashMap<>(); - this.wilderness = config.getBoolean("flight_settings.wilderness"); - String pathPerms = "flight_settings.base_permissions"; - ConfigurationSection csPerms = config.getConfigurationSection(pathPerms); - if (csPerms != null) { - for (String key: csPerms.getKeys(false)) { - Console.debug("--| Loading default role permission: " + key); - basePerms.put(key.toUpperCase(), config.getBoolean(pathPerms + "." + key)); - } - } - - String name = getConfigName(); - requireIsland = V.st(config, "language.invalid.island", name); - requireChallengeSelf = V.st(config, "language.requirements.challenge_self", name); - requireChallengeOther = V.st(config, "language.requirements.challenge_other", name); - requireLevelSelf = V.st(config, "language.requirements.level_self", name); - requireLevelOther = V.st(config, "language.requirements.level_other", name); - roleDenied = V.st(config, "language.requirements.role_denied", name); - - settingsHook = config.getBoolean("gui.hook_settings.enabled"); - settingsButton = U.getConfigItem(config, "gui.hook_settings.button"); - CompatMaterial.setType(settingsButton, CompatMaterial.FEATHER); - - if (config.contains("unlockables.environment.wilderness")) { - Console.debug("", "<< Loading wilderness requirements >>"); - requirements.put(SkyblockRequirementType.WILDERNESS, new SkyblockRequirement[] { - loadRequirement(config, null, "unlockables.environment.wilderness", SkyblockRequirementType.WILDERNESS) - }); - } - - ConfigurationSection csRequireWorld = config.getConfigurationSection("unlockables.environment.worlds"); - if (csRequireWorld != null) { - Console.debug("", "<< Loading world requirements >>"); - List list = new ArrayList<>(); - for (String world: csRequireWorld.getKeys(false)) { - list.add(loadRequirement(config, world, "unlockables.environment.worlds." + world, SkyblockRequirementType.WORLD)); - } - if (list.size() > 0) { - requirements.put(SkyblockRequirementType.WORLD, list.toArray(new SkyblockRequirement[list.size()])); - } - } - - ConfigurationSection csRequireRegion = config.getConfigurationSection("unlockables.environment.regions"); - if (csRequireRegion != null) { - Console.debug("", "<< Loading region requirements >>"); - List list = new ArrayList<>(); - for (String region: csRequireRegion.getKeys(false)) { - list.add(loadRequirement(config, region, "unlockables.environment.regions." + region, SkyblockRequirementType.REGION)); - } - if (list.size() > 0) { - requirements.put(SkyblockRequirementType.REGION, list.toArray(new SkyblockRequirement[list.size()])); - } - } - - ConfigurationSection csRequireRole = config.getConfigurationSection("unlockables.island_roles"); - if (csRequireRole != null) { - Console.debug("", "<< Loading island_role requirements >>"); - List list = new ArrayList<>(); - for (String role: csRequireRole.getKeys(false)) { - if (!islandRoleExists(role)) {Console.severe("An island role specified in the config does not exist (" + role + "). Skipping...");} - list.add(loadRequirement(config, role.toUpperCase(), "unlockables.island_roles." + role, SkyblockRequirementType.ISLAND_ROLE)); - } - if (list.size() > 0) { - requirements.put(SkyblockRequirementType.ISLAND_ROLE, list.toArray(new SkyblockRequirement[list.size()])); - } - } - Console.debug("----END Skyblock Settings----", ""); - PageIslandSettings.initialize(this); - } - - private SkyblockRequirement loadRequirement(FileConfiguration config, String name, String path, SkyblockRequirementType type) { - return new SkyblockRequirement( - loadChallenges(config, path + ".player_"), loadChallenges(config, path + ".island_"), - loadLevel(config, path + ".player_"), loadLevel(config, path + ".island_"), - name, type); - } - - private double loadLevel(FileConfiguration config, String path) { - double level; - return (level = config.getDouble(path + "level", 0)) > 0 ? level : (level = config.getDouble(path + "worth", 0)) > 0 ? level : config.getDouble(path + "value", 0); - } - - private SkyblockChallenge[] loadChallenges(FileConfiguration config, String path) { - ConfigurationSection csChallenges = config.getConfigurationSection(path + "challenges"); - if (csChallenges == null) { - csChallenges = config.getConfigurationSection(path + "missions"); - path = path + "missions"; - } else { - path = path + "challenges"; - } - List challenges = new ArrayList<>(); - if (config.getStringList(path).size() > 0) { - Console.debug("--|> Challenges are a StringList, Adding challenges based on completion..."); - for (String challenge: config.getStringList(path)) { - challenges.add(new SkyblockChallenge(challenge, 0, 1)); - } - } else if (csChallenges != null) { - for (String key: csChallenges.getKeys(false)) { - Console.debug("--| loading SkyblockChallenge: " + key); - if (config.isConfigurationSection(path + "." + key)) { - Console.debug("--|> Challenge is a ConfigurationSection, Adding progress and completions seperately..."); - challenges.add(new SkyblockChallenge(key, - config.getInt(path + "." + key + ".progress", 0), - config.getInt(path + "." + key + ".completed", 0))); - } else { - Console.debug("--|> Challenge has only a single integer value."); - challenges.add(new SkyblockChallenge(key, - config.getInt(path + "." + key, 0), - config.getInt(path + "." + key, 0))); - } - } - - } - return challenges.size() > 0 ? challenges.toArray(new SkyblockChallenge[challenges.size()]) : null; - } - - /** - * - * Global Values - * - */ - - public boolean hasSettingsHook() { - return settingsHook; - } - - public ItemStack getSettingsButton() { - return settingsButton; - } - - public boolean canFlyWilderness() { - return wilderness; - } - - public Map getDefaults() { - return basePerms; - } - - public boolean hasRequirement(SkyblockRequirementType type) { - return requirements.containsKey(type); - } - - public SkyblockRequirement[] getRequirements(SkyblockRequirementType type) { - return requirements.get(type); - } - - public SkyblockRequirement[] getRequirements(CompatRegion[] regions) { - List found = new ArrayList<>(); - SkyblockRequirement[] iter = getRequirements(SkyblockRequirementType.REGION); - for (CompatRegion region: regions) { - for (SkyblockRequirement require: iter) { - if (region.getId().equals(require.getName())) { - found.add(require); - } - } - } - return found.toArray(new SkyblockRequirement[found.size()]); - } - - public boolean hasRequirement(SkyblockRequirementType type, String name) { - if (!hasRequirement(type)) { - return false; - } - for (SkyblockRequirement require: getRequirements(type)) { - if (require.getName().equals(name.toUpperCase())) { - return true; - } - } - return false; - } - - public SkyblockRequirement getRequirement(SkyblockRequirementType type, String name) { - for (SkyblockRequirement require: getRequirements(type)) { - if (require.getName().equals(name.toUpperCase())) { - return require; - } - } - return null; - } - - - - - public IslandWrapper getIslandWrapper(Object rawIsland) { - return (IslandWrapper) super.getTerritoryWrapper(rawIsland); - } - - /** - * This method is called by the children of SkyblockHook when a player enters an island. - * It will track the island each player is on and handle flight requirements for the player. - * - * @param p The player who entered the island. - * @param rawIsland The raw object representing the island. A wrapper will be created for it. - * @param loc Nullable, The location where the player entered the island. - */ - public void onIslandEnter(Player p, Object rawIsland, Location loc) { - super.onTerritoryEnter(p, rawIsland, loc); - } - - /** - * This method is called by the children of SkyblockHook when a player enters an island. - * It will track the island each player is on and handle flight requirements for the player. - * - * @param p The player who entered the island. - */ - public void onIslandExit(final Player p) { - super.onTerritoryExit(p); - } - - /** - * This method is called by the children of SkyblockHook when an island level is updated or changes. - * It will re-evaluate flight requirements of applicable players. - * - * @param island The island. - */ - public void onIslandLevelChange(IslandWrapper island) { - List members = Arrays.asList(getOnlineMembers(island)); - for (Player p: getPlayersOn(island)) { - if (members.contains(p)) { - continue; - } - FlightUser user = getTempFly().getFlightManager().getUser(p); - user.submitFlightResult(checkRoleRequirements(p.getUniqueId(), island)); - } - for (Player p: members) { - FlightUser user = getTempFly().getFlightManager().getUser(p); - user.submitFlightResult(checkFlightRequirements(p.getUniqueId(), p.getLocation())); - user.evaluateFlightRequirement(this, p.getLocation()); - } - } - - /** - * This method is called by the children of SkyblockHook when a player completes a challenge. - * - * Alternatively it will be called during a multi stage challenge when a player completes a portion - * of a challenge or their progress towards completion changes. - * - * It will re-evaluate flight requirements of the player. - * - * @param island The island. - */ - public void onChallengeComplete(Player p) { - Console.debug("-- On challenge complete ---"); - checkFlightRequirements(p.getUniqueId(), p.getLocation()); - IslandWrapper island = getIslandOwnedBy(p.getUniqueId()); - if (island != null) { - for (Player onIsland: getPlayersOn(island)) { - if (onIsland == null || onIsland.equals(p)) { - continue; - } - Console.debug(onIsland.getName()); - Console.debug(p.getName()); - Console.debug(p == onIsland); - FlightUser user = getTempFly().getFlightManager().getUser(onIsland); - if (user == null) { - //TODO why is this returning null users here. - return; - } - user.submitFlightResult(checkRoleRequirements(onIsland.getUniqueId(), island)); - user.evaluateFlightRequirement(this, onIsland.getLocation()); - } - } - FlightUser user = getTempFly().getFlightManager().getUser(p); - user.submitFlightResult(checkRoleRequirements(p.getUniqueId(), island)); - user.evaluateFlightRequirement(this, p.getLocation()); - - this.getPlayersOn(new IslandWrapper(island, null)); - } - - - @Override - public TerritoryWrapper createTerritoryWrapper(Object rawTerritory, TerritoryHook hook) { - return new IslandWrapper(rawTerritory, this); - } - - - - /** - * - * Island Requirements - * - */ - - - public static enum SkyblockRequirementType { - REGION, - WORLD, - WILDERNESS, - ISLAND_ROLE; - } - - - - public void evaluate(Player p) { - getUser(p).submitFlightResult(checkFlightRequirements(p.getUniqueId(), p.getLocation())); - } - - /** - * Check all requirements for a player including wilderness. - * @param u The player trying to fly - * @param loc The location they are trying to fly at. - * @return The flight result - */ - public FlightResult checkFlightRequirements(UUID u, Location loc) { - Console.debug("", "--- SkyblockHook check flight requirements A ---"); - IslandWrapper island = getIslandAt(loc); - if (island == null) { - Console.debug("--|> Island is null, checking wilderness requirements..."); - return canFlyWilderness() ? - new ResultAllow(this, null, V.requirePassDefault) - : new ResultDeny(DenyReason.DISABLED_REGION, this, InquiryType.OUT_OF_SCOPE, V.requireFailDefault, true); - } - return checkFlightRequirements(u, island); - } - - /** - * Evaluate and update flight restrictions for all players on an island. - * @param island - */ - public void evaluate(IslandWrapper island) { - Console.debug("----- evaluate island -----"); - for (Player player: getPlayersOn(island)) { - Console.debug("--| Player: " + player.getUniqueId()); - FlightUser user = getTempFly().getFlightManager().getUser(player); - if (user == null) { - //TODO why is this returning null users here. - return; - } - user.submitFlightResult(checkRoleRequirements(player.getUniqueId(), island)); - user.evaluateFlightRequirement(this, player.getLocation()); - } - } - - @Override - public FlightResult checkFlightRequirements(UUID playerId, TerritoryWrapper territory) { - return checkFlightRequirements(playerId, (IslandWrapper) territory); - } - - /** - * Check all requirements for a player. - * @param u The player trying to fly - * @param loc The location they are trying to fly at. - * @return The flight result - */ - public FlightResult checkFlightRequirements(UUID u, IslandWrapper island) { - Console.debug("", "--- SkyblockHook check flight requirements B ---"); - if (!isEnabled()) { - Console.debug("--|!!!> Hook is not enabled. Returning allowed flight!"); - return new ResultAllow(this, InquiryType.OUT_OF_SCOPE, V.requirePassDefault); - } - return checkRoleRequirements(u, island); - } - - /** - * Check the role requirements of a player on a specific island. - * @param u - * @param island - * @return - */ - public FlightResult checkRoleRequirements(UUID u, IslandWrapper island) { - String role = getIslandRole(u, island); - IslandSettings settings = island.getSettings(); - if (V.debug) { - Console.debug("", "--- SkyblockHook check role requirements ---", "--| Players Role: " + role, "--| Can role fly: " + settings.canFly(role)); - } - return !settings.canFly(role) ? new ResultDeny(DenyReason.DISABLED_REGION, this, InquiryType.OUT_OF_SCOPE, - roleDenied.replaceAll("\\{ROLE}", role), true) : - (hasRequirement(SkyblockRequirementType.ISLAND_ROLE, role) - ? runRequirement(getRequirement(SkyblockRequirementType.ISLAND_ROLE, role), island, u) - .setInquiryType(InquiryType.OUT_OF_SCOPE) - : new ResultAllow(this, null, V.requirePassDefault)); - } - - /** - * Process the requirements for a player to check if a player can fly on the given island. - * @param ir The requirement to check - * @param island The island the player is trying to fly on. - * @param p The player trying to fly. - * @return The flight result. - */ - public FlightResult runRequirement(SkyblockRequirement ir, IslandWrapper island, UUID u) { - if (V.debug) {Console.debug("", "----- Running island flight requirement -----","--| Name: " + ir.getName(),"--| player level: " + ir.getPlayerLevel(),"--| owner level: " + ir.getOwnerLevel());} - Console.debug("--| Players level: " + getIslandLevel(u)); - if (ir.getPlayerLevel() > 0 && ir.getPlayerLevel() > getIslandLevel(u)) { - if (V.debug) { - Console.debug("--|> Fail island level: " + ir.getPlayerLevel() + " / " + getIslandLevel(u), "-----End flight requirements-----", ""); - } - return new ResultDeny(DenyReason.REQUIREMENT, this, null, requireLevelSelf - .replaceAll("\\{LEVEL}", getFormattedIslandLevel(ir.getPlayerLevel())) - .replaceAll("\\{ROLE}", ir.getName()), true); - } - - if (ir.getOwnerLevel() > 0 && ir.getOwnerLevel() > getIslandLevel(getIslandOwner(island))) { - if (V.debug) { - Console.debug("--|> Fail island level: " + ir.getOwnerLevel() + " / " + getIslandLevel(getIslandOwner(island)), "-----End flight requirements-----", ""); - } - return new ResultDeny(DenyReason.REQUIREMENT, this, null, requireLevelOther - .replaceAll("\\{LEVEL}", getFormattedIslandLevel(ir.getOwnerLevel())) - .replaceAll("\\{ROLE}", ir.getName()), true); - } - - for (SkyblockChallenge challenge : ir.getPlayerChallenges()) { - if (!isChallengeCompleted(u, challenge)) { - if (V.debug) { - Console.debug("--|> Fail island challenge: " + challenge, "-----End flight requirements-----", ""); - } - return new ResultDeny(DenyReason.REQUIREMENT, this, null, requireChallengeSelf - .replaceAll("\\{CHALLENGE}", getChallengeName(challenge)) - .replaceAll("\\{COMPLETIONS}", String.valueOf(challenge.getRequiredCompletions())) - .replaceAll("\\{PROGRESS}", String.valueOf(challenge.getRequiredProgress())) - .replaceAll("\\{ROLE}", ir.getName()), true); - } - } - for (SkyblockChallenge challenge : ir.getOwnerChallenges()) { - if (!isChallengeCompleted(getIslandOwner(island), challenge)) { - if (V.debug) { - Console.debug("--|> Fail island challenge | island owner: " + challenge, "-----End flight requirements-----", ""); - } - return new ResultDeny(DenyReason.REQUIREMENT, this, null, requireChallengeOther - .replaceAll("\\{CHALLENGE}", getChallengeName(challenge)) - .replaceAll("\\{COMPLETIONS}", String.valueOf(challenge.getRequiredCompletions())) - .replaceAll("\\{PROGRESS}", String.valueOf(challenge.getRequiredProgress())) - .replaceAll("\\{ROLE}", ir.getName()), true); - } - } - return new ResultAllow(this, null, V.requirePassDefault); - } - - @Override - public FlightResult handleFlightInquiry(FlightUser user, World world) { - if (!isEnabled() || world == null || !hasRequirement(SkyblockRequirementType.WORLD, world.getName())) { - return new ResultAllow(this, InquiryType.WORLD, V.requirePassDefault); - } - UUID u = user.getPlayer().getUniqueId(); - IslandWrapper homeIsland = getTeamIsland(u); - if (homeIsland == null) { - return new ResultDeny(DenyReason.REQUIREMENT, this, InquiryType.WORLD, requireIsland, true); - } - return runRequirement(getRequirement(SkyblockRequirementType.WORLD, world.getName()), homeIsland, u) - .setInquiryType(InquiryType.WORLD); - } - - @Override - public FlightResult handleFlightInquiry(FlightUser user, CompatRegion r) { - if (!isEnabled() || r == null || !hasRequirement(SkyblockRequirementType.REGION, r.getId())) { - return new ResultAllow(this, InquiryType.REGION, V.requirePassDefault); - } - UUID u = user.getPlayer().getUniqueId(); - IslandWrapper homeIsland = getTeamIsland(u); - if (homeIsland == null) { - return new ResultDeny(DenyReason.REQUIREMENT, this, InquiryType.REGION, requireIsland, true); - } - return runRequirement(getRequirement(SkyblockRequirementType.REGION, r.getId()), homeIsland, u) - .setInquiryType(InquiryType.REGION); - } - - @Override - public FlightResult handleFlightInquiry(FlightUser user, CompatRegion[] regions) { - if (!isEnabled() || regions == null || regions.length == 0 || !hasRequirement(SkyblockRequirementType.REGION)) { - return new ResultAllow(this, InquiryType.REGION, V.requirePassDefault); - } - - UUID u = user.getPlayer().getUniqueId(); - IslandWrapper homeIsland = getTeamIsland(u); - for (SkyblockRequirement rq: getRequirements(regions)) { - if (homeIsland == null) { - return new ResultDeny(DenyReason.REQUIREMENT, this, InquiryType.REGION, requireIsland, true); - } - return runRequirement(rq, homeIsland, u).setInquiryType(InquiryType.REGION); - } - return new ResultAllow(this, InquiryType.REGION, V.requirePassDefault); - } - - @Override - public boolean handles(InquiryType type) { - switch (type) { - case LOCATION: - return true; - case REGION: - case WORLD: - default: - return false; - } - } - - - public void openIslandSettings(Player p) { - new PageIslandSettings(tempfly.getGuiManager().createSession(p)); - } - - - /** - * - * TempFlyHook Inheritance - * - */ - - @Override - public String getEmbeddedConfigName() { - return "skyblock_preset_generic"; - } - - @Override - public Genre getGenre() { - return Genre.SKYBLOCK; - } - - @Override - public String getConfigName() { - return getPluginName(); - } - - @SuppressWarnings("serial") - @Override - public Map> getCommands() { - return new HashMap>() {{ - put("island", CmdIslandSettings.class); - }}; - } - - - - /** - * - * Abstract - * - */ - - public String getFormattedIslandLevel(double level) { - return new DecimalFormat("##.##").format(level); - } - - public String getChallengeName(SkyblockChallenge challenge) { - return challenge.getName(); - } - - - /** - * @param island The island in question. - * @return All the team members that are currently online. - */ - public abstract Player[] getOnlineMembers(IslandWrapper island); - - /** - * @param island The island in question - * @return All team members of the island. - */ - public abstract UUID[] getIslandMembers(IslandWrapper island); - - /** - * @param p The player who owns the island or is the primary leader. - * @return The island owned by the player or null if they dont own an island. - */ - public abstract IslandWrapper getIslandOwnedBy(UUID playerId); - - /** - * - * @param id The uuid of the player - * @return The island they are a member of, null if there isnt one. - */ - public abstract IslandWrapper getTeamIsland(UUID playerId); - - /** - * - * @param loc The location. - * @return The island at the location, null if there isn't one. - */ - public abstract IslandWrapper getIslandAt(Location loc); - - @Override - public TerritoryWrapper getTerritoryAt(Location loc) { - return getIslandAt(loc); - } - - /** - * @param loc The location to check. - * @return True if the world given contains islands. - */ - public abstract boolean isIslandWorld(Location loc); - - /** - * - * @param id The player - * @param challenge The name of the challenge - * @return true if the challenge has been completed, false if not completed or if it doesn't exist. - */ - public abstract boolean isChallengeCompleted(UUID playerId, SkyblockChallenge challenge); - - /** - * Check if an island has this role present. Island is included as a parameter to support - * the ability for certain islands to have extra roles in plugins where permission nodes may be more - * complex, and can be added by the island owner at will. - * @param role The role to check - * @return True if the island has this role. - */ - public abstract boolean islandRoleExists(IslandWrapper island, String role); - - /** - * Check if an island role exists in this skyblock plugin. If this plugin supports potentially unlimited - * roles just return true, the method islandRoleExists(UUID, IslandWrapper) will be used on top of this - * to check if roles exist during gameplay. - * @param role The role to check - * @return True if the island has this role. - */ - public abstract boolean islandRoleExists(String role); - - /** - * - * @param island The island - * @param p The player - * @return The name of the players role on the given island. - */ - public abstract String getIslandRole(UUID playerId, IslandWrapper island); - - /** - * - * @param island The island - * @return The UUID of the island owner. Null if there isn't an owner. - */ - public abstract UUID getIslandOwner(IslandWrapper island); - - /** - * The unique identifier of the island. - * Something like the location of the island maybe, not the owner though as that is subject to change - * and some plugins may allow the player to have multiple islands. They would overwrite each other. - * @param island The island - * @return The string identifier of this island to be used for data storage. - */ - public abstract String getIslandIdentifier(Object rawIsland); - - @Override - public String getTerritoryIdentifier(Object rawTerritory) { - return getIslandIdentifier(rawTerritory); - } - - /** - * Get an island from its identifier. - * @param identifier - * @return The island associated with the unique identifier or null if there isnt one. - */ - public abstract IslandWrapper getIslandFromIdentifier(String identifier); - - /** - * As plugins may differ vastly in their permissions and team structure, it is up to you to tell me - * whether this is true or not. For instance in ASkyBlock a coop player is not technically a team member but - * perhaps in a custom skyblock plugin two coop islands merge into one temporarily, meaning they may technically be a team? - * - * @param island The island - * @param p The player - * @return True if the player is a member of the island in any way. - */ - public abstract boolean isIslandMember(UUID playerId, IslandWrapper island); - - /** - * - * @param owner The player who's island is to be checked - * @return The island level of the player. - */ - public abstract double getIslandLevel(UUID playerId); - - /** - * - * @param island The island to be checked - * @return the island level - */ - public abstract double getIslandLevel(IslandWrapper island); - - /** - * Return all the base roles of the skyblock plugin, for instance; OWNER, TEAM, VISITOR, COOP... - * @return - */ - public abstract String[] getRoles(); - - /** - * - * @return True if the location specified is within the boundries of the island given. - */ - public abstract boolean isInIsland(IslandWrapper island, Location loc); - - @Override - public boolean isInTerritory(TerritoryWrapper territory, Location loc) { - return isInIsland((IslandWrapper) territory, loc); - } - -} +package com.moneybags.tempfly.hook.skyblock; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.command.TempFlyCommand; +import com.moneybags.tempfly.fly.result.FlightResult; +import com.moneybags.tempfly.fly.result.FlightResult.DenyReason; +import com.moneybags.tempfly.fly.result.ResultAllow; +import com.moneybags.tempfly.fly.result.ResultDeny; +import com.moneybags.tempfly.hook.IslandSettings; +import com.moneybags.tempfly.hook.TerritoryHook; +import com.moneybags.tempfly.hook.TerritoryWrapper; +import com.moneybags.tempfly.hook.HookManager.Genre; +import com.moneybags.tempfly.hook.region.CompatRegion; +import com.moneybags.tempfly.user.FlightUser; +import com.moneybags.tempfly.util.CompatMaterial; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +/** + * SkyblockHook is a class that represents an object who's purpose is to introduce + * flight requirements centered around a skyblock plugin. The logic, config, data and requirements + * are all taken care of for you. simply extend the class and do the following; + * + * 1) Fill in the abstract methods introduced by this class, do not return null unless it is otherwise specified you may do so. + * 2) Invoke the super methods onIslandEnter and onIslandExit when players enter and leave islands as well as onIslandLevelChange and onChallengeComplete. + * 3) Profit? + */ +public abstract class SkyblockHook extends TerritoryHook { + + private Map basePerms; + private boolean wilderness, settingsHook; + private ItemStack settingsButton; + public String + requireIsland, + requireLevelSelf, + requireLevelOther, + requireChallengeSelf, + requireChallengeOther, + roleDenied; + + + private Map requirements; + + public SkyblockHook(TempFly plugin) { + super(plugin); + } + + @Override + public void onTempflyReload() { + super.onTempflyReload(); + + loadValues(); + for (Player player: Bukkit.getOnlinePlayers()) { + evaluate(player); + } + } + + + + @Override + public boolean needsDataFile() { + return true; + } + + @Override + public boolean forceYaml() { + return true; + } + + @Override + public boolean initializeFiles() throws Exception { + if (!super.initializeFiles()) { + return false; + } + //tempfly.getDataBridge().initializeHookData(this, DataTable.ISLAND_SETTINGS); + return true; + } + + @Override + public boolean initializeHook() { + loadValues(); + return true; + } + + + public void loadValues() { + Console.debug("", "----Loading Skyblock Settings----"); + FileConfiguration config = getConfig(); + basePerms = new HashMap<>(); + requirements = new HashMap<>(); + this.wilderness = config.getBoolean("flight_settings.wilderness"); + String pathPerms = "flight_settings.base_permissions"; + ConfigurationSection csPerms = config.getConfigurationSection(pathPerms); + if (csPerms != null) { + for (String key: csPerms.getKeys(false)) { + Console.debug("--| Loading default role permission: " + key); + basePerms.put(key.toUpperCase(), config.getBoolean(pathPerms + "." + key)); + } + } + + String name = getConfigName(); + requireIsland = V.st(config, "language.invalid.island", name); + requireChallengeSelf = V.st(config, "language.requirements.challenge_self", name); + requireChallengeOther = V.st(config, "language.requirements.challenge_other", name); + requireLevelSelf = V.st(config, "language.requirements.level_self", name); + requireLevelOther = V.st(config, "language.requirements.level_other", name); + roleDenied = V.st(config, "language.requirements.role_denied", name); + + settingsHook = config.getBoolean("gui.hook_settings.enabled"); + settingsButton = U.getConfigItem(config, "gui.hook_settings.button"); + CompatMaterial.setType(settingsButton, CompatMaterial.FEATHER); + + if (config.contains("unlockables.environment.wilderness")) { + Console.debug("", "<< Loading wilderness requirements >>"); + requirements.put(SkyblockRequirementType.WILDERNESS, new SkyblockRequirement[] { + loadRequirement(config, null, "unlockables.environment.wilderness", SkyblockRequirementType.WILDERNESS) + }); + } + + ConfigurationSection csRequireWorld = config.getConfigurationSection("unlockables.environment.worlds"); + if (csRequireWorld != null) { + Console.debug("", "<< Loading world requirements >>"); + List list = new ArrayList<>(); + for (String world: csRequireWorld.getKeys(false)) { + list.add(loadRequirement(config, world, "unlockables.environment.worlds." + world, SkyblockRequirementType.WORLD)); + } + if (list.size() > 0) { + requirements.put(SkyblockRequirementType.WORLD, list.toArray(new SkyblockRequirement[list.size()])); + } + } + + ConfigurationSection csRequireRegion = config.getConfigurationSection("unlockables.environment.regions"); + if (csRequireRegion != null) { + Console.debug("", "<< Loading region requirements >>"); + List list = new ArrayList<>(); + for (String region: csRequireRegion.getKeys(false)) { + list.add(loadRequirement(config, region, "unlockables.environment.regions." + region, SkyblockRequirementType.REGION)); + } + if (list.size() > 0) { + requirements.put(SkyblockRequirementType.REGION, list.toArray(new SkyblockRequirement[list.size()])); + } + } + + ConfigurationSection csRequireRole = config.getConfigurationSection("unlockables.island_roles"); + if (csRequireRole != null) { + Console.debug("", "<< Loading island_role requirements >>"); + List list = new ArrayList<>(); + for (String role: csRequireRole.getKeys(false)) { + if (!islandRoleExists(role)) {Console.severe("An island role specified in the config does not exist (" + role + "). Skipping...");} + list.add(loadRequirement(config, role.toUpperCase(), "unlockables.island_roles." + role, SkyblockRequirementType.ISLAND_ROLE)); + } + if (list.size() > 0) { + requirements.put(SkyblockRequirementType.ISLAND_ROLE, list.toArray(new SkyblockRequirement[list.size()])); + } + } + Console.debug("----END Skyblock Settings----", ""); + PageIslandSettings.initialize(this); + } + + private SkyblockRequirement loadRequirement(FileConfiguration config, String name, String path, SkyblockRequirementType type) { + return new SkyblockRequirement( + loadChallenges(config, path + ".player_"), loadChallenges(config, path + ".island_"), + loadLevel(config, path + ".player_"), loadLevel(config, path + ".island_"), + name, type); + } + + private double loadLevel(FileConfiguration config, String path) { + double level; + return (level = config.getDouble(path + "level", 0)) > 0 ? level : (level = config.getDouble(path + "worth", 0)) > 0 ? level : config.getDouble(path + "value", 0); + } + + private SkyblockChallenge[] loadChallenges(FileConfiguration config, String path) { + ConfigurationSection csChallenges = config.getConfigurationSection(path + "challenges"); + if (csChallenges == null) { + csChallenges = config.getConfigurationSection(path + "missions"); + path = path + "missions"; + } else { + path = path + "challenges"; + } + List challenges = new ArrayList<>(); + if (config.getStringList(path).size() > 0) { + Console.debug("--|> Challenges are a StringList, Adding challenges based on completion..."); + for (String challenge: config.getStringList(path)) { + challenges.add(new SkyblockChallenge(challenge, 0, 1)); + } + } else if (csChallenges != null) { + for (String key: csChallenges.getKeys(false)) { + Console.debug("--| loading SkyblockChallenge: " + key); + if (config.isConfigurationSection(path + "." + key)) { + Console.debug("--|> Challenge is a ConfigurationSection, Adding progress and completions seperately..."); + challenges.add(new SkyblockChallenge(key, + config.getInt(path + "." + key + ".progress", 0), + config.getInt(path + "." + key + ".completed", 0))); + } else { + Console.debug("--|> Challenge has only a single integer value."); + challenges.add(new SkyblockChallenge(key, + config.getInt(path + "." + key, 0), + config.getInt(path + "." + key, 0))); + } + } + + } + return challenges.size() > 0 ? challenges.toArray(new SkyblockChallenge[challenges.size()]) : null; + } + + /** + * + * Global Values + * + */ + + public boolean hasSettingsHook() { + return settingsHook; + } + + public ItemStack getSettingsButton() { + return settingsButton; + } + + public boolean canFlyWilderness() { + return wilderness; + } + + public Map getDefaults() { + return basePerms; + } + + public boolean hasRequirement(SkyblockRequirementType type) { + return requirements.containsKey(type); + } + + public SkyblockRequirement[] getRequirements(SkyblockRequirementType type) { + return requirements.get(type); + } + + public SkyblockRequirement[] getRequirements(CompatRegion[] regions) { + List found = new ArrayList<>(); + SkyblockRequirement[] iter = getRequirements(SkyblockRequirementType.REGION); + for (CompatRegion region: regions) { + for (SkyblockRequirement require: iter) { + if (region.getId().equals(require.getName())) { + found.add(require); + } + } + } + return found.toArray(new SkyblockRequirement[found.size()]); + } + + public boolean hasRequirement(SkyblockRequirementType type, String name) { + if (!hasRequirement(type)) { + return false; + } + for (SkyblockRequirement require: getRequirements(type)) { + if (require.getName().equals(name.toUpperCase())) { + return true; + } + } + return false; + } + + public SkyblockRequirement getRequirement(SkyblockRequirementType type, String name) { + for (SkyblockRequirement require: getRequirements(type)) { + if (require.getName().equals(name.toUpperCase())) { + return require; + } + } + return null; + } + + + + + public IslandWrapper getIslandWrapper(Object rawIsland) { + return (IslandWrapper) super.getTerritoryWrapper(rawIsland); + } + + /** + * This method is called by the children of SkyblockHook when a player enters an island. + * It will track the island each player is on and handle flight requirements for the player. + * + * @param p The player who entered the island. + * @param rawIsland The raw object representing the island. A wrapper will be created for it. + * @param loc Nullable, The location where the player entered the island. + */ + public void onIslandEnter(Player p, Object rawIsland, Location loc) { + super.onTerritoryEnter(p, rawIsland, loc); + } + + /** + * This method is called by the children of SkyblockHook when a player enters an island. + * It will track the island each player is on and handle flight requirements for the player. + * + * @param p The player who entered the island. + */ + public void onIslandExit(final Player p) { + super.onTerritoryExit(p); + } + + /** + * This method is called by the children of SkyblockHook when an island level is updated or changes. + * It will re-evaluate flight requirements of applicable players. + * + * @param island The island. + */ + public void onIslandLevelChange(IslandWrapper island) { + List members = Arrays.asList(getOnlineMembers(island)); + for (Player p: getPlayersOn(island)) { + if (members.contains(p)) { + continue; + } + FlightUser user = getTempFly().getFlightManager().getUser(p); + user.submitFlightResult(checkRoleRequirements(p.getUniqueId(), island)); + } + for (Player p: members) { + FlightUser user = getTempFly().getFlightManager().getUser(p); + user.submitFlightResult(checkFlightRequirements(p.getUniqueId(), p.getLocation())); + user.evaluateFlightRequirement(this, p.getLocation()); + } + } + + /** + * This method is called by the children of SkyblockHook when a player completes a challenge. + * + * Alternatively it will be called during a multi stage challenge when a player completes a portion + * of a challenge or their progress towards completion changes. + * + * It will re-evaluate flight requirements of the player. + * + * @param island The island. + */ + public void onChallengeComplete(Player p) { + Console.debug("-- On challenge complete ---"); + checkFlightRequirements(p.getUniqueId(), p.getLocation()); + IslandWrapper island = getIslandOwnedBy(p.getUniqueId()); + if (island != null) { + for (Player onIsland: getPlayersOn(island)) { + if (onIsland == null || onIsland.equals(p)) { + continue; + } + Console.debug(onIsland.getName()); + Console.debug(p.getName()); + Console.debug(p == onIsland); + FlightUser user = getTempFly().getFlightManager().getUser(onIsland); + if (user == null) { + //TODO why is this returning null users here. + return; + } + user.submitFlightResult(checkRoleRequirements(onIsland.getUniqueId(), island)); + user.evaluateFlightRequirement(this, onIsland.getLocation()); + } + } + FlightUser user = getTempFly().getFlightManager().getUser(p); + user.submitFlightResult(checkRoleRequirements(p.getUniqueId(), island)); + user.evaluateFlightRequirement(this, p.getLocation()); + + this.getPlayersOn(new IslandWrapper(island, null)); + } + + + @Override + public TerritoryWrapper createTerritoryWrapper(Object rawTerritory, TerritoryHook hook) { + return new IslandWrapper(rawTerritory, this); + } + + + + /** + * + * Island Requirements + * + */ + + + public static enum SkyblockRequirementType { + REGION, + WORLD, + WILDERNESS, + ISLAND_ROLE; + } + + + + public void evaluate(Player p) { + getUser(p).submitFlightResult(checkFlightRequirements(p.getUniqueId(), p.getLocation())); + } + + /** + * Check all requirements for a player including wilderness. + * @param u The player trying to fly + * @param loc The location they are trying to fly at. + * @return The flight result + */ + public FlightResult checkFlightRequirements(UUID u, Location loc) { + Console.debug("", "--- SkyblockHook check flight requirements A ---"); + IslandWrapper island = getIslandAt(loc); + if (island == null) { + Console.debug("--|> Island is null, checking wilderness requirements..."); + return canFlyWilderness() ? + new ResultAllow(this, null, V.requirePassDefault) + : new ResultDeny(DenyReason.DISABLED_REGION, this, InquiryType.OUT_OF_SCOPE, V.requireFailDefault, true); + } + return checkFlightRequirements(u, island); + } + + /** + * Evaluate and update flight restrictions for all players on an island. + * @param island + */ + public void evaluate(IslandWrapper island) { + Console.debug("----- evaluate island -----"); + for (Player player: getPlayersOn(island)) { + Console.debug("--| Player: " + player.getUniqueId()); + FlightUser user = getTempFly().getFlightManager().getUser(player); + if (user == null) { + //TODO why is this returning null users here. + return; + } + user.submitFlightResult(checkRoleRequirements(player.getUniqueId(), island)); + user.evaluateFlightRequirement(this, player.getLocation()); + } + } + + @Override + public FlightResult checkFlightRequirements(UUID playerId, TerritoryWrapper territory) { + return checkFlightRequirements(playerId, (IslandWrapper) territory); + } + + /** + * Check all requirements for a player. + * @param u The player trying to fly + * @param loc The location they are trying to fly at. + * @return The flight result + */ + public FlightResult checkFlightRequirements(UUID u, IslandWrapper island) { + Console.debug("", "--- SkyblockHook check flight requirements B ---"); + if (!isEnabled()) { + Console.debug("--|!!!> Hook is not enabled. Returning allowed flight!"); + return new ResultAllow(this, InquiryType.OUT_OF_SCOPE, V.requirePassDefault); + } + return checkRoleRequirements(u, island); + } + + /** + * Check the role requirements of a player on a specific island. + * @param u + * @param island + * @return + */ + public FlightResult checkRoleRequirements(UUID u, IslandWrapper island) { + String role = getIslandRole(u, island); + IslandSettings settings = island.getSettings(); + if (V.debug) { + Console.debug("", "--- SkyblockHook check role requirements ---", "--| Players Role: " + role, "--| Can role fly: " + settings.canFly(role)); + } + return !settings.canFly(role) ? new ResultDeny(DenyReason.DISABLED_REGION, this, InquiryType.OUT_OF_SCOPE, + roleDenied.replaceAll("\\{ROLE}", role), true) : + (hasRequirement(SkyblockRequirementType.ISLAND_ROLE, role) + ? runRequirement(getRequirement(SkyblockRequirementType.ISLAND_ROLE, role), island, u) + .setInquiryType(InquiryType.OUT_OF_SCOPE) + : new ResultAllow(this, null, V.requirePassDefault)); + } + + /** + * Process the requirements for a player to check if a player can fly on the given island. + * @param ir The requirement to check + * @param island The island the player is trying to fly on. + * @param p The player trying to fly. + * @return The flight result. + */ + public FlightResult runRequirement(SkyblockRequirement ir, IslandWrapper island, UUID u) { + if (V.debug) {Console.debug("", "----- Running island flight requirement -----","--| Name: " + ir.getName(),"--| player level: " + ir.getPlayerLevel(),"--| owner level: " + ir.getOwnerLevel());} + Console.debug("--| Players level: " + getIslandLevel(u)); + if (ir.getPlayerLevel() > 0 && ir.getPlayerLevel() > getIslandLevel(u)) { + if (V.debug) { + Console.debug("--|> Fail island level: " + ir.getPlayerLevel() + " / " + getIslandLevel(u), "-----End flight requirements-----", ""); + } + return new ResultDeny(DenyReason.REQUIREMENT, this, null, requireLevelSelf + .replaceAll("\\{LEVEL}", getFormattedIslandLevel(ir.getPlayerLevel())) + .replaceAll("\\{ROLE}", ir.getName()), true); + } + + if (ir.getOwnerLevel() > 0 && ir.getOwnerLevel() > getIslandLevel(getIslandOwner(island))) { + if (V.debug) { + Console.debug("--|> Fail island level: " + ir.getOwnerLevel() + " / " + getIslandLevel(getIslandOwner(island)), "-----End flight requirements-----", ""); + } + return new ResultDeny(DenyReason.REQUIREMENT, this, null, requireLevelOther + .replaceAll("\\{LEVEL}", getFormattedIslandLevel(ir.getOwnerLevel())) + .replaceAll("\\{ROLE}", ir.getName()), true); + } + + for (SkyblockChallenge challenge : ir.getPlayerChallenges()) { + if (!isChallengeCompleted(u, challenge)) { + if (V.debug) { + Console.debug("--|> Fail island challenge: " + challenge, "-----End flight requirements-----", ""); + } + return new ResultDeny(DenyReason.REQUIREMENT, this, null, requireChallengeSelf + .replaceAll("\\{CHALLENGE}", getChallengeName(challenge)) + .replaceAll("\\{COMPLETIONS}", String.valueOf(challenge.getRequiredCompletions())) + .replaceAll("\\{PROGRESS}", String.valueOf(challenge.getRequiredProgress())) + .replaceAll("\\{ROLE}", ir.getName()), true); + } + } + for (SkyblockChallenge challenge : ir.getOwnerChallenges()) { + if (!isChallengeCompleted(getIslandOwner(island), challenge)) { + if (V.debug) { + Console.debug("--|> Fail island challenge | island owner: " + challenge, "-----End flight requirements-----", ""); + } + return new ResultDeny(DenyReason.REQUIREMENT, this, null, requireChallengeOther + .replaceAll("\\{CHALLENGE}", getChallengeName(challenge)) + .replaceAll("\\{COMPLETIONS}", String.valueOf(challenge.getRequiredCompletions())) + .replaceAll("\\{PROGRESS}", String.valueOf(challenge.getRequiredProgress())) + .replaceAll("\\{ROLE}", ir.getName()), true); + } + } + return new ResultAllow(this, null, V.requirePassDefault); + } + + @Override + public FlightResult handleFlightInquiry(FlightUser user, World world) { + if (!isEnabled() || world == null || !hasRequirement(SkyblockRequirementType.WORLD, world.getName())) { + return new ResultAllow(this, InquiryType.WORLD, V.requirePassDefault); + } + UUID u = user.getPlayer().getUniqueId(); + IslandWrapper homeIsland = getTeamIsland(u); + if (homeIsland == null) { + return new ResultDeny(DenyReason.REQUIREMENT, this, InquiryType.WORLD, requireIsland, true); + } + return runRequirement(getRequirement(SkyblockRequirementType.WORLD, world.getName()), homeIsland, u) + .setInquiryType(InquiryType.WORLD); + } + + @Override + public FlightResult handleFlightInquiry(FlightUser user, CompatRegion r) { + if (!isEnabled() || r == null || !hasRequirement(SkyblockRequirementType.REGION, r.getId())) { + return new ResultAllow(this, InquiryType.REGION, V.requirePassDefault); + } + UUID u = user.getPlayer().getUniqueId(); + IslandWrapper homeIsland = getTeamIsland(u); + if (homeIsland == null) { + return new ResultDeny(DenyReason.REQUIREMENT, this, InquiryType.REGION, requireIsland, true); + } + return runRequirement(getRequirement(SkyblockRequirementType.REGION, r.getId()), homeIsland, u) + .setInquiryType(InquiryType.REGION); + } + + @Override + public FlightResult handleFlightInquiry(FlightUser user, CompatRegion[] regions) { + if (!isEnabled() || regions == null || regions.length == 0 || !hasRequirement(SkyblockRequirementType.REGION)) { + return new ResultAllow(this, InquiryType.REGION, V.requirePassDefault); + } + + UUID u = user.getPlayer().getUniqueId(); + IslandWrapper homeIsland = getTeamIsland(u); + for (SkyblockRequirement rq: getRequirements(regions)) { + if (homeIsland == null) { + return new ResultDeny(DenyReason.REQUIREMENT, this, InquiryType.REGION, requireIsland, true); + } + return runRequirement(rq, homeIsland, u).setInquiryType(InquiryType.REGION); + } + return new ResultAllow(this, InquiryType.REGION, V.requirePassDefault); + } + + @Override + public boolean handles(InquiryType type) { + switch (type) { + case LOCATION: + return true; + case REGION: + case WORLD: + default: + return false; + } + } + + + public void openIslandSettings(Player p) { + new PageIslandSettings(tempfly.getGuiManager().createSession(p)); + } + + + /** + * + * TempFlyHook Inheritance + * + */ + + @Override + public String getEmbeddedConfigName() { + return "skyblock_preset_generic"; + } + + @Override + public Genre getGenre() { + return Genre.SKYBLOCK; + } + + @Override + public String getConfigName() { + return getPluginName(); + } + + @SuppressWarnings("serial") + @Override + public Map> getCommands() { + return new HashMap>() {{ + put("island", CmdIslandSettings.class); + }}; + } + + + + /** + * + * Abstract + * + */ + + public String getFormattedIslandLevel(double level) { + return new DecimalFormat("##.##").format(level); + } + + public String getChallengeName(SkyblockChallenge challenge) { + return challenge.getName(); + } + + + /** + * @param island The island in question. + * @return All the team members that are currently online. + */ + public abstract Player[] getOnlineMembers(IslandWrapper island); + + /** + * @param island The island in question + * @return All team members of the island. + */ + public abstract UUID[] getIslandMembers(IslandWrapper island); + + /** + * @param p The player who owns the island or is the primary leader. + * @return The island owned by the player or null if they dont own an island. + */ + public abstract IslandWrapper getIslandOwnedBy(UUID playerId); + + /** + * + * @param id The uuid of the player + * @return The island they are a member of, null if there isnt one. + */ + public abstract IslandWrapper getTeamIsland(UUID playerId); + + /** + * + * @param loc The location. + * @return The island at the location, null if there isn't one. + */ + public abstract IslandWrapper getIslandAt(Location loc); + + @Override + public TerritoryWrapper getTerritoryAt(Location loc) { + return getIslandAt(loc); + } + + /** + * @param loc The location to check. + * @return True if the world given contains islands. + */ + public abstract boolean isIslandWorld(Location loc); + + /** + * + * @param id The player + * @param challenge The name of the challenge + * @return true if the challenge has been completed, false if not completed or if it doesn't exist. + */ + public abstract boolean isChallengeCompleted(UUID playerId, SkyblockChallenge challenge); + + /** + * Check if an island has this role present. Island is included as a parameter to support + * the ability for certain islands to have extra roles in plugins where permission nodes may be more + * complex, and can be added by the island owner at will. + * @param role The role to check + * @return True if the island has this role. + */ + public abstract boolean islandRoleExists(IslandWrapper island, String role); + + /** + * Check if an island role exists in this skyblock plugin. If this plugin supports potentially unlimited + * roles just return true, the method islandRoleExists(UUID, IslandWrapper) will be used on top of this + * to check if roles exist during gameplay. + * @param role The role to check + * @return True if the island has this role. + */ + public abstract boolean islandRoleExists(String role); + + /** + * + * @param island The island + * @param p The player + * @return The name of the players role on the given island. + */ + public abstract String getIslandRole(UUID playerId, IslandWrapper island); + + /** + * + * @param island The island + * @return The UUID of the island owner. Null if there isn't an owner. + */ + public abstract UUID getIslandOwner(IslandWrapper island); + + /** + * The unique identifier of the island. + * Something like the location of the island maybe, not the owner though as that is subject to change + * and some plugins may allow the player to have multiple islands. They would overwrite each other. + * @param island The island + * @return The string identifier of this island to be used for data storage. + */ + public abstract String getIslandIdentifier(Object rawIsland); + + @Override + public String getTerritoryIdentifier(Object rawTerritory) { + return getIslandIdentifier(rawTerritory); + } + + /** + * Get an island from its identifier. + * @param identifier + * @return The island associated with the unique identifier or null if there isnt one. + */ + public abstract IslandWrapper getIslandFromIdentifier(String identifier); + + /** + * As plugins may differ vastly in their permissions and team structure, it is up to you to tell me + * whether this is true or not. For instance in ASkyBlock a coop player is not technically a team member but + * perhaps in a custom skyblock plugin two coop islands merge into one temporarily, meaning they may technically be a team? + * + * @param island The island + * @param p The player + * @return True if the player is a member of the island in any way. + */ + public abstract boolean isIslandMember(UUID playerId, IslandWrapper island); + + /** + * + * @param owner The player who's island is to be checked + * @return The island level of the player. + */ + public abstract double getIslandLevel(UUID playerId); + + /** + * + * @param island The island to be checked + * @return the island level + */ + public abstract double getIslandLevel(IslandWrapper island); + + /** + * Return all the base roles of the skyblock plugin, for instance; OWNER, TEAM, VISITOR, COOP... + * @return + */ + public abstract String[] getRoles(); + + /** + * + * @return True if the location specified is within the boundries of the island given. + */ + public abstract boolean isInIsland(IslandWrapper island, Location loc); + + @Override + public boolean isInTerritory(TerritoryWrapper territory, Location loc) { + return isInIsland((IslandWrapper) territory, loc); + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/skyblock/SkyblockRequirement.java b/src/com/moneybags/tempfly/hook/skyblock/SkyblockRequirement.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/hook/skyblock/SkyblockRequirement.java rename to src/com/moneybags/tempfly/hook/skyblock/SkyblockRequirement.java index 8c3533b..6c5c39d 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/skyblock/SkyblockRequirement.java +++ b/src/com/moneybags/tempfly/hook/skyblock/SkyblockRequirement.java @@ -1,71 +1,71 @@ -package com.moneybags.tempfly.hook.skyblock; - -import javax.annotation.Nullable; - -import com.moneybags.tempfly.hook.skyblock.SkyblockHook.SkyblockRequirementType; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; - -public class SkyblockRequirement { - - private SkyblockRequirementType type; - - private double playerLevel; - private double islandLevel; - @Nullable - private SkyblockChallenge[] playerChallenges; - private SkyblockChallenge[] islandChallenges; - @Nullable - private String name; - - public SkyblockRequirement( - SkyblockChallenge[] playerChallenges, SkyblockChallenge[] islandChallenges, - double playerLevel, double islandLevel, - String name, SkyblockRequirementType type) { - this.type = type; - this.name = name; - - this.playerChallenges = playerChallenges == null ? new SkyblockChallenge[0] : playerChallenges; - this.islandChallenges = islandChallenges == null ? new SkyblockChallenge[0] : islandChallenges; - - this.playerLevel = playerLevel; - this.islandLevel = islandLevel; - - if (V.debug) { - Console.debug("---< Name: " + name, - "---< Player challenges: " + U.arrayToString(this.playerChallenges, " |--| "), - "---< Owner_challenges: " + U.arrayToString(this.islandChallenges, " |--| "), - "---< Player_level: " + playerLevel, - "---< Owner_level: " + islandLevel, - ""); - } - } - - @Nullable - public String getName() { - return name; - } - - public double getPlayerLevel() { - return playerLevel; - } - - public double getOwnerLevel() { - return islandLevel; - } - - @Nullable - public SkyblockChallenge[] getPlayerChallenges() { - return playerChallenges; - } - - public SkyblockChallenge[] getOwnerChallenges() { - return islandChallenges; - } - - public SkyblockRequirementType getType() { - return type; - } - -} +package com.moneybags.tempfly.hook.skyblock; + +import javax.annotation.Nullable; + +import com.moneybags.tempfly.hook.skyblock.SkyblockHook.SkyblockRequirementType; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; + +public class SkyblockRequirement { + + private SkyblockRequirementType type; + + private double playerLevel; + private double islandLevel; + @Nullable + private SkyblockChallenge[] playerChallenges; + private SkyblockChallenge[] islandChallenges; + @Nullable + private String name; + + public SkyblockRequirement( + SkyblockChallenge[] playerChallenges, SkyblockChallenge[] islandChallenges, + double playerLevel, double islandLevel, + String name, SkyblockRequirementType type) { + this.type = type; + this.name = name; + + this.playerChallenges = playerChallenges == null ? new SkyblockChallenge[0] : playerChallenges; + this.islandChallenges = islandChallenges == null ? new SkyblockChallenge[0] : islandChallenges; + + this.playerLevel = playerLevel; + this.islandLevel = islandLevel; + + if (V.debug) { + Console.debug("---< Name: " + name, + "---< Player challenges: " + U.arrayToString(this.playerChallenges, " |--| "), + "---< Owner_challenges: " + U.arrayToString(this.islandChallenges, " |--| "), + "---< Player_level: " + playerLevel, + "---< Owner_level: " + islandLevel, + ""); + } + } + + @Nullable + public String getName() { + return name; + } + + public double getPlayerLevel() { + return playerLevel; + } + + public double getOwnerLevel() { + return islandLevel; + } + + @Nullable + public SkyblockChallenge[] getPlayerChallenges() { + return playerChallenges; + } + + public SkyblockChallenge[] getOwnerChallenges() { + return islandChallenges; + } + + public SkyblockRequirementType getType() { + return type; + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/skyblock/plugins/AskyblockHook.java b/src/com/moneybags/tempfly/hook/skyblock/plugins/AskyblockHook.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/hook/skyblock/plugins/AskyblockHook.java rename to src/com/moneybags/tempfly/hook/skyblock/plugins/AskyblockHook.java index 8ed6e6c..560b227 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/skyblock/plugins/AskyblockHook.java +++ b/src/com/moneybags/tempfly/hook/skyblock/plugins/AskyblockHook.java @@ -1,313 +1,313 @@ -package com.moneybags.tempfly.hook.skyblock.plugins; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryOpenEvent; -import org.bukkit.event.player.PlayerRespawnEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.hook.skyblock.IslandWrapper; -import com.moneybags.tempfly.hook.skyblock.SkyblockChallenge; -import com.moneybags.tempfly.hook.skyblock.SkyblockHook; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.U; -import com.wasteofplastic.askyblock.ASkyBlock; -import com.wasteofplastic.askyblock.ASkyBlockAPI; -import com.wasteofplastic.askyblock.Island; -import com.wasteofplastic.askyblock.events.ChallengeCompleteEvent; -import com.wasteofplastic.askyblock.events.IslandEnterEvent; -import com.wasteofplastic.askyblock.events.IslandExitEvent; -import com.wasteofplastic.askyblock.events.IslandPostLevelEvent; - -/** - * - Dev Notes - - * Askyblock contains events for island enter and island exit. Therefore it will not need to initiate the - * super island tracker in SkyblockHook. - * - * @author Kevin - * - */ -public class AskyblockHook extends SkyblockHook implements Listener { - - public static final String[] ROLES = new String[] {"OWNER", "TEAM", "COOP", "VISITOR"}; - - private ASkyBlockAPI api; - private ASkyBlock asky; - - public AskyblockHook(TempFly plugin) { - super(plugin); - } - - @Override - public boolean initializeHook() { - try {this.api = ASkyBlockAPI.getInstance();} catch (Exception e) { - Console.severe("There was an error while initializing the ASkyBlockAPI hook!"); - return false; - } - - this.asky = (ASkyBlock) Bukkit.getPluginManager().getPlugin("ASkyBlock"); - if (this.asky == null) { - Console.severe("There was an error while initializing the ASkyBlock Plugin hook!"); - return false; - } - - if (super.initializeHook()) { - tempfly.getServer().getPluginManager().registerEvents(this, tempfly); - return true; - } - return false; - } - - /** - * - * Event Handling - * - */ - @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void on(InventoryOpenEvent e) { - if (!hasSettingsHook() || !(e.getPlayer() instanceof Player)) { - return; - } - Player p = (Player) e.getPlayer(); - if (!e.getView().getTitle().equals(asky.myLocale(p.getUniqueId()).igsTitle)) { - return; - } - Inventory inv = e.getInventory(); - int empty = inv.firstEmpty(); - boolean open = false; - if (empty < 0) { - open = true; - e.setCancelled(true); - Inventory rebuild = Bukkit.createInventory(null, inv.getSize()+9, asky.myLocale(p.getUniqueId()).igsTitle); - rebuild.setContents(inv.getContents()); - empty = rebuild.firstEmpty(); - inv = rebuild; - } - inv.setItem(empty, getSettingsButton()); - if (open) { - p.openInventory(inv); - } - } - - @EventHandler (priority = EventPriority.NORMAL, ignoreCancelled = false) - public void on(InventoryClickEvent e) { - if (!hasSettingsHook() || !(e.getWhoClicked() instanceof Player)) { - return; - } - Player p = (Player) e.getWhoClicked(); - if (!e.getView().getTitle().equals(asky.myLocale(p.getUniqueId()).igsTitle)) { - return; - } - ItemStack clicked = e.getCurrentItem(); - if (getSettingsButton().isSimilar(clicked)) { - openIslandSettings(p); - } - } - - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = false) - public void on(IslandEnterEvent e) { - Player p = Bukkit.getPlayer(e.getPlayer()); - if (p == null) { - return; - } - Island island = e.getIsland(); - onIslandEnter(p, island, e.getLocation()); - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = false) - public void on(IslandExitEvent e) { - Player p = Bukkit.getPlayer(e.getPlayer()); - if (p == null || !isCurrentlyTracking(p)) { - return; - } - Island rawIsland = api.getIslandAt(p.getLocation()); - if (rawIsland != null) { - onIslandExit(p); - } - } - - /** - * Askyblock does not call the island exit event on player respawn... - * @param e - */ - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = false) - public void on(PlayerRespawnEvent e) { - Player p = e.getPlayer(); - if (!isCurrentlyTracking(p)) { - return; - } - Island rawIsland = api.getIslandAt(p.getLocation()); - Island newIsland = api.getIslandAt(e.getRespawnLocation()); - if (rawIsland != null && !rawIsland.equals(newIsland)) { - onIslandExit(p); - } - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void on(IslandPostLevelEvent e) { - Island rawIsland = e.getIsland(); - IslandWrapper island = getIslandWrapper(rawIsland); - onIslandLevelChange(island); - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void on(ChallengeCompleteEvent e) { - onChallengeComplete(e.getPlayer()); - } - - - /** - * - * TempFlyHook Inheritance - * - */ - - - @Override - public String getPluginName() { - return "ASkyBlock"; - } - - @Override - public String getEmbeddedConfigName() { - return "skyblock_preset_askyblock"; - } - - - /** - * - * SkyblockHook Inheritance - * - */ - - - @Override - public IslandWrapper getIslandOwnedBy(UUID id) { - return getIslandWrapper(api.getIslandOwnedBy(id)); - } - - @Override - public IslandWrapper getIslandAt(Location loc) { - return getIslandWrapper(api.getIslandAt(loc)); - } - - @Override - public boolean isChallengeCompleted(UUID id, SkyblockChallenge challenge) { - return challenge.getRequiredCompletions() == 0 && challenge.getRequiredProgress() == 0 || api.getChallengeStatus(id).getOrDefault(challenge.getName(), false); - } - - @Override - public boolean islandRoleExists(IslandWrapper island, String role) { - return islandRoleExists(role); - } - - @Override - public boolean islandRoleExists(String role) { - for (String s: ROLES) { - if (s.equalsIgnoreCase(role)) { - return true; - } - } - return false; - } - - @Override - public String getIslandRole(UUID u, IslandWrapper island) { - if (!island.getHook().equals(this)) { - return null; - } - Island rawIsland = (Island) island.getRawIsland(); - return rawIsland.getOwner().equals(u) ? "OWNER" : rawIsland.getMembers().contains(u) ? "TEAM" : api.getCoopIslands(Bukkit.getPlayer(u)).contains(api.getIslandLocation(getIslandOwner(island))) ? "COOP" : "VISITOR"; - } - - @Override - public UUID getIslandOwner(IslandWrapper island) { - if (!island.getHook().equals(this)) { - return null; - } - return ((Island) island.getRawIsland()).getOwner(); - } - - @Override - public String getIslandIdentifier(Object rawIsland) { - return U.locationToString( (rawIsland instanceof IslandWrapper) ? - ((Island) ((IslandWrapper) rawIsland).getRawIsland()).getCenter() - : ((Island) rawIsland).getCenter()); - } - - @Override - public IslandWrapper getIslandFromIdentifier(String identifier) { - return getIslandWrapper(api.getIslandAt(U.locationFromString(identifier))); - } - - @Override - public boolean isIslandMember(UUID u, IslandWrapper island) { - if (!island.getHook().equals(this)) { - return false; - } - return ((Island) island.getRawIsland()).getMembers().contains(u); - } - - @Override - public IslandWrapper getTeamIsland(UUID u) { - return getIslandAt(api.getHomeLocation(u)); - } - - @Override - public double getIslandLevel(UUID u) { - return api.getLongIslandLevel(u); - } - - @Override - public double getIslandLevel(IslandWrapper island) { - return api.getLongIslandLevel(getIslandOwner(island)); - } - - - - @Override - public Player[] getOnlineMembers(IslandWrapper island) { - List online = new ArrayList<>(); - for (UUID u: ((Island) island.getRawIsland()).getMembers()) { - Player p = Bukkit.getPlayer(u); - if (p != null) { - online.add(p); - } - } - return online.toArray(new Player[online.size()]); - } - - - - @Override - public UUID[] getIslandMembers(IslandWrapper island) { - List members = ((Island) island.getRawIsland()).getMembers(); - return members.toArray(new UUID[members.size()]); - } - - @Override - public String[] getRoles() { - return ROLES; - } - - @Override - public boolean isIslandWorld(Location loc) { - return loc.getWorld().equals(api.getIslandWorld()) || loc.getWorld().equals(api.getNetherWorld()); - } - - @Override - public boolean isInIsland(IslandWrapper island, Location loc) { - return ((Island)island.getRawIsland()).inIslandSpace(loc); - } -} +package com.moneybags.tempfly.hook.skyblock.plugins; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryOpenEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.hook.skyblock.IslandWrapper; +import com.moneybags.tempfly.hook.skyblock.SkyblockChallenge; +import com.moneybags.tempfly.hook.skyblock.SkyblockHook; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.U; +import com.wasteofplastic.askyblock.ASkyBlock; +import com.wasteofplastic.askyblock.ASkyBlockAPI; +import com.wasteofplastic.askyblock.Island; +import com.wasteofplastic.askyblock.events.ChallengeCompleteEvent; +import com.wasteofplastic.askyblock.events.IslandEnterEvent; +import com.wasteofplastic.askyblock.events.IslandExitEvent; +import com.wasteofplastic.askyblock.events.IslandPostLevelEvent; + +/** + * - Dev Notes - + * Askyblock contains events for island enter and island exit. Therefore it will not need to initiate the + * super island tracker in SkyblockHook. + * + * @author Kevin + * + */ +public class AskyblockHook extends SkyblockHook implements Listener { + + public static final String[] ROLES = new String[] {"OWNER", "TEAM", "COOP", "VISITOR"}; + + private ASkyBlockAPI api; + private ASkyBlock asky; + + public AskyblockHook(TempFly plugin) { + super(plugin); + } + + @Override + public boolean initializeHook() { + try {this.api = ASkyBlockAPI.getInstance();} catch (Exception e) { + Console.severe("There was an error while initializing the ASkyBlockAPI hook!"); + return false; + } + + this.asky = (ASkyBlock) Bukkit.getPluginManager().getPlugin("ASkyBlock"); + if (this.asky == null) { + Console.severe("There was an error while initializing the ASkyBlock Plugin hook!"); + return false; + } + + if (super.initializeHook()) { + tempfly.getServer().getPluginManager().registerEvents(this, tempfly); + return true; + } + return false; + } + + /** + * + * Event Handling + * + */ + @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void on(InventoryOpenEvent e) { + if (!hasSettingsHook() || !(e.getPlayer() instanceof Player)) { + return; + } + Player p = (Player) e.getPlayer(); + if (!e.getView().getTitle().equals(asky.myLocale(p.getUniqueId()).igsTitle)) { + return; + } + Inventory inv = e.getInventory(); + int empty = inv.firstEmpty(); + boolean open = false; + if (empty < 0) { + open = true; + e.setCancelled(true); + Inventory rebuild = Bukkit.createInventory(null, inv.getSize()+9, asky.myLocale(p.getUniqueId()).igsTitle); + rebuild.setContents(inv.getContents()); + empty = rebuild.firstEmpty(); + inv = rebuild; + } + inv.setItem(empty, getSettingsButton()); + if (open) { + p.openInventory(inv); + } + } + + @EventHandler (priority = EventPriority.NORMAL, ignoreCancelled = false) + public void on(InventoryClickEvent e) { + if (!hasSettingsHook() || !(e.getWhoClicked() instanceof Player)) { + return; + } + Player p = (Player) e.getWhoClicked(); + if (!e.getView().getTitle().equals(asky.myLocale(p.getUniqueId()).igsTitle)) { + return; + } + ItemStack clicked = e.getCurrentItem(); + if (getSettingsButton().isSimilar(clicked)) { + openIslandSettings(p); + } + } + + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = false) + public void on(IslandEnterEvent e) { + Player p = Bukkit.getPlayer(e.getPlayer()); + if (p == null) { + return; + } + Island island = e.getIsland(); + onIslandEnter(p, island, e.getLocation()); + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = false) + public void on(IslandExitEvent e) { + Player p = Bukkit.getPlayer(e.getPlayer()); + if (p == null || !isCurrentlyTracking(p)) { + return; + } + Island rawIsland = api.getIslandAt(p.getLocation()); + if (rawIsland != null) { + onIslandExit(p); + } + } + + /** + * Askyblock does not call the island exit event on player respawn... + * @param e + */ + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = false) + public void on(PlayerRespawnEvent e) { + Player p = e.getPlayer(); + if (!isCurrentlyTracking(p)) { + return; + } + Island rawIsland = api.getIslandAt(p.getLocation()); + Island newIsland = api.getIslandAt(e.getRespawnLocation()); + if (rawIsland != null && !rawIsland.equals(newIsland)) { + onIslandExit(p); + } + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void on(IslandPostLevelEvent e) { + Island rawIsland = e.getIsland(); + IslandWrapper island = getIslandWrapper(rawIsland); + onIslandLevelChange(island); + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void on(ChallengeCompleteEvent e) { + onChallengeComplete(e.getPlayer()); + } + + + /** + * + * TempFlyHook Inheritance + * + */ + + + @Override + public String getPluginName() { + return "ASkyBlock"; + } + + @Override + public String getEmbeddedConfigName() { + return "skyblock_preset_askyblock"; + } + + + /** + * + * SkyblockHook Inheritance + * + */ + + + @Override + public IslandWrapper getIslandOwnedBy(UUID id) { + return getIslandWrapper(api.getIslandOwnedBy(id)); + } + + @Override + public IslandWrapper getIslandAt(Location loc) { + return getIslandWrapper(api.getIslandAt(loc)); + } + + @Override + public boolean isChallengeCompleted(UUID id, SkyblockChallenge challenge) { + return challenge.getRequiredCompletions() == 0 && challenge.getRequiredProgress() == 0 || api.getChallengeStatus(id).getOrDefault(challenge.getName(), false); + } + + @Override + public boolean islandRoleExists(IslandWrapper island, String role) { + return islandRoleExists(role); + } + + @Override + public boolean islandRoleExists(String role) { + for (String s: ROLES) { + if (s.equalsIgnoreCase(role)) { + return true; + } + } + return false; + } + + @Override + public String getIslandRole(UUID u, IslandWrapper island) { + if (!island.getHook().equals(this)) { + return null; + } + Island rawIsland = (Island) island.getRawIsland(); + return rawIsland.getOwner().equals(u) ? "OWNER" : rawIsland.getMembers().contains(u) ? "TEAM" : api.getCoopIslands(Bukkit.getPlayer(u)).contains(api.getIslandLocation(getIslandOwner(island))) ? "COOP" : "VISITOR"; + } + + @Override + public UUID getIslandOwner(IslandWrapper island) { + if (!island.getHook().equals(this)) { + return null; + } + return ((Island) island.getRawIsland()).getOwner(); + } + + @Override + public String getIslandIdentifier(Object rawIsland) { + return U.locationToString( (rawIsland instanceof IslandWrapper) ? + ((Island) ((IslandWrapper) rawIsland).getRawIsland()).getCenter() + : ((Island) rawIsland).getCenter()); + } + + @Override + public IslandWrapper getIslandFromIdentifier(String identifier) { + return getIslandWrapper(api.getIslandAt(U.locationFromString(identifier))); + } + + @Override + public boolean isIslandMember(UUID u, IslandWrapper island) { + if (!island.getHook().equals(this)) { + return false; + } + return ((Island) island.getRawIsland()).getMembers().contains(u); + } + + @Override + public IslandWrapper getTeamIsland(UUID u) { + return getIslandAt(api.getHomeLocation(u)); + } + + @Override + public double getIslandLevel(UUID u) { + return api.getLongIslandLevel(u); + } + + @Override + public double getIslandLevel(IslandWrapper island) { + return api.getLongIslandLevel(getIslandOwner(island)); + } + + + + @Override + public Player[] getOnlineMembers(IslandWrapper island) { + List online = new ArrayList<>(); + for (UUID u: ((Island) island.getRawIsland()).getMembers()) { + Player p = Bukkit.getPlayer(u); + if (p != null) { + online.add(p); + } + } + return online.toArray(new Player[online.size()]); + } + + + + @Override + public UUID[] getIslandMembers(IslandWrapper island) { + List members = ((Island) island.getRawIsland()).getMembers(); + return members.toArray(new UUID[members.size()]); + } + + @Override + public String[] getRoles() { + return ROLES; + } + + @Override + public boolean isIslandWorld(Location loc) { + return loc.getWorld().equals(api.getIslandWorld()) || loc.getWorld().equals(api.getNetherWorld()); + } + + @Override + public boolean isInIsland(IslandWrapper island, Location loc) { + return ((Island)island.getRawIsland()).inIslandSpace(loc); + } +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/skyblock/plugins/BentoHook.java b/src/com/moneybags/tempfly/hook/skyblock/plugins/BentoHook.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/hook/skyblock/plugins/BentoHook.java rename to src/com/moneybags/tempfly/hook/skyblock/plugins/BentoHook.java index f863900..d16aa77 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/skyblock/plugins/BentoHook.java +++ b/src/com/moneybags/tempfly/hook/skyblock/plugins/BentoHook.java @@ -1,322 +1,322 @@ -package com.moneybags.tempfly.hook.skyblock.plugins; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.hook.skyblock.IslandWrapper; -import com.moneybags.tempfly.hook.skyblock.SkyblockChallenge; -import com.moneybags.tempfly.hook.skyblock.SkyblockHook; -import com.moneybags.tempfly.util.Console; - -import world.bentobox.bentobox.BentoBox; -import world.bentobox.bentobox.api.addons.Addon; -import world.bentobox.bentobox.api.events.BentoBoxEvent; -import world.bentobox.bentobox.api.events.IslandBaseEvent; -import world.bentobox.bentobox.api.user.User; -import world.bentobox.bentobox.database.objects.Island; - -/** - * BentoBox does not include built in island tracking or events for player location and islands - * so BentoBoxHook will initiate the super tracker in SkyblockHook. - * @author Kevin - * - */ -public abstract class BentoHook extends SkyblockHook implements Listener { - - - public BentoHook(TempFly plugin) { - super(plugin); - } - - @Override - public boolean initializeHook() { - // initial Bento stuff - - // - if (super.initializeHook()) { - getTempFly().getServer().getPluginManager().registerEvents(this, getTempFly()); - startManualTracking(); - return true; - } - return false; - } - - @Override - public String getFormattedIslandLevel(double level) { - Object levels = getLevelsAddon(); - if (levels == null) { - return super.getFormattedIslandLevel(level); - } - try { - Object manager = levels.getClass().getMethod("getManager").invoke(levels); - return (String) manager.getClass().getMethod("formatLevel", Long.class).invoke(manager, (long) level); - } catch (Exception e) { - e.printStackTrace(); - } - return super.getFormattedIslandLevel(level); - } - - @Override - public String getChallengeName(SkyblockChallenge challenge) { - try { - Object challenges = getChallengeAddon(); - if (challenges == null) { - return super.getChallengeName(challenge); - } - Object manager = challenges.getClass().getMethod("getChallengesManager").invoke(challenges); - Object bentoChallenge = manager.getClass().getMethod("getChallenge", String.class).invoke(manager, challenge.getName()); - if (bentoChallenge == null) { - return super.getChallengeName(challenge); - } - return (String) bentoChallenge.getClass().getMethod("getFriendlyName").invoke(bentoChallenge); - } catch (Exception e) { - e.printStackTrace(); - return super.getChallengeName(challenge); - } - } - - @EventHandler - public void on(IslandBaseEvent e) { - Class clazz = e.getClass(); - if (clazz.getSimpleName().equals("IslandLevelCalculatedEvent")) { - Island rawIsland = e.getIsland(); - Bukkit.getScheduler().runTaskLater(getTempFly(), () -> - super.onIslandLevelChange(getIslandWrapper(rawIsland)) - , 1); - } - } - - @EventHandler - public void on(BentoBoxEvent e) { - Console.debug("--- BentoBoxEvent ---"); - Class clazz = e.getClass(); - if (clazz.getSimpleName().equals("ChallengeCompletedEvent")) { - try { - UUID id = (UUID) clazz.getMethod("getPlayerUUID").invoke(e); - Player p = Bukkit.getPlayer(id); - if (p == null) { - return; - } - super.onChallengeComplete(p); - } catch (Exception exception) { exception.printStackTrace();} - } - } - - @Override - public String getPluginName() { - return "BentoBox"; - } - - @Override - public String getEmbeddedConfigName() { - return "skyblock_preset_bento"; - } - - public User getBentoUser(UUID u) { - return BentoBox.getInstance().getPlayers().getUser(u); - } - - public Object getLevelsAddon() { - Optional t = BentoBox.getInstance().getAddonsManager().getAddonByName("Level"); - return t.isPresent() ? t.get() : null; - } - - public Object getChallengeAddon() { - Optional t = BentoBox.getInstance().getAddonsManager().getAddonByName("Challenges"); - return t.isPresent() ? t.get() : null; - } - - @Override - public IslandWrapper getIslandAt(Location loc) { - Optional t = BentoBox.getInstance().getIslands().getIslandAt(loc); - return t.isPresent() ? getIslandWrapper(t.get()) : null; - } - - @Override - public boolean islandRoleExists(IslandWrapper island, String role) { - for (String s: getRoles()) { - if (role.equalsIgnoreCase(s)) { - return true; - } - } - return false; - } - - @Override - public boolean islandRoleExists(String role) { - return islandRoleExists(null, role); - } - - @Override - public String getIslandRole(UUID u, IslandWrapper island) { - String[] split = BentoBox.getInstance().getRanksManager().getRank(((Island) island.getRawIsland()).getRank(u)).split("\\."); - return split.length > 1 ? split[1].toUpperCase() : split[0].toUpperCase(); - } - - @Override - public String[] getRoles() { - List roles = new ArrayList<>(); - for (String role: BentoBox.getInstance().getRanksManager().getRanks().keySet()) { - String[] split = role.split("\\."); - Console.debug("Adding role: " + (split.length > 1 ? split[1].toUpperCase() : split[0].toUpperCase())); - roles.add(split.length > 1 ? split[1].toUpperCase() : split[0].toUpperCase()); - } - return roles.toArray(new String[roles.size()]); - } - - @Override - public UUID getIslandOwner(IslandWrapper island) { - return ((Island) island.getRawIsland()).getOwner(); - } - - @Override - public String getIslandIdentifier(Object rawIsland) { - return ((Island)rawIsland).getUniqueId(); - } - - @Override - public boolean isIslandMember(UUID u, IslandWrapper island) { - return ((Island) island.getRawIsland()).getMembers().containsKey(u); - } - - @Override - public double getIslandLevel(IslandWrapper island) { - Object level = getLevelsAddon(); - if (level == null) { - return 0; - } - - UUID owner = ((Island)island.getRawIsland()).getOwner(); - try {return (double)((long) level.getClass().getMethod("getIslandLevel", World.class, UUID.class) - .invoke(level, getMainIslandWorld(), owner));} catch (Exception e) { - e.printStackTrace(); - return 0; - } - } - - @Override - public Player[] getOnlineMembers(IslandWrapper island) { - Island rawIsland = (Island) island.getRawIsland(); - List online = new ArrayList<>(); - for (UUID u: rawIsland.getMembers().keySet()) { - Player p = Bukkit.getPlayer(u); - if (p != null && p.isOnline()) { - online.add(p); - } - } - return online.toArray(new Player[online.size()]); - } - - @Override - public UUID[] getIslandMembers(IslandWrapper island) { - Island rawIsland = (Island) island.getRawIsland(); - return rawIsland.getMemberSet().toArray(new UUID[rawIsland.getMemberSet().size()]); - } - - @Override - public IslandWrapper getIslandFromIdentifier(String identifier) { - Optional rawIsland = BentoBox.getInstance().getIslands().getIslandById(identifier); - return rawIsland.isPresent() ? getIslandWrapper(rawIsland.get()) : null; - } - - @Override - public boolean isIslandWorld(Location loc) { - return BentoBox.getInstance().getIWM().inWorld(loc); - } - - - @Override - public IslandWrapper getIslandOwnedBy(UUID playerId) { - World world = getMainIslandWorld(); - Island rawIsland = BentoBox.getInstance().getIslands().getIsland(world, playerId); - if (rawIsland == null) { - Console.debug("--|> The player does not have an island in the given world."); - return null; - } - return rawIsland.getOwner().equals(playerId) ? getIslandWrapper(rawIsland) : null; - } - - @Override - public IslandWrapper getTeamIsland(UUID playerId) { - World world = getMainIslandWorld(); - Island rawIsland = BentoBox.getInstance().getIslands().getIsland(world, playerId); - if (rawIsland == null) { - Console.debug("--|> The player does not have an island in the given world."); - return null; - } - return getIslandWrapper(rawIsland); - } - - @Override - public boolean isChallengeCompleted(UUID u, SkyblockChallenge challenge) { - try { - Object challenges = getChallengeAddon(); - if (challenges == null) { - Console.debug("--|> Challenges addon for BentoBox does not exist!"); - return true; - } - Object manager = challenges.getClass().getMethod("getChallengesManager").invoke(challenges); - Object bentoChallenge = manager.getClass().getMethod("getChallenge", String.class).invoke(manager, challenge.getName()); - if (bentoChallenge == null) { - Console.debug("--|> The challenge specified does not exist!"); - return true; - } - User bentoUser = getBentoUser(u); - if (bentoUser == null) { - Console.debug("--|> Players bento user is null!"); - return false; - } - World world = getMainIslandWorld(); - boolean isCompleted = (boolean) manager.getClass().getMethod("isChallengeComplete", User.class, World.class, bentoChallenge.getClass()).invoke(manager, bentoUser, world, bentoChallenge); - Console.debug("--| Challenge: " + challenge.getName(), "--| isCompleted: " + isCompleted); - if (challenge.getRequiredCompletions() == 1 && !isCompleted) { - return false; - } - long completions = (long) manager.getClass().getMethod("getChallengeTimes", User.class, World.class, String.class) - .invoke(manager, bentoUser, getMainIslandWorld(), challenge.getName()); - Console.debug("--| completions: " + completions); - if (challenge.getRequiredCompletions() > 0 && completions < challenge.getRequiredCompletions()) { - return false; - } - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - @Override - public double getIslandLevel(UUID playerId) { - Object levels = getLevelsAddon(); - if (levels == null) { - Console.debug("--|> Levels addon for BentoBox does not exist!"); - return 0; - } - World world = getMainIslandWorld(); - try {return (double) ((long) levels.getClass().getMethod("getIslandLevel", World.class, UUID.class) - .invoke(levels, world, playerId));} catch (Exception e) { - e.printStackTrace(); - return 0; - } - } - - @Override - public boolean isInIsland(IslandWrapper island, Location loc) { - return ((Island)island.getRawIsland()).inIslandSpace(loc); - } - - - public abstract World getMainIslandWorld(); - - -} +package com.moneybags.tempfly.hook.skyblock.plugins; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.hook.skyblock.IslandWrapper; +import com.moneybags.tempfly.hook.skyblock.SkyblockChallenge; +import com.moneybags.tempfly.hook.skyblock.SkyblockHook; +import com.moneybags.tempfly.util.Console; + +import world.bentobox.bentobox.BentoBox; +import world.bentobox.bentobox.api.addons.Addon; +import world.bentobox.bentobox.api.events.BentoBoxEvent; +import world.bentobox.bentobox.api.events.IslandBaseEvent; +import world.bentobox.bentobox.api.user.User; +import world.bentobox.bentobox.database.objects.Island; + +/** + * BentoBox does not include built in island tracking or events for player location and islands + * so BentoBoxHook will initiate the super tracker in SkyblockHook. + * @author Kevin + * + */ +public abstract class BentoHook extends SkyblockHook implements Listener { + + + public BentoHook(TempFly plugin) { + super(plugin); + } + + @Override + public boolean initializeHook() { + // initial Bento stuff + + // + if (super.initializeHook()) { + getTempFly().getServer().getPluginManager().registerEvents(this, getTempFly()); + startManualTracking(); + return true; + } + return false; + } + + @Override + public String getFormattedIslandLevel(double level) { + Object levels = getLevelsAddon(); + if (levels == null) { + return super.getFormattedIslandLevel(level); + } + try { + Object manager = levels.getClass().getMethod("getManager").invoke(levels); + return (String) manager.getClass().getMethod("formatLevel", Long.class).invoke(manager, (long) level); + } catch (Exception e) { + e.printStackTrace(); + } + return super.getFormattedIslandLevel(level); + } + + @Override + public String getChallengeName(SkyblockChallenge challenge) { + try { + Object challenges = getChallengeAddon(); + if (challenges == null) { + return super.getChallengeName(challenge); + } + Object manager = challenges.getClass().getMethod("getChallengesManager").invoke(challenges); + Object bentoChallenge = manager.getClass().getMethod("getChallenge", String.class).invoke(manager, challenge.getName()); + if (bentoChallenge == null) { + return super.getChallengeName(challenge); + } + return (String) bentoChallenge.getClass().getMethod("getFriendlyName").invoke(bentoChallenge); + } catch (Exception e) { + e.printStackTrace(); + return super.getChallengeName(challenge); + } + } + + @EventHandler + public void on(IslandBaseEvent e) { + Class clazz = e.getClass(); + if (clazz.getSimpleName().equals("IslandLevelCalculatedEvent")) { + Island rawIsland = e.getIsland(); + Bukkit.getScheduler().runTaskLater(getTempFly(), () -> + super.onIslandLevelChange(getIslandWrapper(rawIsland)) + , 1); + } + } + + @EventHandler + public void on(BentoBoxEvent e) { + Console.debug("--- BentoBoxEvent ---"); + Class clazz = e.getClass(); + if (clazz.getSimpleName().equals("ChallengeCompletedEvent")) { + try { + UUID id = (UUID) clazz.getMethod("getPlayerUUID").invoke(e); + Player p = Bukkit.getPlayer(id); + if (p == null) { + return; + } + super.onChallengeComplete(p); + } catch (Exception exception) { exception.printStackTrace();} + } + } + + @Override + public String getPluginName() { + return "BentoBox"; + } + + @Override + public String getEmbeddedConfigName() { + return "skyblock_preset_bento"; + } + + public User getBentoUser(UUID u) { + return BentoBox.getInstance().getPlayers().getUser(u); + } + + public Object getLevelsAddon() { + Optional t = BentoBox.getInstance().getAddonsManager().getAddonByName("Level"); + return t.isPresent() ? t.get() : null; + } + + public Object getChallengeAddon() { + Optional t = BentoBox.getInstance().getAddonsManager().getAddonByName("Challenges"); + return t.isPresent() ? t.get() : null; + } + + @Override + public IslandWrapper getIslandAt(Location loc) { + Optional t = BentoBox.getInstance().getIslands().getIslandAt(loc); + return t.isPresent() ? getIslandWrapper(t.get()) : null; + } + + @Override + public boolean islandRoleExists(IslandWrapper island, String role) { + for (String s: getRoles()) { + if (role.equalsIgnoreCase(s)) { + return true; + } + } + return false; + } + + @Override + public boolean islandRoleExists(String role) { + return islandRoleExists(null, role); + } + + @Override + public String getIslandRole(UUID u, IslandWrapper island) { + String[] split = BentoBox.getInstance().getRanksManager().getRank(((Island) island.getRawIsland()).getRank(u)).split("\\."); + return split.length > 1 ? split[1].toUpperCase() : split[0].toUpperCase(); + } + + @Override + public String[] getRoles() { + List roles = new ArrayList<>(); + for (String role: BentoBox.getInstance().getRanksManager().getRanks().keySet()) { + String[] split = role.split("\\."); + Console.debug("Adding role: " + (split.length > 1 ? split[1].toUpperCase() : split[0].toUpperCase())); + roles.add(split.length > 1 ? split[1].toUpperCase() : split[0].toUpperCase()); + } + return roles.toArray(new String[roles.size()]); + } + + @Override + public UUID getIslandOwner(IslandWrapper island) { + return ((Island) island.getRawIsland()).getOwner(); + } + + @Override + public String getIslandIdentifier(Object rawIsland) { + return ((Island)rawIsland).getUniqueId(); + } + + @Override + public boolean isIslandMember(UUID u, IslandWrapper island) { + return ((Island) island.getRawIsland()).getMembers().containsKey(u); + } + + @Override + public double getIslandLevel(IslandWrapper island) { + Object level = getLevelsAddon(); + if (level == null) { + return 0; + } + + UUID owner = ((Island)island.getRawIsland()).getOwner(); + try {return (double)((long) level.getClass().getMethod("getIslandLevel", World.class, UUID.class) + .invoke(level, getMainIslandWorld(), owner));} catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + @Override + public Player[] getOnlineMembers(IslandWrapper island) { + Island rawIsland = (Island) island.getRawIsland(); + List online = new ArrayList<>(); + for (UUID u: rawIsland.getMembers().keySet()) { + Player p = Bukkit.getPlayer(u); + if (p != null && p.isOnline()) { + online.add(p); + } + } + return online.toArray(new Player[online.size()]); + } + + @Override + public UUID[] getIslandMembers(IslandWrapper island) { + Island rawIsland = (Island) island.getRawIsland(); + return rawIsland.getMemberSet().toArray(new UUID[rawIsland.getMemberSet().size()]); + } + + @Override + public IslandWrapper getIslandFromIdentifier(String identifier) { + Optional rawIsland = BentoBox.getInstance().getIslands().getIslandById(identifier); + return rawIsland.isPresent() ? getIslandWrapper(rawIsland.get()) : null; + } + + @Override + public boolean isIslandWorld(Location loc) { + return BentoBox.getInstance().getIWM().inWorld(loc); + } + + + @Override + public IslandWrapper getIslandOwnedBy(UUID playerId) { + World world = getMainIslandWorld(); + Island rawIsland = BentoBox.getInstance().getIslands().getIsland(world, playerId); + if (rawIsland == null) { + Console.debug("--|> The player does not have an island in the given world."); + return null; + } + return rawIsland.getOwner().equals(playerId) ? getIslandWrapper(rawIsland) : null; + } + + @Override + public IslandWrapper getTeamIsland(UUID playerId) { + World world = getMainIslandWorld(); + Island rawIsland = BentoBox.getInstance().getIslands().getIsland(world, playerId); + if (rawIsland == null) { + Console.debug("--|> The player does not have an island in the given world."); + return null; + } + return getIslandWrapper(rawIsland); + } + + @Override + public boolean isChallengeCompleted(UUID u, SkyblockChallenge challenge) { + try { + Object challenges = getChallengeAddon(); + if (challenges == null) { + Console.debug("--|> Challenges addon for BentoBox does not exist!"); + return true; + } + Object manager = challenges.getClass().getMethod("getChallengesManager").invoke(challenges); + Object bentoChallenge = manager.getClass().getMethod("getChallenge", String.class).invoke(manager, challenge.getName()); + if (bentoChallenge == null) { + Console.debug("--|> The challenge specified does not exist!"); + return true; + } + User bentoUser = getBentoUser(u); + if (bentoUser == null) { + Console.debug("--|> Players bento user is null!"); + return false; + } + World world = getMainIslandWorld(); + boolean isCompleted = (boolean) manager.getClass().getMethod("isChallengeComplete", User.class, World.class, bentoChallenge.getClass()).invoke(manager, bentoUser, world, bentoChallenge); + Console.debug("--| Challenge: " + challenge.getName(), "--| isCompleted: " + isCompleted); + if (challenge.getRequiredCompletions() == 1 && !isCompleted) { + return false; + } + long completions = (long) manager.getClass().getMethod("getChallengeTimes", User.class, World.class, String.class) + .invoke(manager, bentoUser, getMainIslandWorld(), challenge.getName()); + Console.debug("--| completions: " + completions); + if (challenge.getRequiredCompletions() > 0 && completions < challenge.getRequiredCompletions()) { + return false; + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + @Override + public double getIslandLevel(UUID playerId) { + Object levels = getLevelsAddon(); + if (levels == null) { + Console.debug("--|> Levels addon for BentoBox does not exist!"); + return 0; + } + World world = getMainIslandWorld(); + try {return (double) ((long) levels.getClass().getMethod("getIslandLevel", World.class, UUID.class) + .invoke(levels, world, playerId));} catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + @Override + public boolean isInIsland(IslandWrapper island, Location loc) { + return ((Island)island.getRawIsland()).inIslandSpace(loc); + } + + + public abstract World getMainIslandWorld(); + + +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/skyblock/plugins/BskyblockHook.java b/src/com/moneybags/tempfly/hook/skyblock/plugins/BskyblockHook.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/hook/skyblock/plugins/BskyblockHook.java rename to src/com/moneybags/tempfly/hook/skyblock/plugins/BskyblockHook.java index c85f2b2..e238926 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/skyblock/plugins/BskyblockHook.java +++ b/src/com/moneybags/tempfly/hook/skyblock/plugins/BskyblockHook.java @@ -1,60 +1,60 @@ -package com.moneybags.tempfly.hook.skyblock.plugins; - -import java.util.Optional; -import org.bukkit.World; -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.util.Console; - -import world.bentobox.bentobox.BentoBox; -import world.bentobox.bentobox.api.addons.Addon; - -public class BskyblockHook extends BentoHook { - - public static final String BSKYBLOCK = "BSkyBlock"; - - - - public BskyblockHook(TempFly plugin) { - super(plugin); - } - - @Override - public String getHookName() { - return BSKYBLOCK; - } - - @Override - public String getConfigName() { - return BSKYBLOCK; - } - - @Override - public String getDataName() { - return BSKYBLOCK; - } - - @Override - public World getMainIslandWorld() { - Object bsky = getBSkyblockAddon(); - if (bsky == null) { - Console.warn("The BskyBlock hook encountered a problem. It will now disable!"); - setEnabled(false); - return null; - } - Class clazz = bsky.getClass(); - try {return (World) (clazz.getMethod("getOverWorld").invoke(bsky) != null ? clazz.getMethod("getOverWorld").invoke(bsky) - : clazz.getMethod("getNetherWorld").invoke(bsky) != null ? clazz.getMethod("getNetherWorld").invoke(bsky) - : clazz.getMethod("getEndWorld").invoke(bsky));} catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - public Object getBSkyblockAddon() { - Optional addon = BentoBox.getInstance().getAddonsManager().getAddonByName("BSkyBlock"); - return addon.isPresent() ? addon.get() : null; - } - - - -} +package com.moneybags.tempfly.hook.skyblock.plugins; + +import java.util.Optional; +import org.bukkit.World; +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.util.Console; + +import world.bentobox.bentobox.BentoBox; +import world.bentobox.bentobox.api.addons.Addon; + +public class BskyblockHook extends BentoHook { + + public static final String BSKYBLOCK = "BSkyBlock"; + + + + public BskyblockHook(TempFly plugin) { + super(plugin); + } + + @Override + public String getHookName() { + return BSKYBLOCK; + } + + @Override + public String getConfigName() { + return BSKYBLOCK; + } + + @Override + public String getDataName() { + return BSKYBLOCK; + } + + @Override + public World getMainIslandWorld() { + Object bsky = getBSkyblockAddon(); + if (bsky == null) { + Console.warn("The BskyBlock hook encountered a problem. It will now disable!"); + setEnabled(false); + return null; + } + Class clazz = bsky.getClass(); + try {return (World) (clazz.getMethod("getOverWorld").invoke(bsky) != null ? clazz.getMethod("getOverWorld").invoke(bsky) + : clazz.getMethod("getNetherWorld").invoke(bsky) != null ? clazz.getMethod("getNetherWorld").invoke(bsky) + : clazz.getMethod("getEndWorld").invoke(bsky));} catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public Object getBSkyblockAddon() { + Optional addon = BentoBox.getInstance().getAddonsManager().getAddonByName("BSkyBlock"); + return addon.isPresent() ? addon.get() : null; + } + + + +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/skyblock/plugins/IridiumHook.java b/src/com/moneybags/tempfly/hook/skyblock/plugins/IridiumHook.java similarity index 97% rename from TempFly/src/com/moneybags/tempfly/hook/skyblock/plugins/IridiumHook.java rename to src/com/moneybags/tempfly/hook/skyblock/plugins/IridiumHook.java index a0b765c..d00981d 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/skyblock/plugins/IridiumHook.java +++ b/src/com/moneybags/tempfly/hook/skyblock/plugins/IridiumHook.java @@ -1,265 +1,265 @@ -package com.moneybags.tempfly.hook.skyblock.plugins; - -import com.iridium.iridiumskyblock.IridiumSkyblock; -import com.iridium.iridiumskyblock.Island; -import com.iridium.iridiumskyblock.User; -import com.iridium.iridiumskyblock.managers.IslandManager; -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.hook.skyblock.IslandWrapper; -import com.moneybags.tempfly.hook.skyblock.SkyblockChallenge; -import com.moneybags.tempfly.hook.skyblock.SkyblockHook; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryOpenEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; - -/** - * - Dev Notes - - * IridiumSkyblock contains no events or api for island levels and challenges, therefore unless they are implemented - * it is unreasonably difficult for me to performantly update flight requirements in real time when challenges or island - * levels update. The player will need to leave and re-enter the island to update them. - *

- * IridiumSkyblock also does not include built in island tracking or events for player location and islands - * IridiumHook will initiate the super tracker in SkyblockHook. - * - * @author Kevin - */ -public class IridiumHook extends SkyblockHook implements Listener { - - public static final String[] ROLES = new String[]{"OWNER", "COOWNER", "MODERATOR", "MEMBER", "COOP", "VISITOR"}; - - public IridiumHook(TempFly tempfly) { - super(tempfly); - } - - @Override - public boolean initializeHook() { - // initial iridium hook stuff. - - // - if (super.initializeHook()) { - getTempFly().getServer().getPluginManager().registerEvents(this, getTempFly()); - startManualTracking(); - return true; - } - return false; - } - - - @Override - public String getEmbeddedConfigName() { - return "skyblock_preset_iridium"; - } - - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void on(InventoryOpenEvent e) { - if (!hasSettingsHook() || !(e.getPlayer() instanceof Player)) { - return; - } - Console.debug(U.strip(IridiumSkyblock.getInventories().islandMenuGUITitle)); - Console.debug(U.strip(e.getView().getTitle())); - if (!U.strip(e.getView().getTitle()).equals(U.strip(IridiumSkyblock.getInventories().islandMenuGUITitle))) { - return; - } - Inventory inv = e.getInventory(); - inv.setItem(inv.getSize() - 5, getSettingsButton()); - } - - @EventHandler(priority = EventPriority.LOW) - public void on(InventoryClickEvent e) { - if (!hasSettingsHook() || !(e.getWhoClicked() instanceof Player)) { - return; - } - Player p = (Player) e.getWhoClicked(); - if (!U.strip(e.getView().getTitle()).equals(U.strip(IridiumSkyblock.getInventories().islandMenuGUITitle))) { - return; - } - ItemStack clicked = e.getCurrentItem(); - if (getSettingsButton().isSimilar(clicked)) { - e.setCancelled(true); - openIslandSettings(p); - } - } - - - @Override - public Player[] getOnlineMembers(IslandWrapper island) { - List online = new ArrayList<>(); - Island rawIsland = (Island) island.getRawIsland(); - - for (String s : rawIsland.members) { - Player p = Bukkit.getPlayer(UUID.fromString(s)); - if (p != null && p.isOnline()) { - online.add(p); - } - } - - return online.toArray(new Player[0]); - } - - @Override - public UUID[] getIslandMembers(IslandWrapper island) { - List ids = new ArrayList<>(); - Island rawIsland = (Island) island.getRawIsland(); - for (String s : rawIsland.members) { - ids.add(UUID.fromString(s)); - } - return ids.toArray(new UUID[0]); - } - - @Override - public IslandWrapper getIslandOwnedBy(UUID u) { - OfflinePlayer p = Bukkit.getOfflinePlayer(u); - User user = User.getUser(p); - Island rawIsland = user.getIsland(); - if (rawIsland == null || !rawIsland.owner.equals(u.toString())) { - return null; - } - return getIslandWrapper(rawIsland); - } - - @Override - public IslandWrapper getTeamIsland(UUID u) { - OfflinePlayer p = Bukkit.getOfflinePlayer(u); - User user = User.getUser(p); - Island rawIsland = user.getIsland(); - if (rawIsland == null) { - return null; - } - return getIslandWrapper(rawIsland); - } - - @Override - public IslandWrapper getIslandAt(Location loc) { - return getIslandWrapper(IslandManager.getIslandViaLocation(loc)); - } - - @Override - public boolean isChallengeCompleted(UUID u, SkyblockChallenge challenge) { - Console.debug("--|?> Is challenge completed: "); - Island island = (Island) getTeamIsland(u).getRawIsland(); - if (island == null) { - return false; - } - if (!island.getMissionLevels().containsKey(challenge.getName())) { - Console.debug("--|!> island does not contain mission: " + challenge.getName()); - return false; - } - if (island.getMission(challenge.getName()) >= challenge.getRequiredProgress()) { - Console.debug("--|> island meets challenge condition: " + challenge.getName()); - return true; - } - if (V.debug) { - Console.debug("--|> island does not meet challenge condition: " + challenge.getName(), "--| current progress: " + island.getMission(challenge.getName())); - } - return false; - } - - @Override - public boolean islandRoleExists(IslandWrapper island, String role) { - return islandRoleExists(role); - } - - @Override - public boolean islandRoleExists(String role) { - return Arrays.stream(ROLES).anyMatch(it -> it.equalsIgnoreCase(role)); - } - - @Override - public String getIslandRole(UUID u, IslandWrapper island) { - Island rawIsland = (Island) island.getRawIsland(); - IslandWrapper playerIsland = getTeamIsland(u); - - if (playerIsland != null) { - if (rawIsland.getCoop().contains(rawIsland.id)) { - return "COOP"; - } - } - - if (isIslandMember(u, island)) { - return User.getUser(Bukkit.getOfflinePlayer(u)).getRole().toString().toUpperCase(); - } else { - return "VISITOR"; - } - } - - @Override - public UUID getIslandOwner(IslandWrapper island) { - return UUID.fromString(((Island) island.getRawIsland()).owner); - } - - /** - * Each island in iridium skyblock has an int ID. this will be our identifier. - */ - @Override - public String getIslandIdentifier(Object rawIsland) { - if (rawIsland instanceof IslandWrapper) { - rawIsland = ((IslandWrapper) rawIsland).getRawIsland(); - } - return String.valueOf(((Island) rawIsland).id); - } - - @Override - public IslandWrapper getIslandFromIdentifier(String identifier) { - return getIslandWrapper(IslandManager.getIslandViaId(Integer.parseInt(identifier))); - } - - @Override - public boolean isIslandMember(UUID u, IslandWrapper island) { - return ((Island) island.getRawIsland()).members.contains(u.toString()); - } - - @Override - public double getIslandLevel(UUID u) { - IslandWrapper island = getTeamIsland(u); - return island == null ? 0 : ((Island) island.getRawIsland()).value; - } - - @Override - public double getIslandLevel(IslandWrapper island) { - return ((Island) island.getRawIsland()).value; - } - - @Override - public String[] getRoles() { - return ROLES; - } - - @Override - public String getPluginName() { - return "IridiumSkyblock"; - } - - @Override - public boolean isIslandWorld(Location loc) { - // Try catches a benign error when using /reload because iridium isnt ready yet. - try { - return IslandManager.isIslandWorld(loc); - } catch (Exception e) { - return false; - } - } - - @Override - public boolean isInIsland(IslandWrapper island, Location loc) { - // Need to check isIslandWorld since isInIsland only checks min and max x/y but not world. - return ((Island) island.getRawIsland()).isInIsland(loc) && isIslandWorld(loc); - } - -} +package com.moneybags.tempfly.hook.skyblock.plugins; + +import com.iridium.iridiumskyblock.IridiumSkyblock; +import com.iridium.iridiumskyblock.Island; +import com.iridium.iridiumskyblock.User; +import com.iridium.iridiumskyblock.managers.IslandManager; +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.hook.skyblock.IslandWrapper; +import com.moneybags.tempfly.hook.skyblock.SkyblockChallenge; +import com.moneybags.tempfly.hook.skyblock.SkyblockHook; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryOpenEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +/** + * - Dev Notes - + * IridiumSkyblock contains no events or api for island levels and challenges, therefore unless they are implemented + * it is unreasonably difficult for me to performantly update flight requirements in real time when challenges or island + * levels update. The player will need to leave and re-enter the island to update them. + *

+ * IridiumSkyblock also does not include built in island tracking or events for player location and islands + * IridiumHook will initiate the super tracker in SkyblockHook. + * + * @author Kevin + */ +public class IridiumHook extends SkyblockHook implements Listener { + + public static final String[] ROLES = new String[]{"OWNER", "COOWNER", "MODERATOR", "MEMBER", "COOP", "VISITOR"}; + + public IridiumHook(TempFly tempfly) { + super(tempfly); + } + + @Override + public boolean initializeHook() { + // initial iridium hook stuff. + + // + if (super.initializeHook()) { + getTempFly().getServer().getPluginManager().registerEvents(this, getTempFly()); + startManualTracking(); + return true; + } + return false; + } + + + @Override + public String getEmbeddedConfigName() { + return "skyblock_preset_iridium"; + } + + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void on(InventoryOpenEvent e) { + if (!hasSettingsHook() || !(e.getPlayer() instanceof Player)) { + return; + } + Console.debug(U.strip(IridiumSkyblock.getInventories().islandMenuGUITitle)); + Console.debug(U.strip(e.getView().getTitle())); + if (!U.strip(e.getView().getTitle()).equals(U.strip(IridiumSkyblock.getInventories().islandMenuGUITitle))) { + return; + } + Inventory inv = e.getInventory(); + inv.setItem(inv.getSize() - 5, getSettingsButton()); + } + + @EventHandler(priority = EventPriority.LOW) + public void on(InventoryClickEvent e) { + if (!hasSettingsHook() || !(e.getWhoClicked() instanceof Player)) { + return; + } + Player p = (Player) e.getWhoClicked(); + if (!U.strip(e.getView().getTitle()).equals(U.strip(IridiumSkyblock.getInventories().islandMenuGUITitle))) { + return; + } + ItemStack clicked = e.getCurrentItem(); + if (getSettingsButton().isSimilar(clicked)) { + e.setCancelled(true); + openIslandSettings(p); + } + } + + + @Override + public Player[] getOnlineMembers(IslandWrapper island) { + List online = new ArrayList<>(); + Island rawIsland = (Island) island.getRawIsland(); + + for (String s : rawIsland.members) { + Player p = Bukkit.getPlayer(UUID.fromString(s)); + if (p != null && p.isOnline()) { + online.add(p); + } + } + + return online.toArray(new Player[0]); + } + + @Override + public UUID[] getIslandMembers(IslandWrapper island) { + List ids = new ArrayList<>(); + Island rawIsland = (Island) island.getRawIsland(); + for (String s : rawIsland.members) { + ids.add(UUID.fromString(s)); + } + return ids.toArray(new UUID[0]); + } + + @Override + public IslandWrapper getIslandOwnedBy(UUID u) { + OfflinePlayer p = Bukkit.getOfflinePlayer(u); + User user = User.getUser(p); + Island rawIsland = user.getIsland(); + if (rawIsland == null || !rawIsland.owner.equals(u.toString())) { + return null; + } + return getIslandWrapper(rawIsland); + } + + @Override + public IslandWrapper getTeamIsland(UUID u) { + OfflinePlayer p = Bukkit.getOfflinePlayer(u); + User user = User.getUser(p); + Island rawIsland = user.getIsland(); + if (rawIsland == null) { + return null; + } + return getIslandWrapper(rawIsland); + } + + @Override + public IslandWrapper getIslandAt(Location loc) { + return getIslandWrapper(IslandManager.getIslandViaLocation(loc)); + } + + @Override + public boolean isChallengeCompleted(UUID u, SkyblockChallenge challenge) { + Console.debug("--|?> Is challenge completed: "); + Island island = (Island) getTeamIsland(u).getRawIsland(); + if (island == null) { + return false; + } + if (!island.getMissionLevels().containsKey(challenge.getName())) { + Console.debug("--|!> island does not contain mission: " + challenge.getName()); + return false; + } + if (island.getMission(challenge.getName()) >= challenge.getRequiredProgress()) { + Console.debug("--|> island meets challenge condition: " + challenge.getName()); + return true; + } + if (V.debug) { + Console.debug("--|> island does not meet challenge condition: " + challenge.getName(), "--| current progress: " + island.getMission(challenge.getName())); + } + return false; + } + + @Override + public boolean islandRoleExists(IslandWrapper island, String role) { + return islandRoleExists(role); + } + + @Override + public boolean islandRoleExists(String role) { + return Arrays.stream(ROLES).anyMatch(it -> it.equalsIgnoreCase(role)); + } + + @Override + public String getIslandRole(UUID u, IslandWrapper island) { + Island rawIsland = (Island) island.getRawIsland(); + IslandWrapper playerIsland = getTeamIsland(u); + + if (playerIsland != null) { + if (rawIsland.getCoop().contains(rawIsland.id)) { + return "COOP"; + } + } + + if (isIslandMember(u, island)) { + return User.getUser(Bukkit.getOfflinePlayer(u)).getRole().toString().toUpperCase(); + } else { + return "VISITOR"; + } + } + + @Override + public UUID getIslandOwner(IslandWrapper island) { + return UUID.fromString(((Island) island.getRawIsland()).owner); + } + + /** + * Each island in iridium skyblock has an int ID. this will be our identifier. + */ + @Override + public String getIslandIdentifier(Object rawIsland) { + if (rawIsland instanceof IslandWrapper) { + rawIsland = ((IslandWrapper) rawIsland).getRawIsland(); + } + return String.valueOf(((Island) rawIsland).id); + } + + @Override + public IslandWrapper getIslandFromIdentifier(String identifier) { + return getIslandWrapper(IslandManager.getIslandViaId(Integer.parseInt(identifier))); + } + + @Override + public boolean isIslandMember(UUID u, IslandWrapper island) { + return ((Island) island.getRawIsland()).members.contains(u.toString()); + } + + @Override + public double getIslandLevel(UUID u) { + IslandWrapper island = getTeamIsland(u); + return island == null ? 0 : ((Island) island.getRawIsland()).value; + } + + @Override + public double getIslandLevel(IslandWrapper island) { + return ((Island) island.getRawIsland()).value; + } + + @Override + public String[] getRoles() { + return ROLES; + } + + @Override + public String getPluginName() { + return "IridiumSkyblock"; + } + + @Override + public boolean isIslandWorld(Location loc) { + // Try catches a benign error when using /reload because iridium isnt ready yet. + try { + return IslandManager.isIslandWorld(loc); + } catch (Exception e) { + return false; + } + } + + @Override + public boolean isInIsland(IslandWrapper island, Location loc) { + // Need to check isIslandWorld since isInIsland only checks min and max x/y but not world. + return ((Island) island.getRawIsland()).isInIsland(loc) && isIslandWorld(loc); + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/hook/skyblock/plugins/SuperiorHook.java b/src/com/moneybags/tempfly/hook/skyblock/plugins/SuperiorHook.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/hook/skyblock/plugins/SuperiorHook.java rename to src/com/moneybags/tempfly/hook/skyblock/plugins/SuperiorHook.java index 1a08ece..9ea7d45 100644 --- a/TempFly/src/com/moneybags/tempfly/hook/skyblock/plugins/SuperiorHook.java +++ b/src/com/moneybags/tempfly/hook/skyblock/plugins/SuperiorHook.java @@ -1,227 +1,227 @@ -package com.moneybags.tempfly.hook.skyblock.plugins; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; - -import com.bgsoftware.superiorskyblock.api.SuperiorSkyblock; -import com.bgsoftware.superiorskyblock.api.SuperiorSkyblockAPI; -import com.bgsoftware.superiorskyblock.api.events.IslandEnterEvent; -import com.bgsoftware.superiorskyblock.api.events.IslandLeaveEvent; -import com.bgsoftware.superiorskyblock.api.events.IslandWorthUpdateEvent; -import com.bgsoftware.superiorskyblock.api.events.MissionCompleteEvent; -import com.bgsoftware.superiorskyblock.api.island.Island; -import com.bgsoftware.superiorskyblock.api.island.PlayerRole; -import com.bgsoftware.superiorskyblock.api.missions.Mission; -import com.bgsoftware.superiorskyblock.api.wrappers.SuperiorPlayer; -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.hook.skyblock.IslandWrapper; -import com.moneybags.tempfly.hook.skyblock.SkyblockChallenge; -import com.moneybags.tempfly.hook.skyblock.SkyblockHook; -import com.moneybags.tempfly.util.Console; - -public class SuperiorHook extends SkyblockHook implements Listener { - - private SuperiorSkyblock superior; - - private String[] roles; - - public SuperiorHook(TempFly plugin) { - super(plugin); - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onEnter(IslandEnterEvent e) { - Player player = Bukkit.getPlayer(e.getPlayer().getUniqueId()); - super.onIslandEnter(player, e.getIsland(), player.getLocation()); - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onLeave(IslandLeaveEvent e) { - super.onIslandExit(Bukkit.getPlayer(e.getPlayer().getUniqueId())); - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onWorth(IslandWorthUpdateEvent e) { - Island island = e.getIsland(); - onIslandLevelChange(getIslandWrapper(island)); - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMission(MissionCompleteEvent e) { - super.onChallengeComplete(Bukkit.getPlayer(e.getPlayer().getUniqueId())); - } - - - @Override - public boolean initializeHook() { - superior = SuperiorSkyblockAPI.getSuperiorSkyblock(); - if (superior == null) { - Console.severe("There was an error while initializing the SuperiorSkyblock Plugin hook!"); - return false; - } - if (!super.initializeHook()) { - return false; - } - - tempfly.getServer().getPluginManager().registerEvents(this, tempfly); - - List roles = new ArrayList<>(); - for (PlayerRole role: superior.getRoles().getRoles()) { - roles.add(role.getName()); - } - this.roles = roles.toArray(new String[roles.size()]); - - - return true; - } - - @Override - public Player[] getOnlineMembers(IslandWrapper island) { - Island is = (Island) island.getRawIsland(); - List players = new ArrayList<>(); - for (SuperiorPlayer player: is.getIslandMembers(true)) { - if (player.isOnline()) { - players.add(Bukkit.getPlayer(player.getUniqueId())); - } - } - return players.toArray(new Player[players.size()]); - } - - @Override - public UUID[] getIslandMembers(IslandWrapper island) { - Island is = (Island) island.getRawIsland(); - List uids = new ArrayList<>(); - for (SuperiorPlayer player: is.getIslandMembers(true)) { - uids.add(player.getUniqueId()); - } - return uids.toArray(new UUID[uids.size()]); - } - - @Override - public IslandWrapper getIslandOwnedBy(UUID playerId) { - IslandWrapper island = getTeamIsland(playerId); - if (!((Island) island.getRawIsland()).getOwner().getUniqueId().equals(playerId)) { - return null; - } - return island; - } - - @Override - public IslandWrapper getTeamIsland(UUID playerId) { - return getIslandWrapper(superior.getGrid().getIsland(superior.getPlayers().getSuperiorPlayer(playerId))); - } - - @Override - public IslandWrapper getIslandAt(Location loc) { - Island island = superior.getGrid().getIslandAt(loc); - return island == null ? null : getIslandWrapper(island); - } - - @Override - public boolean isIslandWorld(Location loc) { - return superior.getGrid().isIslandsWorld(loc.getWorld()); - } - - @Override - public boolean isChallengeCompleted(UUID playerId, SkyblockChallenge challenge) { - Mission mission = superior.getMissions().getMission(challenge.getName()); - if (mission == null) { - Console.debug("mission is null"); - return false; - } - Console.debug("--| mission: " + challenge.getName(), "--| Players mission progress: " + mission.getProgress(superior.getPlayers().getSuperiorPlayer(playerId))); - - return superior.getPlayers().getSuperiorPlayer(playerId).hasCompletedMission(mission); - } - - @Override - public boolean islandRoleExists(IslandWrapper island, String role) { - return islandRoleExists(role); - } - - @Override - public boolean islandRoleExists(String role) { - try { - return superior.getRoles().getPlayerRole(role) != null; - } catch (IllegalArgumentException e) { - return false; - } - } - - @Override - public String getIslandRole(UUID playerId, IslandWrapper island) { - SuperiorPlayer player = superior.getPlayers().getSuperiorPlayer(playerId); - Island is = ((Island) island.getRawIsland()); - - if (!is.isMember(player)) { - return is.isCoop(player) ? superior.getRoles().getCoopRole().toString() : superior.getRoles().getGuestRole().toString(); - } - return player.getPlayerRole().toString(); - } - - @Override - public UUID getIslandOwner(IslandWrapper island) { - return ((Island) island.getRawIsland()).getOwner().getUniqueId(); - } - - @Override - public String getIslandIdentifier(Object rawIsland) { - return ((Island) rawIsland).getUniqueId().toString(); - } - - @Override - public IslandWrapper getIslandFromIdentifier(String identifier) { - Console.debug("---", identifier, superior.getGrid().getIslandByUUID(UUID.fromString(identifier))); - return getIslandWrapper(superior.getGrid().getIslandByUUID(UUID.fromString(identifier))); - } - - @Override - public boolean isIslandMember(UUID playerId, IslandWrapper island) { - return ((Island) island).isMember(superior.getPlayers().getSuperiorPlayer(playerId)); - } - - @Override - public double getIslandLevel(UUID playerId) { - IslandWrapper island = getTeamIsland(playerId); - return island == null ? 0 : getIslandLevel(island); - } - - @Override - public double getIslandLevel(IslandWrapper island) { - if (island == null) { - return 0; - } - return ((Island) island.getRawIsland()).getIslandLevel().doubleValue(); - } - - @Override - public String[] getRoles() { - return roles; - } - - @Override - public boolean isInIsland(IslandWrapper island, Location loc) { - return island.getRawIsland().equals(superior.getGrid().getIslandAt(loc)); - } - - @Override - public String getPluginName() { - return "SuperiorSkyblock2"; - } - - @Override - public String getEmbeddedConfigName() { - return "skyblock_preset_superior"; - } - - - -} +package com.moneybags.tempfly.hook.skyblock.plugins; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + +import com.bgsoftware.superiorskyblock.api.SuperiorSkyblock; +import com.bgsoftware.superiorskyblock.api.SuperiorSkyblockAPI; +import com.bgsoftware.superiorskyblock.api.events.IslandEnterEvent; +import com.bgsoftware.superiorskyblock.api.events.IslandLeaveEvent; +import com.bgsoftware.superiorskyblock.api.events.IslandWorthUpdateEvent; +import com.bgsoftware.superiorskyblock.api.events.MissionCompleteEvent; +import com.bgsoftware.superiorskyblock.api.island.Island; +import com.bgsoftware.superiorskyblock.api.island.PlayerRole; +import com.bgsoftware.superiorskyblock.api.missions.Mission; +import com.bgsoftware.superiorskyblock.api.wrappers.SuperiorPlayer; +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.hook.skyblock.IslandWrapper; +import com.moneybags.tempfly.hook.skyblock.SkyblockChallenge; +import com.moneybags.tempfly.hook.skyblock.SkyblockHook; +import com.moneybags.tempfly.util.Console; + +public class SuperiorHook extends SkyblockHook implements Listener { + + private SuperiorSkyblock superior; + + private String[] roles; + + public SuperiorHook(TempFly plugin) { + super(plugin); + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onEnter(IslandEnterEvent e) { + Player player = Bukkit.getPlayer(e.getPlayer().getUniqueId()); + super.onIslandEnter(player, e.getIsland(), player.getLocation()); + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onLeave(IslandLeaveEvent e) { + super.onIslandExit(Bukkit.getPlayer(e.getPlayer().getUniqueId())); + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onWorth(IslandWorthUpdateEvent e) { + Island island = e.getIsland(); + onIslandLevelChange(getIslandWrapper(island)); + } + + @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMission(MissionCompleteEvent e) { + super.onChallengeComplete(Bukkit.getPlayer(e.getPlayer().getUniqueId())); + } + + + @Override + public boolean initializeHook() { + superior = SuperiorSkyblockAPI.getSuperiorSkyblock(); + if (superior == null) { + Console.severe("There was an error while initializing the SuperiorSkyblock Plugin hook!"); + return false; + } + if (!super.initializeHook()) { + return false; + } + + tempfly.getServer().getPluginManager().registerEvents(this, tempfly); + + List roles = new ArrayList<>(); + for (PlayerRole role: superior.getRoles().getRoles()) { + roles.add(role.getName()); + } + this.roles = roles.toArray(new String[roles.size()]); + + + return true; + } + + @Override + public Player[] getOnlineMembers(IslandWrapper island) { + Island is = (Island) island.getRawIsland(); + List players = new ArrayList<>(); + for (SuperiorPlayer player: is.getIslandMembers(true)) { + if (player.isOnline()) { + players.add(Bukkit.getPlayer(player.getUniqueId())); + } + } + return players.toArray(new Player[players.size()]); + } + + @Override + public UUID[] getIslandMembers(IslandWrapper island) { + Island is = (Island) island.getRawIsland(); + List uids = new ArrayList<>(); + for (SuperiorPlayer player: is.getIslandMembers(true)) { + uids.add(player.getUniqueId()); + } + return uids.toArray(new UUID[uids.size()]); + } + + @Override + public IslandWrapper getIslandOwnedBy(UUID playerId) { + IslandWrapper island = getTeamIsland(playerId); + if (!((Island) island.getRawIsland()).getOwner().getUniqueId().equals(playerId)) { + return null; + } + return island; + } + + @Override + public IslandWrapper getTeamIsland(UUID playerId) { + return getIslandWrapper(superior.getGrid().getIsland(superior.getPlayers().getSuperiorPlayer(playerId))); + } + + @Override + public IslandWrapper getIslandAt(Location loc) { + Island island = superior.getGrid().getIslandAt(loc); + return island == null ? null : getIslandWrapper(island); + } + + @Override + public boolean isIslandWorld(Location loc) { + return superior.getGrid().isIslandsWorld(loc.getWorld()); + } + + @Override + public boolean isChallengeCompleted(UUID playerId, SkyblockChallenge challenge) { + Mission mission = superior.getMissions().getMission(challenge.getName()); + if (mission == null) { + Console.debug("mission is null"); + return false; + } + Console.debug("--| mission: " + challenge.getName(), "--| Players mission progress: " + mission.getProgress(superior.getPlayers().getSuperiorPlayer(playerId))); + + return superior.getPlayers().getSuperiorPlayer(playerId).hasCompletedMission(mission); + } + + @Override + public boolean islandRoleExists(IslandWrapper island, String role) { + return islandRoleExists(role); + } + + @Override + public boolean islandRoleExists(String role) { + try { + return superior.getRoles().getPlayerRole(role) != null; + } catch (IllegalArgumentException e) { + return false; + } + } + + @Override + public String getIslandRole(UUID playerId, IslandWrapper island) { + SuperiorPlayer player = superior.getPlayers().getSuperiorPlayer(playerId); + Island is = ((Island) island.getRawIsland()); + + if (!is.isMember(player)) { + return is.isCoop(player) ? superior.getRoles().getCoopRole().toString() : superior.getRoles().getGuestRole().toString(); + } + return player.getPlayerRole().toString(); + } + + @Override + public UUID getIslandOwner(IslandWrapper island) { + return ((Island) island.getRawIsland()).getOwner().getUniqueId(); + } + + @Override + public String getIslandIdentifier(Object rawIsland) { + return ((Island) rawIsland).getUniqueId().toString(); + } + + @Override + public IslandWrapper getIslandFromIdentifier(String identifier) { + Console.debug("---", identifier, superior.getGrid().getIslandByUUID(UUID.fromString(identifier))); + return getIslandWrapper(superior.getGrid().getIslandByUUID(UUID.fromString(identifier))); + } + + @Override + public boolean isIslandMember(UUID playerId, IslandWrapper island) { + return ((Island) island).isMember(superior.getPlayers().getSuperiorPlayer(playerId)); + } + + @Override + public double getIslandLevel(UUID playerId) { + IslandWrapper island = getTeamIsland(playerId); + return island == null ? 0 : getIslandLevel(island); + } + + @Override + public double getIslandLevel(IslandWrapper island) { + if (island == null) { + return 0; + } + return ((Island) island.getRawIsland()).getIslandLevel().doubleValue(); + } + + @Override + public String[] getRoles() { + return roles; + } + + @Override + public boolean isInIsland(IslandWrapper island, Location loc) { + return island.getRawIsland().equals(superior.getGrid().getIslandAt(loc)); + } + + @Override + public String getPluginName() { + return "SuperiorSkyblock2"; + } + + @Override + public String getEmbeddedConfigName() { + return "skyblock_preset_superior"; + } + + + +} diff --git a/TempFly/src/com/moneybags/tempfly/time/AsyncTimeExecutor.java b/src/com/moneybags/tempfly/time/AsyncTimeExecutor.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/time/AsyncTimeExecutor.java rename to src/com/moneybags/tempfly/time/AsyncTimeExecutor.java index ccd154b..23d6329 100644 --- a/TempFly/src/com/moneybags/tempfly/time/AsyncTimeExecutor.java +++ b/src/com/moneybags/tempfly/time/AsyncTimeExecutor.java @@ -1,7 +1,7 @@ -package com.moneybags.tempfly.time; - -public interface AsyncTimeExecutor { - - public abstract void execute(AsyncTimeParameters parameters); - -} +package com.moneybags.tempfly.time; + +public interface AsyncTimeExecutor { + + public abstract void execute(AsyncTimeParameters parameters); + +} diff --git a/TempFly/src/com/moneybags/tempfly/time/AsyncTimeParameters.java b/src/com/moneybags/tempfly/time/AsyncTimeParameters.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/time/AsyncTimeParameters.java rename to src/com/moneybags/tempfly/time/AsyncTimeParameters.java index 6f2f11b..9b60760 100644 --- a/TempFly/src/com/moneybags/tempfly/time/AsyncTimeParameters.java +++ b/src/com/moneybags/tempfly/time/AsyncTimeParameters.java @@ -1,77 +1,77 @@ -package com.moneybags.tempfly.time; - -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.CommandSender; - -import com.moneybags.tempfly.TempFly; - -public class AsyncTimeParameters implements Runnable { - - private TempFly tempfly; - private CommandSender s; - private OfflinePlayer p; - private double amount; - private AsyncTimeExecutor executor; - - public AsyncTimeParameters(TempFly tempfly, AsyncTimeExecutor executor, CommandSender s, OfflinePlayer p, double amount) { - this.tempfly = tempfly; - this.executor = executor; - this.s = s; - this.p = p; - this.amount = amount; - } - - public AsyncTimeParameters(TempFly tempfly, AsyncTimeExecutor executor, OfflinePlayer p, double amount) { - this.tempfly = tempfly; - this.executor = executor; - this.p = p; - this.amount = amount; - } - - private double maxTime; - private double currentTime; - - - public void runAsync() { - Bukkit.getScheduler().runTaskAsynchronously(tempfly, this); - } - - @Override - public void run() { - if (Bukkit.isPrimaryThread()) { - this.runAsync(); - return; - } - maxTime = tempfly.getTimeManager().getMaxTime(p.getUniqueId()); - currentTime = tempfly.getTimeManager().getTime(p.getUniqueId()); - - Bukkit.getScheduler().runTask(tempfly, () -> { - executor.execute(this); - }); - } - - public TempFly getTempfly() { - return tempfly; - } - - public double getMaxTime() { - return maxTime; - } - - public double getCurrentTime() { - return currentTime; - } - - public CommandSender getSender() { - return s; - } - - public OfflinePlayer getTarget() { - return p; - } - - public double getAmount() { - return amount; - } -} +package com.moneybags.tempfly.time; + +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; + +import com.moneybags.tempfly.TempFly; + +public class AsyncTimeParameters implements Runnable { + + private TempFly tempfly; + private CommandSender s; + private OfflinePlayer p; + private double amount; + private AsyncTimeExecutor executor; + + public AsyncTimeParameters(TempFly tempfly, AsyncTimeExecutor executor, CommandSender s, OfflinePlayer p, double amount) { + this.tempfly = tempfly; + this.executor = executor; + this.s = s; + this.p = p; + this.amount = amount; + } + + public AsyncTimeParameters(TempFly tempfly, AsyncTimeExecutor executor, OfflinePlayer p, double amount) { + this.tempfly = tempfly; + this.executor = executor; + this.p = p; + this.amount = amount; + } + + private double maxTime; + private double currentTime; + + + public void runAsync() { + Bukkit.getScheduler().runTaskAsynchronously(tempfly, this); + } + + @Override + public void run() { + if (Bukkit.isPrimaryThread()) { + this.runAsync(); + return; + } + maxTime = tempfly.getTimeManager().getMaxTime(p.getUniqueId()); + currentTime = tempfly.getTimeManager().getTime(p.getUniqueId()); + + Bukkit.getScheduler().runTask(tempfly, () -> { + executor.execute(this); + }); + } + + public TempFly getTempfly() { + return tempfly; + } + + public double getMaxTime() { + return maxTime; + } + + public double getCurrentTime() { + return currentTime; + } + + public CommandSender getSender() { + return s; + } + + public OfflinePlayer getTarget() { + return p; + } + + public double getAmount() { + return amount; + } +} diff --git a/TempFly/src/com/moneybags/tempfly/time/TimeManager.java b/src/com/moneybags/tempfly/time/TimeManager.java similarity index 97% rename from TempFly/src/com/moneybags/tempfly/time/TimeManager.java rename to src/com/moneybags/tempfly/time/TimeManager.java index 278feef..3cf0264 100644 --- a/TempFly/src/com/moneybags/tempfly/time/TimeManager.java +++ b/src/com/moneybags/tempfly/time/TimeManager.java @@ -1,397 +1,397 @@ -package com.moneybags.tempfly.time; - -import java.util.UUID; -import java.util.Map.Entry; -import java.util.concurrent.TimeUnit; - -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.event.FlightUserInitializedEvent; -import com.moneybags.tempfly.user.FlightUser; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.DailyDate; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; -import com.moneybags.tempfly.util.data.DataBridge; -import com.moneybags.tempfly.util.data.DataPointer; - -import net.milkbowl.vault.permission.Permission; - -import com.moneybags.tempfly.util.data.DataBridge.DataValue; - -public class TimeManager implements Listener { - - private TempFly tempfly; - - public TimeManager(TempFly tempfly) { - this.tempfly = tempfly; - tempfly.getServer().getPluginManager().registerEvents(this, tempfly); - } - - /** - * Async - * - * Get a players time. - * If offline The databridge will return the most recent staged change - * held in memory for the players time if one exists. Otherwise it will need to pull it from the - * database / yaml data. - * @param u - * @return - */ - private boolean alreadyThrown; - public double getTime(UUID u) { - FlightUser user = tempfly.getFlightManager().getUser(u); - if (user == null && tempfly.getDataBridge().hasSqlEnabled() && Bukkit.getServer().isPrimaryThread() && !alreadyThrown) { - alreadyThrown = true; - try {throw new IllegalStateException("Invocation of getTime() for an offline player should be performed from an asychronous thread! It is not safe to access a database on the main server thread!");} catch (IllegalStateException e) { - e.printStackTrace(); - } - } - DataBridge bridge = tempfly.getDataBridge(); - // If user is not online the data needs pulled from the database. Otherwise get it from memory. - return user == null ? (double) bridge.getOrDefault(DataPointer.of(DataValue.PLAYER_TIME, u.toString()), 0d) : user.getTime(); - } - - /** - * Set a users time. - * If the user is online it will also update their FlightUser object with the new time - * stages the new time to the DataBridge. - * @param u the uuid of the player - * @param seconds The new seconds - */ - public void removeTime(UUID u, AsyncTimeParameters parameters) { - double seconds = parameters.getAmount(); - if (seconds <= 0) { - return; - } - FlightUser user = tempfly.getFlightManager().getUser(Bukkit.getPlayer(u)); - double bal = user == null ? parameters.getCurrentTime() : user.getTime(); - double remaining = (((bal-seconds) >= 0) ? (bal-seconds) : 0); - - if (user != null) { - user.setTime(remaining); - } else { - tempfly.getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_TIME, u.toString()), remaining); - } - } - - /** - * Add time to a user. - * If the user is online it will also update their FlightUser object with the new time - * stages the new time to the DataBridge. - * @param u the uuid of the player - * @param seconds The seconds to add - */ - public void addTime(UUID u, AsyncTimeParameters parameters) { - double seconds = parameters.getAmount(); - if (seconds <= 0) { - return; - } - FlightUser user = tempfly.getFlightManager().getUser(Bukkit.getPlayer(u)); - double maxTime = parameters.getMaxTime(); - if (maxTime == -999) { - return; - } - // If user is not online the data needs pulled from the database. Otherwise get it from memory. - double bal = user == null ? parameters.getCurrentTime() : user.getTime(); - // This line prevents an overflow to -Double.MAX_VALUE. - double remaining = (((bal+seconds) >= bal) ? (bal+seconds) : Double.MAX_VALUE); - if (maxTime > -1 && remaining > maxTime) { - remaining = maxTime; - } - - if (user != null) { - user.setTime(remaining); - } else { - tempfly.getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_TIME, u.toString()), remaining); - } - } - - /** - * Set a users time. - * If the user is online it will also update their FlightUser object with the new time - * stages the new time to the DataBridge. - * @param u the uuid of the player - * @param seconds The new seconds - */ - public void setTime(UUID u, AsyncTimeParameters parameters) { - double seconds = parameters.getAmount(); - if (seconds < 0) { - seconds = 0; - } - FlightUser user = tempfly.getFlightManager().getUser(Bukkit.getPlayer(u)); - double maxTime = parameters.getMaxTime(); - if (maxTime == -999) { - return; - } - if (maxTime > -1 && seconds > maxTime) { - seconds = maxTime; - } - - if (user != null) { - user.setTime(seconds); - } else { - if (tempfly.getDataBridge().hasSqlEnabled()) { - Console.warn("It is currently unsafe to alter player time for offline players while using MYSQL storage! The tempfly plugin currently does not sync player time between servers on a network. If this player is currently on a different server their time will not update and will be overwritten when they log off or switch servers."); - } - DataPointer pointer = DataPointer.of(DataValue.PLAYER_TIME, u.toString()); - tempfly.getDataBridge().stageChange(pointer, seconds); - tempfly.getDataBridge().manualCommit(pointer); - } - } - - - public double getMaxTime(UUID u) { - Console.debug("-- Get max time --"); - Player p = Bukkit.getPlayer(u); - double highest = 0; - boolean hasGroup = false; - if (p != null && p.isOnline()) { - Console.debug("--| Player is online..."); - for (Entry group: V.maxTimeGroups.entrySet()) { - double current = group.getValue(); - // If the group is less than the highest found so far continue. - if (current < highest && current > -1) { - continue; - } - if (p.hasPermission("tempfly.max." + group.getKey())) { - Console.debug("--| Player has group: " + group.getKey() + " | " + group.getValue()); - hasGroup = true; - if (current == -1) { - return current; - } else { - highest = current; - } - } - } - } else { - Console.debug("--| Player is offline..."); - if (!tempfly.getHookManager().hasPermissions()) { - Console.debug("--|> No vault permissions, We cannot check max time!"); - // We are returning -999 to indicate something is wrong and we cannot check the players max balance. - // In this case it is because the server does not have Vault and i can't check the offline players permissions. - return -999; - } - OfflinePlayer op = Bukkit.getOfflinePlayer(u); - Permission perms = tempfly.getHookManager().getPermissions(); - for (Entry group: V.maxTimeGroups.entrySet()) { - double current = group.getValue(); - if (current < highest && current > -1) { - continue; - } - if (op.isOp() || perms.playerHas(Bukkit.getWorlds().get(0).getName(), op, "tempfly.max." + group.getKey())) { - Console.debug("--| Player has group: " + group.getKey() + " | " + group.getValue()); - hasGroup = true; - if (current == -1) { - return current; - } else { - highest = current; - } - } - } - } - Console.debug("--|> Final value: " + (hasGroup ? highest : V.maxTimeBase)); - return hasGroup ? highest : V.maxTimeBase; - } - - - @EventHandler - public void onUserInitialized(FlightUserInitializedEvent e) { - Console.debug("", "--- Time manager will now process user initialization ---"); - Player p = e.getUser().getPlayer(); - if (V.timeDecay && p.hasPlayedBefore()) { - Console.debug("--| Time decay is enabled..."); - long offline = (System.currentTimeMillis() - p.getLastPlayed()) / 1000; - double lost = (offline / V.decayThresh) * V.decayAmount; - double time = e.getUser().getTime(); - lost = lost > time ? time : lost; - if (V.debug) Console.debug("--| Seconds offline: " + offline, "Threshold in seconds: " + V.decayThresh, "--| Seconds lost per threshold: " + V.decayAmount, "--| Seconds lost: " + lost, ""); - if (lost > 0) { - new AsyncTimeParameters(tempfly, (AsyncTimeParameters parameters) -> { - removeTime(p.getUniqueId(), parameters); - }, p, lost).runAsync(); - U.m(p, regexString(V.timeDecayLost, lost)); - } - } - - Bukkit.getScheduler().runTaskAsynchronously(tempfly, () -> { - double maxTime = getMaxTime(p.getUniqueId()); - if (maxTime == -999) { - return; - } - if (!p.hasPlayedBefore() && V.firstJoinTime > 0) { - Console.debug("--| User has not played before, do first join bonus..."); - double currentTime = getTime(p.getUniqueId()); - double bonus = maxTime > -1 && ((currentTime + V.firstJoinTime) > maxTime) ? maxTime - currentTime : V.firstJoinTime; - if (bonus > 0) { - new AsyncTimeParameters(tempfly, (AsyncTimeParameters parameters) -> { - addTime(p.getUniqueId(), parameters); - }, p, bonus).run(); - U.m(p, regexString(V.firstJoin, bonus)); - } - } - loginBonus(p, maxTime); - }); - - } - - /** - * Run the daily login bonus on a player. - * @param p - */ - public void loginBonus(Player p, double maxTime) { - Console.debug("--| Checking daily login bonus..."); - DataBridge bridge = tempfly.getDataBridge(); - long lastBonus = (long) bridge.getOrDefault(DataPointer.of(DataValue.PLAYER_DAILY_BONUS, p.getUniqueId().toString()), 0L); - long sys = System.currentTimeMillis(); - - if (new DailyDate(lastBonus).equals(new DailyDate(sys))) { - Console.debug("--|> Same day no daily bonus :("); - return; - } - double currentTime = getTime(p.getUniqueId()); - double bonus = 0; - if (V.legacyBonus > 0) { - Console.debug("--| Using legacy bonus..."); - bonus = maxTime > -1 && ((currentTime + V.legacyBonus) > maxTime) ? maxTime - currentTime : V.legacyBonus; - if (bonus > 0) { - new AsyncTimeParameters(tempfly, (AsyncTimeParameters parameters) -> { - addTime(p.getUniqueId(), parameters); - }, p, bonus).run(); - U.m(p, regexString(V.dailyLogin, bonus)); - } - bridge.stageChange(DataPointer.of(DataValue.PLAYER_DAILY_BONUS, p.getUniqueId().toString()), sys); - } else if (V.dailyBonus.size() > 0) { - Console.debug("--| Using permission based bonus..."); - for (Entry entry: V.dailyBonus.entrySet()) { - if (p.hasPermission("tempfly.bonus." + entry.getKey())) { - bonus += entry.getValue(); - } - } - bonus = maxTime > -1 && ((currentTime + bonus) > maxTime) ? maxTime - currentTime : bonus; - if (bonus > 0) { - new AsyncTimeParameters(tempfly, (AsyncTimeParameters parameters) -> { - addTime(p.getUniqueId(), parameters); - }, p, bonus).run(); - U.m(p, regexString(V.dailyLogin, bonus)); - } - bridge.stageChange(DataPointer.of(DataValue.PLAYER_DAILY_BONUS, p.getUniqueId().toString()), sys); - } - } - - public String regexString(String s, double seconds) { - //We dont care about the decimal here, it is only used internally for relative time regions. - long - days = formatTime(TimeUnit.DAYS, Math.ceil(seconds)), - hours = formatTime(TimeUnit.HOURS, Math.ceil(seconds)), - minutes = formatTime(TimeUnit.MINUTES, Math.ceil(seconds)), - secs = formatTime(TimeUnit.SECONDS, Math.ceil(seconds)); - - StringBuilder sb = new StringBuilder(); - if (s.contains("{FORMATTED_TIME}")) { - boolean addSpace = false; - if (days > 0) { - regexA(sb, days, V.unitDays, false); - addSpace = true; - } if (hours > 0) { - regexA(sb, hours, V.unitHours, addSpace); - addSpace = true; - } if (minutes > 0) { - regexA(sb, minutes, V.unitMinutes, addSpace); - addSpace = true; - } if (secs > 0 || sb.length() == 0) { - regexA(sb, secs, V.unitSeconds, addSpace); - } - } - return s.replaceAll("\\{FORMATTED_TIME}", sb.toString()) - .replaceAll("\\{DAYS}", String.valueOf(days)) - .replaceAll("\\{HOURS}", String.valueOf(hours)) - .replaceAll("\\{MINUTES}", String.valueOf(minutes)) - .replaceAll("\\{SECONDS}", String.valueOf(secs)); - } - - private void regexA(StringBuilder sb, long quantity, String unit, boolean addSpace) { - sb.append((addSpace ? " " : "") + V.timeFormat - .replaceAll("\\{QUANTITY}", String.valueOf(quantity)) - .replaceAll("\\{UNIT}", unit)); - } - - public long formatTime(TimeUnit unit, double seconds) { - switch (unit) { - case DAYS: - return (long)seconds / 86400; - case HOURS: - return (long)seconds % 86400 / 3600; - case MINUTES: - return (long)seconds % 3600 / 60; - case SECONDS: - return (long)seconds % 60; - default: - return 0; - } - } - - public String getPlaceHolder(Player p, Placeholder type) { - double supply = getTime(p.getUniqueId()); - FlightUser user = tempfly.getFlightManager().getUser(p); - if (user == null) { - return "broken message"; - } - switch (type) { - case TIME_FORMATTED: - { - long - days = formatTime(TimeUnit.DAYS, supply), - hours = formatTime(TimeUnit.HOURS, supply), - minutes = formatTime(TimeUnit.MINUTES, supply), - seconds = formatTime(TimeUnit.SECONDS, supply); - - StringBuilder sb = new StringBuilder(); - if (user.hasInfiniteFlight()) { - sb.append(V.infinity); - } else { - if (days > 0) - sb.append(V.fbDays.replaceAll("\\{DAYS}", String.valueOf(days))); - if (hours > 0) - sb.append(V.fbHours.replaceAll("\\{HOURS}", String.valueOf(hours))); - if (minutes > 0) - sb.append(V.fbMinutes.replaceAll("\\{MINUTES}", String.valueOf(minutes))); - if (seconds > 0 || sb.length() == 0) - sb.append(V.fbSeconds.replaceAll("\\{SECONDS}", String.valueOf(seconds))); - } - return sb.toString(); - } - case TIME_DAYS: - long days = formatTime(TimeUnit.DAYS, supply); - return String.valueOf(days); - case TIME_HOURS: - long hours = formatTime(TimeUnit.HOURS, supply); - return String.valueOf(hours); - case TIME_MINUTES: - long minutes = formatTime(TimeUnit.MINUTES, supply); - return String.valueOf(minutes); - case TIME_SECONDS: - long seconds = formatTime(TimeUnit.SECONDS, supply); - return String.valueOf(seconds); - case TIME_SECONDS_TOTAL: - return String.valueOf((int)Math.floor(supply)); - default: - break; - } - return "broken message"; - } - - - public static enum Placeholder { - TIME_FORMATTED, - TIME_DAYS, - TIME_HOURS, - TIME_MINUTES, - TIME_SECONDS, - TIME_SECONDS_TOTAL; - } -} +package com.moneybags.tempfly.time; + +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.TimeUnit; + +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.event.FlightUserInitializedEvent; +import com.moneybags.tempfly.user.FlightUser; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.DailyDate; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; +import com.moneybags.tempfly.util.data.DataBridge; +import com.moneybags.tempfly.util.data.DataPointer; + +import net.milkbowl.vault.permission.Permission; + +import com.moneybags.tempfly.util.data.DataBridge.DataValue; + +public class TimeManager implements Listener { + + private TempFly tempfly; + + public TimeManager(TempFly tempfly) { + this.tempfly = tempfly; + tempfly.getServer().getPluginManager().registerEvents(this, tempfly); + } + + /** + * Async + * + * Get a players time. + * If offline The databridge will return the most recent staged change + * held in memory for the players time if one exists. Otherwise it will need to pull it from the + * database / yaml data. + * @param u + * @return + */ + private boolean alreadyThrown; + public double getTime(UUID u) { + FlightUser user = tempfly.getFlightManager().getUser(u); + if (user == null && tempfly.getDataBridge().hasSqlEnabled() && Bukkit.getServer().isPrimaryThread() && !alreadyThrown) { + alreadyThrown = true; + try {throw new IllegalStateException("Invocation of getTime() for an offline player should be performed from an asychronous thread! It is not safe to access a database on the main server thread!");} catch (IllegalStateException e) { + e.printStackTrace(); + } + } + DataBridge bridge = tempfly.getDataBridge(); + // If user is not online the data needs pulled from the database. Otherwise get it from memory. + return user == null ? (double) bridge.getOrDefault(DataPointer.of(DataValue.PLAYER_TIME, u.toString()), 0d) : user.getTime(); + } + + /** + * Set a users time. + * If the user is online it will also update their FlightUser object with the new time + * stages the new time to the DataBridge. + * @param u the uuid of the player + * @param seconds The new seconds + */ + public void removeTime(UUID u, AsyncTimeParameters parameters) { + double seconds = parameters.getAmount(); + if (seconds <= 0) { + return; + } + FlightUser user = tempfly.getFlightManager().getUser(Bukkit.getPlayer(u)); + double bal = user == null ? parameters.getCurrentTime() : user.getTime(); + double remaining = (((bal-seconds) >= 0) ? (bal-seconds) : 0); + + if (user != null) { + user.setTime(remaining); + } else { + tempfly.getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_TIME, u.toString()), remaining); + } + } + + /** + * Add time to a user. + * If the user is online it will also update their FlightUser object with the new time + * stages the new time to the DataBridge. + * @param u the uuid of the player + * @param seconds The seconds to add + */ + public void addTime(UUID u, AsyncTimeParameters parameters) { + double seconds = parameters.getAmount(); + if (seconds <= 0) { + return; + } + FlightUser user = tempfly.getFlightManager().getUser(Bukkit.getPlayer(u)); + double maxTime = parameters.getMaxTime(); + if (maxTime == -999) { + return; + } + // If user is not online the data needs pulled from the database. Otherwise get it from memory. + double bal = user == null ? parameters.getCurrentTime() : user.getTime(); + // This line prevents an overflow to -Double.MAX_VALUE. + double remaining = (((bal+seconds) >= bal) ? (bal+seconds) : Double.MAX_VALUE); + if (maxTime > -1 && remaining > maxTime) { + remaining = maxTime; + } + + if (user != null) { + user.setTime(remaining); + } else { + tempfly.getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_TIME, u.toString()), remaining); + } + } + + /** + * Set a users time. + * If the user is online it will also update their FlightUser object with the new time + * stages the new time to the DataBridge. + * @param u the uuid of the player + * @param seconds The new seconds + */ + public void setTime(UUID u, AsyncTimeParameters parameters) { + double seconds = parameters.getAmount(); + if (seconds < 0) { + seconds = 0; + } + FlightUser user = tempfly.getFlightManager().getUser(Bukkit.getPlayer(u)); + double maxTime = parameters.getMaxTime(); + if (maxTime == -999) { + return; + } + if (maxTime > -1 && seconds > maxTime) { + seconds = maxTime; + } + + if (user != null) { + user.setTime(seconds); + } else { + if (tempfly.getDataBridge().hasSqlEnabled()) { + Console.warn("It is currently unsafe to alter player time for offline players while using MYSQL storage! The tempfly plugin currently does not sync player time between servers on a network. If this player is currently on a different server their time will not update and will be overwritten when they log off or switch servers."); + } + DataPointer pointer = DataPointer.of(DataValue.PLAYER_TIME, u.toString()); + tempfly.getDataBridge().stageChange(pointer, seconds); + tempfly.getDataBridge().manualCommit(pointer); + } + } + + + public double getMaxTime(UUID u) { + Console.debug("-- Get max time --"); + Player p = Bukkit.getPlayer(u); + double highest = 0; + boolean hasGroup = false; + if (p != null && p.isOnline()) { + Console.debug("--| Player is online..."); + for (Entry group: V.maxTimeGroups.entrySet()) { + double current = group.getValue(); + // If the group is less than the highest found so far continue. + if (current < highest && current > -1) { + continue; + } + if (p.hasPermission("tempfly.max." + group.getKey())) { + Console.debug("--| Player has group: " + group.getKey() + " | " + group.getValue()); + hasGroup = true; + if (current == -1) { + return current; + } else { + highest = current; + } + } + } + } else { + Console.debug("--| Player is offline..."); + if (!tempfly.getHookManager().hasPermissions()) { + Console.debug("--|> No vault permissions, We cannot check max time!"); + // We are returning -999 to indicate something is wrong and we cannot check the players max balance. + // In this case it is because the server does not have Vault and i can't check the offline players permissions. + return -999; + } + OfflinePlayer op = Bukkit.getOfflinePlayer(u); + Permission perms = tempfly.getHookManager().getPermissions(); + for (Entry group: V.maxTimeGroups.entrySet()) { + double current = group.getValue(); + if (current < highest && current > -1) { + continue; + } + if (op.isOp() || perms.playerHas(Bukkit.getWorlds().get(0).getName(), op, "tempfly.max." + group.getKey())) { + Console.debug("--| Player has group: " + group.getKey() + " | " + group.getValue()); + hasGroup = true; + if (current == -1) { + return current; + } else { + highest = current; + } + } + } + } + Console.debug("--|> Final value: " + (hasGroup ? highest : V.maxTimeBase)); + return hasGroup ? highest : V.maxTimeBase; + } + + + @EventHandler + public void onUserInitialized(FlightUserInitializedEvent e) { + Console.debug("", "--- Time manager will now process user initialization ---"); + Player p = e.getUser().getPlayer(); + if (V.timeDecay && p.hasPlayedBefore()) { + Console.debug("--| Time decay is enabled..."); + long offline = (System.currentTimeMillis() - p.getLastPlayed()) / 1000; + double lost = (offline / V.decayThresh) * V.decayAmount; + double time = e.getUser().getTime(); + lost = lost > time ? time : lost; + if (V.debug) Console.debug("--| Seconds offline: " + offline, "Threshold in seconds: " + V.decayThresh, "--| Seconds lost per threshold: " + V.decayAmount, "--| Seconds lost: " + lost, ""); + if (lost > 0) { + new AsyncTimeParameters(tempfly, (AsyncTimeParameters parameters) -> { + removeTime(p.getUniqueId(), parameters); + }, p, lost).runAsync(); + U.m(p, regexString(V.timeDecayLost, lost)); + } + } + + Bukkit.getScheduler().runTaskAsynchronously(tempfly, () -> { + double maxTime = getMaxTime(p.getUniqueId()); + if (maxTime == -999) { + return; + } + if (!p.hasPlayedBefore() && V.firstJoinTime > 0) { + Console.debug("--| User has not played before, do first join bonus..."); + double currentTime = getTime(p.getUniqueId()); + double bonus = maxTime > -1 && ((currentTime + V.firstJoinTime) > maxTime) ? maxTime - currentTime : V.firstJoinTime; + if (bonus > 0) { + new AsyncTimeParameters(tempfly, (AsyncTimeParameters parameters) -> { + addTime(p.getUniqueId(), parameters); + }, p, bonus).run(); + U.m(p, regexString(V.firstJoin, bonus)); + } + } + loginBonus(p, maxTime); + }); + + } + + /** + * Run the daily login bonus on a player. + * @param p + */ + public void loginBonus(Player p, double maxTime) { + Console.debug("--| Checking daily login bonus..."); + DataBridge bridge = tempfly.getDataBridge(); + long lastBonus = (long) bridge.getOrDefault(DataPointer.of(DataValue.PLAYER_DAILY_BONUS, p.getUniqueId().toString()), 0L); + long sys = System.currentTimeMillis(); + + if (new DailyDate(lastBonus).equals(new DailyDate(sys))) { + Console.debug("--|> Same day no daily bonus :("); + return; + } + double currentTime = getTime(p.getUniqueId()); + double bonus = 0; + if (V.legacyBonus > 0) { + Console.debug("--| Using legacy bonus..."); + bonus = maxTime > -1 && ((currentTime + V.legacyBonus) > maxTime) ? maxTime - currentTime : V.legacyBonus; + if (bonus > 0) { + new AsyncTimeParameters(tempfly, (AsyncTimeParameters parameters) -> { + addTime(p.getUniqueId(), parameters); + }, p, bonus).run(); + U.m(p, regexString(V.dailyLogin, bonus)); + } + bridge.stageChange(DataPointer.of(DataValue.PLAYER_DAILY_BONUS, p.getUniqueId().toString()), sys); + } else if (V.dailyBonus.size() > 0) { + Console.debug("--| Using permission based bonus..."); + for (Entry entry: V.dailyBonus.entrySet()) { + if (p.hasPermission("tempfly.bonus." + entry.getKey())) { + bonus += entry.getValue(); + } + } + bonus = maxTime > -1 && ((currentTime + bonus) > maxTime) ? maxTime - currentTime : bonus; + if (bonus > 0) { + new AsyncTimeParameters(tempfly, (AsyncTimeParameters parameters) -> { + addTime(p.getUniqueId(), parameters); + }, p, bonus).run(); + U.m(p, regexString(V.dailyLogin, bonus)); + } + bridge.stageChange(DataPointer.of(DataValue.PLAYER_DAILY_BONUS, p.getUniqueId().toString()), sys); + } + } + + public String regexString(String s, double seconds) { + //We dont care about the decimal here, it is only used internally for relative time regions. + long + days = formatTime(TimeUnit.DAYS, Math.ceil(seconds)), + hours = formatTime(TimeUnit.HOURS, Math.ceil(seconds)), + minutes = formatTime(TimeUnit.MINUTES, Math.ceil(seconds)), + secs = formatTime(TimeUnit.SECONDS, Math.ceil(seconds)); + + StringBuilder sb = new StringBuilder(); + if (s.contains("{FORMATTED_TIME}")) { + boolean addSpace = false; + if (days > 0) { + regexA(sb, days, V.unitDays, false); + addSpace = true; + } if (hours > 0) { + regexA(sb, hours, V.unitHours, addSpace); + addSpace = true; + } if (minutes > 0) { + regexA(sb, minutes, V.unitMinutes, addSpace); + addSpace = true; + } if (secs > 0 || sb.length() == 0) { + regexA(sb, secs, V.unitSeconds, addSpace); + } + } + return s.replaceAll("\\{FORMATTED_TIME}", sb.toString()) + .replaceAll("\\{DAYS}", String.valueOf(days)) + .replaceAll("\\{HOURS}", String.valueOf(hours)) + .replaceAll("\\{MINUTES}", String.valueOf(minutes)) + .replaceAll("\\{SECONDS}", String.valueOf(secs)); + } + + private void regexA(StringBuilder sb, long quantity, String unit, boolean addSpace) { + sb.append((addSpace ? " " : "") + V.timeFormat + .replaceAll("\\{QUANTITY}", String.valueOf(quantity)) + .replaceAll("\\{UNIT}", unit)); + } + + public long formatTime(TimeUnit unit, double seconds) { + switch (unit) { + case DAYS: + return (long)seconds / 86400; + case HOURS: + return (long)seconds % 86400 / 3600; + case MINUTES: + return (long)seconds % 3600 / 60; + case SECONDS: + return (long)seconds % 60; + default: + return 0; + } + } + + public String getPlaceHolder(Player p, Placeholder type) { + double supply = getTime(p.getUniqueId()); + FlightUser user = tempfly.getFlightManager().getUser(p); + if (user == null) { + return "broken message"; + } + switch (type) { + case TIME_FORMATTED: + { + long + days = formatTime(TimeUnit.DAYS, supply), + hours = formatTime(TimeUnit.HOURS, supply), + minutes = formatTime(TimeUnit.MINUTES, supply), + seconds = formatTime(TimeUnit.SECONDS, supply); + + StringBuilder sb = new StringBuilder(); + if (user.hasInfiniteFlight()) { + sb.append(V.infinity); + } else { + if (days > 0) + sb.append(V.fbDays.replaceAll("\\{DAYS}", String.valueOf(days))); + if (hours > 0) + sb.append(V.fbHours.replaceAll("\\{HOURS}", String.valueOf(hours))); + if (minutes > 0) + sb.append(V.fbMinutes.replaceAll("\\{MINUTES}", String.valueOf(minutes))); + if (seconds > 0 || sb.length() == 0) + sb.append(V.fbSeconds.replaceAll("\\{SECONDS}", String.valueOf(seconds))); + } + return sb.toString(); + } + case TIME_DAYS: + long days = formatTime(TimeUnit.DAYS, supply); + return String.valueOf(days); + case TIME_HOURS: + long hours = formatTime(TimeUnit.HOURS, supply); + return String.valueOf(hours); + case TIME_MINUTES: + long minutes = formatTime(TimeUnit.MINUTES, supply); + return String.valueOf(minutes); + case TIME_SECONDS: + long seconds = formatTime(TimeUnit.SECONDS, supply); + return String.valueOf(seconds); + case TIME_SECONDS_TOTAL: + return String.valueOf((int)Math.floor(supply)); + default: + break; + } + return "broken message"; + } + + + public static enum Placeholder { + TIME_FORMATTED, + TIME_DAYS, + TIME_HOURS, + TIME_MINUTES, + TIME_SECONDS, + TIME_SECONDS_TOTAL; + } +} diff --git a/TempFly/src/com/moneybags/tempfly/user/FlightUser.java b/src/com/moneybags/tempfly/user/FlightUser.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/user/FlightUser.java rename to src/com/moneybags/tempfly/user/FlightUser.java index e9c1289..f545656 100644 --- a/TempFly/src/com/moneybags/tempfly/user/FlightUser.java +++ b/src/com/moneybags/tempfly/user/FlightUser.java @@ -1,1106 +1,1106 @@ -package com.moneybags.tempfly.user; - -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.metadata.MetadataValue; -import org.bukkit.permissions.PermissionAttachmentInfo; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.scheduler.BukkitTask; - -import com.moneybags.tempfly.aesthetic.ActionBarAPI; -import com.moneybags.tempfly.aesthetic.TitleAPI; -import com.moneybags.tempfly.aesthetic.particle.Particles; -import com.moneybags.tempfly.environment.FlightEnvironment; -import com.moneybags.tempfly.environment.RelativeTimeRegion; -import com.moneybags.tempfly.fly.FlightManager; -import com.moneybags.tempfly.fly.RequirementProvider; -import com.moneybags.tempfly.fly.RequirementProvider.InquiryType; -import com.moneybags.tempfly.fly.result.FlightResult; -import com.moneybags.tempfly.hook.region.CompatRegion; -import com.moneybags.tempfly.time.TimeManager; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; -import com.moneybags.tempfly.util.data.DataBridge; -import com.moneybags.tempfly.util.data.DataPointer; -import com.moneybags.tempfly.util.data.DataBridge.DataValue; - - -public class FlightUser { - - - private final FlightManager manager; - private final TimeManager timeManager; - private final Player p; - private final UserEnvironment environment; - - //A list of reasons the player cannot currently fly. - private Map> requirements = new ConcurrentHashMap<>(); - - private BukkitTask - initialTask, enforceTask, damageProtection; - - private TempFlyTimer timer; - - private String - listName, tagName, particle; - - private boolean - enabled, autoEnable, - infinite = true, - bypass = true; - - private int - idle = -1; - - private double - time; - - private long - accumulativeCycle; - - private double - selectedSpeed = -999; - - public FlightUser(Player p, FlightManager manager, - double time, String particle, boolean infinite, boolean bypass, boolean logged, boolean compatLogged, - double selectedSpeed) { - this.manager = manager; - this.timeManager = manager.getTempFly().getTimeManager(); - - this.p = p; - this.time = time; - this.particle = particle; - this.infinite = infinite; - this.bypass = bypass; - this.selectedSpeed = selectedSpeed; - - this.environment = new UserEnvironment(this, p); - this.listName = p.getPlayerListName(); - this.tagName = p.getDisplayName(); - - manager.updateLocation(this, p.getLocation(), p.getLocation(), true, true); - - initialTask = Bukkit.getScheduler().runTaskLater(manager.getTempFly(), new InitialTask(logged, compatLogged), 1); - } - - private class InitialTask implements Runnable { - - boolean - logged, - compatLogged; - - public InitialTask(boolean logged, boolean compatLogged) { - this.logged = logged; - this.compatLogged = compatLogged; - } - - @Override - public void run() { - if (logged && (hasInfiniteFlight() || time > 0) && V.autoFly) { - Console.debug("--| Player is flight logged"); - if (!enableFlight()) { - sendRequirementMessage(); - enforce(1); - } else { - applySpeedCorrect(true, 0); - } - - - } else if (!compatLogged) { - // Compat flight log is when the player logs out while flying but not with tempfly. - // We want to save this value so tempfly doesnt break other plugins flight features. - Console.debug("--| Player is not compat flight logged"); - enforce(1); - if (V.permaTimer && time > 0) { - if (timer != null) { - timer.cancel(); - } - timer = new FlightTimer(); - } - } - manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_FLIGHT_LOG, p.getUniqueId().toString()), false); - manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_COMPAT_FLIGHT_LOG, p.getUniqueId().toString()), false); - } - - } - - public void save() { - Console.debug("", "-----< Save FlightUser: (" + p.getUniqueId().toString() + ") >-----"); - DataBridge bridge = manager.getTempFly().getDataBridge(); - String u = p.getUniqueId().toString(); - bridge.manualCommit( - DataPointer.of(DataValue.PLAYER_TIME, u), - DataPointer.of(DataValue.PLAYER_DAILY_BONUS, u), - DataPointer.of(DataValue.PLAYER_DAMAGE_PROTECTION, u), - DataPointer.of(DataValue.PLAYER_FLIGHT_LOG, u), - DataPointer.of(DataValue.PLAYER_COMPAT_FLIGHT_LOG, u), - DataPointer.of(DataValue.PLAYER_TRAIL, u), - DataPointer.of(DataValue.PLAYER_INFINITE, u), - DataPointer.of(DataValue.PLAYER_BYPASS, u), - DataPointer.of(DataValue.PLAYER_SPEED, u)); - } - - - public FlightManager getFlightManager() { - return manager; - } - - public double getTime() { - return time; - } - - public Player getPlayer() { - return p; - } - - public void setTime(double time) { - if (time <= 0) { - time = 0; - } - double oldTime = this.time; - this.time = time; - manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_TIME, p.getUniqueId().toString()), time); - if ((timer instanceof FlightTimer) - && !hasInfiniteFlight() - && p.isFlying()) { - if (V.actionBar) {doActionBar();} - } - if (time > 0 && (hasAutoFlyQueued()) && !enabled) { - enableFlight(); - } else if (time == 0) { - disableFlight(0, !V.damageTime); - autoEnable = true; - if (timer != null) { - timer.cancel(); - } - } else if (oldTime == 0 && time > 0 && !enabled && V.autoFlyTimeReceived) { - enableFlight(); - } else if (V.permaTimer) { - if (timer != null) { - timer.cancel(); - } - timer = new FlightTimer(); - } - } - - public void resetIdleTimer() { - this.idle = -1; - } - - public boolean isIdle() { - return V.idleThreshold > -1 && idle >= (V.idleThreshold*20); - } - - public boolean hasFlightEnabled() { - return enabled; - } - - public boolean hasAutoFlyQueued() { - return autoEnable;// && V.autoFly; - } - - public void setAutoFly(boolean auto) { - this.autoEnable = auto; - } - - public boolean isOpenForSubmission() { - return hasAutoFlyQueued() || hasFlightEnabled(); - } - - public UserEnvironment getEnvironment() { - return environment; - } - - /** - * @return true if the user has infinite flight and it is enabled. - */ - public boolean hasInfiniteFlight() { - return (p.hasPermission("tempfly.infinite") && infinite) || environment.hasInfiniteFlight(); - } - - /** - * Set whether the user has infinite flight enabled. This has no effect if they do not have the permission tempfly.infinite - * @param enable enable infinite flight? - */ - public void setInfiniteFlight(boolean enable) { - manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_INFINITE, p.getUniqueId().toString()), enable); - this.infinite = enable; - if (!enable && V.actionBar && time > 0) { - doActionBar(); - } else if (!enable && time <= 0) { - disableFlight(0, !V.damageCommand); - setAutoFly(true); - } else if (enable && hasAutoFlyQueued()) { - enableFlight(); - } - } - - /** - * @return true if the user has requirement bypass and it is enabled. - */ - public boolean hasRequirementBypass() { - return p.hasPermission("tempfly.bypass") && bypass; - } - - /** - * Set whether the user has requirement bypass enabled. This has no effect if they do not have the permission tempfly.bypass - * @param enable enable requirement bypass? - */ - public void setRequirementBypass(boolean enable) { - manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_BYPASS, p.getUniqueId().toString()), enable); - this.bypass = enable; - if (enable && hasAutoFlyQueued()) { - enableFlight(); - } else if (!enable && hasFlightEnabled() && hasFlightRequirements()) { - FlightResult result = getCurrentRequirement(); - U.m(p, result.getMessage()); - disableFlight(0, result.hasDamageProtection()); - setAutoFly(true); - } - } - - - /** - * - * --=--------------=-- - * Flight Control - * --=--------------=-- - * - */ - - - - /** - * Internal clean up method called when the player quits or server is reloading. - */ - public void onQuit(boolean reload) { - if (enabled || hasAutoFlyQueued()) { - manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_FLIGHT_LOG, p.getUniqueId().toString()), true); - if (!reload) {disableFlight(-1, false);} - } else if (p.isFlying()) { - manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_COMPAT_FLIGHT_LOG, p.getUniqueId().toString()), true); - } - updateList(true); - updateName(true); - save(); - if (initialTask != null) {initialTask.cancel();} - if (enforceTask != null) {enforceTask.cancel();} - if (timer != null) {timer.cancel();} - removeDamageProtection(); - } - - /** - * This is a safety method to make sure a players flight is disabled. - * This will only try to remove flight if the user has flight mode disabled but are flying anyway. - * - * @param delay The delay in ticks to enforce removal of flight. 1 should suffice. - */ - public void enforce(int delay) { - Console.debug("enforcing disabled flight"); - if (enforceTask != null) { - enforceTask.cancel(); - } - enforceTask = Bukkit.getScheduler().runTaskLater(manager.getTempFly(), new EnforceTask(), delay); - } - - /** - * TODO - * if players take fall damage when flight is lost and they are not supposed to - * there is an infinite flight bug somewhere to track down because the enforcement task is - * removing the flight after is was supposed to be disabled without adding the proper damage protec1tion. - * @author Kevin - * - */ - public class EnforceTask implements Runnable { - - @Override - public void run() { - // If the users flight is enabled again when the task runs we will return. - if (enabled) return; - GameMode m = p.getGameMode(); - if (m == GameMode.CREATIVE && V.creativeTimer) { - Console.debug("--- Enforcing disabled flight A ----"); - p.setFlying(false); - p.setAllowFlight(false); - } else if (m != GameMode.CREATIVE && m != GameMode.SPECTATOR) { - Console.debug("--- Enforcing disabled flight B ----"); - p.setFlying(false); - p.setAllowFlight(false); - } - - } - - } - - /** - * Turn off players flight with a safety delay that will enforce proper removal of flight. - * @param delay The delay in ticks to enforce removal of flight. 1 should suffice. -1 for no enforcement - */ - public void disableFlight(int delay, boolean fallSafely) { - Console.debug("------ disable flight -------"); - if (!enabled) {return;} - enabled = false; - //TODO - if (timer != null && (!V.permaTimer || time <= 0)) { - timer.cancel(); - timer = null; - } - GameMode m = p.getGameMode(); - updateList(true); - updateName(true); - // Fixes a weird bug where fall damage accumulates through flight and damages even when 1 block off the ground. - if (p.isFlying()) {p.setFallDistance(0);} - if (m == GameMode.CREATIVE && V.creativeTimer) { - Console.debug("--> set flying false 1"); - p.setFlying(false); - p.setAllowFlight(false); - } else if (m != GameMode.CREATIVE && m != GameMode.SPECTATOR) { - Console.debug("--> set flying false 2"); - p.setFlying(false); - p.setAllowFlight(false); - if (fallSafely) {addDamageProtection();} - } - if (delay > -1) {enforce(delay);} - } - - /** - * Enable the users flight - * @return false if the users flight can not be enabled due to flight requirements. - */ - @SuppressWarnings("deprecation") - public boolean enableFlight() { - Console.debug("------ enable flight -------"); - if (hasFlightRequirements() && !hasRequirementBypass()) { - setAutoFly(true); - return false; - } - if (time == 0 && !hasInfiniteFlight()) { - setAutoFly(true); - return false; - } - Console.debug("--> set flying true"); - enabled = true; - p.setAllowFlight(true); - p.setFlying(!p.isOnGround()); - applySpeedCorrect(true, 0); - if (timer == null) { - this.timer = new FlightTimer(); - } - return true; - } - - /** - * Method to make sure a player can fly when they are supposed to. - */ - public void applyFlightCorrect() { - Console.debug("------ apply flight correct -------"); - Bukkit.getScheduler().runTaskLater(manager.getTempFly(), () -> { - if (p.isOnline() && hasFlightEnabled()) { - p.setAllowFlight(true); - p.setFlying(true); - } - }, 1); - } - - /** - * - * --=-----------=-- - * Requirement - * --=-----------=-- - * - */ - - - - public RequirementProvider[] getFlightRequirements() { - return requirements.keySet().toArray(new RequirementProvider[requirements.size()]); - } - - public boolean hasFlightRequirement(RequirementProvider requirement) { - return requirements.containsKey(requirement); - } - - public boolean hasFlightRequirement(RequirementProvider requirement, InquiryType type) { - return requirements.getOrDefault(requirement, new HashMap<>()).containsKey(type); - } - - public boolean hasFlightRequirements() { - return requirements.size() > 0; - } - - public void submitFlightRequirement(RequirementProvider requirement, FlightResult failedResult) { - if (V.debug) {Console.debug("", "---- Submitting failed requirement to user (" + p.getName() + ") ----", "--| Requirement: " + requirement.getClass().toGenericString(), "--| Requirements: " + requirements);} - Map types = requirements.getOrDefault(requirement, new HashMap<>()); - InquiryType type = failedResult.getInquiryType(); - if (types.containsKey(type)) { - types.remove(type); - } - types.put(type, failedResult); - this.requirements.put(requirement, types); - if (enabled) { - autoEnable = true; - } - } - - /** - * - * @param requirement - * @param type - * @return true if there are no more requirements - */ - public boolean removeFlightRequirement(RequirementProvider requirement, InquiryType type) { - if (V.debug) {Console.debug("", "---- Removing flight requirement from user ----", "--| Requirement: " + requirement.getClass().toGenericString(), "--| Requirements: " + requirements);} - Map types = requirements.getOrDefault(requirement, new HashMap<>()); - types.remove(type); - if (types.size() == 0) { - this.requirements.remove(requirement); - } else { - this.requirements.put(requirement, types); - } - return !hasFlightRequirements(); - } - - /** - * - * @param requirement - * @param type - * @return true if there are no more requirements - */ - public boolean removeFlightRequirement(RequirementProvider requirement) { - if (V.debug) {Console.debug("", "---- Removing flight requirement from user ----", "--| Requirement: " + requirement.getClass().toGenericString(), "--| Requirements: " + requirements);} - this.requirements.remove(requirement); - return !hasFlightRequirements(); - } - - public void removeFlightRequirements() { - this.requirements.clear(); - } - - public void sendRequirementMessage() { - if (hasFlightRequirements()) { - // lmao whats this trash - U.m(p, requirements.values().iterator().next().values().iterator().next().getMessage()); - } - } - - public FlightResult getCurrentRequirement() { - if (hasFlightRequirements()) { - return requirements.values().iterator().next().values().iterator().next(); - } - return null; - } - - /** - * Quality of life method. - * Evaluate the overall flight status of the user, checks all flight requirements present on the server. - * Used mainly when a player first joins or for some reason is not being tracked and we need to re-check everything. - * Flight will be disabled if a requirement fails. - * The requirement will then be submitted to the user for the auto flight enable feature. - * - * @return false if the user fails. - */ - public boolean evaluateFlightRequirements(Location loc, boolean failMessage) { - List results = new ArrayList<>(); - results.addAll(manager.inquireFlight(this, loc.getWorld())); - results.addAll(manager.inquireFlight(this, loc)); - if (manager.getTempFly().getHookManager().hasRegionProvider()) { - results.addAll(manager.inquireFlight(this, manager.getTempFly().getHookManager().getRegionProvider().getApplicableRegions(p.getLocation()))); - } - results.addAll(manager.inquireFlightBeyondScope(this)); - submitFlightResults(results, false); - if (hasFlightRequirements()) { - if (!hasRequirementBypass() && failMessage) { - sendRequirementMessage(); - } - return false; - } - return true; - } - - /** - * Evaluate the flight status of the user for the requirements introduced by the provider. - * Flight will be disabled if a requirement fails. - * The requirement will then be submitted to the user for the auto flight enable feature. - * - * @param failMessage Do you want the fail message to be sent to the user if they cannot fly? - * @return false if the user fails. - */ - - public boolean evaluateFlightRequirement(RequirementProvider requirement, Location loc) { - List results = new ArrayList<>(); - if (!requirement.handles(InquiryType.WORLD)) { - results.add(requirement.handleFlightInquiry(this, loc.getWorld())); - } - if (!requirement.handles(InquiryType.LOCATION)) { - results.add(requirement.handleFlightInquiry(this, loc)); - } - if (!requirement.handles(InquiryType.REGION) - && manager.getTempFly().getHookManager().hasRegionProvider()) { - results.add(requirement.handleFlightInquiry(this, environment.getCurrentRegionSet())); - } - return submitFlightResults(results, hasFlightEnabled()) && hasFlightRequirement(requirement); - } - - - /** - * Submit a batch of flight results to the FlightUser. - * @param results The results to submit - * @return false if the results disabled the users flight aka user failed. - */ - public boolean submitFlightResult(FlightResult result) { - RequirementProvider provider = result.getRequirement(); - InquiryType type = result.getInquiryType(); - if (!result.isAllowed()) { - submitFlightRequirement(provider, result); - if (!hasRequirementBypass()) { - if (hasFlightEnabled()) { - U.m(p, result.getMessage()); - } - disableFlight(1, result.hasDamageProtection()); - } - return false; - } else { - if (hasFlightRequirement(provider, type) && removeFlightRequirement(provider, type)) { - updateRequirements(result.getMessage()); - } - } - return true; - } - - /** - * Submit a batch of flight results. - * @param results - * @return - */ - public boolean submitFlightResults(List results, boolean failMessage) { - // The result that actually disabled the flight. first come first serve. - FlightResult disabled = null; - // The final result that enabled the flight. - FlightResult enable = null; - - for (FlightResult result: results) { - RequirementProvider provider = result.getRequirement(); - InquiryType type = result.getInquiryType(); - if (!result.isAllowed()) { - if (disabled == null) { - disabled = result; - } - if (!hasFlightRequirement(provider, type)) { - submitFlightRequirement(provider, result); - } - } else { - if (hasFlightRequirement(provider, type) && removeFlightRequirement(provider, type)) { - enable = result; - } - } - } - if (disabled != null) { - if (!hasRequirementBypass()) { - if (failMessage) { - U.m(p, disabled.getMessage()); - } - disableFlight(1, disabled.hasDamageProtection()); - } - return false; - } else if (enable != null) { - updateRequirements(enable.getMessage()); - } - return true; - } - - /** - * Update the flight requirements for the user. Automatically auto enables flight if applicable. - * @return True if there are no more requirements. - */ - public boolean updateRequirements(String enableMessage) { - Console.debug("", "--- updating requirements ---", "--| requirements: " + requirements.toString(), - "--| flight enabled: " + enabled, "--| auto flight: " + autoEnable, "--| time: " + time); - - if (requirements.size() == 0 && !hasFlightEnabled() && (time > 0 || hasInfiniteFlight())) { - if (hasAutoFlyQueued()) { - autoEnable = false; - if (!hasRequirementBypass()) { - Console.debug("--|> AutoFly engaged!"); - U.m(p, enableMessage); - enableFlight(); - } else { - Console.debug("--|> Autofly will not be invoked, User has requirement bypass mode..."); - } - } - return true; - } - return requirements.size() == 0; - } - - - - /** - * - * --=-----------=-- - * Fall Damage - * --=-----------=-- - * - */ - - - public void addDamageProtection() { - removeDamageProtection(); - damageProtection = Bukkit.getScheduler().runTaskLater(manager.getTempFly(), () -> { - removeDamageProtection(); - }, 120); - } - - public void removeDamageProtection() { - if (damageProtection != null) { - damageProtection.cancel(); - damageProtection = null; - } - } - - public boolean hasDamageProtection() { - return damageProtection != null; - } - - - - /** - * - * --=----------=-- - * Aesthetics - * --=----------=-- - * - */ - - - - /** - * This method returns a string to keep the plugin compatible through versions. - * @return The enum string representation of the particle - */ - public String getTrail() { - return particle; - } - - /** - * This method requires a string to keep the plugin compatible through versions. - * The enum value of the particle as a string - * @param particle - */ - public void setTrail(String particle) { - this.particle = particle; - manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_TRAIL, p.getUniqueId().toString()), particle); - } - - public void playTrail() { - if (particle == null || particle.length() == 0) {return;} - - if (p.getGameMode() == GameMode.SPECTATOR) { - return; - } - - if (V.hideVanish) { - for (MetadataValue meta : p.getMetadata("vanished")) { - if (meta.asBoolean()) { - return; - } - } - } - - - Particles.play(p.getLocation(), particle); - } - - public String getListPlaceholder() { - return timeManager.regexString((p.isFlying() && hasFlightEnabled() ? V.listPlaceholderOn : V.listPlaceholderOff) - .replaceAll("\\{PLAYER}", p.getName()) - .replaceAll("\\{OLD_TAG}", listName), time); - } - - public String getTagPlaceholder() { - return timeManager.regexString((p.isFlying() && hasFlightEnabled() ? V.tagPlaceholderOn : V.tagPlaceholderOff) - .replaceAll("\\{PLAYER}", p.getName()) - .replaceAll("\\{OLD_TAG}", tagName), time); - } - - private void updateList(boolean reset) { - if (!V.list) {return;} - p.setPlayerListName(!p.isFlying() || reset - ? listName : timeManager.regexString(V.listName - .replaceAll("\\{PLAYER}", p.getName()) - .replaceAll("\\{OLD_TAG}", tagName), time)); - } - - private void updateName(boolean reset) { - if (!V.tag) {return;} - p.setDisplayName(!p.isFlying() || reset - ? tagName : timeManager.regexString(V.tagName - .replaceAll("\\{PLAYER}", p.getName()) - .replaceAll("\\{OLD_TAG}", tagName), time)); - } - - public void doActionBar() { - ActionBarAPI.sendActionBar(p, timeManager.regexString(V.actionText, getTime())); - } - - - /** - * - * --=-----------=-- - * Speed control - * --=-----------=-- - * - */ - - public double getSpeedPreference() { - return selectedSpeed; - } - - public void setSpeedPreference(double speed) { - this.selectedSpeed = speed; - manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_SPEED, p.getUniqueId().toString()), speed); - } - - public boolean hasSpeedPreference() { - return selectedSpeed > -1 && manager.getFlightEnvironment().allowSpeedPreference(); - } - - /** - * Correct the users flight speed. Takes into account permissions and max world / region speeds. - * @return The resulting speed of the user. - */ - public float applySpeedCorrect(boolean message, int delay) { - float maxSpeed = getMaxSpeed(); - Console.debug("--| Max speed: " + String.valueOf(maxSpeed)); - Console.debug("--| Preferred speed: " + String.valueOf(selectedSpeed)); - if (hasSpeedPreference() && maxSpeed > selectedSpeed && manager.getFlightEnvironment().allowSpeedPreference()) { - maxSpeed = (float) selectedSpeed; - } - - final float val = maxSpeed / 10; - final float def = manager.getFlightEnvironment().getDefaultSpeed() / 10; - Console.debug("--| final speed value: " + val); - if (p.getFlySpeed() > val - || (p.getFlySpeed() != val && !manager.getFlightEnvironment().allowSpeedPreference()) - || (p.getFlySpeed() < val && hasSpeedPreference())) { - Console.debug("--| Players speed needs to be changed."); - Bukkit.getScheduler().runTaskLater(manager.getTempFly(), () -> { - Console.debug("-----> | changing player speed"); - if (p.isOnline()) { - Console.debug("player speed: " + p.getFlySpeed(), "value: " + val); - Console.debug("is speed prefernce allowed? " + manager.getFlightEnvironment().allowSpeedPreference(), - p.getFlySpeed() != val && !manager.getFlightEnvironment().allowSpeedPreference()); - if (p.getFlySpeed() > val && message) { - U.m(p, V.flySpeedLimitSelf.replaceAll("\\{SPEED}", new DecimalFormat("#.##").format(val * 10))); - } - p.setFlySpeed((float) val); - } - }, delay); - - } else if (p.getFlySpeed() != def && !hasSpeedPreference()) { - float fin = Math.min(def, val); - Console.debug("--| Players speed needs to be fixed it is stuck under default speed."); - Bukkit.getScheduler().runTaskLater(manager.getTempFly(), () -> { - Console.debug("-----> | changing player speed"); - if (p.isOnline()) { - Console.debug("player speed: " + p.getFlySpeed(), "value: " + val); - p.setFlySpeed(fin); - } - }, delay); - } - return val; - } - - public float getMaxSpeed() { - Console.debug("get max speed 1"); - CompatRegion[] regions = environment.getCurrentRegionSet(); - FlightEnvironment env = manager.getFlightEnvironment(); - - // Permissions for region speed take priority - float finSpeed = getMaxSpeed(regions); - if (finSpeed != -999) { - Console.debug("2: " + finSpeed); - return finSpeed; - } else if (env.hasMaxSpeed(regions)) { - Console.debug("4: " + env.getMaxSpeed(regions)); - return env.getMaxSpeed(regions); - } - - // Permissions for world speed go next - finSpeed = getMaxSpeed(p.getWorld()); - if (finSpeed != -999) { - Console.debug("3: " + finSpeed); - return finSpeed; - } else if (env.hasMaxSpeed(p.getWorld())) { - Console.debug("4: " + env.getMaxSpeed(p.getWorld())); - return env.getMaxSpeed(p.getWorld()); - } - - // return default environment speed indicator - Console.debug("5: " + env.getDefaultSpeed()); - return env.getDefaultSpeed(); - } - - public float getMaxSpeed(World world) { - return this.calculatePermissionSpeed("world." + world.getName(), "world.*"); - } - - public float getMaxSpeed(CompatRegion[] regions) { - float permSpeed = -999; - for (CompatRegion region: regions) { - permSpeed = Math.max(calculatePermissionSpeed("region." + region.getId(), "region.*"), permSpeed); - Console.debug("--| Region: " + region.getId(), "--| Permission speed for this region is: " + permSpeed); - } - return permSpeed; - } - - private float calculatePermissionSpeed(String permission, String wildcard) { - Console.debug("calc perm speed : " + permission); - float maxBase = -999; - - float maxFound = 0; - for (PermissionAttachmentInfo info: p.getEffectivePermissions()) { - String perm = info.getPermission(); - if (perm.startsWith("tempfly.speed." + permission) - || perm.startsWith("tempfly.speed." + wildcard)) { - Console.debug("found: " + perm); - String[] split = perm.split("\\."); - if (split.length < 5) { - Console.debug("less than 5"); - continue; - } - String num = split[4]; - if (split.length > 5) { - num = num.concat("." + split[5]); - } - num = num.replaceAll("\\[", "").replaceAll("\\]", ""); - Console.debug(num); - try { - float found = Float.parseFloat(num); - maxFound = Math.max(found, maxFound); - } catch (Exception e) {} - } - } - if (maxFound > 0) { - maxBase = maxFound; - } - Console.debug("maxbase: " + maxBase); - - return maxBase; - } - - - /** - * - * --=---------=-- - * Timers - * --=---------=-- - * - */ - - - public boolean hasTimer() { - return this.timer != null; - } - - public abstract class TempFlyTimer extends BukkitRunnable { - - } - - /** - * Ground timer runs every tick when FlightTimer isnt scheduled and simply checks if the player is flying. - * This way the FlightTimer will run as soon as the player starts flying. Otherwise it kinda looks laggy. - * @author Kevin - * - */ - public class GroundTimer extends TempFlyTimer { - - private static final int DELAY = 3; - - public GroundTimer() { - Console.debug("--- new ground timer ---"); - this.runTaskTimer(manager.getTempFly(), 1, DELAY); - } - - @SuppressWarnings("deprecation") - @Override - public void run() { - idle += DELAY; - if (p.isFlying() || V.permaTimer || (V.groundTimer && p.isOnGround())) { - if (!V.idleTimer && isIdle()) { - return; - } - if (p.getGameMode() == GameMode.CREATIVE && !V.creativeTimer) { - return; - } - if (p.getGameMode() == GameMode.SPECTATOR && !V.spectatorTimer) { - return; - } - if (p.getVehicle() != null) { - return; - } - this.cancel(); - timer = new FlightTimer(); - } - } - - } - - /** - * FlightTimer runs every 20 ticks and is in charge of decrementing time among other things such as - * action bar messages. - * @author Kevin - * - */ - - // It looks like were having spaghetti for dinner - public class FlightTimer extends TempFlyTimer { - - private static final int DELAY = 3; - - private boolean previouslyFlying; - - public FlightTimer() { - Console.debug("--- new flight timer--- "); - this.runTaskTimer(manager.getTempFly(), 0, DELAY); - if (doFlightTimer() && V.actionBar && !hasInfiniteFlight() && time > 0) { - doActionBar(); - } - } - - @Override - public void run() { - idle += DELAY; - // Update the players identifiers each tick as it isn't resource heavy it looks good. - doIdentifier(); - // This line fixed an unknown confliction with another plugin on some guys server so i'l just leave it. - //if (enabled) {p.setAllowFlight(true);} - - if (hasInfiniteFlight()) { - return; - } - - if (!doFlightTimer()) { - this.cancel(); - timer = time > 0 ? new GroundTimer() : null; - return; - } - - accumulativeCycle += DELAY * 50; - if (accumulativeCycle >= 1000) { - accumulativeCycle = 0; - executeTimer(); - return; - } - - } - - @Override - public void cancel() { - super.cancel(); - } - - private void executeTimer() { - if (time > 0) { - - double cost = 1; - for (RelativeTimeRegion rtr : environment.getRelativeTimeRegions()) { - cost *= rtr.getFactor(); - } - time = time-cost; - if (time < 0) time = 0; - - manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_TIME, p.getUniqueId().toString()), time); - - if (V.warningTimes.contains((long)time)) { - TitleAPI.sendTitle(p, 15, 30, 15, timeManager.regexString(V.warningTitle, time), - timeManager.regexString(V.warningSubtitle, time)); - } - if (V.actionBar) {doActionBar();} - - if (time == 0) { - timeExpired(); - } - } else if (enabled) { - timeExpired(); - } - } - - private void timeExpired() { - disableFlight(-1, !V.damageTime); - U.m(p, V.invalidTimeSelf); - autoEnable = true; - } - - private boolean doFlightTimer() { - if (time <= 0) { - return false; - } - if (V.permaTimer) { - return doIdleCheck(); - } - if (p.getGameMode() == GameMode.CREATIVE && !V.creativeTimer) { - return false; - } - if (p.getGameMode() == GameMode.SPECTATOR && !V.spectatorTimer) { - return false; - } - if (p.getVehicle() != null) { - return false; - } - if (!p.isFlying()) { - if (V.groundTimer && !doIdleCheck()) { - return false; - } - return V.groundTimer; - } - return doIdleCheck(); - } - - private void doIdentifier() { - if (!enabled) { - return; - } - if (previouslyFlying && !p.isFlying() || !previouslyFlying && p.isFlying()) { - updateList(!p.isFlying()); - updateName(!p.isFlying()); - } - previouslyFlying = p.isFlying(); - } - - /** - * - * @return True if the timer should continue, false if it can switch to ground timer. - */ - private boolean messaged = false; - - private boolean doIdleCheck() { - if (isIdle()) { - if (V.idleDrop) { - disableFlight(0, !V.damageIdle); - } - - if (!this.messaged) { - U.m(p, V.idleDrop ? V.disabledIdle : V.consideredIdle); - this.messaged = true; - } - return V.idleTimer; - } else { - this.messaged = false; - } - - return true; - } - - } -} +package com.moneybags.tempfly.user; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.permissions.PermissionAttachmentInfo; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; + +import com.moneybags.tempfly.aesthetic.ActionBarAPI; +import com.moneybags.tempfly.aesthetic.TitleAPI; +import com.moneybags.tempfly.aesthetic.particle.Particles; +import com.moneybags.tempfly.environment.FlightEnvironment; +import com.moneybags.tempfly.environment.RelativeTimeRegion; +import com.moneybags.tempfly.fly.FlightManager; +import com.moneybags.tempfly.fly.RequirementProvider; +import com.moneybags.tempfly.fly.RequirementProvider.InquiryType; +import com.moneybags.tempfly.fly.result.FlightResult; +import com.moneybags.tempfly.hook.region.CompatRegion; +import com.moneybags.tempfly.time.TimeManager; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; +import com.moneybags.tempfly.util.data.DataBridge; +import com.moneybags.tempfly.util.data.DataPointer; +import com.moneybags.tempfly.util.data.DataBridge.DataValue; + + +public class FlightUser { + + + private final FlightManager manager; + private final TimeManager timeManager; + private final Player p; + private final UserEnvironment environment; + + //A list of reasons the player cannot currently fly. + private Map> requirements = new ConcurrentHashMap<>(); + + private BukkitTask + initialTask, enforceTask, damageProtection; + + private TempFlyTimer timer; + + private String + listName, tagName, particle; + + private boolean + enabled, autoEnable, + infinite = true, + bypass = true; + + private int + idle = -1; + + private double + time; + + private long + accumulativeCycle; + + private double + selectedSpeed = -999; + + public FlightUser(Player p, FlightManager manager, + double time, String particle, boolean infinite, boolean bypass, boolean logged, boolean compatLogged, + double selectedSpeed) { + this.manager = manager; + this.timeManager = manager.getTempFly().getTimeManager(); + + this.p = p; + this.time = time; + this.particle = particle; + this.infinite = infinite; + this.bypass = bypass; + this.selectedSpeed = selectedSpeed; + + this.environment = new UserEnvironment(this, p); + this.listName = p.getPlayerListName(); + this.tagName = p.getDisplayName(); + + manager.updateLocation(this, p.getLocation(), p.getLocation(), true, true); + + initialTask = Bukkit.getScheduler().runTaskLater(manager.getTempFly(), new InitialTask(logged, compatLogged), 1); + } + + private class InitialTask implements Runnable { + + boolean + logged, + compatLogged; + + public InitialTask(boolean logged, boolean compatLogged) { + this.logged = logged; + this.compatLogged = compatLogged; + } + + @Override + public void run() { + if (logged && (hasInfiniteFlight() || time > 0) && V.autoFly) { + Console.debug("--| Player is flight logged"); + if (!enableFlight()) { + sendRequirementMessage(); + enforce(1); + } else { + applySpeedCorrect(true, 0); + } + + + } else if (!compatLogged) { + // Compat flight log is when the player logs out while flying but not with tempfly. + // We want to save this value so tempfly doesnt break other plugins flight features. + Console.debug("--| Player is not compat flight logged"); + enforce(1); + if (V.permaTimer && time > 0) { + if (timer != null) { + timer.cancel(); + } + timer = new FlightTimer(); + } + } + manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_FLIGHT_LOG, p.getUniqueId().toString()), false); + manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_COMPAT_FLIGHT_LOG, p.getUniqueId().toString()), false); + } + + } + + public void save() { + Console.debug("", "-----< Save FlightUser: (" + p.getUniqueId().toString() + ") >-----"); + DataBridge bridge = manager.getTempFly().getDataBridge(); + String u = p.getUniqueId().toString(); + bridge.manualCommit( + DataPointer.of(DataValue.PLAYER_TIME, u), + DataPointer.of(DataValue.PLAYER_DAILY_BONUS, u), + DataPointer.of(DataValue.PLAYER_DAMAGE_PROTECTION, u), + DataPointer.of(DataValue.PLAYER_FLIGHT_LOG, u), + DataPointer.of(DataValue.PLAYER_COMPAT_FLIGHT_LOG, u), + DataPointer.of(DataValue.PLAYER_TRAIL, u), + DataPointer.of(DataValue.PLAYER_INFINITE, u), + DataPointer.of(DataValue.PLAYER_BYPASS, u), + DataPointer.of(DataValue.PLAYER_SPEED, u)); + } + + + public FlightManager getFlightManager() { + return manager; + } + + public double getTime() { + return time; + } + + public Player getPlayer() { + return p; + } + + public void setTime(double time) { + if (time <= 0) { + time = 0; + } + double oldTime = this.time; + this.time = time; + manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_TIME, p.getUniqueId().toString()), time); + if ((timer instanceof FlightTimer) + && !hasInfiniteFlight() + && p.isFlying()) { + if (V.actionBar) {doActionBar();} + } + if (time > 0 && (hasAutoFlyQueued()) && !enabled) { + enableFlight(); + } else if (time == 0) { + disableFlight(0, !V.damageTime); + autoEnable = true; + if (timer != null) { + timer.cancel(); + } + } else if (oldTime == 0 && time > 0 && !enabled && V.autoFlyTimeReceived) { + enableFlight(); + } else if (V.permaTimer) { + if (timer != null) { + timer.cancel(); + } + timer = new FlightTimer(); + } + } + + public void resetIdleTimer() { + this.idle = -1; + } + + public boolean isIdle() { + return V.idleThreshold > -1 && idle >= (V.idleThreshold*20); + } + + public boolean hasFlightEnabled() { + return enabled; + } + + public boolean hasAutoFlyQueued() { + return autoEnable;// && V.autoFly; + } + + public void setAutoFly(boolean auto) { + this.autoEnable = auto; + } + + public boolean isOpenForSubmission() { + return hasAutoFlyQueued() || hasFlightEnabled(); + } + + public UserEnvironment getEnvironment() { + return environment; + } + + /** + * @return true if the user has infinite flight and it is enabled. + */ + public boolean hasInfiniteFlight() { + return (p.hasPermission("tempfly.infinite") && infinite) || environment.hasInfiniteFlight(); + } + + /** + * Set whether the user has infinite flight enabled. This has no effect if they do not have the permission tempfly.infinite + * @param enable enable infinite flight? + */ + public void setInfiniteFlight(boolean enable) { + manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_INFINITE, p.getUniqueId().toString()), enable); + this.infinite = enable; + if (!enable && V.actionBar && time > 0) { + doActionBar(); + } else if (!enable && time <= 0) { + disableFlight(0, !V.damageCommand); + setAutoFly(true); + } else if (enable && hasAutoFlyQueued()) { + enableFlight(); + } + } + + /** + * @return true if the user has requirement bypass and it is enabled. + */ + public boolean hasRequirementBypass() { + return p.hasPermission("tempfly.bypass") && bypass; + } + + /** + * Set whether the user has requirement bypass enabled. This has no effect if they do not have the permission tempfly.bypass + * @param enable enable requirement bypass? + */ + public void setRequirementBypass(boolean enable) { + manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_BYPASS, p.getUniqueId().toString()), enable); + this.bypass = enable; + if (enable && hasAutoFlyQueued()) { + enableFlight(); + } else if (!enable && hasFlightEnabled() && hasFlightRequirements()) { + FlightResult result = getCurrentRequirement(); + U.m(p, result.getMessage()); + disableFlight(0, result.hasDamageProtection()); + setAutoFly(true); + } + } + + + /** + * + * --=--------------=-- + * Flight Control + * --=--------------=-- + * + */ + + + + /** + * Internal clean up method called when the player quits or server is reloading. + */ + public void onQuit(boolean reload) { + if (enabled || hasAutoFlyQueued()) { + manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_FLIGHT_LOG, p.getUniqueId().toString()), true); + if (!reload) {disableFlight(-1, false);} + } else if (p.isFlying()) { + manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_COMPAT_FLIGHT_LOG, p.getUniqueId().toString()), true); + } + updateList(true); + updateName(true); + save(); + if (initialTask != null) {initialTask.cancel();} + if (enforceTask != null) {enforceTask.cancel();} + if (timer != null) {timer.cancel();} + removeDamageProtection(); + } + + /** + * This is a safety method to make sure a players flight is disabled. + * This will only try to remove flight if the user has flight mode disabled but are flying anyway. + * + * @param delay The delay in ticks to enforce removal of flight. 1 should suffice. + */ + public void enforce(int delay) { + Console.debug("enforcing disabled flight"); + if (enforceTask != null) { + enforceTask.cancel(); + } + enforceTask = Bukkit.getScheduler().runTaskLater(manager.getTempFly(), new EnforceTask(), delay); + } + + /** + * TODO + * if players take fall damage when flight is lost and they are not supposed to + * there is an infinite flight bug somewhere to track down because the enforcement task is + * removing the flight after is was supposed to be disabled without adding the proper damage protec1tion. + * @author Kevin + * + */ + public class EnforceTask implements Runnable { + + @Override + public void run() { + // If the users flight is enabled again when the task runs we will return. + if (enabled) return; + GameMode m = p.getGameMode(); + if (m == GameMode.CREATIVE && V.creativeTimer) { + Console.debug("--- Enforcing disabled flight A ----"); + p.setFlying(false); + p.setAllowFlight(false); + } else if (m != GameMode.CREATIVE && m != GameMode.SPECTATOR) { + Console.debug("--- Enforcing disabled flight B ----"); + p.setFlying(false); + p.setAllowFlight(false); + } + + } + + } + + /** + * Turn off players flight with a safety delay that will enforce proper removal of flight. + * @param delay The delay in ticks to enforce removal of flight. 1 should suffice. -1 for no enforcement + */ + public void disableFlight(int delay, boolean fallSafely) { + Console.debug("------ disable flight -------"); + if (!enabled) {return;} + enabled = false; + //TODO + if (timer != null && (!V.permaTimer || time <= 0)) { + timer.cancel(); + timer = null; + } + GameMode m = p.getGameMode(); + updateList(true); + updateName(true); + // Fixes a weird bug where fall damage accumulates through flight and damages even when 1 block off the ground. + if (p.isFlying()) {p.setFallDistance(0);} + if (m == GameMode.CREATIVE && V.creativeTimer) { + Console.debug("--> set flying false 1"); + p.setFlying(false); + p.setAllowFlight(false); + } else if (m != GameMode.CREATIVE && m != GameMode.SPECTATOR) { + Console.debug("--> set flying false 2"); + p.setFlying(false); + p.setAllowFlight(false); + if (fallSafely) {addDamageProtection();} + } + if (delay > -1) {enforce(delay);} + } + + /** + * Enable the users flight + * @return false if the users flight can not be enabled due to flight requirements. + */ + @SuppressWarnings("deprecation") + public boolean enableFlight() { + Console.debug("------ enable flight -------"); + if (hasFlightRequirements() && !hasRequirementBypass()) { + setAutoFly(true); + return false; + } + if (time == 0 && !hasInfiniteFlight()) { + setAutoFly(true); + return false; + } + Console.debug("--> set flying true"); + enabled = true; + p.setAllowFlight(true); + p.setFlying(!p.isOnGround()); + applySpeedCorrect(true, 0); + if (timer == null) { + this.timer = new FlightTimer(); + } + return true; + } + + /** + * Method to make sure a player can fly when they are supposed to. + */ + public void applyFlightCorrect() { + Console.debug("------ apply flight correct -------"); + Bukkit.getScheduler().runTaskLater(manager.getTempFly(), () -> { + if (p.isOnline() && hasFlightEnabled()) { + p.setAllowFlight(true); + p.setFlying(true); + } + }, 1); + } + + /** + * + * --=-----------=-- + * Requirement + * --=-----------=-- + * + */ + + + + public RequirementProvider[] getFlightRequirements() { + return requirements.keySet().toArray(new RequirementProvider[requirements.size()]); + } + + public boolean hasFlightRequirement(RequirementProvider requirement) { + return requirements.containsKey(requirement); + } + + public boolean hasFlightRequirement(RequirementProvider requirement, InquiryType type) { + return requirements.getOrDefault(requirement, new HashMap<>()).containsKey(type); + } + + public boolean hasFlightRequirements() { + return requirements.size() > 0; + } + + public void submitFlightRequirement(RequirementProvider requirement, FlightResult failedResult) { + if (V.debug) {Console.debug("", "---- Submitting failed requirement to user (" + p.getName() + ") ----", "--| Requirement: " + requirement.getClass().toGenericString(), "--| Requirements: " + requirements);} + Map types = requirements.getOrDefault(requirement, new HashMap<>()); + InquiryType type = failedResult.getInquiryType(); + if (types.containsKey(type)) { + types.remove(type); + } + types.put(type, failedResult); + this.requirements.put(requirement, types); + if (enabled) { + autoEnable = true; + } + } + + /** + * + * @param requirement + * @param type + * @return true if there are no more requirements + */ + public boolean removeFlightRequirement(RequirementProvider requirement, InquiryType type) { + if (V.debug) {Console.debug("", "---- Removing flight requirement from user ----", "--| Requirement: " + requirement.getClass().toGenericString(), "--| Requirements: " + requirements);} + Map types = requirements.getOrDefault(requirement, new HashMap<>()); + types.remove(type); + if (types.size() == 0) { + this.requirements.remove(requirement); + } else { + this.requirements.put(requirement, types); + } + return !hasFlightRequirements(); + } + + /** + * + * @param requirement + * @param type + * @return true if there are no more requirements + */ + public boolean removeFlightRequirement(RequirementProvider requirement) { + if (V.debug) {Console.debug("", "---- Removing flight requirement from user ----", "--| Requirement: " + requirement.getClass().toGenericString(), "--| Requirements: " + requirements);} + this.requirements.remove(requirement); + return !hasFlightRequirements(); + } + + public void removeFlightRequirements() { + this.requirements.clear(); + } + + public void sendRequirementMessage() { + if (hasFlightRequirements()) { + // lmao whats this trash + U.m(p, requirements.values().iterator().next().values().iterator().next().getMessage()); + } + } + + public FlightResult getCurrentRequirement() { + if (hasFlightRequirements()) { + return requirements.values().iterator().next().values().iterator().next(); + } + return null; + } + + /** + * Quality of life method. + * Evaluate the overall flight status of the user, checks all flight requirements present on the server. + * Used mainly when a player first joins or for some reason is not being tracked and we need to re-check everything. + * Flight will be disabled if a requirement fails. + * The requirement will then be submitted to the user for the auto flight enable feature. + * + * @return false if the user fails. + */ + public boolean evaluateFlightRequirements(Location loc, boolean failMessage) { + List results = new ArrayList<>(); + results.addAll(manager.inquireFlight(this, loc.getWorld())); + results.addAll(manager.inquireFlight(this, loc)); + if (manager.getTempFly().getHookManager().hasRegionProvider()) { + results.addAll(manager.inquireFlight(this, manager.getTempFly().getHookManager().getRegionProvider().getApplicableRegions(p.getLocation()))); + } + results.addAll(manager.inquireFlightBeyondScope(this)); + submitFlightResults(results, false); + if (hasFlightRequirements()) { + if (!hasRequirementBypass() && failMessage) { + sendRequirementMessage(); + } + return false; + } + return true; + } + + /** + * Evaluate the flight status of the user for the requirements introduced by the provider. + * Flight will be disabled if a requirement fails. + * The requirement will then be submitted to the user for the auto flight enable feature. + * + * @param failMessage Do you want the fail message to be sent to the user if they cannot fly? + * @return false if the user fails. + */ + + public boolean evaluateFlightRequirement(RequirementProvider requirement, Location loc) { + List results = new ArrayList<>(); + if (!requirement.handles(InquiryType.WORLD)) { + results.add(requirement.handleFlightInquiry(this, loc.getWorld())); + } + if (!requirement.handles(InquiryType.LOCATION)) { + results.add(requirement.handleFlightInquiry(this, loc)); + } + if (!requirement.handles(InquiryType.REGION) + && manager.getTempFly().getHookManager().hasRegionProvider()) { + results.add(requirement.handleFlightInquiry(this, environment.getCurrentRegionSet())); + } + return submitFlightResults(results, hasFlightEnabled()) && hasFlightRequirement(requirement); + } + + + /** + * Submit a batch of flight results to the FlightUser. + * @param results The results to submit + * @return false if the results disabled the users flight aka user failed. + */ + public boolean submitFlightResult(FlightResult result) { + RequirementProvider provider = result.getRequirement(); + InquiryType type = result.getInquiryType(); + if (!result.isAllowed()) { + submitFlightRequirement(provider, result); + if (!hasRequirementBypass()) { + if (hasFlightEnabled()) { + U.m(p, result.getMessage()); + } + disableFlight(1, result.hasDamageProtection()); + } + return false; + } else { + if (hasFlightRequirement(provider, type) && removeFlightRequirement(provider, type)) { + updateRequirements(result.getMessage()); + } + } + return true; + } + + /** + * Submit a batch of flight results. + * @param results + * @return + */ + public boolean submitFlightResults(List results, boolean failMessage) { + // The result that actually disabled the flight. first come first serve. + FlightResult disabled = null; + // The final result that enabled the flight. + FlightResult enable = null; + + for (FlightResult result: results) { + RequirementProvider provider = result.getRequirement(); + InquiryType type = result.getInquiryType(); + if (!result.isAllowed()) { + if (disabled == null) { + disabled = result; + } + if (!hasFlightRequirement(provider, type)) { + submitFlightRequirement(provider, result); + } + } else { + if (hasFlightRequirement(provider, type) && removeFlightRequirement(provider, type)) { + enable = result; + } + } + } + if (disabled != null) { + if (!hasRequirementBypass()) { + if (failMessage) { + U.m(p, disabled.getMessage()); + } + disableFlight(1, disabled.hasDamageProtection()); + } + return false; + } else if (enable != null) { + updateRequirements(enable.getMessage()); + } + return true; + } + + /** + * Update the flight requirements for the user. Automatically auto enables flight if applicable. + * @return True if there are no more requirements. + */ + public boolean updateRequirements(String enableMessage) { + Console.debug("", "--- updating requirements ---", "--| requirements: " + requirements.toString(), + "--| flight enabled: " + enabled, "--| auto flight: " + autoEnable, "--| time: " + time); + + if (requirements.size() == 0 && !hasFlightEnabled() && (time > 0 || hasInfiniteFlight())) { + if (hasAutoFlyQueued()) { + autoEnable = false; + if (!hasRequirementBypass()) { + Console.debug("--|> AutoFly engaged!"); + U.m(p, enableMessage); + enableFlight(); + } else { + Console.debug("--|> Autofly will not be invoked, User has requirement bypass mode..."); + } + } + return true; + } + return requirements.size() == 0; + } + + + + /** + * + * --=-----------=-- + * Fall Damage + * --=-----------=-- + * + */ + + + public void addDamageProtection() { + removeDamageProtection(); + damageProtection = Bukkit.getScheduler().runTaskLater(manager.getTempFly(), () -> { + removeDamageProtection(); + }, 120); + } + + public void removeDamageProtection() { + if (damageProtection != null) { + damageProtection.cancel(); + damageProtection = null; + } + } + + public boolean hasDamageProtection() { + return damageProtection != null; + } + + + + /** + * + * --=----------=-- + * Aesthetics + * --=----------=-- + * + */ + + + + /** + * This method returns a string to keep the plugin compatible through versions. + * @return The enum string representation of the particle + */ + public String getTrail() { + return particle; + } + + /** + * This method requires a string to keep the plugin compatible through versions. + * The enum value of the particle as a string + * @param particle + */ + public void setTrail(String particle) { + this.particle = particle; + manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_TRAIL, p.getUniqueId().toString()), particle); + } + + public void playTrail() { + if (particle == null || particle.length() == 0) {return;} + + if (p.getGameMode() == GameMode.SPECTATOR) { + return; + } + + if (V.hideVanish) { + for (MetadataValue meta : p.getMetadata("vanished")) { + if (meta.asBoolean()) { + return; + } + } + } + + + Particles.play(p.getLocation(), particle); + } + + public String getListPlaceholder() { + return timeManager.regexString((p.isFlying() && hasFlightEnabled() ? V.listPlaceholderOn : V.listPlaceholderOff) + .replaceAll("\\{PLAYER}", p.getName()) + .replaceAll("\\{OLD_TAG}", listName), time); + } + + public String getTagPlaceholder() { + return timeManager.regexString((p.isFlying() && hasFlightEnabled() ? V.tagPlaceholderOn : V.tagPlaceholderOff) + .replaceAll("\\{PLAYER}", p.getName()) + .replaceAll("\\{OLD_TAG}", tagName), time); + } + + private void updateList(boolean reset) { + if (!V.list) {return;} + p.setPlayerListName(!p.isFlying() || reset + ? listName : timeManager.regexString(V.listName + .replaceAll("\\{PLAYER}", p.getName()) + .replaceAll("\\{OLD_TAG}", tagName), time)); + } + + private void updateName(boolean reset) { + if (!V.tag) {return;} + p.setDisplayName(!p.isFlying() || reset + ? tagName : timeManager.regexString(V.tagName + .replaceAll("\\{PLAYER}", p.getName()) + .replaceAll("\\{OLD_TAG}", tagName), time)); + } + + public void doActionBar() { + ActionBarAPI.sendActionBar(p, timeManager.regexString(V.actionText, getTime())); + } + + + /** + * + * --=-----------=-- + * Speed control + * --=-----------=-- + * + */ + + public double getSpeedPreference() { + return selectedSpeed; + } + + public void setSpeedPreference(double speed) { + this.selectedSpeed = speed; + manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_SPEED, p.getUniqueId().toString()), speed); + } + + public boolean hasSpeedPreference() { + return selectedSpeed > -1 && manager.getFlightEnvironment().allowSpeedPreference(); + } + + /** + * Correct the users flight speed. Takes into account permissions and max world / region speeds. + * @return The resulting speed of the user. + */ + public float applySpeedCorrect(boolean message, int delay) { + float maxSpeed = getMaxSpeed(); + Console.debug("--| Max speed: " + String.valueOf(maxSpeed)); + Console.debug("--| Preferred speed: " + String.valueOf(selectedSpeed)); + if (hasSpeedPreference() && maxSpeed > selectedSpeed && manager.getFlightEnvironment().allowSpeedPreference()) { + maxSpeed = (float) selectedSpeed; + } + + final float val = maxSpeed / 10; + final float def = manager.getFlightEnvironment().getDefaultSpeed() / 10; + Console.debug("--| final speed value: " + val); + if (p.getFlySpeed() > val + || (p.getFlySpeed() != val && !manager.getFlightEnvironment().allowSpeedPreference()) + || (p.getFlySpeed() < val && hasSpeedPreference())) { + Console.debug("--| Players speed needs to be changed."); + Bukkit.getScheduler().runTaskLater(manager.getTempFly(), () -> { + Console.debug("-----> | changing player speed"); + if (p.isOnline()) { + Console.debug("player speed: " + p.getFlySpeed(), "value: " + val); + Console.debug("is speed prefernce allowed? " + manager.getFlightEnvironment().allowSpeedPreference(), + p.getFlySpeed() != val && !manager.getFlightEnvironment().allowSpeedPreference()); + if (p.getFlySpeed() > val && message) { + U.m(p, V.flySpeedLimitSelf.replaceAll("\\{SPEED}", new DecimalFormat("#.##").format(val * 10))); + } + p.setFlySpeed((float) val); + } + }, delay); + + } else if (p.getFlySpeed() != def && !hasSpeedPreference()) { + float fin = Math.min(def, val); + Console.debug("--| Players speed needs to be fixed it is stuck under default speed."); + Bukkit.getScheduler().runTaskLater(manager.getTempFly(), () -> { + Console.debug("-----> | changing player speed"); + if (p.isOnline()) { + Console.debug("player speed: " + p.getFlySpeed(), "value: " + val); + p.setFlySpeed(fin); + } + }, delay); + } + return val; + } + + public float getMaxSpeed() { + Console.debug("get max speed 1"); + CompatRegion[] regions = environment.getCurrentRegionSet(); + FlightEnvironment env = manager.getFlightEnvironment(); + + // Permissions for region speed take priority + float finSpeed = getMaxSpeed(regions); + if (finSpeed != -999) { + Console.debug("2: " + finSpeed); + return finSpeed; + } else if (env.hasMaxSpeed(regions)) { + Console.debug("4: " + env.getMaxSpeed(regions)); + return env.getMaxSpeed(regions); + } + + // Permissions for world speed go next + finSpeed = getMaxSpeed(p.getWorld()); + if (finSpeed != -999) { + Console.debug("3: " + finSpeed); + return finSpeed; + } else if (env.hasMaxSpeed(p.getWorld())) { + Console.debug("4: " + env.getMaxSpeed(p.getWorld())); + return env.getMaxSpeed(p.getWorld()); + } + + // return default environment speed indicator + Console.debug("5: " + env.getDefaultSpeed()); + return env.getDefaultSpeed(); + } + + public float getMaxSpeed(World world) { + return this.calculatePermissionSpeed("world." + world.getName(), "world.*"); + } + + public float getMaxSpeed(CompatRegion[] regions) { + float permSpeed = -999; + for (CompatRegion region: regions) { + permSpeed = Math.max(calculatePermissionSpeed("region." + region.getId(), "region.*"), permSpeed); + Console.debug("--| Region: " + region.getId(), "--| Permission speed for this region is: " + permSpeed); + } + return permSpeed; + } + + private float calculatePermissionSpeed(String permission, String wildcard) { + Console.debug("calc perm speed : " + permission); + float maxBase = -999; + + float maxFound = 0; + for (PermissionAttachmentInfo info: p.getEffectivePermissions()) { + String perm = info.getPermission(); + if (perm.startsWith("tempfly.speed." + permission) + || perm.startsWith("tempfly.speed." + wildcard)) { + Console.debug("found: " + perm); + String[] split = perm.split("\\."); + if (split.length < 5) { + Console.debug("less than 5"); + continue; + } + String num = split[4]; + if (split.length > 5) { + num = num.concat("." + split[5]); + } + num = num.replaceAll("\\[", "").replaceAll("\\]", ""); + Console.debug(num); + try { + float found = Float.parseFloat(num); + maxFound = Math.max(found, maxFound); + } catch (Exception e) {} + } + } + if (maxFound > 0) { + maxBase = maxFound; + } + Console.debug("maxbase: " + maxBase); + + return maxBase; + } + + + /** + * + * --=---------=-- + * Timers + * --=---------=-- + * + */ + + + public boolean hasTimer() { + return this.timer != null; + } + + public abstract class TempFlyTimer extends BukkitRunnable { + + } + + /** + * Ground timer runs every tick when FlightTimer isnt scheduled and simply checks if the player is flying. + * This way the FlightTimer will run as soon as the player starts flying. Otherwise it kinda looks laggy. + * @author Kevin + * + */ + public class GroundTimer extends TempFlyTimer { + + private static final int DELAY = 3; + + public GroundTimer() { + Console.debug("--- new ground timer ---"); + this.runTaskTimer(manager.getTempFly(), 1, DELAY); + } + + @SuppressWarnings("deprecation") + @Override + public void run() { + idle += DELAY; + if (p.isFlying() || V.permaTimer || (V.groundTimer && p.isOnGround())) { + if (!V.idleTimer && isIdle()) { + return; + } + if (p.getGameMode() == GameMode.CREATIVE && !V.creativeTimer) { + return; + } + if (p.getGameMode() == GameMode.SPECTATOR && !V.spectatorTimer) { + return; + } + if (p.getVehicle() != null) { + return; + } + this.cancel(); + timer = new FlightTimer(); + } + } + + } + + /** + * FlightTimer runs every 20 ticks and is in charge of decrementing time among other things such as + * action bar messages. + * @author Kevin + * + */ + + // It looks like were having spaghetti for dinner + public class FlightTimer extends TempFlyTimer { + + private static final int DELAY = 3; + + private boolean previouslyFlying; + + public FlightTimer() { + Console.debug("--- new flight timer--- "); + this.runTaskTimer(manager.getTempFly(), 0, DELAY); + if (doFlightTimer() && V.actionBar && !hasInfiniteFlight() && time > 0) { + doActionBar(); + } + } + + @Override + public void run() { + idle += DELAY; + // Update the players identifiers each tick as it isn't resource heavy it looks good. + doIdentifier(); + // This line fixed an unknown confliction with another plugin on some guys server so i'l just leave it. + //if (enabled) {p.setAllowFlight(true);} + + if (hasInfiniteFlight()) { + return; + } + + if (!doFlightTimer()) { + this.cancel(); + timer = time > 0 ? new GroundTimer() : null; + return; + } + + accumulativeCycle += DELAY * 50; + if (accumulativeCycle >= 1000) { + accumulativeCycle = 0; + executeTimer(); + return; + } + + } + + @Override + public void cancel() { + super.cancel(); + } + + private void executeTimer() { + if (time > 0) { + + double cost = 1; + for (RelativeTimeRegion rtr : environment.getRelativeTimeRegions()) { + cost *= rtr.getFactor(); + } + time = time-cost; + if (time < 0) time = 0; + + manager.getTempFly().getDataBridge().stageChange(DataPointer.of(DataValue.PLAYER_TIME, p.getUniqueId().toString()), time); + + if (V.warningTimes.contains((long)time)) { + TitleAPI.sendTitle(p, 15, 30, 15, timeManager.regexString(V.warningTitle, time), + timeManager.regexString(V.warningSubtitle, time)); + } + if (V.actionBar) {doActionBar();} + + if (time == 0) { + timeExpired(); + } + } else if (enabled) { + timeExpired(); + } + } + + private void timeExpired() { + disableFlight(-1, !V.damageTime); + U.m(p, V.invalidTimeSelf); + autoEnable = true; + } + + private boolean doFlightTimer() { + if (time <= 0) { + return false; + } + if (V.permaTimer) { + return doIdleCheck(); + } + if (p.getGameMode() == GameMode.CREATIVE && !V.creativeTimer) { + return false; + } + if (p.getGameMode() == GameMode.SPECTATOR && !V.spectatorTimer) { + return false; + } + if (p.getVehicle() != null) { + return false; + } + if (!p.isFlying()) { + if (V.groundTimer && !doIdleCheck()) { + return false; + } + return V.groundTimer; + } + return doIdleCheck(); + } + + private void doIdentifier() { + if (!enabled) { + return; + } + if (previouslyFlying && !p.isFlying() || !previouslyFlying && p.isFlying()) { + updateList(!p.isFlying()); + updateName(!p.isFlying()); + } + previouslyFlying = p.isFlying(); + } + + /** + * + * @return True if the timer should continue, false if it can switch to ground timer. + */ + private boolean messaged = false; + + private boolean doIdleCheck() { + if (isIdle()) { + if (V.idleDrop) { + disableFlight(0, !V.damageIdle); + } + + if (!this.messaged) { + U.m(p, V.idleDrop ? V.disabledIdle : V.consideredIdle); + this.messaged = true; + } + return V.idleTimer; + } else { + this.messaged = false; + } + + return true; + } + + } +} diff --git a/TempFly/src/com/moneybags/tempfly/user/UserEnvironment.java b/src/com/moneybags/tempfly/user/UserEnvironment.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/user/UserEnvironment.java rename to src/com/moneybags/tempfly/user/UserEnvironment.java index d82ba0f..6bb898f 100644 --- a/TempFly/src/com/moneybags/tempfly/user/UserEnvironment.java +++ b/src/com/moneybags/tempfly/user/UserEnvironment.java @@ -1,159 +1,159 @@ -package com.moneybags.tempfly.user; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.environment.FlightEnvironment; -import com.moneybags.tempfly.environment.RelativeTimeRegion; -import com.moneybags.tempfly.hook.region.CompatRegion; -import com.moneybags.tempfly.util.Console; - -public class UserEnvironment { - - private final FlightUser user; - private final FlightEnvironment environment; - - private boolean freeFlight; - - private final List encompassing = new LinkedList<>(); - - private final List rtRegions = new ArrayList<>(); - private RelativeTimeRegion rtWorld; - - public UserEnvironment(FlightUser user, Player p) { - Console.debug("--| Loading user environment..."); - this.user = user; - this.environment = user.getFlightManager().getFlightEnvironment(); - - encompassing.addAll(Arrays.asList( - user.getFlightManager().getTempFly().getHookManager().hasRegionProvider() - ? user.getFlightManager().getTempFly().getHookManager().getRegionProvider().getApplicableRegions(user.getPlayer().getLocation()) - : new CompatRegion[0])); - - StringBuilder builder = new StringBuilder(); - encompassing.stream().forEach(rg -> builder.append(rg.getId() + ", ")); - Console.debug("--| Current regions: " + builder); - asessRtRegions(); - asessRtWorld(); - asessInfiniteFlight(); - } - - public FlightUser getUser() { - return user; - } - - - /** - * - * --=-----------------=-- - * Real Time Regions - * --=-----------------=-- - * - */ - - - - public CompatRegion[] getCurrentRegionSet() { - return encompassing == null ? null : encompassing.toArray(new CompatRegion[encompassing.size()]); - } - - public void updateCurrentRegionSet(CompatRegion[] regions) { - this.encompassing.clear(); - this.encompassing.addAll(Arrays.asList(regions)); - asessRtRegions(); - asessInfiniteFlight(); - } - - public boolean isInside(CompatRegion region) { - for (CompatRegion inside: encompassing) { - if (inside.equals(region)) { - return true; - } - } - return false; - } - - - /** - * - * --=------------=-- - * RelativeTime - * --=------------=-- - * - */ - - - public RelativeTimeRegion[] getRelativeTimeRegions() { - List list = new LinkedList<>(); - list.addAll(rtRegions); - if (rtWorld != null) list.add(rtWorld); - return list.toArray(new RelativeTimeRegion[list.size()]); - } - - public void asessRtWorld() { - rtWorld = environment.getRelativeTime(user.getPlayer().getWorld()); - } - - public void asessRtRegions() { - RelativeTimeRegion[] rtArray = user.getFlightManager().getFlightEnvironment().getRelativeTimeRegions(); - if (rtArray.length == 0) { - return; - } - List regions = new ArrayList<>(); - for(CompatRegion r : encompassing) { - regions.add(r.getId()); - } - for (RelativeTimeRegion rt : rtArray) { - String rtName = rt.getName(); - if ((regions.contains(rtName)) && !(rtRegions.contains(rt))) { - rtRegions.add(rt); - } else if (!(regions.contains(rtName)) && (rtRegions.contains(rt))) { - rtRegions.remove(rt); - } - } - } - - public void asessInfiniteFlight() { - if (environment.isInfinite(user.getPlayer().getWorld())) { - freeFlight = true; - return; - } - - for (CompatRegion r: encompassing) { - if (environment.isInfinite(r)) { - freeFlight = true; - return; - } - } - freeFlight = false; - } - - public boolean hasInfiniteFlight() { - return freeFlight; - } - - - /** - * @param regions The list of regions to check - * @return True if the list is the same. - */ - public boolean checkIdenticalRegions(List regions) { - if (regions.size() != encompassing.size()) { - return false; - } - check: - for (CompatRegion check: regions) { - for (CompatRegion current: encompassing) { - if (current.equals(check)) { - continue check; - } - } - return false; - } - return true; - } -} +package com.moneybags.tempfly.user; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.environment.FlightEnvironment; +import com.moneybags.tempfly.environment.RelativeTimeRegion; +import com.moneybags.tempfly.hook.region.CompatRegion; +import com.moneybags.tempfly.util.Console; + +public class UserEnvironment { + + private final FlightUser user; + private final FlightEnvironment environment; + + private boolean freeFlight; + + private final List encompassing = new LinkedList<>(); + + private final List rtRegions = new ArrayList<>(); + private RelativeTimeRegion rtWorld; + + public UserEnvironment(FlightUser user, Player p) { + Console.debug("--| Loading user environment..."); + this.user = user; + this.environment = user.getFlightManager().getFlightEnvironment(); + + encompassing.addAll(Arrays.asList( + user.getFlightManager().getTempFly().getHookManager().hasRegionProvider() + ? user.getFlightManager().getTempFly().getHookManager().getRegionProvider().getApplicableRegions(user.getPlayer().getLocation()) + : new CompatRegion[0])); + + StringBuilder builder = new StringBuilder(); + encompassing.stream().forEach(rg -> builder.append(rg.getId() + ", ")); + Console.debug("--| Current regions: " + builder); + asessRtRegions(); + asessRtWorld(); + asessInfiniteFlight(); + } + + public FlightUser getUser() { + return user; + } + + + /** + * + * --=-----------------=-- + * Real Time Regions + * --=-----------------=-- + * + */ + + + + public CompatRegion[] getCurrentRegionSet() { + return encompassing == null ? null : encompassing.toArray(new CompatRegion[encompassing.size()]); + } + + public void updateCurrentRegionSet(CompatRegion[] regions) { + this.encompassing.clear(); + this.encompassing.addAll(Arrays.asList(regions)); + asessRtRegions(); + asessInfiniteFlight(); + } + + public boolean isInside(CompatRegion region) { + for (CompatRegion inside: encompassing) { + if (inside.equals(region)) { + return true; + } + } + return false; + } + + + /** + * + * --=------------=-- + * RelativeTime + * --=------------=-- + * + */ + + + public RelativeTimeRegion[] getRelativeTimeRegions() { + List list = new LinkedList<>(); + list.addAll(rtRegions); + if (rtWorld != null) list.add(rtWorld); + return list.toArray(new RelativeTimeRegion[list.size()]); + } + + public void asessRtWorld() { + rtWorld = environment.getRelativeTime(user.getPlayer().getWorld()); + } + + public void asessRtRegions() { + RelativeTimeRegion[] rtArray = user.getFlightManager().getFlightEnvironment().getRelativeTimeRegions(); + if (rtArray.length == 0) { + return; + } + List regions = new ArrayList<>(); + for(CompatRegion r : encompassing) { + regions.add(r.getId()); + } + for (RelativeTimeRegion rt : rtArray) { + String rtName = rt.getName(); + if ((regions.contains(rtName)) && !(rtRegions.contains(rt))) { + rtRegions.add(rt); + } else if (!(regions.contains(rtName)) && (rtRegions.contains(rt))) { + rtRegions.remove(rt); + } + } + } + + public void asessInfiniteFlight() { + if (environment.isInfinite(user.getPlayer().getWorld())) { + freeFlight = true; + return; + } + + for (CompatRegion r: encompassing) { + if (environment.isInfinite(r)) { + freeFlight = true; + return; + } + } + freeFlight = false; + } + + public boolean hasInfiniteFlight() { + return freeFlight; + } + + + /** + * @param regions The list of regions to check + * @return True if the list is the same. + */ + public boolean checkIdenticalRegions(List regions) { + if (regions.size() != encompassing.size()) { + return false; + } + check: + for (CompatRegion check: regions) { + for (CompatRegion current: encompassing) { + if (current.equals(check)) { + continue check; + } + } + return false; + } + return true; + } +} diff --git a/TempFly/src/com/moneybags/tempfly/user/UserLoader.java b/src/com/moneybags/tempfly/user/UserLoader.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/user/UserLoader.java rename to src/com/moneybags/tempfly/user/UserLoader.java index 4f3f667..60a2b19 100644 --- a/TempFly/src/com/moneybags/tempfly/user/UserLoader.java +++ b/src/com/moneybags/tempfly/user/UserLoader.java @@ -1,88 +1,88 @@ -package com.moneybags.tempfly.user; - -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import com.moneybags.tempfly.aesthetic.particle.Particles; -import com.moneybags.tempfly.fly.FlightManager; -import com.moneybags.tempfly.time.TimeManager; -import com.moneybags.tempfly.util.data.DataBridge; -import com.moneybags.tempfly.util.data.DataPointer; -import com.moneybags.tempfly.util.data.DataBridge.DataValue; - -public class UserLoader implements Runnable { - - private UUID u; - private FlightManager manager; - private boolean async; - - public UserLoader(UUID u, FlightManager manager, boolean async) { - this.u = u; - this.manager = manager; - this.async = async; - } - - double time; - - String particle; - - boolean - infinite, - bypass, - logged, - compatLogged, - ready; - - double - selectedSpeed; - - @Override - public void run() { - final DataBridge bridge = manager.getTempFly().getDataBridge(); - final TimeManager timeManager = manager.getTempFly().getTimeManager(); - - if (bridge.hasSqlEnabled()) { - PreparedStatement st = bridge.prepareStatement("INSERT IGNORE INTO tempfly_data(uuid) VALUES(?)"); - try { - st.setString(1, u.toString()); - st.execute(); - st.close(); - } catch (SQLException e) { - e.printStackTrace(); - return; - } - - } - - - time = timeManager.getTime(u); - particle = Particles.loadTrail(u); - infinite = (boolean) bridge.getOrDefault(DataPointer.of(DataValue.PLAYER_INFINITE, u.toString()), true); - bypass = (boolean) bridge.getOrDefault(DataPointer.of(DataValue.PLAYER_BYPASS, u.toString()), true); - logged = (boolean) bridge.getOrDefault(DataPointer.of(DataValue.PLAYER_FLIGHT_LOG, u.toString()), false); - compatLogged = (boolean) bridge.getOrDefault(DataPointer.of(DataValue.PLAYER_COMPAT_FLIGHT_LOG, u.toString()), false); - selectedSpeed = (double) bridge.getOrDefault(DataPointer.of(DataValue.PLAYER_SPEED, u.toString()), -999D); - ready = true; - if (async) { - manager.addUser(Bukkit.getPlayer(u)); - } - } - - public boolean isReady() { - return ready; - } - - public FlightUser buildUser() { - return new FlightUser(Bukkit.getPlayer(u), manager, time, particle, infinite, bypass, logged, compatLogged, selectedSpeed); - } - - public FlightUser buildUser(Player p) { - return new FlightUser(p, manager, time, particle, infinite, bypass, logged, compatLogged, selectedSpeed); - } - - -} +package com.moneybags.tempfly.user; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import com.moneybags.tempfly.aesthetic.particle.Particles; +import com.moneybags.tempfly.fly.FlightManager; +import com.moneybags.tempfly.time.TimeManager; +import com.moneybags.tempfly.util.data.DataBridge; +import com.moneybags.tempfly.util.data.DataPointer; +import com.moneybags.tempfly.util.data.DataBridge.DataValue; + +public class UserLoader implements Runnable { + + private UUID u; + private FlightManager manager; + private boolean async; + + public UserLoader(UUID u, FlightManager manager, boolean async) { + this.u = u; + this.manager = manager; + this.async = async; + } + + double time; + + String particle; + + boolean + infinite, + bypass, + logged, + compatLogged, + ready; + + double + selectedSpeed; + + @Override + public void run() { + final DataBridge bridge = manager.getTempFly().getDataBridge(); + final TimeManager timeManager = manager.getTempFly().getTimeManager(); + + if (bridge.hasSqlEnabled()) { + PreparedStatement st = bridge.prepareStatement("INSERT IGNORE INTO tempfly_data(uuid) VALUES(?)"); + try { + st.setString(1, u.toString()); + st.execute(); + st.close(); + } catch (SQLException e) { + e.printStackTrace(); + return; + } + + } + + + time = timeManager.getTime(u); + particle = Particles.loadTrail(u); + infinite = (boolean) bridge.getOrDefault(DataPointer.of(DataValue.PLAYER_INFINITE, u.toString()), true); + bypass = (boolean) bridge.getOrDefault(DataPointer.of(DataValue.PLAYER_BYPASS, u.toString()), true); + logged = (boolean) bridge.getOrDefault(DataPointer.of(DataValue.PLAYER_FLIGHT_LOG, u.toString()), false); + compatLogged = (boolean) bridge.getOrDefault(DataPointer.of(DataValue.PLAYER_COMPAT_FLIGHT_LOG, u.toString()), false); + selectedSpeed = (double) bridge.getOrDefault(DataPointer.of(DataValue.PLAYER_SPEED, u.toString()), -999D); + ready = true; + if (async) { + manager.addUser(Bukkit.getPlayer(u)); + } + } + + public boolean isReady() { + return ready; + } + + public FlightUser buildUser() { + return new FlightUser(Bukkit.getPlayer(u), manager, time, particle, infinite, bypass, logged, compatLogged, selectedSpeed); + } + + public FlightUser buildUser(Player p) { + return new FlightUser(p, manager, time, particle, infinite, bypass, logged, compatLogged, selectedSpeed); + } + + +} diff --git a/TempFly/src/com/moneybags/tempfly/util/AutoSave.java b/src/com/moneybags/tempfly/util/AutoSave.java similarity index 94% rename from TempFly/src/com/moneybags/tempfly/util/AutoSave.java rename to src/com/moneybags/tempfly/util/AutoSave.java index 34151dd..dcb9f4c 100644 --- a/TempFly/src/com/moneybags/tempfly/util/AutoSave.java +++ b/src/com/moneybags/tempfly/util/AutoSave.java @@ -1,20 +1,20 @@ -package com.moneybags.tempfly.util; - -import org.bukkit.scheduler.BukkitRunnable; - -import com.moneybags.tempfly.util.data.DataBridge; - -public class AutoSave extends BukkitRunnable { - - private DataBridge bridge; - - public AutoSave(DataBridge bridge) { - this.bridge = bridge; - } - - @Override - public void run() { - bridge.commitAll(); - } - -} +package com.moneybags.tempfly.util; + +import org.bukkit.scheduler.BukkitRunnable; + +import com.moneybags.tempfly.util.data.DataBridge; + +public class AutoSave extends BukkitRunnable { + + private DataBridge bridge; + + public AutoSave(DataBridge bridge) { + this.bridge = bridge; + } + + @Override + public void run() { + bridge.commitAll(); + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/util/CompatMaterial.java b/src/com/moneybags/tempfly/util/CompatMaterial.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/util/CompatMaterial.java rename to src/com/moneybags/tempfly/util/CompatMaterial.java index a97cc95..24da512 100644 --- a/TempFly/src/com/moneybags/tempfly/util/CompatMaterial.java +++ b/src/com/moneybags/tempfly/util/CompatMaterial.java @@ -1,73 +1,73 @@ -package com.moneybags.tempfly.util; - -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - -public enum CompatMaterial { - - GRAY_STAINED_GLASS_PANE( - "STAINED_GLASS_PANE", (short) 7), - - BLACK_STAINED_GLASS_PANE( - "STAINED_GLASS_PANE", (short) 15), - - LIME_STAINED_GLASS( - "STAINED_GLASS", (short) 5), - - WHITE_STAINED_GLASS( - "STAINED_GLASS", (short) 0), - - RED_WOOL( - "WOOL", (short) 14), - - LIME_WOOL( - "WOOL", (short) 5), - - EMERALD, - - DIAMOND, - - COAL, - - REDSTONE_TORCH( - "REDSTONE_TORCH_ON", (short)0), - - FEATHER, - - LAVA_BUCKET; - - private String oldMaterial; - private short oldData; - - private CompatMaterial(String oldMaterial, short oldData) { - this.oldMaterial = oldMaterial; - this.oldData = oldData; - } - - private CompatMaterial() { - - } - - @SuppressWarnings("deprecation") - public static ItemStack get(CompatMaterial mat) { - try { - return new ItemStack(Material.valueOf(mat.toString())); - } catch (Exception e) {} - try { - return new ItemStack(Material.valueOf(mat.oldMaterial), 1, mat.oldData); - } catch (Exception e) { - } - return null; - } - - @SuppressWarnings("deprecation") - public static void setType(ItemStack item, CompatMaterial mat) { - try { - item.setType(Material.valueOf(mat.toString())); - } catch (Exception e) {} - try { - item.setType(Material.valueOf(mat.oldMaterial)); - item.setDurability(mat.oldData); - } catch (Exception e) {} - } -} +package com.moneybags.tempfly.util; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +public enum CompatMaterial { + + GRAY_STAINED_GLASS_PANE( + "STAINED_GLASS_PANE", (short) 7), + + BLACK_STAINED_GLASS_PANE( + "STAINED_GLASS_PANE", (short) 15), + + LIME_STAINED_GLASS( + "STAINED_GLASS", (short) 5), + + WHITE_STAINED_GLASS( + "STAINED_GLASS", (short) 0), + + RED_WOOL( + "WOOL", (short) 14), + + LIME_WOOL( + "WOOL", (short) 5), + + EMERALD, + + DIAMOND, + + COAL, + + REDSTONE_TORCH( + "REDSTONE_TORCH_ON", (short)0), + + FEATHER, + + LAVA_BUCKET; + + private String oldMaterial; + private short oldData; + + private CompatMaterial(String oldMaterial, short oldData) { + this.oldMaterial = oldMaterial; + this.oldData = oldData; + } + + private CompatMaterial() { + + } + + @SuppressWarnings("deprecation") + public static ItemStack get(CompatMaterial mat) { + try { + return new ItemStack(Material.valueOf(mat.toString())); + } catch (Exception e) {} + try { + return new ItemStack(Material.valueOf(mat.oldMaterial), 1, mat.oldData); + } catch (Exception e) { + } + return null; + } + + @SuppressWarnings("deprecation") + public static void setType(ItemStack item, CompatMaterial mat) { + try { + item.setType(Material.valueOf(mat.toString())); + } catch (Exception e) {} + try { + item.setType(Material.valueOf(mat.oldMaterial)); + item.setDurability(mat.oldData); + } catch (Exception e) {} + } +} diff --git a/TempFly/src/com/moneybags/tempfly/util/Console.java b/src/com/moneybags/tempfly/util/Console.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/util/Console.java rename to src/com/moneybags/tempfly/util/Console.java index f1d5770..8c2e3bf 100644 --- a/TempFly/src/com/moneybags/tempfly/util/Console.java +++ b/src/com/moneybags/tempfly/util/Console.java @@ -1,61 +1,61 @@ -package com.moneybags.tempfly.util; - -import java.util.logging.Logger; - -public final class Console { - - private static Logger logger; - - private Console() {} - - public static void setLogger(Logger logger) { - Console.logger = logger; - } - - public static void generateException(String message) { - try {throw new Exception(message);} catch (Exception e) { - e.printStackTrace(); - } - } - - public static void info(String... m){ - for (String s: m) {info(s);} - } - - public static void info(String m){ - logger.info(m); - } - - public static void warn(String... m){ - for (String s: m) {warn(s);} - } - - public static void warn(String m){ - logger.warning(m); - } - - public static void severe(String... m){ - for (String s: m) {severe(s);} - } - - public static void severe(String m){ - logger.severe(m); - } - - /** - * lmao - */ - public static void extreme(String m) { - for (int x = 0; x < 23; x++) severe((x > 10 && x < 13) ? m : (x == 11 || x == 13) ? "--------------" : "!!!"); - } - - public static void debug(Object obj) { - if (V.debug) {logger.info("[DEBUG] " + String.valueOf(obj));} - } - - public static void debug(Object... objects) { - if (V.debug) { - for (Object obj: objects) {logger.info("[DEBUG] " + String.valueOf(obj));} - } - } -} +package com.moneybags.tempfly.util; + +import java.util.logging.Logger; + +public final class Console { + + private static Logger logger; + + private Console() {} + + public static void setLogger(Logger logger) { + Console.logger = logger; + } + + public static void generateException(String message) { + try {throw new Exception(message);} catch (Exception e) { + e.printStackTrace(); + } + } + + public static void info(String... m){ + for (String s: m) {info(s);} + } + + public static void info(String m){ + logger.info(m); + } + + public static void warn(String... m){ + for (String s: m) {warn(s);} + } + + public static void warn(String m){ + logger.warning(m); + } + + public static void severe(String... m){ + for (String s: m) {severe(s);} + } + + public static void severe(String m){ + logger.severe(m); + } + + /** + * lmao + */ + public static void extreme(String m) { + for (int x = 0; x < 23; x++) severe((x > 10 && x < 13) ? m : (x == 11 || x == 13) ? "--------------" : "!!!"); + } + + public static void debug(Object obj) { + if (V.debug) {logger.info("[DEBUG] " + String.valueOf(obj));} + } + + public static void debug(Object... objects) { + if (V.debug) { + for (Object obj: objects) {logger.info("[DEBUG] " + String.valueOf(obj));} + } + } +} diff --git a/TempFly/src/com/moneybags/tempfly/util/DailyDate.java b/src/com/moneybags/tempfly/util/DailyDate.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/util/DailyDate.java rename to src/com/moneybags/tempfly/util/DailyDate.java index 0b37579..815e2e7 100644 --- a/TempFly/src/com/moneybags/tempfly/util/DailyDate.java +++ b/src/com/moneybags/tempfly/util/DailyDate.java @@ -1,25 +1,25 @@ -package com.moneybags.tempfly.util; - -import java.util.Date; - -public class DailyDate extends Date { - - private static final long serialVersionUID = 7853013854292147249L; - - public DailyDate(long millis) { - super(millis); - } - - //Shhhh - @SuppressWarnings("deprecation") - @Override - public boolean equals(Object o) { - if (!(o instanceof Date)) { - return false; - } - Date date = (Date) o; - - return date.getDay() == this.getDay() && date.getMonth() == this.getMonth() && date.getYear() == this.getYear(); - } - -} +package com.moneybags.tempfly.util; + +import java.util.Date; + +public class DailyDate extends Date { + + private static final long serialVersionUID = 7853013854292147249L; + + public DailyDate(long millis) { + super(millis); + } + + //Shhhh + @SuppressWarnings("deprecation") + @Override + public boolean equals(Object o) { + if (!(o instanceof Date)) { + return false; + } + Date date = (Date) o; + + return date.getDay() == this.getDay() && date.getMonth() == this.getMonth() && date.getYear() == this.getYear(); + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/util/ParticleTask.java b/src/com/moneybags/tempfly/util/ParticleTask.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/util/ParticleTask.java rename to src/com/moneybags/tempfly/util/ParticleTask.java index 551792e..7cb3bd0 100644 --- a/TempFly/src/com/moneybags/tempfly/util/ParticleTask.java +++ b/src/com/moneybags/tempfly/util/ParticleTask.java @@ -1,25 +1,25 @@ -package com.moneybags.tempfly.util; - -import org.bukkit.scheduler.BukkitRunnable; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.user.FlightUser; - -public class ParticleTask extends BukkitRunnable { - - private TempFly tempfly; - - public ParticleTask(TempFly tempfly) { - this.tempfly = tempfly; - } - - @Override - public void run() { - for (FlightUser user: tempfly.getFlightManager().getUsers()) { - if (user.hasFlightEnabled() && user.getPlayer().isFlying()) { - user.playTrail(); - } - } - } - -} +package com.moneybags.tempfly.util; + +import org.bukkit.scheduler.BukkitRunnable; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.user.FlightUser; + +public class ParticleTask extends BukkitRunnable { + + private TempFly tempfly; + + public ParticleTask(TempFly tempfly) { + this.tempfly = tempfly; + } + + @Override + public void run() { + for (FlightUser user: tempfly.getFlightManager().getUsers()) { + if (user.hasFlightEnabled() && user.getPlayer().isFlying()) { + user.playTrail(); + } + } + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/util/U.java b/src/com/moneybags/tempfly/util/U.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/util/U.java rename to src/com/moneybags/tempfly/util/U.java index cec17ad..58da00e 100644 --- a/TempFly/src/com/moneybags/tempfly/util/U.java +++ b/src/com/moneybags/tempfly/util/U.java @@ -1,141 +1,141 @@ -package com.moneybags.tempfly.util; - -import com.google.common.base.Joiner; -import com.google.common.base.Strings; -import com.google.common.primitives.Doubles; -import org.bukkit.*; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import java.util.Arrays; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -public class U { - - private static final Pattern LOCATION_STRING_PATTERN = Pattern.compile("~"); - private static final String PREFIX = "{PREFIX}"; - - public static void command(String s) { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), s); - } - - public static boolean isPlayer(CommandSender s){ - return s instanceof Player; - } - - public static String locationToString(Location loc) { - if (loc == null) { - return null; - } - - return String.format( - "%s~%d~%d~%d", - loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ() - ); - } - - public static Location locationFromString(String loc) { - String[] args = LOCATION_STRING_PATTERN.split(loc); - - if (args.length < 4) { - return null; - } - - World world = Bukkit.getWorld(args[0]); - - if (world == null) { - return null; - } - - Double x = Doubles.tryParse(args[1]); - Double y = Doubles.tryParse(args[2]); - Double z = Doubles.tryParse(args[3]); - - return (x == null || y == null || z == null) ? null : new Location(world, x, y , z); - } - - public static String cc(String m) { - return ChatColor.translateAlternateColorCodes('&', Strings.nullToEmpty(m)); - } - - public static String strip(String m) { - return ChatColor.stripColor(U.cc(m)); - } - - public static void m(CommandSender p, String s) { - if (s == null || s.equals(PREFIX) || s.length() == 0) { - return; - } - - p.sendMessage(s.replace(PREFIX, V.prefix)); - } - - public static void m(OfflinePlayer p, String s) { - if (p.isOnline()) { - m((Player) p, s); - } - } - - public static void m(Player p, String s) { - if (s == null || s.isEmpty() || s.equals(V.prefix) || s.equals(PREFIX)) { - return; - } - - p.sendMessage(s.replace(PREFIX, V.prefix)); - } - - public static boolean hasPermission(CommandSender s, String perm){ - return !isPlayer(s) || s.hasPermission(perm); - } - - public static String locToString(Location loc) { - return locationToString(loc); - } - - public static Location locFromString(String loc) { - return locationFromString(loc); - } - - public static ItemStack getConfigItem(FileConfiguration config, String path) { - ConfigurationSection section = config.getConfigurationSection(path); - - if (section == null) { - return new ItemStack(Material.STONE); - } - - ItemStack item = new ItemStack(Material.STONE, Math.max(1, section.getInt("amount", 1))); - ItemMeta meta = item.getItemMeta(); - - meta.setDisplayName(cc(ChatColor.RESET + section.getString("name", "&cThis item is broken. :'("))); - meta.setLore( - section.getStringList("lore").stream() - .map(it -> cc(ChatColor.RESET + it)) - .collect(Collectors.toList()) - ); - - item.setItemMeta(meta); - return item; - } - - public static String arrayToString(Object[] array, String divider) { - if (array == null) { - return null; - } - - return Joiner.on(Strings.nullToEmpty(divider)).join(array); - } - - public static String[] skipArray(String[] array, int skip) { - if (array.length <= skip) { - return new String[0]; - } - - return Arrays.copyOfRange(array, skip, array.length); - } - -} +package com.moneybags.tempfly.util; + +import com.google.common.base.Joiner; +import com.google.common.base.Strings; +import com.google.common.primitives.Doubles; +import org.bukkit.*; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Arrays; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class U { + + private static final Pattern LOCATION_STRING_PATTERN = Pattern.compile("~"); + private static final String PREFIX = "{PREFIX}"; + + public static void command(String s) { + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), s); + } + + public static boolean isPlayer(CommandSender s){ + return s instanceof Player; + } + + public static String locationToString(Location loc) { + if (loc == null) { + return null; + } + + return String.format( + "%s~%d~%d~%d", + loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ() + ); + } + + public static Location locationFromString(String loc) { + String[] args = LOCATION_STRING_PATTERN.split(loc); + + if (args.length < 4) { + return null; + } + + World world = Bukkit.getWorld(args[0]); + + if (world == null) { + return null; + } + + Double x = Doubles.tryParse(args[1]); + Double y = Doubles.tryParse(args[2]); + Double z = Doubles.tryParse(args[3]); + + return (x == null || y == null || z == null) ? null : new Location(world, x, y , z); + } + + public static String cc(String m) { + return ChatColor.translateAlternateColorCodes('&', Strings.nullToEmpty(m)); + } + + public static String strip(String m) { + return ChatColor.stripColor(U.cc(m)); + } + + public static void m(CommandSender p, String s) { + if (s == null || s.equals(PREFIX) || s.length() == 0) { + return; + } + + p.sendMessage(s.replace(PREFIX, V.prefix)); + } + + public static void m(OfflinePlayer p, String s) { + if (p.isOnline()) { + m((Player) p, s); + } + } + + public static void m(Player p, String s) { + if (s == null || s.isEmpty() || s.equals(V.prefix) || s.equals(PREFIX)) { + return; + } + + p.sendMessage(s.replace(PREFIX, V.prefix)); + } + + public static boolean hasPermission(CommandSender s, String perm){ + return !isPlayer(s) || s.hasPermission(perm); + } + + public static String locToString(Location loc) { + return locationToString(loc); + } + + public static Location locFromString(String loc) { + return locationFromString(loc); + } + + public static ItemStack getConfigItem(FileConfiguration config, String path) { + ConfigurationSection section = config.getConfigurationSection(path); + + if (section == null) { + return new ItemStack(Material.STONE); + } + + ItemStack item = new ItemStack(Material.STONE, Math.max(1, section.getInt("amount", 1))); + ItemMeta meta = item.getItemMeta(); + + meta.setDisplayName(cc(ChatColor.RESET + section.getString("name", "&cThis item is broken. :'("))); + meta.setLore( + section.getStringList("lore").stream() + .map(it -> cc(ChatColor.RESET + it)) + .collect(Collectors.toList()) + ); + + item.setItemMeta(meta); + return item; + } + + public static String arrayToString(Object[] array, String divider) { + if (array == null) { + return null; + } + + return Joiner.on(Strings.nullToEmpty(divider)).join(array); + } + + public static String[] skipArray(String[] array, int skip) { + if (array.length <= skip) { + return new String[0]; + } + + return Arrays.copyOfRange(array, skip, array.length); + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/util/V.java b/src/com/moneybags/tempfly/util/V.java similarity index 97% rename from TempFly/src/com/moneybags/tempfly/util/V.java rename to src/com/moneybags/tempfly/util/V.java index 04fd72e..16a3c42 100644 --- a/TempFly/src/com/moneybags/tempfly/util/V.java +++ b/src/com/moneybags/tempfly/util/V.java @@ -1,463 +1,463 @@ -package com.moneybags.tempfly.util; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import com.moneybags.tempfly.util.data.Files; -import com.moneybags.tempfly.util.data.Files.C; - -/** - * TODO Most of these values should be relocated to their manager objects - * @author Kevin - * - */ -public class V { - - public static String - prefix, - reload, - infinity, - - invalidParticle, - invalidPermission, - invalidPlayer, - invalidNumber, - invalidTimeSelf, - invalidTimeOther, - invalidSender, - invalidCommand, - invalidReciever, - invalidFlyerSelf, - invalidFunds, - invalidEconomy, - - timeGivenOther, - timeGivenSelf, - timeRemovedOther, - timeRemovedSelf, - timeSentOther, - timeSentSelf, - timeSetOther, - timeSetSelf, - timeMaxOther, - timeMaxSelf, - timeDecayLost, - timeFormat, - timePurchased, - firstJoin, - dailyLogin, - - unitSeconds, - unitMinutes, - unitHours, - unitDays, - - infoHeader, - infoPlayer, - infoDays, - infoHours, - infoMinutes, - infoSeconds, - infoFooter, - infoInfinite, - - flyEnabledOther, - flyEnabledSelf, - flyDisabledOther, - flyDisabledSelf, - flySpeedOther, - flySpeedSelf, - flySpeedDenied, - flySpeedLimitSelf, - flySpeedLimitOther, - flyAlreadyEnabled, - flyAlreadyDisabled, - flyInfiniteEnabled, - flyInfiniteDisabled, - flyBypassEnabled, - flyBypassDisabled, - - disabledIdle, - consideredIdle, - - requireFailOther, - requireFailDefault, - requirePassDefault, - requireFailCombat, - requirePassCombat, - requireFailRegion, - requireFailWorld, - requireFailHeight, - requireFailStruct, - - particleType, - listName, - listPlaceholderOn, - listPlaceholderOff, - tagName, - tagPlaceholderOn, - tagPlaceholderOff, - - fbDays, - fbHours, - fbMinutes, - fbSeconds, - - warningTitle, - warningSubtitle, - - actionText, - - trailRemovedSelf, - trailRemovedOther, - trailSetSelf, - trailSetOther, - - vaultPermsRequired; - - public static boolean - permaTimer, - groundTimer, - creativeTimer, - spectatorTimer, - idleTimer, - idleDrop, - payable, - particles, - particleDefault, - list, - tag, - // Combat tag - tagAttackPlayer, - tagAttackMob, - tagAttackedByPlayer, - tagAttackedByMob, - tagAttackedBySelf, - // Fall damage - damageCommand, - damageTime, - damageCombat, - damageIdle, - damageWorld, - damageRegion, - damageStruct, - - infiniteDisablePayment, - infiniteDisableBonus, - infiniteDisableDecay, - - autoFly, - autoFlyTimeReceived, - actionBar, - timeDecay, - flightToggle, - hideVanish, - shop, - - debug, - disableTracker, - disableTab, - - bugInfiniteA, - bugInfiniteB; - - public static int - idleThreshold, - save, - combatTagPvp, - combatTagPve, - maxY, - decayThresh; - - public static double - maxTimeBase, - firstJoinTime, - legacyBonus, - decayAmount; - - public static List - help, - helpExtended, - disabledWorlds, - disabledRegions, - overrideFlightPermissions; - - public static List - warningTimes; - - public static Map - dailyBonus, - maxTimeGroups; - - public static void loadValues() { - dailyBonus = new HashMap<>(); - maxTimeGroups = new HashMap<>(); - - help = new ArrayList<>(); - helpExtended = new ArrayList<>(); - disabledWorlds = new ArrayList<>(); - disabledRegions = new ArrayList<>(); - overrideFlightPermissions = new ArrayList<>(); - - FileConfiguration config = Files.config; - - prefix = st(C.LANG, "system.prefix"); - reload = st(C.LANG, "system.reload"); - - invalidParticle = st(C.LANG, "general.invalid.particle"); - invalidPermission = st(C.LANG, "general.invalid.permission"); - invalidPlayer = st(C.LANG, "general.invalid.player"); - invalidNumber = st(C.LANG, "general.invalid.number"); - invalidSender = st(C.LANG, "general.invalid.sender"); - invalidCommand = st(C.LANG, "general.invalid.command"); - invalidTimeOther = st(C.LANG, "general.invalid.time_other"); - invalidTimeSelf = st(C.LANG, "general.invalid.time_self"); - invalidReciever = st(C.LANG, "general.invalid.reciever"); - invalidFlyerSelf = st(C.LANG, "general.invalid.flyer_self"); - invalidFunds = st(C.LANG, "general.invalid.funds"); - invalidEconomy = st(C.LANG, "general.invalid.economy"); - vaultPermsRequired = st(C.LANG, "general.invalid.vault_perms"); - - timeGivenOther = st(C.LANG, "general.time.given_other"); - timeGivenSelf = st(C.LANG, "general.time.given_self"); - timeRemovedOther = st(C.LANG, "general.time.removed_other"); - timeRemovedSelf = st(C.LANG, "general.time.removed_self"); - timeSentOther = st(C.LANG, "general.time.sent_other"); - timeSentSelf = st(C.LANG, "general.time.sent_self"); - timeSetOther = st(C.LANG, "general.time.set_other"); - timeSetSelf = st(C.LANG, "general.time.set_self"); - timeMaxOther = st(C.LANG, "general.time.max_other"); - timeMaxSelf = st(C.LANG, "general.time.max_self"); - timeDecayLost = st(C.LANG, "general.time.decay"); - timeFormat = st(C.LANG, "general.time.format"); - timePurchased = st(C.LANG, "general.time.purchased"); - firstJoin = st(C.LANG, "general.time.first_join"); - dailyLogin = st(C.LANG, "general.time.daily_login"); - - unitSeconds = st(C.LANG, "general.unit.seconds", "s"); - unitMinutes = st(C.LANG, "general.unit.minutes", "m"); - unitHours = st(C.LANG, "general.unit.hours", "h"); - unitDays = st(C.LANG, "general.unit.days", "d"); - - infoHeader = st(C.LANG, "general.info.header"); - infoPlayer = st(C.LANG, "general.info.player"); - infoDays = st(C.LANG, "general.info.days"); - infoHours = st(C.LANG, "general.info.hours"); - infoMinutes = st(C.LANG, "general.info.minutes"); - infoSeconds = st(C.LANG, "general.info.seconds"); - infoFooter = st(C.LANG, "general.info.footer"); - infoInfinite = st(C.LANG, "general.info.infinite"); - - flyEnabledOther = st(C.LANG, "general.fly.enabled_other"); - flyEnabledSelf = st(C.LANG, "general.fly.enabled_self"); - flyDisabledOther = st(C.LANG, "general.fly.disabled_other"); - flyDisabledSelf = st(C.LANG, "general.fly.disabled_self"); - flySpeedOther = st(C.LANG, "general.fly.speed_other"); - flySpeedSelf = st(C.LANG, "general.fly.speed_self"); - flySpeedLimitOther = st(C.LANG, "general.fly.speed_limit_other"); - flySpeedLimitSelf = st(C.LANG, "general.fly.speed_limit_self"); - flySpeedDenied = st(C.LANG, "general.fly.speed_restricted"); - flyAlreadyEnabled = st(C.LANG, "general.fly.already_enabled"); - flyAlreadyDisabled = st(C.LANG, "general.fly.already_disabled"); - flyInfiniteEnabled = st(C.LANG, "general.fly.infinite_enabled"); - flyInfiniteDisabled = st(C.LANG, "general.fly.infinite_disabled"); - flyBypassEnabled = st(C.LANG, "general.fly.bypass_enabled"); - flyBypassDisabled = st(C.LANG, "general.fly.bypass_disabled"); - - disabledIdle = st(C.LANG, "general.fly.idle_drop"); - consideredIdle = st(C.LANG, "general.fly.idle"); - - requireFailOther = st(C.LANG, "general.requirement.fail.default_other"); - requireFailDefault = st(C.LANG, "general.requirement.fail.default"); - requirePassDefault = st(C.LANG, "general.requirement.pass.default"); - requireFailCombat = st(C.LANG, "general.requirement.fail.combat"); - requirePassCombat = st(C.LANG, "general.requirement.pass.combat"); - requireFailRegion = st(C.LANG, "general.requirement.fail.region"); - requireFailWorld = st(C.LANG, "general.requirement.fail.world"); - requireFailHeight = st(C.LANG, "general.requirement.fail.height"); - requireFailStruct = st(C.LANG, "general.requirement.fail.structure"); - - fbDays = st(C.LANG, "aesthetic.featherboard.days"); - fbHours = st(C.LANG, "aesthetic.featherboard.hours"); - fbMinutes = st(C.LANG, "aesthetic.featherboard.minutes"); - fbSeconds = st(C.LANG, "aesthetic.featherboard.seconds"); - infinity = st(C.LANG, "aesthetic.symbols.infinity"); - - warningTitle = st(C.CONFIG, "aesthetic.warning.title"); - warningSubtitle = st(C.CONFIG, "aesthetic.warning.subtitle"); - - actionText = st(C.CONFIG, "aesthetic.action_bar.text"); - - trailRemovedSelf = st(C.LANG, "aesthetic.trail.removed_self"); - trailRemovedOther = st(C.LANG, "aesthetic.trail.removed_other"); - trailSetSelf = st(C.LANG, "aesthetic.trail.set_self"); - trailSetOther = st(C.LANG, "aesthetic.trail.set_other"); - - List h = Files.lang.getStringList("system.help"); - if (h != null) { - for (String s: h) { - help.add(U.cc(s)); - } - } - - List he = Files.lang.getStringList("system.help_extended"); - if (he != null) { - for (String s: he) { - helpExtended.add(U.cc(s)); - } - } - - try { - warningTimes = Files.config.getLongList("aesthetic.warning.seconds"); - } catch (Exception e) { - warningTimes = new ArrayList<>(); - Console.warn("You can only set numbers under (aesthetic.warning.seconds) in the config!"); - } - - - disabledWorlds = Files.config.getStringList("general.disabled.worlds"); - if (disabledWorlds == null) { - disabledWorlds = new ArrayList<>(); - } - - disabledRegions = Files.config.getStringList("general.disabled.regions"); - if (disabledRegions == null) { - disabledRegions = new ArrayList<>(); - } - - overrideFlightPermissions = Files.config.getStringList("general.fly_override_permissions"); - if (overrideFlightPermissions == null) { - overrideFlightPermissions = new ArrayList<>(); - } - - - save = config.getInt("system.backup", 5); - debug = config.getBoolean("system.debug"); - disableTracker = config.getBoolean("system.disable_region_tracking"); - disableTab = config.getBoolean("system.disable_tab"); - - permaTimer = config.getBoolean("general.timer.constant"); - groundTimer = config.getBoolean("general.timer.ground"); - creativeTimer = config.getBoolean("general.timer.creative"); - spectatorTimer = config.getBoolean("general.timer.spectator"); - idleTimer = config.getBoolean("general.timer.idle"); - idleDrop = config.getBoolean("general.idle.drop_player"); - idleThreshold = config.getInt("general.idle.threshold"); - payable = config.getBoolean("general.time.payable"); - particles = config.getBoolean("aesthetic.identifier.particles.enabled"); - particleType = config.getString("aesthetic.identifier.particles.type", "VILLAGER_HAPPY"); - particleDefault = config.getBoolean("aesthetic.identifier.particles.display_by_default"); - hideVanish = config.getBoolean("aesthetic.identifier.particles.hide_vanish"); - list = config.getBoolean("aesthetic.identifier.tab_list.enabled"); - listName = st(C.CONFIG, "aesthetic.identifier.tab_list.name"); - listPlaceholderOn = st(C.CONFIG, "aesthetic.identifier.tab_list.placeholder.enabled"); - listPlaceholderOff = st(C.CONFIG, "aesthetic.identifier.tab_list.placeholder.disabled"); - tag = config.getBoolean("aesthetic.identifier.name_tag.enabled"); - tagName = st(C.CONFIG, "aesthetic.identifier.name_tag.name"); - tagPlaceholderOn = st(C.CONFIG, "aesthetic.identifier.name_tag.placeholder.enabled"); - tagPlaceholderOff = st(C.CONFIG, "aesthetic.identifier.name_tag.placeholder.disabled"); - tagAttackPlayer = config.getBoolean("general.combat.attack_player"); - tagAttackMob = config.getBoolean("general.combat.attack_mob"); - tagAttackedByPlayer = config.getBoolean("general.combat.attacked_by_player"); - tagAttackedByMob = config.getBoolean("general.combat.attacked_by_mob"); - tagAttackedBySelf = config.getBoolean("general.combat.self_inflicted"); - combatTagPvp = config.getInt("general.combat.pvp_tag", 5) * 20; - combatTagPve = config.getInt("general.combat.pve_tag", 10) * 20; - timeDecay = config.getBoolean("general.time_decay.enabled"); - decayThresh = config.getInt("general.time_decay.threshold", 3600); - decayAmount = config.getDouble("general.time_decay.seconds_lost", 15); - firstJoinTime = config.getLong("general.bonus.first_join", 0); - legacyBonus = config.getLong("general.bonus.daily_login", 0); - shop = config.getBoolean("shop.general.enabled", false); - - bugInfiniteA = config.getBoolean("workarounds.infinite_flight.fix_a"); - bugInfiniteB = config.getBoolean("workarounds.infinite_flight.fix_b"); - - maxY = config.getInt("general.flight.maximum_height", 275); - autoFly = config.getBoolean("general.flight.auto_enable", true); - autoFlyTimeReceived = config.getBoolean("general.flight.enable_on_time_received", false); - - - damageCommand = config.getBoolean("general.damage.on_command"); - damageTime = config.getBoolean("general.damage.out_of_time"); - damageCombat = config.getBoolean("general.damage.combat"); - damageIdle = config.getBoolean("general.damage.idle"); - damageWorld = config.getBoolean("general.damage.disabled_world"); - damageRegion = config.getBoolean("general.damage.disabled_region"); - damageStruct = config.getBoolean("general.damage.structure_proximity"); - - actionBar = config.getBoolean("aesthetic.action_bar.enabled"); - - double legacyBonus = config.getDouble("general.bonus.daily_login"); - if (legacyBonus == 0) { - ConfigurationSection csPerms = config.getConfigurationSection("general.bonus.daily_login"); - if (csPerms != null) { - for (String key: csPerms.getKeys(false)) { - double value = config.getDouble("general.bonus.daily_login." + key); - if (value > 0 && !dailyBonus.containsKey(key)) { - dailyBonus.put(key, value); - } - } - } - } - maxTimeBase = config.getDouble("general.time.max.base", -1); - ConfigurationSection csMax = config.getConfigurationSection("general.time.max.groups"); - if (csMax != null) { - for (String s: csMax.getKeys(false)) { - maxTimeGroups.put(s, config.getDouble("general.time.max.groups." + s)); - } - } - } - - private static int missingMessages = 0; - - private static String st(C file, String key){ - try{ - switch (file) - { - case CONFIG: - return U.cc(Files.config.getString(key)).replaceAll("\\{PREFIX}", prefix); - case LANG: - return U.cc(Files.lang.getString(key)).replaceAll("\\{PREFIX}", prefix); - default: - return ""; - } - } catch (Exception e) { - Console.warn("There is a missing message in the file: (" + file.toString().toLowerCase() + ".yml) | Path: (" + key + ")"); - if (missingMessages++ < 3) {Console.warn("THIS IS NOT AN ERROR! You simply need to add the missing message.");} - return U.cc("&cThis message is broken! :("); - } - } - - public static String st(FileConfiguration config, String key, String fileName){ - try{ - return U.cc(config.getString(key)).replaceAll("\\{PREFIX}", prefix); - } catch (Exception e) { - Console.warn("There is a missing message in the file: (" + fileName + ".yml) | Path: (" + key + ")"); - if (missingMessages++ < 3) {Console.warn("THIS IS NOT AN ERROR! You simply need to add the missing message.");} - return U.cc("&cThis message is broken! :("); - } - } - - private static String st(C file, String key, String def){ - try{ - switch (file) - { - case CONFIG: - return U.cc(Files.config.getString(key)).replaceAll("\\{PREFIX}", prefix); - case LANG: - return U.cc(Files.lang.getString(key)).replaceAll("\\{PREFIX}", prefix); - default: - return ""; - } - } catch (Exception e) { - Console.warn("There is a missing message in the file: (" + file.toString().toLowerCase() + ") | Path: (" + key + ")"); - if (missingMessages++ < 3) {Console.warn("THIS IS NOT AN ERROR! You simply need to add the missing messagge.");} - return U.cc(def); - } - } -} +package com.moneybags.tempfly.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import com.moneybags.tempfly.util.data.Files; +import com.moneybags.tempfly.util.data.Files.C; + +/** + * TODO Most of these values should be relocated to their manager objects + * @author Kevin + * + */ +public class V { + + public static String + prefix, + reload, + infinity, + + invalidParticle, + invalidPermission, + invalidPlayer, + invalidNumber, + invalidTimeSelf, + invalidTimeOther, + invalidSender, + invalidCommand, + invalidReciever, + invalidFlyerSelf, + invalidFunds, + invalidEconomy, + + timeGivenOther, + timeGivenSelf, + timeRemovedOther, + timeRemovedSelf, + timeSentOther, + timeSentSelf, + timeSetOther, + timeSetSelf, + timeMaxOther, + timeMaxSelf, + timeDecayLost, + timeFormat, + timePurchased, + firstJoin, + dailyLogin, + + unitSeconds, + unitMinutes, + unitHours, + unitDays, + + infoHeader, + infoPlayer, + infoDays, + infoHours, + infoMinutes, + infoSeconds, + infoFooter, + infoInfinite, + + flyEnabledOther, + flyEnabledSelf, + flyDisabledOther, + flyDisabledSelf, + flySpeedOther, + flySpeedSelf, + flySpeedDenied, + flySpeedLimitSelf, + flySpeedLimitOther, + flyAlreadyEnabled, + flyAlreadyDisabled, + flyInfiniteEnabled, + flyInfiniteDisabled, + flyBypassEnabled, + flyBypassDisabled, + + disabledIdle, + consideredIdle, + + requireFailOther, + requireFailDefault, + requirePassDefault, + requireFailCombat, + requirePassCombat, + requireFailRegion, + requireFailWorld, + requireFailHeight, + requireFailStruct, + + particleType, + listName, + listPlaceholderOn, + listPlaceholderOff, + tagName, + tagPlaceholderOn, + tagPlaceholderOff, + + fbDays, + fbHours, + fbMinutes, + fbSeconds, + + warningTitle, + warningSubtitle, + + actionText, + + trailRemovedSelf, + trailRemovedOther, + trailSetSelf, + trailSetOther, + + vaultPermsRequired; + + public static boolean + permaTimer, + groundTimer, + creativeTimer, + spectatorTimer, + idleTimer, + idleDrop, + payable, + particles, + particleDefault, + list, + tag, + // Combat tag + tagAttackPlayer, + tagAttackMob, + tagAttackedByPlayer, + tagAttackedByMob, + tagAttackedBySelf, + // Fall damage + damageCommand, + damageTime, + damageCombat, + damageIdle, + damageWorld, + damageRegion, + damageStruct, + + infiniteDisablePayment, + infiniteDisableBonus, + infiniteDisableDecay, + + autoFly, + autoFlyTimeReceived, + actionBar, + timeDecay, + flightToggle, + hideVanish, + shop, + + debug, + disableTracker, + disableTab, + + bugInfiniteA, + bugInfiniteB; + + public static int + idleThreshold, + save, + combatTagPvp, + combatTagPve, + maxY, + decayThresh; + + public static double + maxTimeBase, + firstJoinTime, + legacyBonus, + decayAmount; + + public static List + help, + helpExtended, + disabledWorlds, + disabledRegions, + overrideFlightPermissions; + + public static List + warningTimes; + + public static Map + dailyBonus, + maxTimeGroups; + + public static void loadValues() { + dailyBonus = new HashMap<>(); + maxTimeGroups = new HashMap<>(); + + help = new ArrayList<>(); + helpExtended = new ArrayList<>(); + disabledWorlds = new ArrayList<>(); + disabledRegions = new ArrayList<>(); + overrideFlightPermissions = new ArrayList<>(); + + FileConfiguration config = Files.config; + + prefix = st(C.LANG, "system.prefix"); + reload = st(C.LANG, "system.reload"); + + invalidParticle = st(C.LANG, "general.invalid.particle"); + invalidPermission = st(C.LANG, "general.invalid.permission"); + invalidPlayer = st(C.LANG, "general.invalid.player"); + invalidNumber = st(C.LANG, "general.invalid.number"); + invalidSender = st(C.LANG, "general.invalid.sender"); + invalidCommand = st(C.LANG, "general.invalid.command"); + invalidTimeOther = st(C.LANG, "general.invalid.time_other"); + invalidTimeSelf = st(C.LANG, "general.invalid.time_self"); + invalidReciever = st(C.LANG, "general.invalid.reciever"); + invalidFlyerSelf = st(C.LANG, "general.invalid.flyer_self"); + invalidFunds = st(C.LANG, "general.invalid.funds"); + invalidEconomy = st(C.LANG, "general.invalid.economy"); + vaultPermsRequired = st(C.LANG, "general.invalid.vault_perms"); + + timeGivenOther = st(C.LANG, "general.time.given_other"); + timeGivenSelf = st(C.LANG, "general.time.given_self"); + timeRemovedOther = st(C.LANG, "general.time.removed_other"); + timeRemovedSelf = st(C.LANG, "general.time.removed_self"); + timeSentOther = st(C.LANG, "general.time.sent_other"); + timeSentSelf = st(C.LANG, "general.time.sent_self"); + timeSetOther = st(C.LANG, "general.time.set_other"); + timeSetSelf = st(C.LANG, "general.time.set_self"); + timeMaxOther = st(C.LANG, "general.time.max_other"); + timeMaxSelf = st(C.LANG, "general.time.max_self"); + timeDecayLost = st(C.LANG, "general.time.decay"); + timeFormat = st(C.LANG, "general.time.format"); + timePurchased = st(C.LANG, "general.time.purchased"); + firstJoin = st(C.LANG, "general.time.first_join"); + dailyLogin = st(C.LANG, "general.time.daily_login"); + + unitSeconds = st(C.LANG, "general.unit.seconds", "s"); + unitMinutes = st(C.LANG, "general.unit.minutes", "m"); + unitHours = st(C.LANG, "general.unit.hours", "h"); + unitDays = st(C.LANG, "general.unit.days", "d"); + + infoHeader = st(C.LANG, "general.info.header"); + infoPlayer = st(C.LANG, "general.info.player"); + infoDays = st(C.LANG, "general.info.days"); + infoHours = st(C.LANG, "general.info.hours"); + infoMinutes = st(C.LANG, "general.info.minutes"); + infoSeconds = st(C.LANG, "general.info.seconds"); + infoFooter = st(C.LANG, "general.info.footer"); + infoInfinite = st(C.LANG, "general.info.infinite"); + + flyEnabledOther = st(C.LANG, "general.fly.enabled_other"); + flyEnabledSelf = st(C.LANG, "general.fly.enabled_self"); + flyDisabledOther = st(C.LANG, "general.fly.disabled_other"); + flyDisabledSelf = st(C.LANG, "general.fly.disabled_self"); + flySpeedOther = st(C.LANG, "general.fly.speed_other"); + flySpeedSelf = st(C.LANG, "general.fly.speed_self"); + flySpeedLimitOther = st(C.LANG, "general.fly.speed_limit_other"); + flySpeedLimitSelf = st(C.LANG, "general.fly.speed_limit_self"); + flySpeedDenied = st(C.LANG, "general.fly.speed_restricted"); + flyAlreadyEnabled = st(C.LANG, "general.fly.already_enabled"); + flyAlreadyDisabled = st(C.LANG, "general.fly.already_disabled"); + flyInfiniteEnabled = st(C.LANG, "general.fly.infinite_enabled"); + flyInfiniteDisabled = st(C.LANG, "general.fly.infinite_disabled"); + flyBypassEnabled = st(C.LANG, "general.fly.bypass_enabled"); + flyBypassDisabled = st(C.LANG, "general.fly.bypass_disabled"); + + disabledIdle = st(C.LANG, "general.fly.idle_drop"); + consideredIdle = st(C.LANG, "general.fly.idle"); + + requireFailOther = st(C.LANG, "general.requirement.fail.default_other"); + requireFailDefault = st(C.LANG, "general.requirement.fail.default"); + requirePassDefault = st(C.LANG, "general.requirement.pass.default"); + requireFailCombat = st(C.LANG, "general.requirement.fail.combat"); + requirePassCombat = st(C.LANG, "general.requirement.pass.combat"); + requireFailRegion = st(C.LANG, "general.requirement.fail.region"); + requireFailWorld = st(C.LANG, "general.requirement.fail.world"); + requireFailHeight = st(C.LANG, "general.requirement.fail.height"); + requireFailStruct = st(C.LANG, "general.requirement.fail.structure"); + + fbDays = st(C.LANG, "aesthetic.featherboard.days"); + fbHours = st(C.LANG, "aesthetic.featherboard.hours"); + fbMinutes = st(C.LANG, "aesthetic.featherboard.minutes"); + fbSeconds = st(C.LANG, "aesthetic.featherboard.seconds"); + infinity = st(C.LANG, "aesthetic.symbols.infinity"); + + warningTitle = st(C.CONFIG, "aesthetic.warning.title"); + warningSubtitle = st(C.CONFIG, "aesthetic.warning.subtitle"); + + actionText = st(C.CONFIG, "aesthetic.action_bar.text"); + + trailRemovedSelf = st(C.LANG, "aesthetic.trail.removed_self"); + trailRemovedOther = st(C.LANG, "aesthetic.trail.removed_other"); + trailSetSelf = st(C.LANG, "aesthetic.trail.set_self"); + trailSetOther = st(C.LANG, "aesthetic.trail.set_other"); + + List h = Files.lang.getStringList("system.help"); + if (h != null) { + for (String s: h) { + help.add(U.cc(s)); + } + } + + List he = Files.lang.getStringList("system.help_extended"); + if (he != null) { + for (String s: he) { + helpExtended.add(U.cc(s)); + } + } + + try { + warningTimes = Files.config.getLongList("aesthetic.warning.seconds"); + } catch (Exception e) { + warningTimes = new ArrayList<>(); + Console.warn("You can only set numbers under (aesthetic.warning.seconds) in the config!"); + } + + + disabledWorlds = Files.config.getStringList("general.disabled.worlds"); + if (disabledWorlds == null) { + disabledWorlds = new ArrayList<>(); + } + + disabledRegions = Files.config.getStringList("general.disabled.regions"); + if (disabledRegions == null) { + disabledRegions = new ArrayList<>(); + } + + overrideFlightPermissions = Files.config.getStringList("general.fly_override_permissions"); + if (overrideFlightPermissions == null) { + overrideFlightPermissions = new ArrayList<>(); + } + + + save = config.getInt("system.backup", 5); + debug = config.getBoolean("system.debug"); + disableTracker = config.getBoolean("system.disable_region_tracking"); + disableTab = config.getBoolean("system.disable_tab"); + + permaTimer = config.getBoolean("general.timer.constant"); + groundTimer = config.getBoolean("general.timer.ground"); + creativeTimer = config.getBoolean("general.timer.creative"); + spectatorTimer = config.getBoolean("general.timer.spectator"); + idleTimer = config.getBoolean("general.timer.idle"); + idleDrop = config.getBoolean("general.idle.drop_player"); + idleThreshold = config.getInt("general.idle.threshold"); + payable = config.getBoolean("general.time.payable"); + particles = config.getBoolean("aesthetic.identifier.particles.enabled"); + particleType = config.getString("aesthetic.identifier.particles.type", "VILLAGER_HAPPY"); + particleDefault = config.getBoolean("aesthetic.identifier.particles.display_by_default"); + hideVanish = config.getBoolean("aesthetic.identifier.particles.hide_vanish"); + list = config.getBoolean("aesthetic.identifier.tab_list.enabled"); + listName = st(C.CONFIG, "aesthetic.identifier.tab_list.name"); + listPlaceholderOn = st(C.CONFIG, "aesthetic.identifier.tab_list.placeholder.enabled"); + listPlaceholderOff = st(C.CONFIG, "aesthetic.identifier.tab_list.placeholder.disabled"); + tag = config.getBoolean("aesthetic.identifier.name_tag.enabled"); + tagName = st(C.CONFIG, "aesthetic.identifier.name_tag.name"); + tagPlaceholderOn = st(C.CONFIG, "aesthetic.identifier.name_tag.placeholder.enabled"); + tagPlaceholderOff = st(C.CONFIG, "aesthetic.identifier.name_tag.placeholder.disabled"); + tagAttackPlayer = config.getBoolean("general.combat.attack_player"); + tagAttackMob = config.getBoolean("general.combat.attack_mob"); + tagAttackedByPlayer = config.getBoolean("general.combat.attacked_by_player"); + tagAttackedByMob = config.getBoolean("general.combat.attacked_by_mob"); + tagAttackedBySelf = config.getBoolean("general.combat.self_inflicted"); + combatTagPvp = config.getInt("general.combat.pvp_tag", 5) * 20; + combatTagPve = config.getInt("general.combat.pve_tag", 10) * 20; + timeDecay = config.getBoolean("general.time_decay.enabled"); + decayThresh = config.getInt("general.time_decay.threshold", 3600); + decayAmount = config.getDouble("general.time_decay.seconds_lost", 15); + firstJoinTime = config.getLong("general.bonus.first_join", 0); + legacyBonus = config.getLong("general.bonus.daily_login", 0); + shop = config.getBoolean("shop.general.enabled", false); + + bugInfiniteA = config.getBoolean("workarounds.infinite_flight.fix_a"); + bugInfiniteB = config.getBoolean("workarounds.infinite_flight.fix_b"); + + maxY = config.getInt("general.flight.maximum_height", 275); + autoFly = config.getBoolean("general.flight.auto_enable", true); + autoFlyTimeReceived = config.getBoolean("general.flight.enable_on_time_received", false); + + + damageCommand = config.getBoolean("general.damage.on_command"); + damageTime = config.getBoolean("general.damage.out_of_time"); + damageCombat = config.getBoolean("general.damage.combat"); + damageIdle = config.getBoolean("general.damage.idle"); + damageWorld = config.getBoolean("general.damage.disabled_world"); + damageRegion = config.getBoolean("general.damage.disabled_region"); + damageStruct = config.getBoolean("general.damage.structure_proximity"); + + actionBar = config.getBoolean("aesthetic.action_bar.enabled"); + + double legacyBonus = config.getDouble("general.bonus.daily_login"); + if (legacyBonus == 0) { + ConfigurationSection csPerms = config.getConfigurationSection("general.bonus.daily_login"); + if (csPerms != null) { + for (String key: csPerms.getKeys(false)) { + double value = config.getDouble("general.bonus.daily_login." + key); + if (value > 0 && !dailyBonus.containsKey(key)) { + dailyBonus.put(key, value); + } + } + } + } + maxTimeBase = config.getDouble("general.time.max.base", -1); + ConfigurationSection csMax = config.getConfigurationSection("general.time.max.groups"); + if (csMax != null) { + for (String s: csMax.getKeys(false)) { + maxTimeGroups.put(s, config.getDouble("general.time.max.groups." + s)); + } + } + } + + private static int missingMessages = 0; + + private static String st(C file, String key){ + try{ + switch (file) + { + case CONFIG: + return U.cc(Files.config.getString(key)).replaceAll("\\{PREFIX}", prefix); + case LANG: + return U.cc(Files.lang.getString(key)).replaceAll("\\{PREFIX}", prefix); + default: + return ""; + } + } catch (Exception e) { + Console.warn("There is a missing message in the file: (" + file.toString().toLowerCase() + ".yml) | Path: (" + key + ")"); + if (missingMessages++ < 3) {Console.warn("THIS IS NOT AN ERROR! You simply need to add the missing message.");} + return U.cc("&cThis message is broken! :("); + } + } + + public static String st(FileConfiguration config, String key, String fileName){ + try{ + return U.cc(config.getString(key)).replaceAll("\\{PREFIX}", prefix); + } catch (Exception e) { + Console.warn("There is a missing message in the file: (" + fileName + ".yml) | Path: (" + key + ")"); + if (missingMessages++ < 3) {Console.warn("THIS IS NOT AN ERROR! You simply need to add the missing message.");} + return U.cc("&cThis message is broken! :("); + } + } + + private static String st(C file, String key, String def){ + try{ + switch (file) + { + case CONFIG: + return U.cc(Files.config.getString(key)).replaceAll("\\{PREFIX}", prefix); + case LANG: + return U.cc(Files.lang.getString(key)).replaceAll("\\{PREFIX}", prefix); + default: + return ""; + } + } catch (Exception e) { + Console.warn("There is a missing message in the file: (" + file.toString().toLowerCase() + ") | Path: (" + key + ")"); + if (missingMessages++ < 3) {Console.warn("THIS IS NOT AN ERROR! You simply need to add the missing messagge.");} + return U.cc(def); + } + } +} diff --git a/TempFly/src/com/moneybags/tempfly/util/data/DataBridge.java b/src/com/moneybags/tempfly/util/data/DataBridge.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/util/data/DataBridge.java rename to src/com/moneybags/tempfly/util/data/DataBridge.java index 862caf5..2b70495 100644 --- a/TempFly/src/com/moneybags/tempfly/util/data/DataBridge.java +++ b/src/com/moneybags/tempfly/util/data/DataBridge.java @@ -1,693 +1,693 @@ -package com.moneybags.tempfly.util.data; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.stream.Collectors; -import java.util.zip.DataFormatException; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; - -import com.moneybags.tempfly.TempFly; -import com.moneybags.tempfly.hook.TempFlyHook; -import com.moneybags.tempfly.hook.HookManager; -import com.moneybags.tempfly.hook.HookManager.Genre; -import com.moneybags.tempfly.util.Console; -import com.moneybags.tempfly.util.U; -import com.moneybags.tempfly.util.V; -import com.mysql.cj.jdbc.MysqlConnectionPoolDataSource; -import com.mysql.cj.jdbc.MysqlDataSource; - - -public class DataBridge implements DataFileHolder { - - private TempFly tempfly; - private MysqlDataSource dataSource; - - private File dataf; - private FileConfiguration data; - - private ExecutorService executor; - - // Staged changes are held in local memory until either the autosave runs, or they are forcefully committed. - // The databridge will act like these changes are part of the database even though they are local. - // It will look to see if there is data here first before it queries the database or YAML file. - - private Map changes = new ConcurrentHashMap<>(); - // A list of pointers that tell the asynchronous batch manager to save the data they point to - // if it exists in the list of changes. - - private List manualCommit = new ArrayList<>(); - - public MysqlDataSource getDataSource() { - return dataSource; - } - - public boolean hasSqlEnabled() { - return dataSource != null; - } - - public boolean connectSql() throws SQLException { - String - host = Files.config.getString("system.mysql.host"), - name = Files.config.getString("system.mysql.name"), - user = Files.config.getString("system.mysql.user"), - pass = Files.config.getString("system.mysql.pass"); - - MysqlDataSource dataSource = new MysqlConnectionPoolDataSource(); - dataSource.setServerName(host); - dataSource.setPortNumber(Files.config.getInt("system.mysql.port")); - dataSource.setDatabaseName(name); - dataSource.setUser(user); - dataSource.setPassword(pass); - - try (Connection conn = dataSource.getConnection()) { - if (!conn.isValid(1)) { - Console.severe("Could not establish a connection to the database!"); - return false; - } - } - - this.dataSource = dataSource; - return true; - } - - private void initDb() throws IOException, SQLException { - String setup; - try (InputStream in = tempfly.getResource("dbsetup.sql")) { - setup = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n")); - } - String[] queries = setup.split(";"); - for (String query : queries) { - if (query.isBlank()) continue; - try (Connection conn = dataSource.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.execute(); - } - } - Console.info("§2Database setup complete."); - } - - public DataBridge(TempFly tempfly) throws IOException, SQLException { - this.tempfly = tempfly; - if (Files.config.getBoolean("system.mysql.enabled")) { - connectSql(); - initDb(); - } - - // If connection is null we will default to yaml storage. - if (!hasSqlEnabled()) { - dataf = new File(tempfly.getDataFolder(), "data.yml"); - if (!dataf.exists()){ - dataf.getParentFile().mkdirs(); - tempfly.saveResource("data.yml", false); - } - data = new YamlConfiguration(); - try { data.load(dataf); } catch (Exception e1) { - Console.severe("There is a problem inside the data.yml, If you cannot fix the issue, please contact the developer."); - e1.printStackTrace(); - } - formatYamlData(tempfly); - } - this.executor = Executors.newCachedThreadPool(); - } - - - /** - * format the data file from legacy TempFly version. - * @param plugin - */ - private void formatYamlData(TempFly plugin) { - double version = data.getDouble("version", 0.0); - if (version < 2.0) { - Console.warn("Your data file needs to update to support the current version. Updating to version 2.0 now..."); - if (!backupLegacyData("update_2_backup_")) { - Bukkit.getPluginManager().disablePlugin(plugin); - return; - } - - data.set("version", 2.0); - ConfigurationSection csPlayers = data.getConfigurationSection("players"); - if (csPlayers != null) { - Map time = new HashMap<>(); - for (String key: csPlayers.getKeys(false)) { - time.put(key, data.getDouble("players." + key)); - } - for (Entry entry: time.entrySet()) { - String uuid = entry.getKey(); - double value = entry.getValue(); - data.set("players." + uuid + ".time", value); - data.set("players." + uuid + ".logged_in_flight", false); - data.set("players." + uuid + ".trail", ""); - } - } - List disco = data.getStringList("flight_disconnect"); - if (disco != null) { - for (String uuid: disco) { - data.set("players." + uuid + ".logged_in_flight", true); - } - } - data.set("flight_disconnect", null); - saveData(); - - } else if (version < 3.0) { - Console.warn("", "This tempfly version has a new data management system, (data.yml) will be backed for your safety.", ""); - if (!backupLegacyData("update_3_backup_")) { - Bukkit.getPluginManager().disablePlugin(plugin); - return; - } - data.set("version", 3.0); - saveData(); - } else if (version < 4.0) { - if (!backupLegacyData("update_4_backup_")) { - Bukkit.getPluginManager().disablePlugin(plugin); - return; - } - data.set("version", 4.0); - saveData(); - } - } - - /** - * Create a data backup from legacy TempFly version when updating. - * @return - */ - private boolean backupLegacyData(String file) { - Console.info("Creating a backup of your data file..."); - File f = new File(tempfly.getDataFolder(), file + String.valueOf(new Random().nextInt(99999)) + ".yml"); - try { - data.save(f); - } catch (Exception e) { - Console.severe("-----------------------------------", "There was an error while trying to backup the data file", "For your safety the plugin will disable. Please contact the tempfly developer."); - e.printStackTrace(); - return false; - } - return true; - } - - - public void stageChange(DataPointer pointer, Object data) { - stageChange(pointer, data, null); - } - /** - * Stage a change to be sent to the database later. - * @param pointer The type and path of the data - * @param data the data. - */ - public void stageChange(DataPointer pointer, Object data, DataFileHolder fileHolder) { - DataValue value = pointer.getValue(); - String[] path = pointer.getPath(); - if (V.debug) {//Console.debug(""); Console.debug("-----------Staging new change-----------"); Console.debug("--| Type: " + value.toString()); Console.debug("--| Path: " + U.arrayToString(pointer.getPath(), " | ")); Console.debug("--| Data: " + String.valueOf(data)); - } - - - changes.put(pointer, new StagedChange(value, data, path, fileHolder)); - } - - public boolean isStaged(DataPointer pointer) { - return changes.containsKey(pointer); - } - - /** - * Commit all changes to the database or yaml if applicable. - * Adds all the staged changes to the manual batch and runs the async batch collector. - */ - public void commitAll() { - Console.debug("", "--------> DataBridge Commit <--------", "--|>> Adding (ALL) changes to the commit queue"); - manualCommit.clear(); - manualCommit.addAll(changes.keySet()); - if (manualCommit.size() == 0) { - return; - } - executor.submit(() -> { - executeCommit(); - }); - } - - /** - * Collects StagedChanges using the pointers collected in the manual batch and sends data to the database. - */ - private void executeCommit() { - List commit = new ArrayList<>(); - - if (V.debug) {Console.debug("", "-|>>>>> Preparing to execute the commit queue");} - - List pl = new ArrayList<>(); - pl.addAll(manualCommit); - manualCommit.clear(); - - pointers: - for (DataPointer pointer: pl) { - if (V.debug) {Console.debug("", "--| Looking for data type:" + pointer.getValue().toString(), "--| Path:" + U.arrayToString(pointer.getPath(), " | "));} - Console.debug("looking for: " + pointer.hashCode()); - StagedChange change = changes.get(pointer); - if (change != null) { - Console.debug("--|> Found a staged change that matches: data=(" + change.getData() + ")"); - commit.add(change); - changes.remove(pointer); - continue pointers; - } - Console.debug("--|> No changes to save for this type..."); - } - - - if (commit.size() == 0 && V.debug) { Console.debug(">>>>> No changes to save...", "-----------End commit---------", ""); - return; - } - - if (V.debug) { Console.debug("Preparing to set value for (" + String.valueOf(commit.size()) + ") change" + (commit.size() > 1 ? "s" : "") + " found...");} - List altered = new ArrayList<>(); - for (StagedChange change: commit) { - DataFileHolder holder = change.getValue().getTable().getDataFileHolder(tempfly); - if (!altered.contains(holder)) { - altered.add(holder); - } - try { - setValue(change, holder.forceYaml()); - } catch (SQLException e) { - e.printStackTrace(); - continue; - } - } - for (DataFileHolder holder: altered) { - if (!hasSqlEnabled() || holder.forceYaml()) { - holder.saveData(); - } - } - Console.debug("-----------End commit---------", ""); - } - - /** - * Manually add data pointers to the next manual commit and run the async batch collector. - * @param pointers - */ - public void manualCommit(DataPointer... pointers) { - manualCommit.addAll(Arrays.asList(pointers)); - Console.debug(manualCommit.toString()); - executor.submit(() -> { - executeCommit(); - }); - } - - /** - * Drop ALL changes, resets data back to the original state unless it has been commited. - */ - public void dropChanges() { - manualCommit.clear(); - changes.clear(); - } - - /** - * Get a value from the table - * @param value - * @param row - * @return - * @throws SQLException - * @throws DataFormatException - */ - public Object getValue(DataPointer pointer) throws SQLException { - DataValue value = pointer.getValue(); - String[] path = pointer.getPath(); - if (V.debug) {Console.debug("", "-----Data Bridge Get Value-----", "--| Type: " + value.toString(), "--| Path: " + U.arrayToString(pointer.getPath(), " | ")); } - - Console.debug("--| Checking local staged changes"); - - StagedChange change = changes.get(pointer); - if (change != null) { - Console.debug("--|> found cached value... Returning local data!"); - return change.getData(); - } - Console.debug("--|> No local data found, prepare for data retrieval!"); - - if (!hasSqlEnabled()) { - Console.debug("--| Using YAML"); - int index = 0; - StringBuilder sb = new StringBuilder(); - for (String s: value.getYamlPath()) { - sb.append((sb.length() > 0 ? "." : "") + s); - if (path.length > index) { - sb.append("." + path[index]); - } - index++; - } - return value.getTable().getDataFileHolder(tempfly).getDataConfiguration().get(sb.toString()); - } else { - Console.debug("--| Using SQL"); - DataTable table = value.getTable(); - - - String statement = "SELECT " + value.getSqlColumn() + " FROM " + table.getSqlTable() + " WHERE " + table.getPrimaryKey() + " = ?"; - Console.debug(statement); - try (PreparedStatement st = dataSource.getConnection().prepareStatement(statement)) { - st.setString(1, path[0]); - ResultSet result = st.executeQuery(); - if (result.next()) { - return result.getObject(value.getSqlColumn()); - } - } - } - return null; - } - - public PreparedStatement prepareStatement(String statement) { - if (!hasSqlEnabled()) { - return null; - } - try { - return getDataSource().getConnection().prepareStatement(statement); - } catch (SQLException e) { - e.printStackTrace(); - return null; - } - } - - public Object getOrDefault(DataPointer pointer, Object def) { - Object object; - try { - object = getValue(pointer); - } catch (SQLException e) { - e.printStackTrace(); - return def; - } - if (V.debug) {Console.debug("", "-----Data Bridge Get or Default Value-----", "--|> Got: " + object, "--|> Returning: " + String.valueOf(object == null ? def : object));} - return object == null ? def : object; - } - - public Map getValues(DataTable table, String yamlPathTo, String row, String... extra) { - return getValues(table, null, yamlPathTo, row, extra); - } - - /** - * Get all values from the table for the given row. - * Assumes the row is path to the ConfigurationSection in yaml - * @param value - * @param row - * @return - */ - - public Map getValues(DataTable table, DataFileHolder fileHolder, String yamlPathTo, String row, String... extra) { - Map values = new HashMap<>(); - if (!hasSqlEnabled() || fileHolder.forceYaml()) { - FileConfiguration df = fileHolder == null ? - table.getDataFileHolder(tempfly).getDataConfiguration() - : fileHolder.getDataConfiguration(); - String path = yamlPathTo + "." + row + "." + U.arrayToString(extra, "."); - ConfigurationSection csValues = df.getConfigurationSection(path); - if (csValues != null) { - for (String key: csValues.getKeys(false)) { - values.put(key, df.get(path + "." + key)); - } - } - } - for (StagedChange local: changes.values()) { - if (local.comparePathPartial(row)) { - values.put(local.getPath()[local.getPath().length-1], local.getData()); - } - } - return values; - } - - public void setValue(StagedChange change, boolean forceYaml) throws SQLException { - DataValue value = change.getValue(); - String[] path = change.getPath(); - if (V.debug) {Console.debug("", "-----Data Bridge Set Value-----", "--| Type: " + value.toString(), "--| Path: " + U.arrayToString(path, " | ")); } - if (!hasSqlEnabled() || forceYaml) { - int index = 0; - StringBuilder sb = new StringBuilder(); - for (String s: value.getYamlPath()) { - sb.append((sb.length() > 0 ? "." : "") + s); - if (path.length > index) { - sb.append("." + path[index]); - } - index++; - } - if (V.debug) {Console.debug("--| Setting yaml value: " + sb.toString(), "--| New data: " + String.valueOf(change.getData()));} - FileConfiguration yaml = change.getFileHolder() == null ? - value.getTable().getDataFileHolder(tempfly).getDataConfiguration() - : change.getFileHolder().getDataConfiguration(); - if (!yaml.contains(sb.toString())) { - yaml.createSection(sb.toString()); - } - yaml.set(sb.toString(), change.getData()); - } else { - Console.debug("UPDATE " + value.getTable().getSqlTable() + " SET " + value.getSqlColumn() - + " = ? WHERE " + value.getTable().getPrimaryKey() + " = " + path[0]); - PreparedStatement st = dataSource.getConnection().prepareStatement( - "UPDATE " + value.getTable().getSqlTable() + " SET " + value.getSqlColumn() - + " = ? WHERE " + value.getTable().getPrimaryKey() + " = ?"); - Class type = value.getType(); - if (type.equals(Boolean.TYPE)) { - st.setBoolean(1, (boolean) change.getData()); - } else if (type.equals(Double.TYPE)) { - st.setDouble(1, (double) change.getData()); - } else if (type.equals(String.class)) { - st.setString(1, (String) change.getData()); - } else if (type.equals(Long.TYPE)) { - st.setLong(1, (long) change.getData()); - } - st.setString(2, path[0]); - st.execute(); - st.close(); - } - } - - - public static enum DataTable { - TEMPFLY_DATA("uuid"), - ISLAND_SETTINGS; - - private DataTable() {} - - private String primary; - - private DataTable(String primary) { - this.primary = primary; - } - - public String getPrimaryKey() { - return primary; - } - - public DataFileHolder getDataFileHolder(TempFly tempfly) { - switch (this) { - case TEMPFLY_DATA: - return tempfly.getDataBridge(); - case ISLAND_SETTINGS: - HookManager hooks = tempfly.getHookManager(); - TempFlyHook[] hook; - if ((hook = hooks.getGenre(Genre.SKYBLOCK)) != null && hook.length > 0) { - return (DataFileHolder) hook[0]; - } - break; - default: - return null; - } - return null; - } - - public String getSqlTable() { - switch (this) { - case TEMPFLY_DATA: - return "tempfly_data"; - case ISLAND_SETTINGS: - //return tempfly.getHookManager().getGenre(Genre.SKYBLOCK)[0].getHookedPlugin() + "_island_settings"; - default: - return null; - } - } - } - - public static enum DataValue { - PLAYER_TIME( - DataTable.TEMPFLY_DATA, - Double.TYPE, - "player_time", - new String[] {"players", "time"}, - false), - PLAYER_FLIGHT_LOG( - DataTable.TEMPFLY_DATA, - Boolean.TYPE, - "logged_in_flight", - new String[] {"players", "logged_in_flight"}, - false), - PLAYER_COMPAT_FLIGHT_LOG( - DataTable.TEMPFLY_DATA, - Boolean.TYPE, - "compat_logged_in_flight", - new String[] {"players", "compat_logged_in_flight"}, - false), - PLAYER_DAMAGE_PROTECTION( - DataTable.TEMPFLY_DATA, - Boolean.TYPE, - "damage_protection", - new String[] {"players", "damage_protection"}, - false), - PLAYER_DAILY_BONUS( - DataTable.TEMPFLY_DATA, - Long.TYPE, - "last_daily_bonus", - new String[] {"players", "last_daily_bonus"}, - false), - PLAYER_TRAIL( - DataTable.TEMPFLY_DATA, - String.class, - "trail", - new String[] {"players", "trail"}, - false), - PLAYER_INFINITE( - DataTable.TEMPFLY_DATA, - Boolean.TYPE, - "infinite", - new String[] {"players", "infinite"}, - false), - PLAYER_BYPASS( - DataTable.TEMPFLY_DATA, - Boolean.TYPE, - "bypass", - new String[] {"players", "bypass"}, - false), - PLAYER_SPEED( - DataTable.TEMPFLY_DATA, - Double.TYPE, - "speed", - new String[] {"players", "speed"}, - false), - - - - - ISLAND_SETTING( - DataTable.ISLAND_SETTINGS, - Boolean.TYPE, - null, - new String[] {"islands", "settings"}, - true); - - private DataTable table; - private Class type; - private String - sqlColumn; - - private String[] - yamlPath; - private boolean dynamic; - - private DataValue(DataTable table, Class type, String sqlColumn, String[] yamlPath, boolean dynamic) { - this.table = table; - this.type = type; - this.sqlColumn = sqlColumn; - this.yamlPath = yamlPath; - this.dynamic = dynamic; - } - - public DataTable getTable() { - return table; - } - - public Class getType() { - return type; - } - - public String getSqlColumn() { - return sqlColumn; - } - - public String[] getYamlPath() { - return yamlPath; - } - - public boolean hasDynamicPath() { - return dynamic; - } - } - - protected class StagedChange { - DataValue value; - String[] path; - Object data; - DataFileHolder fileHolder; - - public StagedChange(DataValue value, Object data, String[] path, DataFileHolder fileHolder) { - this.value = value; - this.path = path; - this.data = data; - this.fileHolder = fileHolder; - } - - public DataPointer getPointer() { - return DataPointer.of(value, path); - } - - public DataFileHolder getFileHolder() { - return fileHolder; - } - - public DataValue getValue() { - return value; - } - - public String[] getPath() { - return path; - } - - public Object getData() { - return data; - } - - public boolean comparePathPartial(String... path) { - for (int index = 0; path.length > index; index++) { - if (this.path.length <= index || !path[index].equals(this.path[index])) { - return false; - } - } - return true; - } - - } - - @Override - public File getDataFile() { - return dataf; - } - - @Override - public FileConfiguration getDataConfiguration() { - return data; - } - - @Override - public void setDataFile(File file) { - this.dataf = file; - } - - @Override - public void setDataConfiguration(FileConfiguration data) { - this.data = data; - } - - @Override - public void saveData() { - try { data.save(dataf); } catch (Exception e) {e.printStackTrace();} - } - -} +package com.moneybags.tempfly.util.data; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.Collectors; +import java.util.zip.DataFormatException; + +import org.bukkit.Bukkit; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import com.moneybags.tempfly.TempFly; +import com.moneybags.tempfly.hook.TempFlyHook; +import com.moneybags.tempfly.hook.HookManager; +import com.moneybags.tempfly.hook.HookManager.Genre; +import com.moneybags.tempfly.util.Console; +import com.moneybags.tempfly.util.U; +import com.moneybags.tempfly.util.V; +import com.mysql.cj.jdbc.MysqlConnectionPoolDataSource; +import com.mysql.cj.jdbc.MysqlDataSource; + + +public class DataBridge implements DataFileHolder { + + private TempFly tempfly; + private MysqlDataSource dataSource; + + private File dataf; + private FileConfiguration data; + + private ExecutorService executor; + + // Staged changes are held in local memory until either the autosave runs, or they are forcefully committed. + // The databridge will act like these changes are part of the database even though they are local. + // It will look to see if there is data here first before it queries the database or YAML file. + + private Map changes = new ConcurrentHashMap<>(); + // A list of pointers that tell the asynchronous batch manager to save the data they point to + // if it exists in the list of changes. + + private List manualCommit = new ArrayList<>(); + + public MysqlDataSource getDataSource() { + return dataSource; + } + + public boolean hasSqlEnabled() { + return dataSource != null; + } + + public boolean connectSql() throws SQLException { + String + host = Files.config.getString("system.mysql.host"), + name = Files.config.getString("system.mysql.name"), + user = Files.config.getString("system.mysql.user"), + pass = Files.config.getString("system.mysql.pass"); + + MysqlDataSource dataSource = new MysqlConnectionPoolDataSource(); + dataSource.setServerName(host); + dataSource.setPortNumber(Files.config.getInt("system.mysql.port")); + dataSource.setDatabaseName(name); + dataSource.setUser(user); + dataSource.setPassword(pass); + + try (Connection conn = dataSource.getConnection()) { + if (!conn.isValid(1)) { + Console.severe("Could not establish a connection to the database!"); + return false; + } + } + + this.dataSource = dataSource; + return true; + } + + private void initDb() throws IOException, SQLException { + String setup; + try (InputStream in = tempfly.getResource("dbsetup.sql")) { + setup = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n")); + } + String[] queries = setup.split(";"); + for (String query : queries) { + if (query.isBlank()) continue; + try (Connection conn = dataSource.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.execute(); + } + } + Console.info("§2Database setup complete."); + } + + public DataBridge(TempFly tempfly) throws IOException, SQLException { + this.tempfly = tempfly; + if (Files.config.getBoolean("system.mysql.enabled")) { + connectSql(); + initDb(); + } + + // If connection is null we will default to yaml storage. + if (!hasSqlEnabled()) { + dataf = new File(tempfly.getDataFolder(), "data.yml"); + if (!dataf.exists()){ + dataf.getParentFile().mkdirs(); + tempfly.saveResource("data.yml", false); + } + data = new YamlConfiguration(); + try { data.load(dataf); } catch (Exception e1) { + Console.severe("There is a problem inside the data.yml, If you cannot fix the issue, please contact the developer."); + e1.printStackTrace(); + } + formatYamlData(tempfly); + } + this.executor = Executors.newCachedThreadPool(); + } + + + /** + * format the data file from legacy TempFly version. + * @param plugin + */ + private void formatYamlData(TempFly plugin) { + double version = data.getDouble("version", 0.0); + if (version < 2.0) { + Console.warn("Your data file needs to update to support the current version. Updating to version 2.0 now..."); + if (!backupLegacyData("update_2_backup_")) { + Bukkit.getPluginManager().disablePlugin(plugin); + return; + } + + data.set("version", 2.0); + ConfigurationSection csPlayers = data.getConfigurationSection("players"); + if (csPlayers != null) { + Map time = new HashMap<>(); + for (String key: csPlayers.getKeys(false)) { + time.put(key, data.getDouble("players." + key)); + } + for (Entry entry: time.entrySet()) { + String uuid = entry.getKey(); + double value = entry.getValue(); + data.set("players." + uuid + ".time", value); + data.set("players." + uuid + ".logged_in_flight", false); + data.set("players." + uuid + ".trail", ""); + } + } + List disco = data.getStringList("flight_disconnect"); + if (disco != null) { + for (String uuid: disco) { + data.set("players." + uuid + ".logged_in_flight", true); + } + } + data.set("flight_disconnect", null); + saveData(); + + } else if (version < 3.0) { + Console.warn("", "This tempfly version has a new data management system, (data.yml) will be backed for your safety.", ""); + if (!backupLegacyData("update_3_backup_")) { + Bukkit.getPluginManager().disablePlugin(plugin); + return; + } + data.set("version", 3.0); + saveData(); + } else if (version < 4.0) { + if (!backupLegacyData("update_4_backup_")) { + Bukkit.getPluginManager().disablePlugin(plugin); + return; + } + data.set("version", 4.0); + saveData(); + } + } + + /** + * Create a data backup from legacy TempFly version when updating. + * @return + */ + private boolean backupLegacyData(String file) { + Console.info("Creating a backup of your data file..."); + File f = new File(tempfly.getDataFolder(), file + String.valueOf(new Random().nextInt(99999)) + ".yml"); + try { + data.save(f); + } catch (Exception e) { + Console.severe("-----------------------------------", "There was an error while trying to backup the data file", "For your safety the plugin will disable. Please contact the tempfly developer."); + e.printStackTrace(); + return false; + } + return true; + } + + + public void stageChange(DataPointer pointer, Object data) { + stageChange(pointer, data, null); + } + /** + * Stage a change to be sent to the database later. + * @param pointer The type and path of the data + * @param data the data. + */ + public void stageChange(DataPointer pointer, Object data, DataFileHolder fileHolder) { + DataValue value = pointer.getValue(); + String[] path = pointer.getPath(); + if (V.debug) {//Console.debug(""); Console.debug("-----------Staging new change-----------"); Console.debug("--| Type: " + value.toString()); Console.debug("--| Path: " + U.arrayToString(pointer.getPath(), " | ")); Console.debug("--| Data: " + String.valueOf(data)); + } + + + changes.put(pointer, new StagedChange(value, data, path, fileHolder)); + } + + public boolean isStaged(DataPointer pointer) { + return changes.containsKey(pointer); + } + + /** + * Commit all changes to the database or yaml if applicable. + * Adds all the staged changes to the manual batch and runs the async batch collector. + */ + public void commitAll() { + Console.debug("", "--------> DataBridge Commit <--------", "--|>> Adding (ALL) changes to the commit queue"); + manualCommit.clear(); + manualCommit.addAll(changes.keySet()); + if (manualCommit.size() == 0) { + return; + } + executor.submit(() -> { + executeCommit(); + }); + } + + /** + * Collects StagedChanges using the pointers collected in the manual batch and sends data to the database. + */ + private void executeCommit() { + List commit = new ArrayList<>(); + + if (V.debug) {Console.debug("", "-|>>>>> Preparing to execute the commit queue");} + + List pl = new ArrayList<>(); + pl.addAll(manualCommit); + manualCommit.clear(); + + pointers: + for (DataPointer pointer: pl) { + if (V.debug) {Console.debug("", "--| Looking for data type:" + pointer.getValue().toString(), "--| Path:" + U.arrayToString(pointer.getPath(), " | "));} + Console.debug("looking for: " + pointer.hashCode()); + StagedChange change = changes.get(pointer); + if (change != null) { + Console.debug("--|> Found a staged change that matches: data=(" + change.getData() + ")"); + commit.add(change); + changes.remove(pointer); + continue pointers; + } + Console.debug("--|> No changes to save for this type..."); + } + + + if (commit.size() == 0 && V.debug) { Console.debug(">>>>> No changes to save...", "-----------End commit---------", ""); + return; + } + + if (V.debug) { Console.debug("Preparing to set value for (" + String.valueOf(commit.size()) + ") change" + (commit.size() > 1 ? "s" : "") + " found...");} + List altered = new ArrayList<>(); + for (StagedChange change: commit) { + DataFileHolder holder = change.getValue().getTable().getDataFileHolder(tempfly); + if (!altered.contains(holder)) { + altered.add(holder); + } + try { + setValue(change, holder.forceYaml()); + } catch (SQLException e) { + e.printStackTrace(); + continue; + } + } + for (DataFileHolder holder: altered) { + if (!hasSqlEnabled() || holder.forceYaml()) { + holder.saveData(); + } + } + Console.debug("-----------End commit---------", ""); + } + + /** + * Manually add data pointers to the next manual commit and run the async batch collector. + * @param pointers + */ + public void manualCommit(DataPointer... pointers) { + manualCommit.addAll(Arrays.asList(pointers)); + Console.debug(manualCommit.toString()); + executor.submit(() -> { + executeCommit(); + }); + } + + /** + * Drop ALL changes, resets data back to the original state unless it has been commited. + */ + public void dropChanges() { + manualCommit.clear(); + changes.clear(); + } + + /** + * Get a value from the table + * @param value + * @param row + * @return + * @throws SQLException + * @throws DataFormatException + */ + public Object getValue(DataPointer pointer) throws SQLException { + DataValue value = pointer.getValue(); + String[] path = pointer.getPath(); + if (V.debug) {Console.debug("", "-----Data Bridge Get Value-----", "--| Type: " + value.toString(), "--| Path: " + U.arrayToString(pointer.getPath(), " | ")); } + + Console.debug("--| Checking local staged changes"); + + StagedChange change = changes.get(pointer); + if (change != null) { + Console.debug("--|> found cached value... Returning local data!"); + return change.getData(); + } + Console.debug("--|> No local data found, prepare for data retrieval!"); + + if (!hasSqlEnabled()) { + Console.debug("--| Using YAML"); + int index = 0; + StringBuilder sb = new StringBuilder(); + for (String s: value.getYamlPath()) { + sb.append((sb.length() > 0 ? "." : "") + s); + if (path.length > index) { + sb.append("." + path[index]); + } + index++; + } + return value.getTable().getDataFileHolder(tempfly).getDataConfiguration().get(sb.toString()); + } else { + Console.debug("--| Using SQL"); + DataTable table = value.getTable(); + + + String statement = "SELECT " + value.getSqlColumn() + " FROM " + table.getSqlTable() + " WHERE " + table.getPrimaryKey() + " = ?"; + Console.debug(statement); + try (PreparedStatement st = dataSource.getConnection().prepareStatement(statement)) { + st.setString(1, path[0]); + ResultSet result = st.executeQuery(); + if (result.next()) { + return result.getObject(value.getSqlColumn()); + } + } + } + return null; + } + + public PreparedStatement prepareStatement(String statement) { + if (!hasSqlEnabled()) { + return null; + } + try { + return getDataSource().getConnection().prepareStatement(statement); + } catch (SQLException e) { + e.printStackTrace(); + return null; + } + } + + public Object getOrDefault(DataPointer pointer, Object def) { + Object object; + try { + object = getValue(pointer); + } catch (SQLException e) { + e.printStackTrace(); + return def; + } + if (V.debug) {Console.debug("", "-----Data Bridge Get or Default Value-----", "--|> Got: " + object, "--|> Returning: " + String.valueOf(object == null ? def : object));} + return object == null ? def : object; + } + + public Map getValues(DataTable table, String yamlPathTo, String row, String... extra) { + return getValues(table, null, yamlPathTo, row, extra); + } + + /** + * Get all values from the table for the given row. + * Assumes the row is path to the ConfigurationSection in yaml + * @param value + * @param row + * @return + */ + + public Map getValues(DataTable table, DataFileHolder fileHolder, String yamlPathTo, String row, String... extra) { + Map values = new HashMap<>(); + if (!hasSqlEnabled() || fileHolder.forceYaml()) { + FileConfiguration df = fileHolder == null ? + table.getDataFileHolder(tempfly).getDataConfiguration() + : fileHolder.getDataConfiguration(); + String path = yamlPathTo + "." + row + "." + U.arrayToString(extra, "."); + ConfigurationSection csValues = df.getConfigurationSection(path); + if (csValues != null) { + for (String key: csValues.getKeys(false)) { + values.put(key, df.get(path + "." + key)); + } + } + } + for (StagedChange local: changes.values()) { + if (local.comparePathPartial(row)) { + values.put(local.getPath()[local.getPath().length-1], local.getData()); + } + } + return values; + } + + public void setValue(StagedChange change, boolean forceYaml) throws SQLException { + DataValue value = change.getValue(); + String[] path = change.getPath(); + if (V.debug) {Console.debug("", "-----Data Bridge Set Value-----", "--| Type: " + value.toString(), "--| Path: " + U.arrayToString(path, " | ")); } + if (!hasSqlEnabled() || forceYaml) { + int index = 0; + StringBuilder sb = new StringBuilder(); + for (String s: value.getYamlPath()) { + sb.append((sb.length() > 0 ? "." : "") + s); + if (path.length > index) { + sb.append("." + path[index]); + } + index++; + } + if (V.debug) {Console.debug("--| Setting yaml value: " + sb.toString(), "--| New data: " + String.valueOf(change.getData()));} + FileConfiguration yaml = change.getFileHolder() == null ? + value.getTable().getDataFileHolder(tempfly).getDataConfiguration() + : change.getFileHolder().getDataConfiguration(); + if (!yaml.contains(sb.toString())) { + yaml.createSection(sb.toString()); + } + yaml.set(sb.toString(), change.getData()); + } else { + Console.debug("UPDATE " + value.getTable().getSqlTable() + " SET " + value.getSqlColumn() + + " = ? WHERE " + value.getTable().getPrimaryKey() + " = " + path[0]); + PreparedStatement st = dataSource.getConnection().prepareStatement( + "UPDATE " + value.getTable().getSqlTable() + " SET " + value.getSqlColumn() + + " = ? WHERE " + value.getTable().getPrimaryKey() + " = ?"); + Class type = value.getType(); + if (type.equals(Boolean.TYPE)) { + st.setBoolean(1, (boolean) change.getData()); + } else if (type.equals(Double.TYPE)) { + st.setDouble(1, (double) change.getData()); + } else if (type.equals(String.class)) { + st.setString(1, (String) change.getData()); + } else if (type.equals(Long.TYPE)) { + st.setLong(1, (long) change.getData()); + } + st.setString(2, path[0]); + st.execute(); + st.close(); + } + } + + + public static enum DataTable { + TEMPFLY_DATA("uuid"), + ISLAND_SETTINGS; + + private DataTable() {} + + private String primary; + + private DataTable(String primary) { + this.primary = primary; + } + + public String getPrimaryKey() { + return primary; + } + + public DataFileHolder getDataFileHolder(TempFly tempfly) { + switch (this) { + case TEMPFLY_DATA: + return tempfly.getDataBridge(); + case ISLAND_SETTINGS: + HookManager hooks = tempfly.getHookManager(); + TempFlyHook[] hook; + if ((hook = hooks.getGenre(Genre.SKYBLOCK)) != null && hook.length > 0) { + return (DataFileHolder) hook[0]; + } + break; + default: + return null; + } + return null; + } + + public String getSqlTable() { + switch (this) { + case TEMPFLY_DATA: + return "tempfly_data"; + case ISLAND_SETTINGS: + //return tempfly.getHookManager().getGenre(Genre.SKYBLOCK)[0].getHookedPlugin() + "_island_settings"; + default: + return null; + } + } + } + + public static enum DataValue { + PLAYER_TIME( + DataTable.TEMPFLY_DATA, + Double.TYPE, + "player_time", + new String[] {"players", "time"}, + false), + PLAYER_FLIGHT_LOG( + DataTable.TEMPFLY_DATA, + Boolean.TYPE, + "logged_in_flight", + new String[] {"players", "logged_in_flight"}, + false), + PLAYER_COMPAT_FLIGHT_LOG( + DataTable.TEMPFLY_DATA, + Boolean.TYPE, + "compat_logged_in_flight", + new String[] {"players", "compat_logged_in_flight"}, + false), + PLAYER_DAMAGE_PROTECTION( + DataTable.TEMPFLY_DATA, + Boolean.TYPE, + "damage_protection", + new String[] {"players", "damage_protection"}, + false), + PLAYER_DAILY_BONUS( + DataTable.TEMPFLY_DATA, + Long.TYPE, + "last_daily_bonus", + new String[] {"players", "last_daily_bonus"}, + false), + PLAYER_TRAIL( + DataTable.TEMPFLY_DATA, + String.class, + "trail", + new String[] {"players", "trail"}, + false), + PLAYER_INFINITE( + DataTable.TEMPFLY_DATA, + Boolean.TYPE, + "infinite", + new String[] {"players", "infinite"}, + false), + PLAYER_BYPASS( + DataTable.TEMPFLY_DATA, + Boolean.TYPE, + "bypass", + new String[] {"players", "bypass"}, + false), + PLAYER_SPEED( + DataTable.TEMPFLY_DATA, + Double.TYPE, + "speed", + new String[] {"players", "speed"}, + false), + + + + + ISLAND_SETTING( + DataTable.ISLAND_SETTINGS, + Boolean.TYPE, + null, + new String[] {"islands", "settings"}, + true); + + private DataTable table; + private Class type; + private String + sqlColumn; + + private String[] + yamlPath; + private boolean dynamic; + + private DataValue(DataTable table, Class type, String sqlColumn, String[] yamlPath, boolean dynamic) { + this.table = table; + this.type = type; + this.sqlColumn = sqlColumn; + this.yamlPath = yamlPath; + this.dynamic = dynamic; + } + + public DataTable getTable() { + return table; + } + + public Class getType() { + return type; + } + + public String getSqlColumn() { + return sqlColumn; + } + + public String[] getYamlPath() { + return yamlPath; + } + + public boolean hasDynamicPath() { + return dynamic; + } + } + + protected class StagedChange { + DataValue value; + String[] path; + Object data; + DataFileHolder fileHolder; + + public StagedChange(DataValue value, Object data, String[] path, DataFileHolder fileHolder) { + this.value = value; + this.path = path; + this.data = data; + this.fileHolder = fileHolder; + } + + public DataPointer getPointer() { + return DataPointer.of(value, path); + } + + public DataFileHolder getFileHolder() { + return fileHolder; + } + + public DataValue getValue() { + return value; + } + + public String[] getPath() { + return path; + } + + public Object getData() { + return data; + } + + public boolean comparePathPartial(String... path) { + for (int index = 0; path.length > index; index++) { + if (this.path.length <= index || !path[index].equals(this.path[index])) { + return false; + } + } + return true; + } + + } + + @Override + public File getDataFile() { + return dataf; + } + + @Override + public FileConfiguration getDataConfiguration() { + return data; + } + + @Override + public void setDataFile(File file) { + this.dataf = file; + } + + @Override + public void setDataConfiguration(FileConfiguration data) { + this.data = data; + } + + @Override + public void saveData() { + try { data.save(dataf); } catch (Exception e) {e.printStackTrace();} + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/util/data/DataFileHolder.java b/src/com/moneybags/tempfly/util/data/DataFileHolder.java similarity index 95% rename from TempFly/src/com/moneybags/tempfly/util/data/DataFileHolder.java rename to src/com/moneybags/tempfly/util/data/DataFileHolder.java index 583ffad..a5f83ff 100644 --- a/TempFly/src/com/moneybags/tempfly/util/data/DataFileHolder.java +++ b/src/com/moneybags/tempfly/util/data/DataFileHolder.java @@ -1,22 +1,22 @@ -package com.moneybags.tempfly.util.data; - -import java.io.File; - -import org.bukkit.configuration.file.FileConfiguration; - -public interface DataFileHolder { - - public abstract File getDataFile(); - - public abstract FileConfiguration getDataConfiguration(); - - public abstract void setDataFile(File file); - - public abstract void setDataConfiguration(FileConfiguration data); - - public abstract void saveData(); - - public default boolean forceYaml() { - return false; - } -} +package com.moneybags.tempfly.util.data; + +import java.io.File; + +import org.bukkit.configuration.file.FileConfiguration; + +public interface DataFileHolder { + + public abstract File getDataFile(); + + public abstract FileConfiguration getDataConfiguration(); + + public abstract void setDataFile(File file); + + public abstract void setDataConfiguration(FileConfiguration data); + + public abstract void saveData(); + + public default boolean forceYaml() { + return false; + } +} diff --git a/TempFly/src/com/moneybags/tempfly/util/data/DataPointer.java b/src/com/moneybags/tempfly/util/data/DataPointer.java similarity index 94% rename from TempFly/src/com/moneybags/tempfly/util/data/DataPointer.java rename to src/com/moneybags/tempfly/util/data/DataPointer.java index 696f114..74c9e35 100644 --- a/TempFly/src/com/moneybags/tempfly/util/data/DataPointer.java +++ b/src/com/moneybags/tempfly/util/data/DataPointer.java @@ -1,41 +1,41 @@ -package com.moneybags.tempfly.util.data; - -import com.moneybags.tempfly.util.data.DataBridge.DataValue; - -public class DataPointer { - - public static DataPointer of(DataValue value, String... path) { - return new DataPointer(value, path); - } - - private DataValue value; - private String[] path; - - private DataPointer(DataValue value, String... path) { - this.value = value; - this.path = path; - } - - public DataValue getValue() { - return value; - } - - public String[] getPath() { - return path; - } - - @Override - public int hashCode() { - int code = 0; - for (String string: path) { - code += string.hashCode(); - } - return value.toString().hashCode() + code; - } - - @Override - public boolean equals(Object obj) { - return obj.hashCode() == this.hashCode(); - } - -} +package com.moneybags.tempfly.util.data; + +import com.moneybags.tempfly.util.data.DataBridge.DataValue; + +public class DataPointer { + + public static DataPointer of(DataValue value, String... path) { + return new DataPointer(value, path); + } + + private DataValue value; + private String[] path; + + private DataPointer(DataValue value, String... path) { + this.value = value; + this.path = path; + } + + public DataValue getValue() { + return value; + } + + public String[] getPath() { + return path; + } + + @Override + public int hashCode() { + int code = 0; + for (String string: path) { + code += string.hashCode(); + } + return value.toString().hashCode() + code; + } + + @Override + public boolean equals(Object obj) { + return obj.hashCode() == this.hashCode(); + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/util/data/Files.java b/src/com/moneybags/tempfly/util/data/Files.java similarity index 96% rename from TempFly/src/com/moneybags/tempfly/util/data/Files.java rename to src/com/moneybags/tempfly/util/data/Files.java index 8fe61da..ca1d447 100644 --- a/TempFly/src/com/moneybags/tempfly/util/data/Files.java +++ b/src/com/moneybags/tempfly/util/data/Files.java @@ -1,89 +1,89 @@ -package com.moneybags.tempfly.util.data; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; - -import com.moneybags.tempfly.util.Console; - -/** - * This class is going to be reworked in a future version. Too much static abuse and repetition. - * - */ -public class Files { - - public static enum C { - CONFIG, - LANG, - DATA, - PAGE; - } - - private static File - configf, - langf, - pagef; - - public static FileConfiguration - config, - lang, - page; - - public static void createFiles(Plugin plugin){ - configf = new File(plugin.getDataFolder(), "config.yml"); - langf = new File(plugin.getDataFolder(), "lang.yml"); - pagef = new File(plugin.getDataFolder(), "page.yml"); - - if (!configf.exists()){ - configf.getParentFile().mkdirs(); - plugin.saveResource("config.yml", false); - } - if (!langf.exists()){ - langf.getParentFile().mkdirs(); - plugin.saveResource("lang.yml", false); - } - if (!pagef.exists()){ - pagef.getParentFile().mkdirs(); - plugin.saveResource("page.yml", false); - } - - config = new YamlConfiguration(); - lang = new YamlConfiguration(); - page = new YamlConfiguration(); - - try { - config.load(configf); - } catch (IOException | InvalidConfigurationException e1){ - Console.severe("There is a problem inside the config.yml, If you cannot fix the issue, please contact the developer."); - e1.printStackTrace(); - } - try { - lang.load(langf); - } catch (IOException | InvalidConfigurationException e1){ - Console.severe("There is a problem inside the lang.yml, If you cannot fix the issue, please contact the developer."); - e1.printStackTrace(); - } - try { - page.load(pagef); - } catch (IOException | InvalidConfigurationException e1){ - Console.severe("There is a problem inside the page.yml, If you cannot fix the issue, please contact the developer."); - e1.printStackTrace(); - } - } - - - public static void createConfig(InputStream stream, File file) throws IOException { - byte[] buffer = new byte[stream.available()]; - stream.read(buffer); - OutputStream outStream = new FileOutputStream(file); - outStream.write(buffer); - outStream.close(); - } - -} +package com.moneybags.tempfly.util.data; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.Plugin; + +import com.moneybags.tempfly.util.Console; + +/** + * This class is going to be reworked in a future version. Too much static abuse and repetition. + * + */ +public class Files { + + public static enum C { + CONFIG, + LANG, + DATA, + PAGE; + } + + private static File + configf, + langf, + pagef; + + public static FileConfiguration + config, + lang, + page; + + public static void createFiles(Plugin plugin){ + configf = new File(plugin.getDataFolder(), "config.yml"); + langf = new File(plugin.getDataFolder(), "lang.yml"); + pagef = new File(plugin.getDataFolder(), "page.yml"); + + if (!configf.exists()){ + configf.getParentFile().mkdirs(); + plugin.saveResource("config.yml", false); + } + if (!langf.exists()){ + langf.getParentFile().mkdirs(); + plugin.saveResource("lang.yml", false); + } + if (!pagef.exists()){ + pagef.getParentFile().mkdirs(); + plugin.saveResource("page.yml", false); + } + + config = new YamlConfiguration(); + lang = new YamlConfiguration(); + page = new YamlConfiguration(); + + try { + config.load(configf); + } catch (IOException | InvalidConfigurationException e1){ + Console.severe("There is a problem inside the config.yml, If you cannot fix the issue, please contact the developer."); + e1.printStackTrace(); + } + try { + lang.load(langf); + } catch (IOException | InvalidConfigurationException e1){ + Console.severe("There is a problem inside the lang.yml, If you cannot fix the issue, please contact the developer."); + e1.printStackTrace(); + } + try { + page.load(pagef); + } catch (IOException | InvalidConfigurationException e1){ + Console.severe("There is a problem inside the page.yml, If you cannot fix the issue, please contact the developer."); + e1.printStackTrace(); + } + } + + + public static void createConfig(InputStream stream, File file) throws IOException { + byte[] buffer = new byte[stream.available()]; + stream.read(buffer); + OutputStream outStream = new FileOutputStream(file); + outStream.write(buffer); + outStream.close(); + } + +} diff --git a/TempFly/src/com/moneybags/tempfly/util/data/Reloadable.java b/src/com/moneybags/tempfly/util/data/Reloadable.java similarity index 93% rename from TempFly/src/com/moneybags/tempfly/util/data/Reloadable.java rename to src/com/moneybags/tempfly/util/data/Reloadable.java index aaab069..fe72a23 100644 --- a/TempFly/src/com/moneybags/tempfly/util/data/Reloadable.java +++ b/src/com/moneybags/tempfly/util/data/Reloadable.java @@ -1,9 +1,9 @@ -package com.moneybags.tempfly.util.data; - -public interface Reloadable { - - public default void onTempflyReload() { - return; - } - -} +package com.moneybags.tempfly.util.data; + +public interface Reloadable { + + public default void onTempflyReload() { + return; + } + +}