From ffe995ef5f1893bf46bdccb6eb9c514c02422417 Mon Sep 17 00:00:00 2001 From: William Date: Mon, 28 Oct 2024 20:49:57 +0000 Subject: [PATCH] refactor: significantly refactor internals, remove Sponge (#708) * feat: start database refactor Adds database migrations * refactor: refactor database system Now supports migrations * refactor: begin major internals rewrite move to using provider-style interfaces similar to huskclaims bukkit done, still need to do fabric and sponge * refactor: remove sponge, checkstyle Low usage and high maintenance time cost. We will examine Forge instead in the future. * refactor: implement refactoring changes on fabric also fix various refactor quirks on Bukkit * refactor: tidy metrics logic * build: bump deps --- .github/workflows/ci.yml | 24 - .github/workflows/release.yml | 23 - .scripts/ensure-java-17 | 19 - README.md | 4 +- build.gradle | 32 +- .../william278/huskhomes/BukkitHuskHomes.java | 369 +++++------- .../huskhomes/api/HuskHomesAPI.java | 2 +- .../huskhomes/command/BukkitCommand.java | 71 +-- .../huskhomes/hook/BukkitHookProvider.java | 61 ++ .../huskhomes/hook/PlaceholderAPIHook.java | 64 +- .../huskhomes/hook/VaultEconomyHook.java | 13 +- .../importer/EssentialsXImporter.java | 9 +- .../listener/BukkitEventListener.java | 38 +- .../william278/huskhomes/user/BukkitUser.java | 2 + .../huskhomes/user/BukkitUserProvider.java | 54 ++ ...r.java => BukkitSavePositionProvider.java} | 2 +- .../huskhomes/BukkitPluginTests.java | 53 +- common/build.gradle | 19 +- .../net/william278/huskhomes/HuskHomes.java | 394 ++++-------- .../huskhomes/api/BaseHuskHomesAPI.java | 29 +- .../huskhomes/command/BackCommand.java | 6 +- .../william278/huskhomes/command/Command.java | 11 +- .../huskhomes/command/CommandProvider.java | 126 ++++ .../huskhomes/command/DelHomeCommand.java | 9 +- .../huskhomes/command/DelWarpCommand.java | 7 +- .../huskhomes/command/DisabledCommand.java | 6 +- .../huskhomes/command/EditHomeCommand.java | 13 +- .../huskhomes/command/EditWarpCommand.java | 3 +- .../huskhomes/command/HomeCommand.java | 6 +- .../huskhomes/command/HomeListCommand.java | 18 +- .../huskhomes/command/HuskHomesCommand.java | 37 +- .../huskhomes/command/InGameCommand.java | 4 +- .../huskhomes/command/ListCommand.java | 4 +- .../william278/huskhomes/command/Node.java | 66 +- .../huskhomes/command/PrivateHomeCommand.java | 8 +- .../huskhomes/command/PublicHomeCommand.java | 8 +- .../command/PublicHomeListCommand.java | 8 +- .../{RTPCommand.java => RtpCommand.java} | 30 +- .../command/SavedPositionCommand.java | 10 +- .../huskhomes/command/SetHomeCommand.java | 5 +- .../huskhomes/command/SetPositionCommand.java | 4 +- .../huskhomes/command/SetSpawnCommand.java | 6 +- .../huskhomes/command/SetWarpCommand.java | 7 +- .../huskhomes/command/SpawnCommand.java | 6 +- .../{TabProvider.java => TabCompletable.java} | 2 +- .../huskhomes/command/TpAllCommand.java | 20 +- .../huskhomes/command/TpCommand.java | 16 +- .../huskhomes/command/TpHereCommand.java | 10 +- .../huskhomes/command/TpIgnoreCommand.java | 8 +- .../huskhomes/command/TpOfflineCommand.java | 15 +- ...uestCommand.java => TpRequestCommand.java} | 14 +- .../huskhomes/command/TpRespondCommand.java | 6 +- .../huskhomes/command/TpaAllCommand.java | 4 +- ...vider.java => UserListTabCompletable.java} | 10 +- .../huskhomes/command/WarpCommand.java | 7 +- .../huskhomes/command/WarpListCommand.java | 8 +- .../william278/huskhomes/config/Locales.java | 2 +- .../huskhomes/database/Database.java | 253 ++++++-- .../huskhomes/database/DatabaseProvider.java | 74 +++ .../huskhomes/database/H2Database.java | 526 +++++++++------- .../huskhomes/database/MySqlDatabase.java | 570 ++++++++++-------- .../database/PostgreSqlDatabase.java | 567 +++++++++-------- .../huskhomes/database/SqLiteDatabase.java | 551 +++++++++-------- .../huskhomes/hook/BlueMapHook.java | 15 +- .../william278/huskhomes/hook/DynmapHook.java | 15 +- .../huskhomes/hook/EconomyHook.java | 4 +- .../net/william278/huskhomes/hook/Hook.java | 48 +- .../huskhomes/hook/HookProvider.java | 120 ++++ .../william278/huskhomes/hook/MapHook.java | 20 +- .../huskhomes/hook/MapHookProvider.java | 77 +++ .../huskhomes/hook/Pl3xMapHook.java | 12 +- .../william278/huskhomes/hook/PlanHook.java | 30 +- .../william278/huskhomes/hook/PluginHook.java | 44 ++ .../huskhomes/importer/Importer.java | 24 +- .../huskhomes/listener/EventListener.java | 76 +-- .../huskhomes/listener/ListenerProvider.java | 34 ++ .../huskhomes/manager/HomesManager.java | 45 +- .../william278/huskhomes/manager/Manager.java | 13 +- .../huskhomes/manager/ManagerProvider.java | 39 ++ .../huskhomes/manager/RequestsManager.java | 39 +- .../huskhomes/manager/WarpsManager.java | 32 +- .../william278/huskhomes/network/Broker.java | 19 +- .../huskhomes/network/BrokerProvider.java | 53 ++ .../william278/huskhomes/network/Message.java | 2 +- .../william278/huskhomes/network/Payload.java | 28 +- .../network/PluginMessageBroker.java | 2 +- .../huskhomes/network/RedisBroker.java | 2 +- .../william278/huskhomes/position/Home.java | 4 +- .../random/RandomTeleportProvider.java | 49 ++ .../huskhomes/teleport/Teleport.java | 18 +- .../huskhomes/teleport/TeleportRequest.java | 2 +- .../huskhomes/teleport/Username.java | 5 +- .../huskhomes/user/ConsoleUser.java | 14 +- .../william278/huskhomes/user/SavedUser.java | 2 +- .../net/william278/huskhomes/user/User.java | 10 +- .../huskhomes/user/UserProvider.java | 105 ++++ .../huskhomes/util/AudiencesProvider.java | 69 +++ .../huskhomes/util/MetaProvider.java | 98 +++ ...esolver.java => SavePositionProvider.java} | 2 +- .../{Validator.java => TextValidator.java} | 38 +- .../src/main/resources/database/h2_schema.sql | 50 +- .../resources/database/mariadb_schema.sql | 50 +- .../migrations/0-h2-add_metadata_table.sql | 7 + .../0-mariadb-add_metadata_table.sql | 6 + .../migrations/0-mysql-add_metadata_table.sql | 6 + .../0-postgresql-add_metadata_table.sql | 7 + .../0-sqlite-add_metadata_table.sql | 5 + .../main/resources/database/mysql_schema.sql | 42 +- .../resources/database/postgresql_schema.sql | 130 ++-- .../main/resources/database/sqlite_schema.sql | 64 +- .../network/MessageSerializationTests.java | 2 +- .../position/SavedPositionTests.java | 4 +- config/checkstyle/checkstyle.xml | 361 ----------- docs/API-Events.md | 4 +- docs/API-Examples.md | 3 +- docs/API.md | 7 +- docs/Command-Conflicts.md | 2 +- docs/Config-Files.md | 2 +- docs/Economy-Hook.md | 8 - docs/Managing-Access.md | 2 +- docs/Setup.md | 17 +- fabric/build.gradle | 3 +- .../william278/huskhomes/FabricHuskHomes.java | 255 +++----- .../huskhomes/api/FabricHuskHomesAPI.java | 2 +- .../huskhomes/command/FabricCommand.java | 66 +- .../huskhomes/hook/FabricHookProvider.java | 60 ++ .../hook/FabricImpactorEconomyHook.java | 25 +- .../hook/FabricPlaceholderAPIHook.java | 25 +- .../listener/FabricEventListener.java | 22 +- .../william278/huskhomes/user/FabricUser.java | 2 + .../huskhomes/user/FabricUserProvider.java | 54 ++ ...r.java => FabricSavePositionProvider.java} | 2 +- gradle.properties | 13 +- .../william278/huskhomes/PaperHuskHomes.java | 2 +- .../listener/PaperEventListener.java | 21 +- settings.gradle | 3 - sponge/build.gradle | 81 --- .../william278/huskhomes/SpongeHuskHomes.java | 445 -------------- .../huskhomes/command/SpongeCommand.java | 208 ------- .../event/SpongeDeleteAllHomesEvent.java | 69 --- .../event/SpongeDeleteAllWarpsEvent.java | 60 -- .../event/SpongeEventDispatcher.java | 145 ----- .../event/SpongeHomeCreateEvent.java | 98 --- .../event/SpongeHomeDeleteEvent.java | 68 --- .../huskhomes/event/SpongeHomeEditEvent.java | 76 --- .../huskhomes/event/SpongeHomeListEvent.java | 83 --- .../event/SpongeRandomTeleportEvent.java | 65 -- .../SpongeReceiveTeleportRequestEvent.java | 69 --- .../SpongeReplyTeleportRequestEvent.java | 69 --- .../event/SpongeSendTeleportRequestEvent.java | 69 --- .../huskhomes/event/SpongeTeleportEvent.java | 60 -- .../SpongeTeleportWarmupCancelledEvent.java | 70 --- .../event/SpongeTeleportWarmupEvent.java | 67 -- .../event/SpongeWarpCreateEvent.java | 87 --- .../event/SpongeWarpDeleteEvent.java | 69 --- .../huskhomes/event/SpongeWarpEditEvent.java | 77 --- .../huskhomes/event/SpongeWarpListEvent.java | 76 --- .../huskhomes/hook/SpongeEconomyHook.java | 89 --- .../listener/SpongeEventListener.java | 116 ---- .../william278/huskhomes/user/SpongeUser.java | 161 ----- .../huskhomes/util/SpongeSafetyResolver.java | 100 --- .../william278/huskhomes/util/SpongeTask.java | 147 ----- 162 files changed, 3890 insertions(+), 5730 deletions(-) delete mode 100644 .scripts/ensure-java-17 create mode 100644 bukkit/src/main/java/net/william278/huskhomes/hook/BukkitHookProvider.java create mode 100644 bukkit/src/main/java/net/william278/huskhomes/user/BukkitUserProvider.java rename bukkit/src/main/java/net/william278/huskhomes/util/{BukkitSafetyResolver.java => BukkitSavePositionProvider.java} (98%) create mode 100644 common/src/main/java/net/william278/huskhomes/command/CommandProvider.java rename common/src/main/java/net/william278/huskhomes/command/{RTPCommand.java => RtpCommand.java} (91%) rename common/src/main/java/net/william278/huskhomes/command/{TabProvider.java => TabCompletable.java} (97%) rename common/src/main/java/net/william278/huskhomes/command/{TeleportRequestCommand.java => TpRequestCommand.java} (87%) rename common/src/main/java/net/william278/huskhomes/command/{UserListTabProvider.java => UserListTabCompletable.java} (79%) create mode 100644 common/src/main/java/net/william278/huskhomes/database/DatabaseProvider.java create mode 100644 common/src/main/java/net/william278/huskhomes/hook/HookProvider.java create mode 100644 common/src/main/java/net/william278/huskhomes/hook/MapHookProvider.java create mode 100644 common/src/main/java/net/william278/huskhomes/hook/PluginHook.java create mode 100644 common/src/main/java/net/william278/huskhomes/listener/ListenerProvider.java create mode 100644 common/src/main/java/net/william278/huskhomes/manager/ManagerProvider.java create mode 100644 common/src/main/java/net/william278/huskhomes/network/BrokerProvider.java create mode 100644 common/src/main/java/net/william278/huskhomes/random/RandomTeleportProvider.java create mode 100644 common/src/main/java/net/william278/huskhomes/user/UserProvider.java create mode 100644 common/src/main/java/net/william278/huskhomes/util/AudiencesProvider.java create mode 100644 common/src/main/java/net/william278/huskhomes/util/MetaProvider.java rename common/src/main/java/net/william278/huskhomes/util/{SafetyResolver.java => SavePositionProvider.java} (98%) rename common/src/main/java/net/william278/huskhomes/util/{Validator.java => TextValidator.java} (75%) create mode 100644 common/src/main/resources/database/migrations/0-h2-add_metadata_table.sql create mode 100644 common/src/main/resources/database/migrations/0-mariadb-add_metadata_table.sql create mode 100644 common/src/main/resources/database/migrations/0-mysql-add_metadata_table.sql create mode 100644 common/src/main/resources/database/migrations/0-postgresql-add_metadata_table.sql create mode 100644 common/src/main/resources/database/migrations/0-sqlite-add_metadata_table.sql delete mode 100644 config/checkstyle/checkstyle.xml create mode 100644 fabric/src/main/java/net/william278/huskhomes/hook/FabricHookProvider.java create mode 100644 fabric/src/main/java/net/william278/huskhomes/user/FabricUserProvider.java rename fabric/src/main/java/net/william278/huskhomes/util/{FabricSafetyResolver.java => FabricSavePositionProvider.java} (98%) delete mode 100644 sponge/build.gradle delete mode 100644 sponge/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/command/SpongeCommand.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeDeleteAllHomesEvent.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeDeleteAllWarpsEvent.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeEventDispatcher.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeCreateEvent.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeDeleteEvent.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeEditEvent.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeListEvent.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeRandomTeleportEvent.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeReceiveTeleportRequestEvent.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeReplyTeleportRequestEvent.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeSendTeleportRequestEvent.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeTeleportEvent.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeTeleportWarmupCancelledEvent.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeTeleportWarmupEvent.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpCreateEvent.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpDeleteEvent.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpEditEvent.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpListEvent.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/hook/SpongeEconomyHook.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/listener/SpongeEventListener.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/user/SpongeUser.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/util/SpongeSafetyResolver.java delete mode 100644 sponge/src/main/java/net/william278/huskhomes/util/SpongeTask.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fd91f6c8..0ec03de0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,19 +53,15 @@ jobs: changelog: ${{ github.event.head_commit.message }} distro-names: | paper - sponge-10 fabric-1.21.3 distro-groups: | paper - sponge fabric distro-descriptions: | Paper - Sponge API 10 Fabric 1.21.3 files: | target/HuskHomes-Paper-${{ env.version_name }}.jar - target/HuskHomes-Sponge-${{ env.version_name }}.jar target/HuskHomes-Fabric-${{ env.version_name }}+mc.1.21.3.jar - name: 'Spigot: Publish to Modrinth & Hangar 🚰' uses: WiIIiam278/mc-publish@hangar @@ -112,26 +108,6 @@ jobs: 1.21.2 1.21.3 java: 17 - - name: 'Sponge: Publish to Modrinth 🧽' - uses: WiIIiam278/mc-publish@hangar - if: success() || failure() - with: - modrinth-id: J6U9o3JG - modrinth-featured: false - modrinth-token: ${{ secrets.MODRINTH_TOKEN }} - modrinth-dependencies: | - bluemap | suggests | * - plan | suggests | * - files-primary: target/HuskHomes-Sponge-${{ env.version_name }}.jar - name: HuskHomes (Sponge) v${{ env.version_name }} - version: ${{ env.version_name }} - version-type: alpha - changelog: ${{ github.event.head_commit.message }} - loaders: | - sponge - game-versions: | - 1.19.4 - java: 17 - name: 'Fabric: Publish to Modrinth & CurseForge 🧵' uses: WiIIiam278/mc-publish@hangar if: success() || failure() diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a62742c7..c4e15cc3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -42,19 +42,15 @@ jobs: changelog: ${{ github.event.release.body }} distro-names: | paper - sponge-10 fabric-1.21.3 distro-groups: | paper - sponge fabric distro-descriptions: | Paper - Sponge API 10 Fabric 1.21.3 files: | target/HuskHomes-Paper-${{ github.event.release.tag_name }}.jar - target/HuskHomes-Sponge-${{ github.event.release.tag_name }}.jar target/HuskHomes-Fabric-${{ github.event.release.tag_name }}+mc.1.21.3.jar - name: 'Spigot: Publish to Modrinth & Hangar 🚰' uses: WiIIiam278/mc-publish@hangar @@ -100,25 +96,6 @@ jobs: 1.21.2 1.21.3 java: 17 - - name: 'Sponge: Publish to Modrinth 🧽' - uses: WiIIiam278/mc-publish@hangar - with: - modrinth-id: J6U9o3JG - modrinth-featured: false - modrinth-token: ${{ secrets.MODRINTH_TOKEN }} - modrinth-dependencies: | - bluemap | suggests | * - plan | suggests | * - files-primary: target/HuskHomes-Sponge-${{ github.event.release.tag_name }}.jar - name: HuskHomes (Sponge) v${{ github.event.release.tag_name }} - version: ${{ env.version_name }} - version-type: release - changelog: ${{ github.event.release.body }} - loaders: | - sponge - game-versions: | - 1.19.4 - java: 17 - name: 'Fabric: Publish to Modrinth & CurseForge 🧵' uses: WiIIiam278/mc-publish@hangar with: diff --git a/.scripts/ensure-java-17 b/.scripts/ensure-java-17 deleted file mode 100644 index 016a6ce2..00000000 --- a/.scripts/ensure-java-17 +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/bash - -JV=$(java -version 2>&1 >/dev/null | head -1) -echo "$JV" | sed -E 's/^.*version "([^".]*)\.[^"]*".*$/\1/' - -if [ "$JV" != 17 ]; then - case "$1" in - install) - echo "installing sdkman..." - curl -s "https://get.sdkman.io" | bash - source ~/.sdkman/bin/sdkman-init.sh - sdk install java 17.0.2-open - ;; - use) - echo "must source ~/.sdkman/bin/sdkman-init.sh" - exit 1 - ;; - esac -fi \ No newline at end of file diff --git a/README.md b/README.md index 06783cd7..7cca18ca 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ **HuskHomes** is a powerful, intuitive and flexible teleportation plugin for _Minecraft: Java Edition_ servers. HuskHomes contains a meaty—but not bloated—set of player teleportation features, including set homes, warps, public homes, teleport requests, previous and offline position teleporting—and more. -HuskHomes can be used on your Spigot, Sponge or Fabric server, and with a MySQL Database even works cross-server, letting players teleport across your proxy (Bungee or Velocity) network! +HuskHomes can be used on your Spigot or Fabric server, and with a MySQL Database even works cross-server, letting players teleport across your proxy (Bungee or Velocity) network! ## Features **⭐ Works cross-server** — Let players seamlessly teleport and set homes across your proxies network of servers using MySQL/MariaDB. @@ -66,7 +66,7 @@ Translations of the plugin locales are welcome to help make the plugin more acce - [Modrinth](https://modrinth.com/plugin/huskhomes) — View the plugin Modrinth page (Also: [Spigot](https://www.spigotmc.org/resources/huskhomes.83767/), [Polymart](https://polymart.org/resource/huskhomes.284/), [Hangar](https://hangar.papermc.io/William278/HuskHomes), & [CurseForge](https://www.curseforge.com/minecraft/mc-mods/huskhomes/)) - [Issues](https://github.com/WiIIiam278/HuskHomes/issues) — File a bug report or feature request - [Discord](https://discord.gg/tVYhJfyDWG) — Get help, ask questions -- [bStats](https://bstats.org/plugin/bukkit/HuskHomes/8430) — View plugin metrics (Also: [Sponge](https://bstats.org/plugin/sponge/HuskHomes/18423)) +- [bStats](https://bstats.org/plugin/bukkit/HuskHomes/8430) — View plugin metrics --- © [William278](https://william278.net/), 2023. Licensed under the Apache-2.0 License. diff --git a/build.gradle b/build.gradle index 8dca525b..12bda5b6 100644 --- a/build.gradle +++ b/build.gradle @@ -4,8 +4,7 @@ plugins { id 'io.github.goooler.shadow' version '8.1.8' id 'org.cadixdev.licenser' version '0.6.1' apply false id 'fabric-loom' version "$fabric_loom_version" apply false - id 'org.ajoberstar.grgit' version '5.2.2' - id 'checkstyle' + id 'org.ajoberstar.grgit' version '5.3.0' id 'maven-publish' id 'java' } @@ -13,7 +12,7 @@ plugins { group 'net.william278' version "$ext.plugin_version${versionMetadata()}" description "$ext.plugin_description" -defaultTasks 'licenseFormat', 'check', 'build' +defaultTasks 'licenseFormat', 'build' ext { set 'version', version.toString() @@ -60,7 +59,6 @@ publishing { allprojects { apply plugin: 'io.github.goooler.shadow' apply plugin: 'org.cadixdev.licenser' - apply plugin: 'checkstyle' apply plugin: 'java' compileJava.options.encoding = 'UTF-8' @@ -78,7 +76,6 @@ allprojects { maven { url 'https://repo.papermc.io/repository/maven-public/' } maven { url 'https://mvn-repo.arim.space/lesser-gpl3/' } maven { url 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/' } - maven { url 'https://repo.spongepowered.org/repository/maven-public/' } maven { url 'https://repo.extendedclip.com/content/repositories/placeholderapi/' } maven { url 'https://repo.minebench.de/' } maven { url 'https://repo.alessiodp.com/releases/' } @@ -89,9 +86,9 @@ allprojects { } dependencies { - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.11.0' - testImplementation 'org.junit.jupiter:junit-jupiter-params:5.11.0' - testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.11.0' + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.11.3' + testImplementation 'org.junit.jupiter:junit-jupiter-params:5.11.3' + testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.11.3' testCompileOnly 'org.jetbrains:annotations:24.1.0' } @@ -102,10 +99,6 @@ allprojects { newLine = true } - checkstyle { - toolVersion = '10.12.0' - } - test { useJUnitPlatform() } @@ -139,7 +132,7 @@ subprojects { } // API publishing - if (['common', 'bukkit', 'fabric', 'sponge'].contains(project.name)) { + if (['common', 'bukkit', 'fabric'].contains(project.name)) { java { withSourcesJar() withJavadocJar() @@ -191,19 +184,6 @@ subprojects { } } } - - if (['sponge'].contains(project.name)) { - publications { - mavenJavaSponge(MavenPublication) { - groupId = 'net.william278.huskhomes' - artifactId = 'huskhomes-sponge' - version = "$rootProject.version" - artifact shadowJar - artifact sourcesJar - artifact javadocJar - } - } - } } } diff --git a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java index 087d6dd1..fa4d37bd 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java +++ b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java @@ -19,13 +19,14 @@ package net.william278.huskhomes; +import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.platform.AudienceProvider; import net.kyori.adventure.platform.bukkit.BukkitAudiences; import net.william278.desertwell.util.Version; import net.william278.huskhomes.api.HuskHomesAPI; @@ -35,31 +36,23 @@ import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Server; import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.config.Spawn; -import net.william278.huskhomes.database.*; +import net.william278.huskhomes.database.Database; import net.william278.huskhomes.event.BukkitEventDispatcher; +import net.william278.huskhomes.hook.BukkitHookProvider; import net.william278.huskhomes.hook.Hook; -import net.william278.huskhomes.hook.PlaceholderAPIHook; -import net.william278.huskhomes.hook.VaultEconomyHook; -import net.william278.huskhomes.importer.EssentialsXImporter; import net.william278.huskhomes.listener.BukkitEventListener; import net.william278.huskhomes.listener.EventListener; import net.william278.huskhomes.manager.Manager; import net.william278.huskhomes.network.Broker; import net.william278.huskhomes.network.PluginMessageBroker; -import net.william278.huskhomes.network.RedisBroker; import net.william278.huskhomes.position.Location; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.World; -import net.william278.huskhomes.random.NormalDistributionEngine; import net.william278.huskhomes.random.RandomTeleportEngine; -import net.william278.huskhomes.user.BukkitUser; -import net.william278.huskhomes.user.ConsoleUser; -import net.william278.huskhomes.user.OnlineUser; -import net.william278.huskhomes.user.SavedUser; -import net.william278.huskhomes.util.BukkitSafetyResolver; +import net.william278.huskhomes.user.*; +import net.william278.huskhomes.util.BukkitSavePositionProvider; import net.william278.huskhomes.util.BukkitTask; import net.william278.huskhomes.util.UnsafeBlocks; -import net.william278.huskhomes.util.Validator; import org.bstats.bukkit.Metrics; import org.bstats.charts.SimplePie; import org.bukkit.Bukkit; @@ -72,7 +65,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import space.arim.morepaperlib.MorePaperLib; -import space.arim.morepaperlib.commands.CommandRegistration; import space.arim.morepaperlib.scheduling.AsynchronousScheduler; import space.arim.morepaperlib.scheduling.AttachedScheduler; import space.arim.morepaperlib.scheduling.GracefulScheduling; @@ -82,45 +74,48 @@ import java.io.File; import java.nio.file.Path; import java.util.*; import java.util.logging.Level; -import java.util.stream.Collectors; @Getter -@Setter @NoArgsConstructor public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask.Supplier, BukkitEventDispatcher, - PluginMessageListener, BukkitSafetyResolver { + PluginMessageListener, BukkitHookProvider, BukkitSavePositionProvider, BukkitUserProvider { - /** - * Metrics ID for HuskHomes on Bukkit. - */ - private static final int METRICS_ID = 8430; - - private final Set savedUsers = Sets.newHashSet(); - private final Map> globalPlayerList = Maps.newConcurrentMap(); - private final Set currentlyOnWarmup = Sets.newConcurrentHashSet(); - private final Set currentlyInvulnerable = Sets.newConcurrentHashSet(); - - private Settings settings; - private Locales locales; - private Database database; - private Validator validator; - private Manager manager; - private EventListener eventListener; - private RandomTeleportEngine randomTeleportEngine; - private Spawn serverSpawn; - private UnsafeBlocks unsafeBlocks; - private List hooks; - private List commands; - @Getter(AccessLevel.NONE) - private Server server; - @Getter(AccessLevel.NONE) - private BukkitAudiences audiences; - @Getter(AccessLevel.NONE) - private MorePaperLib paperLib; + private AudienceProvider audiences; private AsynchronousScheduler asyncScheduler; private RegionalScheduler regionalScheduler; + private MorePaperLib morePaperLib; + + private final Set savedUsers = Sets.newHashSet(); + private final Set currentlyOnWarmup = Sets.newConcurrentHashSet(); + private final Set currentlyInvulnerable = Sets.newConcurrentHashSet(); + private final Map onlineUserMap = Maps.newHashMap(); + private final Map> globalUserList = Maps.newConcurrentMap(); + private final List commands = Lists.newArrayList(); + + @Setter + private Set hooks = Sets.newHashSet(); + @Setter + private Settings settings; + @Setter + private Locales locales; + @Setter + private Database database; + @Setter + private Manager manager; + @Setter + private EventListener eventListener; + @Setter + private RandomTeleportEngine randomTeleportEngine; + @Setter + private Spawn serverSpawn; + @Setter + private UnsafeBlocks unsafeBlocks; + @Setter @Nullable private Broker broker; + @Setter + @Nullable + private Server serverName; // Super constructor for unit testing @TestOnly @@ -129,130 +124,105 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask super(loader, description, dataFolder, file); } + @Override + public void onLoad() { + this.load(); + } + @Override public void onEnable() { - // Create adventure audience this.audiences = BukkitAudiences.create(this); - this.paperLib = new MorePaperLib(this); - this.validator = new Validator(this); - - // Load settings and locales - initialize("plugin config & locale files", (plugin) -> loadConfigs()); - - // Initialize the database - final Database.Type type = getSettings().getDatabase().getType(); - initialize(type.getDisplayName() + " database connection", (plugin) -> { - this.database = switch (type) { - case MYSQL, MARIADB -> new MySqlDatabase(this); - case SQLITE -> new SqLiteDatabase(this); - case H2 -> new H2Database(this); - case POSTGRESQL -> new PostgreSqlDatabase(this); - }; - - database.initialize(); - }); - - // Initialize the manager - this.manager = new Manager(this); - - // Initialize the network messenger if proxy mode is enabled - final Settings.CrossServerSettings crossServer = getSettings().getCrossServer(); - if (crossServer.isEnabled()) { - initialize(crossServer.getBrokerType().getDisplayName() + " message broker", (plugin) -> { - broker = switch (crossServer.getBrokerType()) { - case PLUGIN_MESSAGE -> new PluginMessageBroker(this); - case REDIS -> new RedisBroker(this); - }; - broker.initialize(); - }); - } - - // Set the random teleport engine - setRandomTeleportEngine(new NormalDistributionEngine(this)); - - // Register plugin hooks (Economy, Maps, Plan) - initialize("hooks", (plugin) -> { - this.registerHooks(); - - if (!hooks.isEmpty()) { - hooks.forEach(hook -> { - try { - hook.initialize(); - } catch (Throwable e) { - log(Level.WARNING, "Failed to initialize " + hook.getName() + " hook", e); - } - }); - log(Level.INFO, "Registered " + hooks.size() + " plugin hooks: " + hooks.stream() - .map(Hook::getName) - .collect(Collectors.joining(", "))); - } - }); - - // Register event listener - initialize("events", (plugin) -> this.eventListener = getListener().register(this)); - - // Register commands - initialize("commands", (plugin) -> this.commands = BukkitCommand.Type.getCommands(this)); - - // Initialize the API - initialize("API", (plugin) -> HuskHomesAPI.register(this)); - - // Hook into bStats and check for updates - initialize("metrics", (plugin) -> this.registerMetrics(METRICS_ID)); - this.checkForUpdates(); - } - - // Register the event listener - @NotNull - protected BukkitEventListener getListener() { - return new BukkitEventListener(this); - } - - @Override - public void registerHooks() { - HuskHomes.super.registerHooks(); - - // Hooks - if (getSettings().getEconomy().isEnabled() && isDependencyLoaded("Vault")) { - getHooks().add(new VaultEconomyHook(this)); - } - if (isDependencyLoaded("PlaceholderAPI")) { - getHooks().add(new PlaceholderAPIHook(this)); - } - } - - @Override - public void registerImporters() { - HuskHomes.super.registerImporters(); - - // Importers - if (isDependencyLoaded("Essentials")) { - getHooks().add(new EssentialsXImporter(this)); - } - } - - @Override - public boolean isDependencyLoaded(@NotNull String name) { - return Bukkit.getPluginManager().getPlugin(name) != null; + this.morePaperLib = new MorePaperLib(this); + this.enable(); + this.loadCommands(); } @Override public void onDisable() { - HuskHomesAPI.unregister(); - if (this.eventListener != null) { - this.eventListener.handlePluginDisable(); + this.shutdown(); + if (this.audiences != null) { + this.audiences.close(); } - if (database != null) { - database.terminate(); + } + + @Override + public void loadAPI() { + HuskHomesAPI.register(this); + } + + @Override + public void loadMetrics() { + try { + final Metrics metrics = new Metrics(this, BSTATS_BUKKIT_PLUGIN_ID); + metrics.addCustomChart(new SimplePie("bungee_mode", + () -> Boolean.toString(getSettings().getCrossServer().isEnabled())) + ); + metrics.addCustomChart(new SimplePie("language", + () -> getSettings().getLanguage().toLowerCase()) + ); + metrics.addCustomChart(new SimplePie("database_type", + () -> getSettings().getDatabase().getType().getDisplayName()) + ); + metrics.addCustomChart(new SimplePie("using_economy", + () -> Boolean.toString(getSettings().getEconomy().isEnabled())) + ); + metrics.addCustomChart(new SimplePie("using_map", + () -> Boolean.toString(getSettings().getMapHook().isEnabled())) + ); + getBroker().ifPresent(broker -> metrics.addCustomChart(new SimplePie("messenger_type", + () -> settings.getCrossServer().getBrokerType().getDisplayName() + ))); + } catch (Throwable e) { + log(Level.WARNING, "Failed to register plugin metrics", e); } + } + + // Register the event listener + @Override + @NotNull + public BukkitEventListener createListener() { + return new BukkitEventListener(this); + } + + @Override + public void disablePlugin() { + log(Level.INFO, "Disabling HuskHomes..."); + getServer().getPluginManager().disablePlugin(this); + } + + @NotNull + @Override + public Version getPluginVersion() { + return Version.fromString(getDescription().getVersion()); + } + + @Override + @NotNull + public String getServerType() { + return String.format("%s/%s", getServer().getName(), getServer().getVersion()); + } + + @Override + @NotNull + public Version getMinecraftVersion() { + return Version.fromString(getServer().getBukkitVersion()); + } + + @Override + public boolean isDependencyAvailable(@NotNull String name) { + return Bukkit.getPluginManager().getPlugin(name) != null; + } + + @Override + public Optional getBroker() { + return Optional.ofNullable(broker); + } + + @Override + public void closeBroker() { if (broker != null) { broker.close(); } - if (audiences != null) { - audiences.close(); - audiences = null; - } - cancelTasks(); } @Override @@ -261,14 +231,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask return new ConsoleUser(audiences.console()); } - @NotNull - @Override - public List getOnlineUsers() { - return Bukkit.getOnlinePlayers().stream() - .map(player -> (OnlineUser) BukkitUser.adapt(player, this)) - .toList(); - } - @NotNull @Override public Audience getAudience(@NotNull UUID user) { @@ -280,13 +242,11 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask Objects.requireNonNull(Adapter.adapt(position).getWorld()).setSpawnLocation(Adapter.adapt(position)); } - @NotNull @Override - public Broker getMessenger() { - if (broker == null) { - throw new IllegalStateException("Attempted to access message broker when it was not initialized"); - } - return broker; + public void registerCommands(@NotNull List commands) { + commands.stream().peek(this.commands::add) + .map(c -> new BukkitCommand(c, getPlugin())) + .forEach(BukkitCommand::register); } @Override @@ -294,26 +254,10 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask return Optional.ofNullable(serverSpawn); } - @Override - public void setServerSpawn(@NotNull Spawn spawn) { - this.serverSpawn = spawn; - } - - @Override - @NotNull - public Version getVersion() { - return Version.fromString(getDescription().getVersion(), "-"); - } - @Override @NotNull public String getServerName() { - return server != null ? server.getName() : "server"; - } - - @Override - public void setServerName(@NotNull Server server) { - this.server = server; + return serverName != null ? serverName.getName() : "server"; } @Override @@ -329,40 +273,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask } @Override - public void registerMetrics(int metricsId) { - if (!getVersion().getMetadata().isBlank()) { - return; - } - - try { - final Metrics metrics = new Metrics(this, metricsId); - metrics.addCustomChart(new SimplePie("bungee_mode", - () -> Boolean.toString(getSettings().getCrossServer().isEnabled()) - )); - - if (getSettings().getCrossServer().isEnabled()) { - metrics.addCustomChart(new SimplePie("messenger_type", - () -> getSettings().getCrossServer().getBrokerType().getDisplayName()) - ); - } - - metrics.addCustomChart(new SimplePie("language", - () -> getSettings().getLanguage().toLowerCase())); - metrics.addCustomChart(new SimplePie("database_type", - () -> getSettings().getDatabase().getType().getDisplayName())); - metrics.addCustomChart(new SimplePie("using_economy", - () -> Boolean.toString(getSettings().getEconomy().isEnabled()))); - metrics.addCustomChart(new SimplePie("using_map", - () -> Boolean.toString(getSettings().getMapHook().isEnabled()))); - - getMapHook().ifPresent(hook -> metrics.addCustomChart(new SimplePie("map_type", hook::getName))); - } catch (Throwable e) { - log(Level.WARNING, "Failed to register bStats metrics (" + e.getMessage() + ")"); - } - } - - @Override - public void initializePluginChannels() { + public void setupPluginMessagingChannels() { final String channelId = PluginMessageBroker.BUNGEE_CHANNEL_ID; getServer().getMessenger().registerIncomingPluginChannel(this, channelId, this); getServer().getMessenger().registerOutgoingPluginChannel(this, channelId); @@ -379,15 +290,15 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask @Override public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte[] message) { - if (broker != null && broker instanceof PluginMessageBroker pluginMessenger - && getSettings().getCrossServer().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { - pluginMessenger.onReceive(channel, BukkitUser.adapt(player, this), message); + if (broker != null && broker instanceof PluginMessageBroker pluginMessenger && + getSettings().getCrossServer().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { + pluginMessenger.onReceive(channel, getOnlineUser(player), message); } } @NotNull public GracefulScheduling getScheduler() { - return paperLib.scheduling(); + return morePaperLib.scheduling(); } @NotNull @@ -407,9 +318,11 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask return getScheduler().entitySpecificScheduler(((BukkitUser) user).getPlayer()); } - @NotNull - public CommandRegistration getCommandRegistrar() { - return paperLib.commandRegistration(); + @Override + public void closeDatabase() { + if (database != null) { + database.close(); + } } @Override diff --git a/bukkit/src/main/java/net/william278/huskhomes/api/HuskHomesAPI.java b/bukkit/src/main/java/net/william278/huskhomes/api/HuskHomesAPI.java index c2b10f52..1940db5f 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/api/HuskHomesAPI.java +++ b/bukkit/src/main/java/net/william278/huskhomes/api/HuskHomesAPI.java @@ -82,7 +82,7 @@ public class HuskHomesAPI extends BaseHuskHomesAPI { */ @NotNull public OnlineUser adaptUser(@NotNull Player player) { - return BukkitUser.adapt(player, (BukkitHuskHomes) plugin); + return ((BukkitHuskHomes) plugin).getOnlineUser(player); } /** diff --git a/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java b/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java index 94d0798e..d1711070 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java +++ b/bukkit/src/main/java/net/william278/huskhomes/command/BukkitCommand.java @@ -20,9 +20,6 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.BukkitHuskHomes; -import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.teleport.TeleportRequest; -import net.william278.huskhomes.user.BukkitUser; import net.william278.huskhomes.user.CommandUser; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -33,7 +30,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; -import java.util.function.Function; public class BukkitCommand extends org.bukkit.command.Command { @@ -48,7 +44,7 @@ public class BukkitCommand extends org.bukkit.command.Command { @Override public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) { - this.command.onExecuted(sender instanceof Player p ? BukkitUser.adapt(p, plugin) : plugin.getConsole(), args); + this.command.onExecuted(sender instanceof Player p ? plugin.getOnlineUser(p) : plugin.getConsole(), args); return true; } @@ -56,16 +52,17 @@ public class BukkitCommand extends org.bukkit.command.Command { @Override public List tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException { - if (!(this.command instanceof TabProvider provider)) { + if (!(this.command instanceof TabCompletable completable)) { return List.of(); } - final CommandUser user = sender instanceof Player p ? BukkitUser.adapt(p, plugin) : plugin.getConsole(); - return provider.getSuggestions(user, args); + final CommandUser user = sender instanceof Player p ? plugin.getOnlineUser(p) : plugin.getConsole(); + return completable.getSuggestions(user, args); } public void register() { // Register with bukkit - plugin.getCommandRegistrar().getServerCommandMap().register("huskhomes", this); + plugin.getMorePaperLib().commandRegistration().getServerCommandMap() + .register("huskhomes", this); // Register permissions BukkitCommand.addPermission( @@ -108,7 +105,7 @@ public class BukkitCommand extends org.bukkit.command.Command { return null; } - Permission permission; + final Permission permission; if (description.isEmpty()) { permission = new Permission(node, permissionDefault, childNodes); } else { @@ -124,58 +121,4 @@ public class BukkitCommand extends org.bukkit.command.Command { return isOperatorCommand ? PermissionDefault.OP : PermissionDefault.TRUE; } - /** - * Commands available on the Bukkit HuskHomes implementation. - */ - public enum Type { - HOME_COMMAND(PrivateHomeCommand::new), - SET_HOME_COMMAND(SetHomeCommand::new), - HOME_LIST_COMMAND(HomeListCommand::new), - DEL_HOME_COMMAND(DelHomeCommand::new), - EDIT_HOME_COMMAND(EditHomeCommand::new), - PUBLIC_HOME_COMMAND(PublicHomeCommand::new), - PUBLIC_HOME_LIST_COMMAND(PublicHomeListCommand::new), - WARP_COMMAND(WarpCommand::new), - SET_WARP_COMMAND(SetWarpCommand::new), - WARP_LIST_COMMAND(WarpListCommand::new), - DEL_WARP_COMMAND(DelWarpCommand::new), - EDIT_WARP_COMMAND(EditWarpCommand::new), - TP_COMMAND(TpCommand::new), - TP_HERE_COMMAND(TpHereCommand::new), - TPA_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA)), - TPA_HERE_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA_HERE)), - TPACCEPT_COMMAND((plugin) -> new TpRespondCommand(plugin, true)), - TPDECLINE_COMMAND((plugin) -> new TpRespondCommand(plugin, false)), - RTP_COMMAND(RTPCommand::new), - TP_IGNORE_COMMAND(TpIgnoreCommand::new), - TP_OFFLINE_COMMAND(TpOfflineCommand::new), - TP_ALL_COMMAND(TpAllCommand::new), - TPA_ALL_COMMAND(TpaAllCommand::new), - SPAWN_COMMAND(SpawnCommand::new), - SET_SPAWN_COMMAND(SetSpawnCommand::new), - BACK_COMMAND(BackCommand::new), - HUSKHOMES_COMMAND(HuskHomesCommand::new); - - private final Function supplier; - - Type(@NotNull Function supplier) { - this.supplier = supplier; - } - - @NotNull - public Command createCommand(@NotNull HuskHomes plugin) { - return supplier.apply(plugin); - } - - @NotNull - public static List getCommands(@NotNull BukkitHuskHomes plugin) { - return Arrays.stream(values()) - .map((type) -> type.createCommand(plugin)) - .filter((command) -> !plugin.getSettings().isCommandDisabled(command)) - .peek((command) -> new BukkitCommand(command, plugin).register()) - .toList(); - } - - } - } \ No newline at end of file diff --git a/bukkit/src/main/java/net/william278/huskhomes/hook/BukkitHookProvider.java b/bukkit/src/main/java/net/william278/huskhomes/hook/BukkitHookProvider.java new file mode 100644 index 00000000..303ed14b --- /dev/null +++ b/bukkit/src/main/java/net/william278/huskhomes/hook/BukkitHookProvider.java @@ -0,0 +1,61 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.hook; + +import net.william278.huskhomes.BukkitHuskHomes; +import net.william278.huskhomes.importer.EssentialsXImporter; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public interface BukkitHookProvider extends HookProvider { + + @Override + @NotNull + default List getAvailableHooks() { + final List hooks = HookProvider.super.getAvailableHooks(); + + // Hooks + if (getPlugin().getSettings().getEconomy().isEnabled() && isDependencyAvailable("Vault")) { + getHooks().add(new VaultEconomyHook(getPlugin())); + } + if (isDependencyAvailable("PlaceholderAPI")) { + getHooks().add(new PlaceholderAPIHook(getPlugin())); + } + + // Importers + if (isDependencyAvailable("Essentials")) { + getHooks().add(new EssentialsXImporter(getPlugin())); + } + + return hooks; + } + + + @Override + default boolean isDependencyAvailable(@NotNull String name) { + return getPlugin().getServer().getPluginManager().getPlugin(name) != null; + } + + @Override + @NotNull + BukkitHuskHomes getPlugin(); + +} diff --git a/bukkit/src/main/java/net/william278/huskhomes/hook/PlaceholderAPIHook.java b/bukkit/src/main/java/net/william278/huskhomes/hook/PlaceholderAPIHook.java index e175feb3..d84b1bd8 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/hook/PlaceholderAPIHook.java +++ b/bukkit/src/main/java/net/william278/huskhomes/hook/PlaceholderAPIHook.java @@ -19,10 +19,12 @@ package net.william278.huskhomes.hook; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.expansion.PlaceholderExpansion; import net.william278.huskhomes.BukkitHuskHomes; -import net.william278.huskhomes.user.BukkitUser; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.SavedUser; import org.bukkit.OfflinePlayer; @@ -31,25 +33,38 @@ import org.jetbrains.annotations.Nullable; import java.util.List; +@PluginHook( + name = "PlaceholderAPI", + register = PluginHook.Register.ON_LOAD +) public class PlaceholderAPIHook extends Hook { public PlaceholderAPIHook(@NotNull BukkitHuskHomes plugin) { - super(plugin, "PlaceholderAPI"); + super(plugin); } @Override - public void initialize() { - new HuskHomesExpansion((BukkitHuskHomes) plugin).register(); + public void load() { + new HuskHomesExpansion( + (BukkitHuskHomes) plugin, + plugin.getPluginVersion().toStringWithoutMetadata() + ).register(); } + @Override + public void unload() { + } + + @Getter + @RequiredArgsConstructor public static class HuskHomesExpansion extends PlaceholderExpansion { @NotNull + @Getter(AccessLevel.NONE) private final BukkitHuskHomes plugin; - - private HuskHomesExpansion(@NotNull BukkitHuskHomes plugin) { - this.plugin = plugin; - } + private final String version; + private final String author = "William278"; + private final String identifier = "huskhomes"; @Override @Nullable @@ -59,11 +74,11 @@ public class PlaceholderAPIHook extends Hook { } // Return the requested data - final OnlineUser player = BukkitUser.adapt(offlinePlayer.getPlayer(), plugin); + final OnlineUser player = plugin.getOnlineUser(offlinePlayer.getPlayer()); return switch (params) { case "homes_count" -> String.valueOf(plugin.getManager().homes() .getUserHomes() - .getOrDefault(player.getUsername(), List.of()).size()); + .getOrDefault(player.getName(), List.of()).size()); case "max_homes" -> String.valueOf(plugin.getManager().homes().getMaxHomes(player)); case "max_public_homes" -> String.valueOf(plugin.getManager().homes().getMaxPublicHomes(player)); case "free_home_slots" -> String.valueOf(plugin.getManager().homes().getFreeHomes(player)); @@ -72,42 +87,19 @@ public class PlaceholderAPIHook extends Hook { .orElse(0)); case "homes_list" -> String.join(", ", plugin.getManager().homes() .getUserHomes() - .getOrDefault(player.getUsername(), List.of())); + .getOrDefault(player.getName(), List.of())); case "public_homes_count" -> String.valueOf(plugin.getManager().homes() .getPublicHomes() - .getOrDefault(player.getUsername(), List.of()).size()); + .getOrDefault(player.getName(), List.of()).size()); case "public_homes_list" -> String.join(", ", plugin.getManager().homes() .getPublicHomes() - .getOrDefault(player.getUsername(), List.of())); + .getOrDefault(player.getName(), List.of())); case "ignoring_tp_requests" -> getBooleanValue(plugin.getManager().requests() .isIgnoringRequests(player)); default -> null; }; } - @Override - public boolean persist() { - return true; - } - - @Override - @NotNull - public String getIdentifier() { - return "huskhomes"; - } - - @Override - @NotNull - public String getAuthor() { - return "William278"; - } - - @Override - @NotNull - public String getVersion() { - return plugin.getVersion().toStringWithoutMetadata(); - } - @NotNull private String getBooleanValue(final boolean bool) { return bool ? PlaceholderAPIPlugin.booleanTrue() : PlaceholderAPIPlugin.booleanFalse(); diff --git a/bukkit/src/main/java/net/william278/huskhomes/hook/VaultEconomyHook.java b/bukkit/src/main/java/net/william278/huskhomes/hook/VaultEconomyHook.java index 923524d7..fc94f885 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/hook/VaultEconomyHook.java +++ b/bukkit/src/main/java/net/william278/huskhomes/hook/VaultEconomyHook.java @@ -31,16 +31,20 @@ import org.jetbrains.annotations.NotNull; /** * A hook that hooks into the Vault API to provide economy features. */ +@PluginHook( + name = "Vault", + register = PluginHook.Register.ON_LOAD +) public class VaultEconomyHook extends EconomyHook { protected Economy economy; public VaultEconomyHook(@NotNull HuskHomes plugin) { - super(plugin, "Vault (Economy)"); + super(plugin); } @Override - public void initialize() { + public void load() { final RegisteredServiceProvider economyProvider = ((BukkitHuskHomes) plugin).getServer() .getServicesManager().getRegistration(Economy.class); if (economyProvider != null) { @@ -48,6 +52,11 @@ public class VaultEconomyHook extends EconomyHook { } } + @Override + public void unload() { + this.economy = null; + } + @Override public double getPlayerBalance(@NotNull OnlineUser player) { return economy.getBalance(((BukkitUser) player).getPlayer()); diff --git a/bukkit/src/main/java/net/william278/huskhomes/importer/EssentialsXImporter.java b/bukkit/src/main/java/net/william278/huskhomes/importer/EssentialsXImporter.java index 3998c97f..975ec509 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/importer/EssentialsXImporter.java +++ b/bukkit/src/main/java/net/william278/huskhomes/importer/EssentialsXImporter.java @@ -24,6 +24,7 @@ import com.earth2me.essentials.Warps; import com.earth2me.essentials.commands.WarpNotFoundException; import net.william278.huskhomes.BukkitHuskHomes; import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.hook.PluginHook; import net.william278.huskhomes.user.User; import net.william278.huskhomes.util.ValidationException; import org.jetbrains.annotations.NotNull; @@ -33,12 +34,16 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; +@PluginHook( + name = "EssentialsX", + register = PluginHook.Register.ON_LOAD +) public class EssentialsXImporter extends Importer { private final Essentials essentials; public EssentialsXImporter(@NotNull HuskHomes plugin) { - super("EssentialsX", List.of(ImportData.HOMES, ImportData.WARPS), plugin); + super(List.of(ImportData.HOMES, ImportData.WARPS), plugin); this.essentials = (Essentials) ((BukkitHuskHomes) plugin).getServer() .getPluginManager().getPlugin("Essentials"); } @@ -96,7 +101,7 @@ public class EssentialsXImporter extends Importer { @NotNull private String normalizeName(@NotNull String name) { try { - plugin.getValidator().validateName(name); + plugin.validateName(name); return name; } catch (ValidationException e) { // Remove spaces diff --git a/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java b/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java index db7a3ad0..bc3cb167 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java +++ b/bukkit/src/main/java/net/william278/huskhomes/listener/BukkitEventListener.java @@ -21,7 +21,6 @@ package net.william278.huskhomes.listener; import net.william278.huskhomes.BukkitHuskHomes; import net.william278.huskhomes.config.Settings; -import net.william278.huskhomes.user.BukkitUser; import org.bukkit.Location; import org.bukkit.block.data.type.Bed; import org.bukkit.block.data.type.RespawnAnchor; @@ -41,25 +40,24 @@ public class BukkitEventListener extends EventListener implements Listener { super(plugin); } - @NotNull - public BukkitEventListener register(@NotNull BukkitHuskHomes plugin) { - plugin.getServer().getPluginManager().registerEvents(this, plugin); - return this; + @Override + public void register() { + getPlugin().getServer().getPluginManager().registerEvents(this, getPlugin()); } @EventHandler(priority = EventPriority.NORMAL) public void onPlayerJoin(PlayerJoinEvent event) { - super.handlePlayerJoin(BukkitUser.adapt(event.getPlayer(), (BukkitHuskHomes) plugin)); + super.handlePlayerJoin(getPlugin().getOnlineUser(event.getPlayer())); } @EventHandler(priority = EventPriority.NORMAL) public void onPlayerLeave(PlayerQuitEvent event) { - super.handlePlayerLeave(BukkitUser.adapt(event.getPlayer(), (BukkitHuskHomes) plugin)); + super.handlePlayerLeave(getPlugin().getOnlineUser(event.getPlayer())); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onPlayerDeath(PlayerDeathEvent event) { - super.handlePlayerDeath(BukkitUser.adapt(event.getEntity(), (BukkitHuskHomes) plugin)); + super.handlePlayerDeath(getPlugin().getOnlineUser(event.getEntity())); } @EventHandler(priority = EventPriority.NORMAL) @@ -67,7 +65,7 @@ public class BukkitEventListener extends EventListener implements Listener { if (usePaperEvents) { return; } - super.handlePlayerRespawn(BukkitUser.adapt(event.getPlayer(), (BukkitHuskHomes) plugin)); + super.handlePlayerRespawn(getPlugin().getOnlineUser(event.getPlayer())); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @@ -78,25 +76,25 @@ public class BukkitEventListener extends EventListener implements Listener { if (player.hasMetadata("NPC")) { return; } - if (!(event.getCause() == PlayerTeleportEvent.TeleportCause.COMMAND - || event.getCause() == PlayerTeleportEvent.TeleportCause.PLUGIN)) { + if (!(event.getCause() == PlayerTeleportEvent.TeleportCause.COMMAND || + event.getCause() == PlayerTeleportEvent.TeleportCause.PLUGIN)) { return; } this.handlePlayerTeleport( - BukkitUser.adapt(player, (BukkitHuskHomes) plugin), - BukkitHuskHomes.Adapter.adapt(event.getFrom(), plugin.getServerName()) + getPlugin().getOnlineUser(player), + BukkitHuskHomes.Adapter.adapt(event.getFrom(), getPlugin().getServerName()) ); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onPlayerUpdateRespawnLocation(PlayerInteractEvent event) { - final Settings.CrossServerSettings crossServer = plugin.getSettings().getCrossServer(); + final Settings.CrossServerSettings crossServer = getPlugin().getSettings().getCrossServer(); if (usePaperEvents || !(crossServer.isEnabled()) && crossServer.isGlobalRespawning()) { return; } if (event.getClickedBlock() == null || !(event.getClickedBlock().getBlockData() instanceof Bed - || event.getClickedBlock().getBlockData() instanceof RespawnAnchor)) { + || event.getClickedBlock().getBlockData() instanceof RespawnAnchor)) { return; } @@ -107,10 +105,16 @@ public class BukkitEventListener extends EventListener implements Listener { // Update the player's respawn location this.handlePlayerUpdateSpawnPoint( - BukkitUser.adapt(event.getPlayer(), (BukkitHuskHomes) plugin), - BukkitHuskHomes.Adapter.adapt(location, plugin.getServerName()) + getPlugin().getOnlineUser(event.getPlayer()), + BukkitHuskHomes.Adapter.adapt(location, getPlugin().getServerName()) ); } + @Override + @NotNull + protected BukkitHuskHomes getPlugin() { + return (BukkitHuskHomes) super.getPlugin(); + } + } diff --git a/bukkit/src/main/java/net/william278/huskhomes/user/BukkitUser.java b/bukkit/src/main/java/net/william278/huskhomes/user/BukkitUser.java index 88c2802e..c447a012 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/user/BukkitUser.java +++ b/bukkit/src/main/java/net/william278/huskhomes/user/BukkitUser.java @@ -29,6 +29,7 @@ import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.metadata.MetadataValue; import org.bukkit.permissions.PermissionAttachmentInfo; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -49,6 +50,7 @@ public class BukkitUser extends OnlineUser { } @NotNull + @ApiStatus.Internal public static BukkitUser adapt(@NotNull Player player, @NotNull BukkitHuskHomes plugin) { return new BukkitUser(player, plugin); } diff --git a/bukkit/src/main/java/net/william278/huskhomes/user/BukkitUserProvider.java b/bukkit/src/main/java/net/william278/huskhomes/user/BukkitUserProvider.java new file mode 100644 index 00000000..6dcf32a1 --- /dev/null +++ b/bukkit/src/main/java/net/william278/huskhomes/user/BukkitUserProvider.java @@ -0,0 +1,54 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.user; + +import net.william278.huskhomes.BukkitHuskHomes; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.UUID; + +public interface BukkitUserProvider extends UserProvider { + + @Override + @NotNull + default OnlineUser getOnlineUser(@NotNull UUID uuid) { + return getOnlineUser(getPlugin().getServer().getPlayer(uuid)); + } + + @NotNull + default BukkitUser getOnlineUser(@Nullable Player player) { + if (player == null) { + throw new IllegalArgumentException("Player is not online"); + } + BukkitUser user = (BukkitUser) getOnlineUserMap().get(player.getUniqueId()); + if (user == null) { + user = BukkitUser.adapt(player, getPlugin()); + getOnlineUserMap().put(player.getUniqueId(), user); + return user; + } + return user; + } + + @NotNull + BukkitHuskHomes getPlugin(); + +} diff --git a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitSafetyResolver.java b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitSavePositionProvider.java similarity index 98% rename from bukkit/src/main/java/net/william278/huskhomes/util/BukkitSafetyResolver.java rename to bukkit/src/main/java/net/william278/huskhomes/util/BukkitSavePositionProvider.java index 7aaa161f..bd0c1798 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitSafetyResolver.java +++ b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitSavePositionProvider.java @@ -30,7 +30,7 @@ import org.jetbrains.annotations.NotNull; import java.util.Optional; import java.util.concurrent.CompletableFuture; -public interface BukkitSafetyResolver extends SafetyResolver { +public interface BukkitSavePositionProvider extends SavePositionProvider { @Override default CompletableFuture> findSafeGroundLocation(@NotNull Location location) { diff --git a/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java b/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java index fc40a81f..21535caf 100644 --- a/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java +++ b/bukkit/src/test/java/net/william278/huskhomes/BukkitPluginTests.java @@ -23,7 +23,6 @@ import be.seeseemelk.mockbukkit.MockBukkit; import be.seeseemelk.mockbukkit.ServerMock; import be.seeseemelk.mockbukkit.entity.PlayerMock; import de.themoep.minedown.adventure.MineDown; -import net.william278.huskhomes.command.BukkitCommand; import net.william278.huskhomes.command.Command; import net.william278.huskhomes.position.*; import net.william278.huskhomes.user.BukkitUser; @@ -47,7 +46,7 @@ import java.util.Optional; import java.util.stream.Stream; /** - * Uses MockBukkit to test the plugin on a mock Paper server implementing the Bukkit 1.17 API. + * Uses MockBukkit to test the plugin on a mock Paper server implementing the Bukkit API. */ @DisplayName("Bukkit Plugin Tests (1.17.1)") public class BukkitPluginTests { @@ -76,14 +75,14 @@ public class BukkitPluginTests { @Test @DisplayName("Test Command Registration") public void testCommandRegistration() { - Assertions.assertEquals(BukkitCommand.Type.values().length, plugin.getCommands().size()); + Assertions.assertFalse(plugin.getCommands().isEmpty()); } @Test @DisplayName("Test Player Adapter") public void testPlayerAdaption() { PlayerMock player = server.addPlayer(); - Assertions.assertNotNull(BukkitUser.adapt(player, plugin)); + Assertions.assertNotNull(plugin.getOnlineUser(player)); } @Test @@ -109,14 +108,14 @@ public class BukkitPluginTests { .orElseThrow(() -> new IllegalStateException("Failed to load locale")); final String simpleLocaleText = plugin.getLocales().getRawLocale("error_in_game_only") .orElseThrow(() -> new IllegalStateException("Failed to load raw locale")); - BukkitUser.adapt(player, plugin).sendMessage(simpleLocale); + plugin.getOnlineUser(player).sendMessage(simpleLocale); player.assertSaid(simpleLocaleText); } @Test @DisplayName("Test Message Dispatching") public void testMessageDispatching() { - final BukkitUser user = BukkitUser.adapt(server.addPlayer(), plugin); + final BukkitUser user = plugin.getOnlineUser(server.addPlayer()); final MineDown locale = plugin.getLocales() .getLocale("teleporting_action_bar_warmup", Integer.toString(3)) @@ -139,7 +138,7 @@ public class BukkitPluginTests { @DisplayName("Test Locale Parsing") public void testLocaleParsing() { final Map rawLocales = plugin.getLocales().getRawLocales(); - BukkitUser user = BukkitUser.adapt(server.addPlayer(), plugin); + BukkitUser user = plugin.getOnlineUser(server.addPlayer()); rawLocales.forEach((key, value) -> { Optional locale = plugin.getLocales().getLocale(key); Assertions.assertTrue(locale.isPresent()); @@ -178,7 +177,7 @@ public class BukkitPluginTests { final PlayerMock player = server.addPlayer(); player.setOp(true); - final BukkitUser playerUser = BukkitUser.adapt(player, plugin); + final OnlineUser playerUser = (plugin).getOnlineUser(player); return commands.stream() .flatMap(command -> Stream.of(Arguments.of(command, playerUser, command.getName()))); } @@ -194,7 +193,7 @@ public class BukkitPluginTests { @Nested @DisplayName("Validator Tests") - public class ValidatorTests { + public class TextValidatorTests { @DisplayName("Test Validator Accepts Valid Names") @ParameterizedTest(name = "Valid Name: \"{0}\"") @@ -202,7 +201,7 @@ public class BukkitPluginTests { "ValidName", "Valid_Name", "Valid-Name", "ValidN4me", "ValidName123", "VN-123", "ValidName_123", "V" }) public void testValidNameIsValid(@NotNull String name) { - Assertions.assertDoesNotThrow(() -> plugin.getValidator().validateName(name)); + Assertions.assertDoesNotThrow(() -> plugin.validateName(name)); } @DisplayName("Test Validator Rejects Invalid Names") @@ -213,7 +212,7 @@ public class BukkitPluginTests { public void testInvalidNameIsInvalid(@NotNull String name) { Assertions.assertThrows( ValidationException.class, - () -> plugin.getValidator().validateName(name) + () -> plugin.validateName(name) ); } @@ -227,7 +226,7 @@ public class BukkitPluginTests { + " description that is 255 characters long and should be accepted by the validator" }) public void testValidDescriptionIsValid(@NotNull String description) { - Assertions.assertDoesNotThrow(() -> plugin.getValidator().validateDescription(description)); + Assertions.assertDoesNotThrow(() -> plugin.validateDescription(description)); } @DisplayName("Test Validator Rejects Invalid Descriptions") @@ -241,7 +240,7 @@ public class BukkitPluginTests { public void testInvalidDescriptionIsInvalid(@NotNull String description) { Assertions.assertThrows( ValidationException.class, - () -> plugin.getValidator().validateDescription(description) + () -> plugin.validateDescription(description) ); } @@ -256,7 +255,7 @@ public class BukkitPluginTests { @BeforeAll public static void setup() { - player = BukkitUser.adapt(server.addPlayer(), plugin); + player = plugin.getOnlineUser(server.addPlayer()); } @DisplayName("Test Applying Cooldown") @@ -264,7 +263,7 @@ public class BukkitPluginTests { @Test public void testApplyingCooldown() { plugin.getDatabase().ensureUser(player); - Assertions.assertTrue(plugin.getDatabase().getUserData(player.getUuid()).isPresent()); + Assertions.assertTrue(plugin.getDatabase().getUser(player.getUuid()).isPresent()); plugin.getDatabase().setCooldown(ACTION, player, Instant.now().plus(DURATION)); Assertions.assertTrue(plugin.getDatabase().getCooldown(ACTION, player).isPresent()); @@ -319,7 +318,7 @@ public class BukkitPluginTests { .anyMatch(warp -> warp.equals(name))); } - // test warp renaming + // Test warp renaming @DisplayName("Test Warp Renaming") @ParameterizedTest(name = "Rename: \"{0}\" > \"{0}2\"") @MethodSource("provideWarpData") @@ -465,9 +464,9 @@ public class BukkitPluginTests { @DisplayName("Ensure User Data") @BeforeAll public static void createHomeUser() { - homeOwner = BukkitUser.adapt(server.addPlayer("TestUser278"), plugin); + homeOwner = plugin.getOnlineUser(server.addPlayer("TestUser278")); plugin.getDatabase().ensureUser(homeOwner); - Assertions.assertTrue(plugin.getDatabase().getUserData(homeOwner.getUuid()).isPresent()); + Assertions.assertTrue(plugin.getDatabase().getUser(homeOwner.getUuid()).isPresent()); } @DisplayName("Test Home Creation") @@ -479,7 +478,7 @@ public class BukkitPluginTests { Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent()); Assertions.assertTrue(plugin.getManager().homes() .getUserHomes() - .get(owner.getUsername()).stream() + .get(owner.getName()).stream() .anyMatch(home -> home.equals(name))); } @@ -495,11 +494,11 @@ public class BukkitPluginTests { Assertions.assertFalse(plugin.getDatabase().getHome(owner, name).isPresent()); Assertions.assertTrue(plugin.getManager().homes() .getUserHomes() - .get(owner.getUsername()).stream() + .get(owner.getName()).stream() .anyMatch(home -> home.equals(newName))); Assertions.assertFalse(plugin.getManager().homes() .getUserHomes() - .get(owner.getUsername()).stream() + .get(owner.getName()).stream() .anyMatch(home -> home.equals(name))); // Rename back to original name @@ -507,7 +506,7 @@ public class BukkitPluginTests { Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent()); Assertions.assertTrue(plugin.getManager().homes() .getUserHomes() - .get(owner.getUsername()).stream() + .get(owner.getName()).stream() .anyMatch(home -> home.equals(name))); } @@ -518,7 +517,7 @@ public class BukkitPluginTests { @SuppressWarnings("unused") public void testHomeDescription(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position position) { - final String description = "This is a test description for the home " + name + "!"; + final String description = "This is a description for the home " + name + "!"; plugin.getManager().homes().setHomeDescription(owner, name, description); Assertions.assertTrue(plugin.getDatabase().getHome(owner, name).isPresent()); @@ -585,7 +584,7 @@ public class BukkitPluginTests { Assertions.assertTrue(homePrivacy.isPresent()); Assertions.assertTrue(homePrivacy.get()); Assertions.assertTrue(plugin.getManager().homes().getPublicHomes() - .get(owner.getUsername()).contains(name)); + .get(owner.getName()).contains(name)); } @DisplayName("Test Making Home Private") @@ -601,7 +600,7 @@ public class BukkitPluginTests { Assertions.assertTrue(homePrivacy.isPresent()); Assertions.assertFalse(homePrivacy.get()); Assertions.assertFalse(plugin.getManager().homes().getPublicHomes() - .getOrDefault(owner.getUsername(), List.of()) + .getOrDefault(owner.getName(), List.of()) .contains(name)); } @@ -631,7 +630,7 @@ public class BukkitPluginTests { plugin.getManager().homes().deleteHome(owner, name); Assertions.assertFalse(plugin.getDatabase().getHome(owner, name).isPresent()); Assertions.assertFalse(plugin.getManager().homes().getUserHomes() - .getOrDefault(owner.getUsername(), List.of()) + .getOrDefault(owner.getName(), List.of()) .contains(name)); plugin.getManager().homes().createHome(owner, name, position); @@ -644,7 +643,7 @@ public class BukkitPluginTests { final int deleted = plugin.getManager().homes().deleteAllHomes(homeOwner); Assertions.assertTrue(plugin.getDatabase().getHomes(homeOwner).isEmpty()); Assertions.assertTrue(plugin.getManager().homes().getUserHomes() - .get(homeOwner.getUsername()).isEmpty()); + .get(homeOwner.getName()).isEmpty()); Assertions.assertEquals(HOME_NAMES.size(), deleted); } diff --git a/common/build.gradle b/common/build.gradle index 25df2298..99c32ed4 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -10,11 +10,20 @@ dependencies { api 'org.apache.commons:commons-text:1.12.0' api 'com.google.code.gson:gson:2.11.0' api 'com.github.Exlll.ConfigLib:configlib-yaml:v4.5.0' - api('com.zaxxer:HikariCP:5.1.0') { + api('com.zaxxer:HikariCP:6.0.0') { exclude module: 'slf4j-api' } + compileOnly 'org.jetbrains:annotations:24.1.0' + compileOnly 'com.google.guava:guava:33.3.0-jre' compileOnly 'net.kyori:adventure-api:4.17.0' + compileOnly 'net.kyori:adventure-platform-api:4.3.4' + compileOnly 'com.github.plan-player-analytics:Plan:5.5.2391' + compileOnly 'com.github.BlueMap-Minecraft:BlueMapAPI:2.6.0' + compileOnly 'us.dynmap:DynmapCoreAPI:3.4' + compileOnly 'maven.modrinth:pl3xmap:1.20.4-489' + compileOnly 'org.projectlombok:lombok:1.18.34' + compileOnly "redis.clients:jedis:${jedis_version}" compileOnly "org.xerial:sqlite-jdbc:${sqlite_driver_version}" compileOnly "com.mysql:mysql-connector-j:${mysql_driver_version}" @@ -22,14 +31,6 @@ dependencies { compileOnly "com.h2database:h2:${h2_driver_version}" compileOnly "org.postgresql:postgresql:${postgresql_driver_version}" - compileOnly 'org.jetbrains:annotations:24.1.0' - compileOnly 'com.google.guava:guava:33.3.0-jre' - compileOnly 'com.github.plan-player-analytics:Plan:5.5.2391' - compileOnly 'com.github.BlueMap-Minecraft:BlueMapAPI:2.6.0' - compileOnly 'us.dynmap:DynmapCoreAPI:3.4' - compileOnly 'maven.modrinth:pl3xmap:1.20.4-489' - compileOnly 'org.projectlombok:lombok:1.18.34' - testImplementation 'com.github.plan-player-analytics:Plan:5.5.2391' testImplementation 'com.github.yuriy-g:simple-java-plot:5c502c2e98' testImplementation 'com.google.guava:guava:33.3.0-jre' diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index 0564e6a4..58cefedf 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -21,49 +21,138 @@ package net.william278.huskhomes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import net.kyori.adventure.audience.Audience; import net.kyori.adventure.key.Key; -import net.william278.desertwell.util.ThrowingConsumer; -import net.william278.desertwell.util.UpdateChecker; -import net.william278.desertwell.util.Version; +import net.william278.huskhomes.api.BaseHuskHomesAPI; import net.william278.huskhomes.command.Command; +import net.william278.huskhomes.command.CommandProvider; import net.william278.huskhomes.config.ConfigProvider; import net.william278.huskhomes.config.Server; import net.william278.huskhomes.config.Settings; -import net.william278.huskhomes.database.Database; +import net.william278.huskhomes.database.DatabaseProvider; import net.william278.huskhomes.event.EventDispatcher; -import net.william278.huskhomes.hook.*; -import net.william278.huskhomes.importer.Importer; -import net.william278.huskhomes.manager.Manager; -import net.william278.huskhomes.network.Broker; +import net.william278.huskhomes.hook.HookProvider; +import net.william278.huskhomes.hook.PluginHook; +import net.william278.huskhomes.listener.ListenerProvider; +import net.william278.huskhomes.manager.ManagerProvider; +import net.william278.huskhomes.network.BrokerProvider; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.World; -import net.william278.huskhomes.random.RandomTeleportEngine; +import net.william278.huskhomes.random.RandomTeleportProvider; import net.william278.huskhomes.user.ConsoleUser; -import net.william278.huskhomes.user.OnlineUser; -import net.william278.huskhomes.user.SavedUser; -import net.william278.huskhomes.user.User; +import net.william278.huskhomes.user.UserProvider; import net.william278.huskhomes.util.*; import org.intellij.lang.annotations.Subst; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.InputStream; -import java.util.*; -import java.util.function.Consumer; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; import java.util.logging.Level; -import java.util.stream.Collectors; -import java.util.stream.Stream; /** * Represents a cross-platform instance of the plugin. */ -public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolver, TransactionResolver, ConfigProvider { +public interface HuskHomes extends Task.Supplier, EventDispatcher, SavePositionProvider, TransactionResolver, + ConfigProvider, DatabaseProvider, BrokerProvider, MetaProvider, HookProvider, RandomTeleportProvider, + AudiencesProvider, UserProvider, TextValidator, ManagerProvider, ListenerProvider, CommandProvider { + + int BSTATS_BUKKIT_PLUGIN_ID = 8430; /** - * The spigot resource ID, used for update checking. + * Load plugin systems. + * + * @since 4.8 */ - int SPIGOT_RESOURCE_ID = 83767; + default void load() { + try { + loadConfigs(); + loadHooks(); + registerHooks(PluginHook.Register.ON_LOAD); + } catch (Throwable e) { + log(Level.SEVERE, "An error occurred whilst loading HuskHomes", e); + disablePlugin(); + return; + } + log(Level.INFO, String.format("Successfully loaded HuskHomes v%s", getPluginVersion())); + } + + /** + * Enable all plugin systems. + * + * @since 4.8 + */ + default void enable() { + try { + loadDatabase(); + loadBroker(); + loadManager(); + loadRandomTeleportEngine(); + loadListeners(); + registerHooks(PluginHook.Register.ON_ENABLE); + loadAPI(); + if (getPluginVersion().getMetadata().isBlank()) { + loadMetrics(); + } + } catch (Throwable e) { + log(Level.SEVERE, "An error occurred whilst enabling HuskHomes", e); + disablePlugin(); + return; + } + log(Level.INFO, String.format("Successfully enabled HuskHomes v%s", getPluginVersion())); + checkForUpdates(); + } + + /** + * Shutdown plugin subsystems. + * + * @since 4.8 + */ + default void shutdown() { + log(Level.INFO, String.format("Disabling HuskHomes v%s...", getPluginVersion())); + try { + unloadHooks(); + closeDatabase(); + closeBroker(); + cancelTasks(); + unloadAPI(); + } catch (Throwable e) { + log(Level.SEVERE, "An error occurred whilst disabling HuskHomes", e); + } + log(Level.INFO, String.format("Successfully disabled HuskHomes v%s", getPluginVersion())); + } + + /** + * Register the API instance. + * + * @since 4.8 + */ + void loadAPI(); + + /** + * Unregister the API instance. + * + * @since 4.8 + */ + default void unloadAPI() { + BaseHuskHomesAPI.unregister(); + } + + /** + * Load plugin metrics. + * + * @since 4.8 + */ + void loadMetrics(); + + /** + * Disable the plugin. + * + * @since 4.8 + */ + void disablePlugin(); /** * Get the user representing the server console. @@ -73,82 +162,6 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve @NotNull ConsoleUser getConsole(); - /** - * The {@link Set} of online {@link OnlineUser}s on this server. - * - * @return a {@link Set} of currently online {@link OnlineUser}s - */ - @NotNull - List getOnlineUsers(); - - - /** - * Get the adventure {@link Audience} for a given {@link UUID}. - * - * @param user The {@link UUID} of the user to get the {@link Audience} for. - * @return The {@link Audience} for the given {@link UUID}. - */ - @NotNull - Audience getAudience(@NotNull UUID user); - - /** - * Finds a local {@link OnlineUser} by their name. Auto-completes partially typed names for the closest match - * - * @param playerName the name of the player to find - * @return an {@link Optional} containing the {@link OnlineUser} if found, or an empty {@link Optional} if not found - */ - default Optional getOnlineUser(@NotNull String playerName) { - return getOnlineUserExact(playerName) - .or(() -> getOnlineUsers().stream() - .filter(user -> user.getUsername().toLowerCase().startsWith(playerName.toLowerCase())) - .findFirst()); - } - - /** - * Finds a local {@link OnlineUser} by their name. - * - * @param playerName the name of the player to find - * @return an {@link Optional} containing the {@link OnlineUser} if found, or an empty {@link Optional} if not found - */ - default Optional getOnlineUserExact(@NotNull String playerName) { - return getOnlineUsers().stream() - .filter(user -> user.getUsername().equalsIgnoreCase(playerName)) - .findFirst(); - } - - @NotNull - Set getSavedUsers(); - - default Optional getSavedUser(@NotNull User user) { - return getSavedUsers().stream() - .filter(savedUser -> savedUser.getUser().equals(user)) - .findFirst(); - } - - default void editUserData(@NotNull User user, @NotNull Consumer editor) { - runAsync(() -> getSavedUser(user) - .ifPresent(result -> { - editor.accept(result); - getDatabase().updateUserData(result); - })); - } - - /** - * Initialize a faucet of the plugin. - * - * @param name the name of the faucet - * @param runner a runnable for initializing the faucet - */ - default void initialize(@NotNull String name, @NotNull ThrowingConsumer runner) { - log(Level.INFO, "Initializing " + name + "..."); - try { - runner.accept(this); - } catch (Exception e) { - throw new IllegalStateException("Failed to initialize " + name, e); - } - log(Level.INFO, "Successfully initialized " + name); - } - /** * The canonical spawn {@link Position} of this server, if it has been set. * @@ -168,96 +181,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve */ void setWorldSpawn(@NotNull Position position); - /** - * Returns the {@link Server} the plugin is on. - * - * @return The {@link Server} object - */ - @NotNull - String getServerName(); - - void setServer(@NotNull Server server); - - void setUnsafeBlocks(@NotNull UnsafeBlocks unsafeBlocks); - - @NotNull - UnsafeBlocks getUnsafeBlocks(); - - /** - * The {@link Database} that store persistent plugin data. - * - * @return the {@link Database} implementation for accessing data - */ - @NotNull - Database getDatabase(); - - /** - * The {@link Validator} for validating home names and descriptions. - * - * @return the {@link Validator} instance - */ - @NotNull - Validator getValidator(); - - /** - * The {@link Manager} that manages home, warp and user data. - * - * @return the {@link Manager} implementation - */ - @NotNull - Manager getManager(); - - /** - * The {@link Broker} that sends cross-network messages. - * - * @return the {@link Broker} implementation - */ - @NotNull - Broker getMessenger(); - - /** - * The {@link RandomTeleportEngine} that manages random teleports. - * - * @return the {@link RandomTeleportEngine} implementation - */ - @NotNull - RandomTeleportEngine getRandomTeleportEngine(); - - /** - * Sets the {@link RandomTeleportEngine} to be used for processing random teleports. - * - * @param randomTeleportEngine the {@link RandomTeleportEngine} to use - */ - void setRandomTeleportEngine(@NotNull RandomTeleportEngine randomTeleportEngine); - - /** - * Set of active {@link Hook}s running on the server. - * - * @return the {@link Set} of active {@link Hook}s - */ - @NotNull - List getHooks(); - - void setHooks(@NotNull List hooks); - - default Optional getHook(@NotNull Class hookClass) { - return getHooks().stream() - .filter(hook -> hookClass.isAssignableFrom(hook.getClass())) - .map(hookClass::cast) - .findFirst(); - } - - default Optional getMapHook() { - return getHook(MapHook.class); - } - - @NotNull - default List getImporters() { - return getHooks().stream() - .filter(hook -> Importer.class.isAssignableFrom(hook.getClass())) - .map(Importer.class::cast) - .collect(Collectors.toList()); - } + void setServerName(@NotNull Server serverName); /** * Returns a resource read from the plugin resources folder. @@ -276,14 +200,6 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve @NotNull List getWorlds(); - /** - * Returns the plugin version. - * - * @return the plugin {@link Version} - */ - @NotNull - Version getVersion(); - /** * Returns a list of enabled commands. * @@ -299,64 +215,6 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve .map(type::cast); } - default void registerHooks() { - setHooks(new ArrayList<>()); - - if (getSettings().getMapHook().isEnabled()) { - if (isDependencyLoaded("Dynmap")) { - getHooks().add(new DynmapHook(this)); - } else if (isDependencyLoaded("BlueMap")) { - getHooks().add(new BlueMapHook(this)); - } else if (isDependencyLoaded("Pl3xMap")) { - getHooks().add(new Pl3xMapHook(this)); - } - } - if (isDependencyLoaded("Plan")) { - getHooks().add(new PlanHook(this)); - } - } - - default void registerImporters() { - } - - boolean isDependencyLoaded(@NotNull String name); - - @NotNull - Map> getGlobalPlayerList(); - - default List getPlayerList(boolean includeVanished) { - return Stream.concat( - getGlobalPlayerList().values().stream().flatMap(Collection::stream), - getLocalPlayerList(includeVanished).stream() - ).distinct().sorted().toList(); - } - - @NotNull - @SuppressWarnings("unused") - default List getPlayerList() { - return getPlayerList(true); - } - - default void setPlayerList(@NotNull String server, @NotNull List players) { - getGlobalPlayerList().values().forEach(list -> { - list.removeAll(players); - list.removeAll(getLocalPlayerList()); - }); - getGlobalPlayerList().put(server, players); - } - - @NotNull - default List getLocalPlayerList(boolean includeVanished) { - return getOnlineUsers().stream() - .filter(user -> includeVanished || !user.isVanished()) - .map(OnlineUser::getUsername) - .toList(); - } - - default List getLocalPlayerList() { - return getLocalPlayerList(true); - } - @NotNull Set getCurrentlyOnWarmup(); @@ -383,38 +241,6 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve return this.getCurrentlyInvulnerable().contains(uuid); } - @NotNull - default UpdateChecker getUpdateChecker() { - return UpdateChecker.builder() - .currentVersion(getVersion()) - .endpoint(UpdateChecker.Endpoint.SPIGOT) - .resource(Integer.toString(SPIGOT_RESOURCE_ID)) - .build(); - } - - default void checkForUpdates() { - if (getSettings().isCheckForUpdates()) { - getUpdateChecker().check().thenAccept(checked -> { - if (!checked.isUpToDate()) { - log(Level.WARNING, "A new version of HuskHomes is available: v" - + checked.getLatestVersion() + " (running v" + getVersion() + ")"); - } - }); - } - } - - /** - * Registers the plugin with bStats metrics. - * - * @param metricsId the bStats id for the plugin - */ - void registerMetrics(int metricsId); - - /** - * Initialize plugin messaging channels. - */ - void initializePluginChannels(); - /** * Log a message to the console. * diff --git a/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java b/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java index e2ee29fc..8334a2c4 100644 --- a/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java +++ b/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java @@ -95,7 +95,7 @@ public class BaseHuskHomesAPI { * @since 3.0 */ public final CompletableFuture> getUserData(@NotNull UUID uuid) { - return plugin.supplyAsync(() -> plugin.getDatabase().getUserData(uuid)); + return plugin.supplyAsync(() -> plugin.getDatabase().getUser(uuid)); } /** @@ -106,7 +106,7 @@ public class BaseHuskHomesAPI { * @since 3.0 */ public final CompletableFuture> getUserData(@NotNull String username) { - return plugin.supplyAsync(() -> plugin.getDatabase().getUserDataByName(username)); + return plugin.supplyAsync(() -> plugin.getDatabase().getUser(username)); } /** @@ -779,27 +779,28 @@ public class BaseHuskHomesAPI { * @param timedTeleport Whether the teleport should be timed or not (requiring a warmup where they must stand still * for a period of time) * @param rtpArgs Arguments that will be passed to the implementing {@link RandomTeleportEngine} - * @since 3.0 * @apiNote This method was updated in version 4.6.3 to support the new Cross-Server RTP function, - * for the original function use {@link #randomlyTeleportPlayerLocally(OnlineUser, boolean, String...)} + * for the original function use {@link #randomlyTeleportPlayerLocally(OnlineUser, boolean, String...)} + * @since 3.0 */ public final void randomlyTeleportPlayer(@NotNull OnlineUser user, boolean timedTeleport, @NotNull String... rtpArgs) { - if (plugin.getSettings().getRtp().isCrossServer() && (plugin.getSettings().getCrossServer().isEnabled() - && plugin.getSettings().getCrossServer().getBrokerType() == Broker.Type.REDIS)) { + if (plugin.getSettings().getRtp().isCrossServer() && (plugin.getSettings().getCrossServer().isEnabled() && + plugin.getSettings().getCrossServer().getBrokerType() == Broker.Type.REDIS)) { List allowedServers = plugin.getSettings().getRtp().getRandomTargetServers(); String randomServer = allowedServers.get(random.nextInt(allowedServers.size())); if (randomServer.equals(plugin.getServerName())) { randomlyTeleportPlayerLocally(user, timedTeleport, rtpArgs); return; } - Message.builder() + + plugin.getBroker().ifPresent(b -> Message.builder() .scope(Message.Scope.SERVER) .target(randomServer) .type(Message.Type.REQUEST_RTP_LOCATION) .payload(Payload.withStringList( - List.of(user.getPosition().getWorld().getName(), user.getUsername()))) - .build().send(plugin.getMessenger(), user); + List.of(user.getPosition().getWorld().getName(), user.getName()))) + .build().send(b, user)); return; } randomlyTeleportPlayerLocally(user, timedTeleport, rtpArgs); @@ -810,9 +811,9 @@ public class BaseHuskHomesAPI { * generated by the current {@link RandomTeleportEngine}. * * @param user The {@link OnlineUser} to teleport - * @since 3.0 * @apiNote This method was updated in version 4.6.3 to support the new Cross-Server RTP function, - * for the original function use {@link #randomlyTeleportPlayerLocally(OnlineUser)} + * for the original function use {@link #randomlyTeleportPlayerLocally(OnlineUser)} + * @since 3.0 */ public final void randomlyTeleportPlayer(@NotNull OnlineUser user) { this.randomlyTeleportPlayer(user, false); @@ -831,7 +832,7 @@ public class BaseHuskHomesAPI { * @since 4.6.3 */ public final void randomlyTeleportPlayerLocally(@NotNull OnlineUser user, boolean timedTeleport, - @NotNull String... rtpArgs) { + @NotNull String... rtpArgs) { plugin.getRandomTeleportEngine() .getRandomPosition(user.getPosition().getWorld(), rtpArgs) .thenAccept(position -> { @@ -904,7 +905,7 @@ public class BaseHuskHomesAPI { * * @return instance of the HuskHomes API * @throws NotRegisteredException if the API has not yet been registered. - * @since 1.0 + * @since 4.8 */ @NotNull public static BaseHuskHomesAPI getInstance() throws NotRegisteredException { @@ -917,7 +918,7 @@ public class BaseHuskHomesAPI { /** * (Internal use only) - Unregister the API instance. * - * @since 1.0 + * @since 4.8 */ @ApiStatus.Internal public static void unregister() { diff --git a/common/src/main/java/net/william278/huskhomes/command/BackCommand.java b/common/src/main/java/net/william278/huskhomes/command/BackCommand.java index 7bd92762..8fada071 100644 --- a/common/src/main/java/net/william278/huskhomes/command/BackCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/BackCommand.java @@ -33,7 +33,11 @@ import java.util.Optional; public class BackCommand extends InGameCommand { protected BackCommand(@NotNull HuskHomes plugin) { - super("back", List.of(), "", plugin); + super( + List.of("back"), + "", + plugin + ); addAdditionalPermissions(Map.of( "death", false, "previous", false diff --git a/common/src/main/java/net/william278/huskhomes/command/Command.java b/common/src/main/java/net/william278/huskhomes/command/Command.java index c948a13a..17bd5445 100644 --- a/common/src/main/java/net/william278/huskhomes/command/Command.java +++ b/common/src/main/java/net/william278/huskhomes/command/Command.java @@ -19,11 +19,11 @@ package net.william278.huskhomes.command; +import com.google.common.collect.Maps; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.user.CommandUser; import org.jetbrains.annotations.NotNull; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -32,11 +32,10 @@ public abstract class Command extends Node { private final String usage; private final Map additionalPermissions; - protected Command(@NotNull String name, @NotNull List aliases, @NotNull String usage, - @NotNull HuskHomes plugin) { - super(name, aliases, plugin); + protected Command(@NotNull List aliases, @NotNull String usage, @NotNull HuskHomes plugin) { + super(aliases, plugin); this.usage = usage; - this.additionalPermissions = new HashMap<>(); + this.additionalPermissions = Maps.newTreeMap(); } @Override @@ -82,7 +81,7 @@ public abstract class Command extends Node { @NotNull public String getDescription() { - return plugin.getLocales().getRawLocale(getName() + "_command_description") + return plugin.getLocales().getRawLocale(String.format("%s_command_description", getName())) .orElse(getUsage()); } diff --git a/common/src/main/java/net/william278/huskhomes/command/CommandProvider.java b/common/src/main/java/net/william278/huskhomes/command/CommandProvider.java new file mode 100644 index 00000000..ca19ab09 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/command/CommandProvider.java @@ -0,0 +1,126 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.command; + +import com.google.common.collect.Lists; +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.teleport.TeleportRequest; +import net.william278.huskhomes.user.CommandUser; +import org.jetbrains.annotations.NotNull; + +import java.util.Comparator; +import java.util.List; +import java.util.Optional; + +public interface CommandProvider { + + + /** + * Get the list of registered commands + * + * @return the list of commands + * @since 4.8 + */ + @NotNull + List getCommands(); + + /** + * Get a command by its class + * + * @param commandClass the class of the command to get + * @param the type of command + * @return the command, or null if not found + */ + default Optional getCommand(@NotNull Class commandClass) { + return getCommands().stream() + .filter(commandClass::isInstance) + .map(commandClass::cast) + .findFirst(); + } + + /** + * Returns whether a user can use a command + * + * @param commandClass the class of the command to check + * @param user the user to check + * @param nodes the nodes to check + * @param the type of command + * @return whether the user can use the command + */ + default boolean canUseCommand(@NotNull Class commandClass, @NotNull CommandUser user, + @NotNull String... nodes) { + return getCommand(commandClass).map(command -> command.hasPermission(user, nodes)).orElse(false); + } + + /** + * Register a batch of command with the platform implementation + * + * @param commands the list of commands to register + * @since 4.8 + */ + void registerCommands(@NotNull List commands); + + /** + * Registers all plugin commands + * + * @since 4.8 + */ + default void loadCommands() { + final List commands = Lists.newArrayList(); + + // Instantiate commands + commands.add(new PrivateHomeCommand(getPlugin())); + commands.add(new SetHomeCommand(getPlugin())); + commands.add(new HomeListCommand(getPlugin())); + commands.add(new DelHomeCommand(getPlugin())); + commands.add(new EditHomeCommand(getPlugin())); + commands.add(new PublicHomeCommand(getPlugin())); + commands.add(new PublicHomeListCommand(getPlugin())); + commands.add(new WarpCommand(getPlugin())); + commands.add(new SetWarpCommand(getPlugin())); + commands.add(new WarpListCommand(getPlugin())); + commands.add(new DelWarpCommand(getPlugin())); + commands.add(new EditWarpCommand(getPlugin())); + commands.add(new TpCommand(getPlugin())); + commands.add(new TpHereCommand(getPlugin())); + commands.add(new TpRequestCommand(getPlugin(), TeleportRequest.Type.TPA)); + commands.add(new TpRequestCommand(getPlugin(), TeleportRequest.Type.TPA_HERE)); + commands.add(new TpRespondCommand(getPlugin(), true)); + commands.add(new TpRespondCommand(getPlugin(), false)); + commands.add(new RtpCommand(getPlugin())); + commands.add(new TpIgnoreCommand(getPlugin())); + commands.add(new TpOfflineCommand(getPlugin())); + commands.add(new TpAllCommand(getPlugin())); + commands.add(new SpawnCommand(getPlugin())); + commands.add(new SetSpawnCommand(getPlugin())); + commands.add(new BackCommand(getPlugin())); + commands.add(new HuskHomesCommand(getPlugin())); + + // Filter, sort, and register + registerCommands(commands.stream() + .filter((command) -> !getPlugin().getSettings().isCommandDisabled(command)) + .sorted(Comparator.comparing(Command::getName)) + .toList()); + } + + @NotNull + HuskHomes getPlugin(); + +} diff --git a/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java index 93dc63e4..fcbbb28b 100644 --- a/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/DelHomeCommand.java @@ -31,7 +31,12 @@ import java.util.List; public class DelHomeCommand extends SavedPositionCommand { public DelHomeCommand(@NotNull HuskHomes plugin) { - super("delhome", List.of(), PositionCommandType.HOME, List.of(), plugin); + super( + List.of("delhome"), + PositionCommandType.HOME, + List.of(), + plugin + ); } @Override @@ -45,7 +50,7 @@ public class DelHomeCommand extends SavedPositionCommand { @Override public void execute(@NotNull CommandUser executor, @NotNull Home home, @NotNull String[] args) { if (executor instanceof OnlineUser user && !home.getOwner().equals(user) - && !user.hasPermission(getOtherPermission())) { + && !user.hasPermission(getOtherPermission())) { plugin.getLocales().getLocale("error_no_permission") .ifPresent(user::sendMessage); return; diff --git a/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java index 53b51fad..7848617e 100644 --- a/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/DelWarpCommand.java @@ -30,7 +30,12 @@ import java.util.List; public class DelWarpCommand extends SavedPositionCommand { public DelWarpCommand(@NotNull HuskHomes plugin) { - super("delwarp", List.of(), PositionCommandType.WARP, List.of(), plugin); + super( + List.of("delwarp"), + PositionCommandType.WARP, + List.of(), + plugin + ); setOperatorCommand(true); } diff --git a/common/src/main/java/net/william278/huskhomes/command/DisabledCommand.java b/common/src/main/java/net/william278/huskhomes/command/DisabledCommand.java index 0709d9d6..20d5c3af 100644 --- a/common/src/main/java/net/william278/huskhomes/command/DisabledCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/DisabledCommand.java @@ -28,7 +28,11 @@ import java.util.List; public class DisabledCommand extends Command { public DisabledCommand(@NotNull String name, @NotNull HuskHomes plugin) { - super(name, List.of(), "", plugin); + super( + List.of(name), + "", + plugin + ); setOperatorCommand(true); } diff --git a/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java index 97ade4c2..eedf30b8 100644 --- a/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/EditHomeCommand.java @@ -40,8 +40,7 @@ public class EditHomeCommand extends SavedPositionCommand { public EditHomeCommand(@NotNull HuskHomes plugin) { super( - "edithome", - List.of(), + List.of("edithome"), PositionCommandType.HOME, List.of("rename", "description", "relocate", "privacy"), plugin @@ -104,7 +103,7 @@ public class EditHomeCommand extends SavedPositionCommand { .ifPresent(executor::sendMessage); } else { plugin.getLocales().getLocale("edit_home_update_name_other", - home.getOwner().getUsername(), original.getName(), newName) + home.getOwner().getName(), original.getName(), newName) .ifPresent(executor::sendMessage); } }); @@ -137,7 +136,7 @@ public class EditHomeCommand extends SavedPositionCommand { .ifPresent(executor::sendMessage); } else { plugin.getLocales().getLocale("edit_home_update_description_other", - home.getOwner().getUsername(), home.getName(), + home.getOwner().getName(), home.getName(), original.getMeta().getDescription(), newDescription) .ifPresent(executor::sendMessage); } @@ -166,7 +165,7 @@ public class EditHomeCommand extends SavedPositionCommand { .ifPresent(executor::sendMessage); } else { plugin.getLocales().getLocale("edit_home_update_location_other", - home.getOwner().getUsername(), home.getName()) + home.getOwner().getName(), home.getName()) .ifPresent(executor::sendMessage); } }); @@ -220,7 +219,7 @@ public class EditHomeCommand extends SavedPositionCommand { .ifPresent(executor::sendMessage); } else { plugin.getLocales().getLocale("edit_home_privacy_" + privacy + "_success_other", - home.getOwner().getUsername(), home.getName()) + home.getOwner().getName(), home.getName()) .ifPresent(executor::sendMessage); } }); @@ -244,7 +243,7 @@ public class EditHomeCommand extends SavedPositionCommand { .ifPresent(messages::add); } else { plugin.getLocales().getLocale("edit_home_menu_title_other", - home.getOwner().getUsername(), home.getName()) + home.getOwner().getName(), home.getName()) .ifPresent(messages::add); } diff --git a/common/src/main/java/net/william278/huskhomes/command/EditWarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/EditWarpCommand.java index ce3c126b..36a0abb0 100644 --- a/common/src/main/java/net/william278/huskhomes/command/EditWarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/EditWarpCommand.java @@ -38,8 +38,7 @@ public class EditWarpCommand extends SavedPositionCommand { public EditWarpCommand(@NotNull HuskHomes plugin) { super( - "editwarp", - List.of(), + List.of("editwarp"), PositionCommandType.WARP, List.of("rename", "description", "relocate"), plugin diff --git a/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java index 16c647dd..1ab6f977 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HomeCommand.java @@ -33,9 +33,9 @@ import java.util.Optional; public abstract class HomeCommand extends SavedPositionCommand { - protected HomeCommand(@NotNull String name, @NotNull List aliases, @NotNull PositionCommandType type, + protected HomeCommand(@NotNull List aliases, @NotNull PositionCommandType type, @NotNull HuskHomes plugin) { - super(name, aliases, type, List.of(), plugin); + super(aliases, type, List.of(), plugin); addAdditionalPermissions(Map.of("player", true)); } @@ -51,7 +51,7 @@ public abstract class HomeCommand extends SavedPositionCommand { if (executor instanceof OnlineUser user && !user.hasPermission(getOtherPermission()) && (!home.getOwner().equals(user) && !home.isPublic())) { plugin.getLocales().getLocale("error_public_home_invalid", - home.getOwner().getUsername(), home.getName()) + home.getOwner().getName(), home.getName()) .ifPresent(executor::sendMessage); return; } diff --git a/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java b/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java index 46664810..8a5e7d3e 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HomeListCommand.java @@ -37,14 +37,18 @@ import java.util.stream.Collectors; public class HomeListCommand extends ListCommand { protected HomeListCommand(@NotNull HuskHomes plugin) { - super("homelist", List.of("homes"), "[player] [page]", plugin); + super( + List.of("homelist", "homes"), + "[player] [page]", + plugin + ); addAdditionalPermissions(Map.of("other", true)); } @Override public void execute(@NotNull CommandUser executor, @NotNull String[] args) { final Optional homeOwner = args.length > 0 ? parseStringArg(args, 0) - : executor instanceof OnlineUser user ? Optional.of(user.getUsername()) : Optional.empty(); + : executor instanceof OnlineUser user ? Optional.of(user.getName()) : Optional.empty(); final int pageNumber = parseIntArg(args, args.length > 1 ? 1 : 0).orElse(1); if (homeOwner.isEmpty()) { plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) @@ -56,7 +60,7 @@ public class HomeListCommand extends ListCommand { } protected void showHomeList(@NotNull CommandUser executor, @NotNull String homeOwner, int pageNumber) { - final Optional targetUser = plugin.getDatabase().getUserDataByName(homeOwner).map(SavedUser::getUser); + final Optional targetUser = plugin.getDatabase().getUser(homeOwner).map(SavedUser::getUser); final User user; final int page; if (targetUser.isEmpty()) { @@ -74,7 +78,7 @@ public class HomeListCommand extends ListCommand { } if (executor instanceof OnlineUser onlineUser && !user.getUuid().equals(onlineUser.getUuid()) - && !executor.hasPermission(getPermission("other"))) { + && !executor.hasPermission(getPermission("other"))) { plugin.getLocales().getLocale("error_no_permission") .ifPresent(executor::sendMessage); return; @@ -97,7 +101,7 @@ public class HomeListCommand extends ListCommand { @NotNull List homes) { if (homes.isEmpty()) { if (!executor.equals(user)) { - plugin.getLocales().getLocale("error_no_homes_set_other", user.getUsername()) + plugin.getLocales().getLocale("error_no_homes_set_other", user.getName()) .ifPresent(executor::sendMessage); } else { plugin.getLocales().getLocale("error_no_homes_set").ifPresent(executor::sendMessage); @@ -105,7 +109,7 @@ public class HomeListCommand extends ListCommand { return Optional.empty(); } - final String homeListArguments = !executor.equals(user) ? " " + user.getUsername() : ""; + final String homeListArguments = !executor.equals(user) ? " " + user.getName() : ""; final PaginatedList homeList = PaginatedList.of(homes.stream().map(home -> plugin.getLocales() .getRawLocale("home_list_item", @@ -124,7 +128,7 @@ public class HomeListCommand extends ListCommand { plugin.getLocales() .getBaseList(plugin.getSettings().getGeneral().getListItemsPerPage()) .setHeaderFormat(plugin.getLocales().getRawLocale("home_list_page_title", - user.getUsername(), "%first_item_on_page_index%", + user.getName(), "%first_item_on_page_index%", "%last_item_on_page_index%", "%total_items%") .orElse("")) .setCommand("/huskhomes:homelist" + homeListArguments).build()); diff --git a/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java b/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java index b9d0c1ce..656f91eb 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java @@ -39,7 +39,7 @@ import java.util.logging.Level; import java.util.stream.Collectors; import java.util.stream.IntStream; -public class HuskHomesCommand extends Command implements TabProvider { +public class HuskHomesCommand extends Command implements TabCompletable { private static final Map SUB_COMMANDS = Map.of( "about", false, @@ -55,14 +55,18 @@ public class HuskHomesCommand extends Command implements TabProvider { private final AboutMenu aboutMenu; protected HuskHomesCommand(@NotNull HuskHomes plugin) { - super("huskhomes", List.of(), "[" + String.join("|", SUB_COMMANDS.keySet()) + "]", plugin); + super( + List.of("huskhomes"), + "[" + String.join("|", SUB_COMMANDS.keySet()) + "]", + plugin + ); addAdditionalPermissions(SUB_COMMANDS); this.updateChecker = plugin.getUpdateChecker(); this.aboutMenu = AboutMenu.builder() .title(Component.text("HuskHomes")) .description(Component.text("The powerful & intuitive homes, warps, and teleportation suite")) - .version(plugin.getVersion()) + .version(plugin.getPluginVersion()) .credits("Author", AboutMenu.Credit.of("William278").description("Click to visit website").url("https://william278.net")) .credits("Contributors", @@ -118,14 +122,14 @@ public class HuskHomesCommand extends Command implements TabProvider { executor.sendMessage(new MineDown( "[HuskHomes](#00fb9a bold) [| Reloaded config & message files.](#00fb9a)\n" - + "[ℹ If you have modified the database or cross-server message broker settings," - + " you need to restart your server for these changes to take effect.](gray)" + + "[ℹ If you have modified the database or cross-server message broker settings," + + " you need to restart your server for these changes to take effect.](gray)" )); } case "import" -> { if (!importersLoaded) { importersLoaded = true; - plugin.registerImporters(); + plugin.loadHooks(); } if (plugin.getImporters().isEmpty()) { plugin.getLocales().getLocale("error_no_importers_available") @@ -152,12 +156,12 @@ public class HuskHomesCommand extends Command implements TabProvider { } case "update" -> updateChecker.check().thenAccept(checked -> { if (checked.isUpToDate()) { - plugin.getLocales().getLocale("up_to_date", plugin.getVersion().toString()) + plugin.getLocales().getLocale("up_to_date", plugin.getPlugin().toString()) .ifPresent(executor::sendMessage); return; } plugin.getLocales().getLocale("update_available", checked.getLatestVersion().toString(), - plugin.getVersion().toString()).ifPresent(executor::sendMessage); + plugin.getPluginVersion().toString()).ifPresent(executor::sendMessage); }); default -> plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) .ifPresent(executor::sendMessage); @@ -169,8 +173,7 @@ public class HuskHomesCommand extends Command implements TabProvider { switch (parseStringArg(args, 0).orElse("list")) { case "start" -> parseStringArg(args, 1).ifPresentOrElse( name -> { - final Optional importer = plugin.getImporters().stream() - .filter(available -> available.getImporterName().equalsIgnoreCase(name)).findFirst(); + final Optional importer = plugin.getImporterByName(name); if (importer.isEmpty()) { plugin.getLocales().getLocale("error_invalid_importer") .ifPresent(executor::sendMessage); @@ -203,9 +206,9 @@ public class HuskHomesCommand extends Command implements TabProvider { plugin.runAsync(() -> { Optional savedUser; try { - savedUser = plugin.getDatabase().getUserData(UUID.fromString(nameOrUuid.get())); + savedUser = plugin.getDatabase().getUser(UUID.fromString(nameOrUuid.get())); } catch (IllegalArgumentException e) { - savedUser = plugin.getDatabase().getUserDataByName(nameOrUuid.get()); + savedUser = plugin.getDatabase().getUser(nameOrUuid.get()); } if (savedUser.isEmpty()) { @@ -218,14 +221,14 @@ public class HuskHomesCommand extends Command implements TabProvider { if (!parseStringArg(args, 1) .map(a -> a.equalsIgnoreCase("confirm")).orElse(false)) { plugin.getLocales().getLocale("delete_player_confirm", - savedUser.get().getUser().getUsername()).ifPresent(executor::sendMessage); + savedUser.get().getUser().getName()).ifPresent(executor::sendMessage); return; } final int homesDeleted = plugin.getManager().homes().deleteAllHomes(user); - plugin.getDatabase().deleteUserData(user.getUuid()); + plugin.getDatabase().deleteUser(user.getUuid()); plugin.getLocales().getLocale("delete_player_success", - savedUser.get().getUser().getUsername(), Integer.toString(homesDeleted)) + savedUser.get().getUser().getName(), Integer.toString(homesDeleted)) .ifPresent(executor::sendMessage); }); } @@ -318,7 +321,7 @@ public class HuskHomesCommand extends Command implements TabProvider { private PaginatedList getImporterList() { return PaginatedList.of(plugin.getImporters().stream() .map(importer -> plugin.getLocales().getRawLocale("importer_list_item", - Locales.escapeText(importer.getImporterName()), + Locales.escapeText(importer.getName()), Locales.escapeText(importer.getSupportedImportData().stream() .map(Importer.ImportData::getName) .collect(Collectors.joining(", ")))) @@ -346,7 +349,7 @@ public class HuskHomesCommand extends Command implements TabProvider { if (!args[0].equalsIgnoreCase("import") && !args[1].equalsIgnoreCase("start")) { yield null; } - yield plugin.getImporters().stream().map(Importer::getImporterName).toList(); + yield plugin.getImporters().stream().map(Importer::getName).toList(); } default -> null; }; diff --git a/common/src/main/java/net/william278/huskhomes/command/InGameCommand.java b/common/src/main/java/net/william278/huskhomes/command/InGameCommand.java index aade5643..f8584c99 100644 --- a/common/src/main/java/net/william278/huskhomes/command/InGameCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/InGameCommand.java @@ -28,9 +28,9 @@ import java.util.List; public abstract class InGameCommand extends Command { - protected InGameCommand(@NotNull String name, @NotNull List aliases, @NotNull String usage, + protected InGameCommand(@NotNull List aliases, @NotNull String usage, @NotNull HuskHomes plugin) { - super(name, aliases, usage, plugin); + super(aliases, usage, plugin); } @Override diff --git a/common/src/main/java/net/william278/huskhomes/command/ListCommand.java b/common/src/main/java/net/william278/huskhomes/command/ListCommand.java index 71aba1db..9efcc575 100644 --- a/common/src/main/java/net/william278/huskhomes/command/ListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/ListCommand.java @@ -32,9 +32,9 @@ public abstract class ListCommand extends Command { protected final Map cachedLists; - protected ListCommand(@NotNull String name, @NotNull List aliases, @NotNull String usage, + protected ListCommand(@NotNull List aliases, @NotNull String usage, @NotNull HuskHomes plugin) { - super(name, aliases, usage, plugin); + super(aliases, usage, plugin); this.cachedLists = new HashMap<>(); } diff --git a/common/src/main/java/net/william278/huskhomes/command/Node.java b/common/src/main/java/net/william278/huskhomes/command/Node.java index ef85f73a..e4d82b23 100644 --- a/common/src/main/java/net/william278/huskhomes/command/Node.java +++ b/common/src/main/java/net/william278/huskhomes/command/Node.java @@ -27,55 +27,64 @@ import net.william278.huskhomes.position.World; import net.william278.huskhomes.teleport.Teleportable; import net.william278.huskhomes.user.CommandUser; import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.user.SavedUser; +import net.william278.huskhomes.user.User; import org.jetbrains.annotations.NotNull; -import java.util.List; -import java.util.Optional; -import java.util.StringJoiner; -import java.util.UUID; +import java.util.*; public abstract class Node implements Executable { protected static final String PERMISSION_PREFIX = "huskhomes.command"; protected final HuskHomes plugin; - private final String name; - private final List aliases; - - @Setter @Getter + private final List aliases; + @Getter + @Setter private boolean operatorCommand = false; - protected Node(@NotNull String name, @NotNull List aliases, @NotNull HuskHomes plugin) { - if (name.isBlank()) { + protected Node(@NotNull List aliases, @NotNull HuskHomes plugin) { + if (aliases.isEmpty()) { throw new IllegalArgumentException("Command name cannot be blank"); } - this.name = name; this.aliases = aliases; this.plugin = plugin; } - @NotNull - public String getName() { - return name; - } - - @NotNull - public List getAliases() { - return aliases; - } - @NotNull public String getPermission(@NotNull String... child) { final StringJoiner joiner = new StringJoiner(".") .add(PERMISSION_PREFIX) .add(getName()); - for (final String node : child) { + for (String node : child) { joiner.add(node); } return joiner.toString().trim(); } + public boolean hasPermission(@NotNull CommandUser executor, @NotNull String... child) { + return executor.hasPermission(getPermission(child)) || executor.hasPermission(getPermission("*")); + } + + @NotNull + public String getName() { + if (aliases.isEmpty()) { + throw new IllegalStateException("Primary alias of command node is blank"); + } + return aliases.get(0); + } + + protected Optional resolveUser(@NotNull CommandUser executor, @NotNull String[] args) { + return parseStringArg(args, 0) + .flatMap(a -> plugin.getDatabase().getUser(a)).map(SavedUser::getUser) + .or(() -> { + if (executor instanceof OnlineUser online) { + return Optional.of(online); + } + return Optional.empty(); + }); + } protected Optional parseIntArg(@NotNull String[] args, int index) { try { if (args.length > index) { @@ -184,4 +193,17 @@ public abstract class Node implements Executable { } + protected Optional parseBooleanArg(@NotNull String[] args, int index) { + if (args.length <= index) { + return Optional.empty(); + } + final String arg = args[index].toLowerCase(Locale.ENGLISH); + if (arg.equals("true") || arg.equals("enable") || arg.equals("on")) { + return Optional.of(true); + } else if (arg.equals("false") || arg.equals("disable") || arg.equals("off")) { + return Optional.of(false); + } + return Optional.empty(); + } + } \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/command/PrivateHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/PrivateHomeCommand.java index 5be9ef6e..3ff1f420 100644 --- a/common/src/main/java/net/william278/huskhomes/command/PrivateHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/PrivateHomeCommand.java @@ -30,7 +30,11 @@ import java.util.List; public class PrivateHomeCommand extends HomeCommand { protected PrivateHomeCommand(@NotNull HuskHomes plugin) { - super("home", List.of(), PositionCommandType.HOME, plugin); + super( + List.of("home"), + PositionCommandType.HOME, + plugin + ); } @Override @@ -49,7 +53,7 @@ public class PrivateHomeCommand extends HomeCommand { return; } plugin.getCommand(HomeListCommand.class) - .ifPresent(command -> command.showHomeList(executor, user.getUsername(), 1)); + .ifPresent(command -> command.showHomeList(executor, user.getName(), 1)); return; } super.execute(executor, args); diff --git a/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java index c4cbd25f..e016bfc9 100644 --- a/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/PublicHomeCommand.java @@ -26,10 +26,14 @@ import org.jetbrains.annotations.NotNull; import java.util.List; -public class PublicHomeCommand extends HomeCommand implements TabProvider { +public class PublicHomeCommand extends HomeCommand implements TabCompletable { protected PublicHomeCommand(@NotNull HuskHomes plugin) { - super("phome", List.of("publichome"), PositionCommandType.PUBLIC_HOME, plugin); + super( + List.of("phome", "publichome"), + PositionCommandType.PUBLIC_HOME, + plugin + ); } @Override diff --git a/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java b/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java index 19a20836..04db4051 100644 --- a/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/PublicHomeListCommand.java @@ -35,7 +35,11 @@ import java.util.stream.Collectors; public class PublicHomeListCommand extends ListCommand { protected PublicHomeListCommand(@NotNull HuskHomes plugin) { - super("phomelist", List.of("phomes", "publichomelist"), "[page]", plugin); + super( + List.of("phomelist", "phomes", "publichomelist"), + "[page]", + plugin + ); } @Override @@ -75,7 +79,7 @@ public class PublicHomeListCommand extends ListCommand { .filter(h -> h.getName().equals(home.getName())).count() > 1 ? home.getSafeIdentifier() : Locales.escapeText(home.getName()), home.getSafeIdentifier(), - Locales.escapeText(home.getOwner().getUsername()), + Locales.escapeText(home.getOwner().getName()), home.getMeta().getDescription().isBlank() ? plugin.getLocales().getNone() : Locales.escapeText(home.getMeta().getDescription()) diff --git a/common/src/main/java/net/william278/huskhomes/command/RTPCommand.java b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java similarity index 91% rename from common/src/main/java/net/william278/huskhomes/command/RTPCommand.java rename to common/src/main/java/net/william278/huskhomes/command/RtpCommand.java index 862f68dd..3f36a186 100644 --- a/common/src/main/java/net/william278/huskhomes/command/RTPCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java @@ -37,12 +37,16 @@ import java.util.Map; import java.util.Optional; import java.util.Random; -public class RTPCommand extends Command implements UserListTabProvider { +public class RtpCommand extends Command implements UserListTabCompletable { private final Random random = new Random(); - protected RTPCommand(@NotNull HuskHomes plugin) { - super("rtp", List.of(), "[player] [world]", plugin); + protected RtpCommand(@NotNull HuskHomes plugin) { + super( + List.of("rtp"), + "[player] [world]", + plugin + ); addAdditionalPermissions(Map.of( "other", true @@ -75,8 +79,9 @@ public class RTPCommand extends Command implements UserListTabProvider { @Override public List suggest(@NotNull CommandUser user, @NotNull String[] args) { return switch (args.length) { - case 0, 1 -> user.hasPermission(getPermission("other")) ? UserListTabProvider.super.suggestLocal(args) - : user instanceof OnlineUser online ? List.of(online.getUsername()) : List.of(); + case 0, 1 -> user.hasPermission(getPermission("other")) + ? UserListTabCompletable.super.suggest(user, args) + : user instanceof OnlineUser online ? List.of(online.getName()) : List.of(); case 2 -> plugin.getWorlds().stream() .filter(world -> !plugin.getSettings().getRtp().isWorldRtpRestricted(world)) .map(World::getName) @@ -148,19 +153,20 @@ public class RTPCommand extends Command implements UserListTabProvider { .ifPresent(teleporter::sendMessage); if (plugin.getSettings().getRtp().isCrossServer() && plugin.getSettings().getCrossServer().isEnabled() - && plugin.getSettings().getCrossServer().getBrokerType() == Broker.Type.REDIS) { + && plugin.getSettings().getCrossServer().getBrokerType() == Broker.Type.REDIS) { List allowedServers = plugin.getSettings().getRtp().getRandomTargetServers(); String randomServer = allowedServers.get(random.nextInt(allowedServers.size())); if (randomServer.equals(plugin.getServerName())) { performLocalRTP(teleporter, executor, world, args); return; } - Message.builder() + + plugin.getBroker().ifPresent(b -> Message.builder() .type(Message.Type.REQUEST_RTP_LOCATION) .scope(Message.Scope.SERVER) .target(randomServer) - .payload(Payload.withRTPRequest(Payload.RTPRequest.of(teleporter.getUsername(), world.getName()))) - .build().send(plugin.getMessenger(), teleporter); + .payload(Payload.withRTPRequest(Payload.RTPRequest.of(teleporter.getName(), world.getName()))) + .build().send(b, teleporter)); return; } @@ -171,9 +177,9 @@ public class RTPCommand extends Command implements UserListTabProvider { * Performs the RTP locally. * * @param teleporter person to teleport - * @param executor the person executing the teleport - * @param world the world to teleport to - * @param args rtp engine args + * @param executor the person executing the teleport + * @param world the world to teleport to + * @param args rtp engine args */ private void performLocalRTP(@NotNull OnlineUser teleporter, @NotNull CommandUser executor, @NotNull World world, @NotNull String[] args) { diff --git a/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java b/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java index de19a532..78962308 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SavedPositionCommand.java @@ -33,15 +33,15 @@ import org.jetbrains.annotations.NotNull; import java.util.*; -public abstract class SavedPositionCommand extends Command implements TabProvider { +public abstract class SavedPositionCommand extends Command implements TabCompletable { protected final List arguments; protected final PositionCommandType positionType; - protected SavedPositionCommand(@NotNull String name, @NotNull List aliases, + protected SavedPositionCommand(@NotNull List aliases, @NotNull PositionCommandType positionType, @NotNull List arguments, @NotNull HuskHomes plugin) { - super(name, aliases, "" + formatUsage(arguments), plugin); + super(aliases, "" + formatUsage(arguments), plugin); this.positionType = positionType; this.arguments = arguments; @@ -98,7 +98,7 @@ public abstract class SavedPositionCommand extends Comm return Optional.empty(); } - final Optional optionalHome = plugin.getDatabase().getUserDataByName(ownerUsername) + final Optional optionalHome = plugin.getDatabase().getUser(ownerUsername) .flatMap(owner -> resolveHomeByName(owner.getUser(), ownerHome)); if (optionalHome.isEmpty()) { plugin.getLocales().getLocale(executor.hasPermission(getOtherPermission()) @@ -243,7 +243,7 @@ public abstract class SavedPositionCommand extends Comm yield plugin.getManager().homes().getUserHomeIdentifiers(); } if (executor instanceof OnlineUser user) { - yield plugin.getManager().homes().getUserHomes().get(user.getUsername()); + yield plugin.getManager().homes().getUserHomes().get(user.getName()); } yield plugin.getManager().homes().getUserHomeIdentifiers(); } diff --git a/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java b/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java index 94a75c08..d9c0f707 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SetHomeCommand.java @@ -32,7 +32,10 @@ import java.util.Optional; public class SetHomeCommand extends SetPositionCommand { protected SetHomeCommand(@NotNull HuskHomes plugin) { - super("sethome", plugin); + super( + List.of("sethome"), + plugin + ); } @Override diff --git a/common/src/main/java/net/william278/huskhomes/command/SetPositionCommand.java b/common/src/main/java/net/william278/huskhomes/command/SetPositionCommand.java index 18895e31..64fc2998 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SetPositionCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SetPositionCommand.java @@ -28,8 +28,8 @@ import java.util.Optional; public abstract class SetPositionCommand extends InGameCommand { - protected SetPositionCommand(@NotNull String name, @NotNull HuskHomes plugin) { - super(name, List.of(), "", plugin); + protected SetPositionCommand(@NotNull List aliases, @NotNull HuskHomes plugin) { + super(aliases, "", plugin); } @Override diff --git a/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java b/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java index 7f5093b0..2818a975 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SetSpawnCommand.java @@ -32,7 +32,11 @@ import static net.william278.huskhomes.config.Settings.CrossServerSettings.Globa public class SetSpawnCommand extends InGameCommand { protected SetSpawnCommand(@NotNull HuskHomes plugin) { - super("setspawn", List.of(), "", plugin); + super( + List.of("setspawn"), + "", + plugin + ); setOperatorCommand(true); } diff --git a/common/src/main/java/net/william278/huskhomes/command/SetWarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/SetWarpCommand.java index a85e374f..5610557c 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SetWarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SetWarpCommand.java @@ -24,10 +24,15 @@ import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.util.ValidationException; import org.jetbrains.annotations.NotNull; +import java.util.List; + public class SetWarpCommand extends SetPositionCommand { protected SetWarpCommand(@NotNull HuskHomes plugin) { - super("setwarp", plugin); + super( + List.of("setwarp"), + plugin + ); setOperatorCommand(true); } diff --git a/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java b/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java index b6589e03..e4e33659 100644 --- a/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/SpawnCommand.java @@ -34,7 +34,11 @@ import java.util.Optional; public class SpawnCommand extends Command { protected SpawnCommand(@NotNull HuskHomes plugin) { - super("spawn", List.of(), "[player]", plugin); + super( + List.of("spawn"), + "[player]", + plugin + ); addAdditionalPermissions(Map.of("other", true)); } diff --git a/common/src/main/java/net/william278/huskhomes/command/TabProvider.java b/common/src/main/java/net/william278/huskhomes/command/TabCompletable.java similarity index 97% rename from common/src/main/java/net/william278/huskhomes/command/TabProvider.java rename to common/src/main/java/net/william278/huskhomes/command/TabCompletable.java index 10cbf5a7..ca4867f6 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TabProvider.java +++ b/common/src/main/java/net/william278/huskhomes/command/TabCompletable.java @@ -25,7 +25,7 @@ import org.jetbrains.annotations.Nullable; import java.util.List; -public interface TabProvider { +public interface TabCompletable { @Nullable List suggest(@NotNull CommandUser user, @NotNull String[] args); diff --git a/common/src/main/java/net/william278/huskhomes/command/TpAllCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpAllCommand.java index deeb4bad..f0febef9 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpAllCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpAllCommand.java @@ -33,13 +33,17 @@ import java.util.List; public class TpAllCommand extends InGameCommand { protected TpAllCommand(@NotNull HuskHomes plugin) { - super("tpall", List.of(), "", plugin); + super( + List.of("tpall"), + "", + plugin + ); setOperatorCommand(true); } @Override public void execute(@NotNull OnlineUser executor, @NotNull String[] args) { - if (plugin.getGlobalPlayerList().size() <= 1) { + if (plugin.getGlobalUserList().size() <= 1) { plugin.getLocales().getLocale("error_no_players_online") .ifPresent(executor::sendMessage); return; @@ -58,13 +62,11 @@ public class TpAllCommand extends InGameCommand { return; } - if (plugin.getSettings().getCrossServer().isEnabled()) { - Message.builder() - .target(Message.TARGET_ALL) - .type(Message.Type.TELEPORT_TO_POSITION) - .payload(Payload.withPosition(targetPosition)) - .build().send(plugin.getMessenger(), executor); - } + plugin.getBroker().ifPresent(b -> Message.builder() + .target(Message.TARGET_ALL) + .type(Message.Type.TELEPORT_TO_POSITION) + .payload(Payload.withPosition(targetPosition)) + .build().send(b, executor)); plugin.getLocales().getLocale("teleporting_all_players") .ifPresent(executor::sendMessage); diff --git a/common/src/main/java/net/william278/huskhomes/command/TpCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpCommand.java index 5193d805..05df9cdb 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpCommand.java @@ -25,16 +25,22 @@ import net.william278.huskhomes.position.Position; import net.william278.huskhomes.teleport.*; import net.william278.huskhomes.user.CommandUser; import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.user.User; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.stream.Collectors; -public class TpCommand extends Command implements TabProvider { +public class TpCommand extends Command implements TabCompletable { protected TpCommand(@NotNull HuskHomes plugin) { - super("tp", List.of("tpo"), "[] [target]", plugin); + super( + List.of("tp", "tpo"), + "[] [target]", + plugin + ); + addAdditionalPermissions(Map.of("coordinates", true, "other", true)); setOperatorCommand(true); } @@ -89,7 +95,7 @@ public class TpCommand extends Command implements TabProvider { // Determine teleporter and target names, validate permissions final @Nullable String targetName = target instanceof Username username ? username.name() - : target instanceof OnlineUser online ? online.getUsername() : null; + : target instanceof OnlineUser online ? online.getName() : null; if (executor instanceof OnlineUser online) { if (online.equals(teleporter)) { if (teleporter.getUsername().equalsIgnoreCase(targetName)) { @@ -136,7 +142,7 @@ public class TpCommand extends Command implements TabProvider { ((int) relative.getX() + " " + (int) relative.getY()), ((int) relative.getX() + " " + (int) relative.getY() + " " + (int) relative.getZ())) : List.of()); - completions.addAll(plugin.getPlayerList(false)); + plugin.getUserList().stream().map(User::getName).forEach(completions::add); return completions.stream() .filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : "")) .sorted().collect(Collectors.toList()); @@ -155,7 +161,7 @@ public class TpCommand extends Command implements TabProvider { : List.of() ); if (user.hasPermission(getPermission("other"))) { - completions.addAll(plugin.getPlayerList(false)); + plugin.getUserList().stream().map(User::getName).forEach(completions::add); } } return completions.stream() diff --git a/common/src/main/java/net/william278/huskhomes/command/TpHereCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpHereCommand.java index 8180499d..6e5bf331 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpHereCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpHereCommand.java @@ -27,10 +27,14 @@ import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Optional; -public class TpHereCommand extends InGameCommand implements UserListTabProvider { +public class TpHereCommand extends InGameCommand implements UserListTabCompletable { protected TpHereCommand(@NotNull HuskHomes plugin) { - super("tphere", List.of("tpohere"), "", plugin); + super( + List.of("tphere", "tpohere"), + "", + plugin + ); setOperatorCommand(true); } @@ -51,7 +55,7 @@ public class TpHereCommand extends InGameCommand implements UserListTabProvider .target(executor.getPosition()) .buildAndComplete(false, target); - plugin.getLocales().getLocale("teleporting_other_complete", target, executor.getUsername()); + plugin.getLocales().getLocale("teleporting_other_complete", target, executor.getName()); } } diff --git a/common/src/main/java/net/william278/huskhomes/command/TpIgnoreCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpIgnoreCommand.java index d86bd77a..a16d380b 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpIgnoreCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpIgnoreCommand.java @@ -31,7 +31,11 @@ import java.util.List; public class TpIgnoreCommand extends InGameCommand { protected TpIgnoreCommand(@NotNull HuskHomes plugin) { - super("tpignore", List.of(), "", plugin); + super( + List.of("tpignore"), + "", + plugin + ); } @Override @@ -39,7 +43,7 @@ public class TpIgnoreCommand extends InGameCommand { final RequestsManager manager = plugin.getManager().requests(); final boolean isIgnoringRequests = !manager.isIgnoringRequests(onlineUser); - plugin.editUserData(onlineUser, (SavedUser user) -> user.setIgnoringTeleports(isIgnoringRequests)); + plugin.editSavedUser(onlineUser, (SavedUser user) -> user.setIgnoringTeleports(isIgnoringRequests)); plugin.getLocales().getRawLocale("tpignore_toggle_" + (isIgnoringRequests ? "on" : "off"), plugin.getLocales().getRawLocale("tpignore_toggle_button").orElse("")) diff --git a/common/src/main/java/net/william278/huskhomes/command/TpOfflineCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpOfflineCommand.java index 1ea80af3..a8c36827 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpOfflineCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpOfflineCommand.java @@ -30,10 +30,15 @@ import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Optional; -public class TpOfflineCommand extends InGameCommand implements UserListTabProvider { +public class TpOfflineCommand extends InGameCommand implements UserListTabCompletable { protected TpOfflineCommand(@NotNull HuskHomes plugin) { - super("tpoffline", List.of(), "", plugin); + super( + List.of("tpoffline"), + "", + plugin + ); + setOperatorCommand(true); } @@ -47,7 +52,7 @@ public class TpOfflineCommand extends InGameCommand implements UserListTabProvid } final Optional targetUserData = plugin.getDatabase() - .getUserDataByName(optionalUser.get()) + .getUser(optionalUser.get()) .map(SavedUser::getUser); if (targetUserData.isEmpty()) { plugin.getLocales().getLocale("error_player_not_found", optionalUser.get()) @@ -61,12 +66,12 @@ public class TpOfflineCommand extends InGameCommand implements UserListTabProvid private void teleportToOfflinePosition(@NotNull OnlineUser user, @NotNull User target, @NotNull String[] args) { final Optional position = plugin.getDatabase().getOfflinePosition(target); if (position.isEmpty()) { - plugin.getLocales().getLocale("error_no_offline_position", target.getUsername()) + plugin.getLocales().getLocale("error_no_offline_position", target.getName()) .ifPresent(user::sendMessage); return; } - plugin.getLocales().getLocale("teleporting_offline_player", target.getUsername()) + plugin.getLocales().getLocale("teleporting_offline_player", target.getName()) .ifPresent(user::sendMessage); Teleport.builder(plugin) .teleporter(user) diff --git a/common/src/main/java/net/william278/huskhomes/command/TeleportRequestCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpRequestCommand.java similarity index 87% rename from common/src/main/java/net/william278/huskhomes/command/TeleportRequestCommand.java rename to common/src/main/java/net/william278/huskhomes/command/TpRequestCommand.java index 53ab499b..56909acc 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TeleportRequestCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpRequestCommand.java @@ -29,13 +29,17 @@ import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Optional; -public class TeleportRequestCommand extends InGameCommand implements UserListTabProvider { +public class TpRequestCommand extends InGameCommand implements UserListTabCompletable { private final TeleportRequest.Type requestType; - protected TeleportRequestCommand(@NotNull HuskHomes plugin, @NotNull TeleportRequest.Type requestType) { - super(requestType == TeleportRequest.Type.TPA ? "tpa" : "tpahere", List.of(), "", plugin); - this.requestType = requestType; + protected TpRequestCommand(@NotNull HuskHomes plugin, @NotNull TeleportRequest.Type type) { + super( + List.of(type == TeleportRequest.Type.TPA ? "tpa" : "tpahere"), + "", + plugin + ); + this.requestType = type; } @Override @@ -56,7 +60,7 @@ public class TeleportRequestCommand extends InGameCommand implements UserListTab // Ensure the user does not send a request to themselves final String target = optionalTarget.get(); - if (target.equalsIgnoreCase(onlineUser.getUsername())) { + if (target.equalsIgnoreCase(onlineUser.getName())) { plugin.getLocales().getLocale("error_teleport_request_self") .ifPresent(onlineUser::sendMessage); return; diff --git a/common/src/main/java/net/william278/huskhomes/command/TpRespondCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpRespondCommand.java index d43319e9..0a4ae731 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpRespondCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpRespondCommand.java @@ -30,14 +30,14 @@ import java.util.Optional; * A command used for responding to tp requests - can either be a /tpaccept or /tpdecline command, controlled by the * acceptRequestCommand flag. */ -public class TpRespondCommand extends InGameCommand implements UserListTabProvider { +public class TpRespondCommand extends InGameCommand implements UserListTabCompletable { private final boolean accept; protected TpRespondCommand(@NotNull HuskHomes plugin, boolean accept) { super( - accept ? "tpaccept" : "tpdecline", - accept ? List.of("tpyes") : List.of("tpno", "tpdeny"), + accept ? List.of("tpaccept", "tpyes") + : List.of("tpdecline", "tpno", "tpdeny"), "[player]", plugin ); diff --git a/common/src/main/java/net/william278/huskhomes/command/TpaAllCommand.java b/common/src/main/java/net/william278/huskhomes/command/TpaAllCommand.java index 9798b5c2..5e507142 100644 --- a/common/src/main/java/net/william278/huskhomes/command/TpaAllCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/TpaAllCommand.java @@ -28,13 +28,13 @@ import java.util.List; public class TpaAllCommand extends InGameCommand { protected TpaAllCommand(@NotNull HuskHomes plugin) { - super("tpaall", List.of(), "", plugin); + super(List.of("tpaall"), "", plugin); setOperatorCommand(true); } @Override public void execute(@NotNull OnlineUser executor, @NotNull String[] args) { - if (plugin.getGlobalPlayerList().size() <= 1) { + if (plugin.getGlobalUserList().size() <= 1) { plugin.getLocales().getLocale("error_no_players_online") .ifPresent(executor::sendMessage); return; diff --git a/common/src/main/java/net/william278/huskhomes/command/UserListTabProvider.java b/common/src/main/java/net/william278/huskhomes/command/UserListTabCompletable.java similarity index 79% rename from common/src/main/java/net/william278/huskhomes/command/UserListTabProvider.java rename to common/src/main/java/net/william278/huskhomes/command/UserListTabCompletable.java index fbe8392c..cdabfb9f 100644 --- a/common/src/main/java/net/william278/huskhomes/command/UserListTabProvider.java +++ b/common/src/main/java/net/william278/huskhomes/command/UserListTabCompletable.java @@ -21,22 +21,18 @@ package net.william278.huskhomes.command; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.user.CommandUser; +import net.william278.huskhomes.user.User; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; -public interface UserListTabProvider extends TabProvider { +public interface UserListTabCompletable extends TabCompletable { @Override @Nullable default List suggest(@NotNull CommandUser user, @NotNull String[] args) { - return args.length < 2 ? getPlugin().getPlayerList(false) : null; - } - - @Nullable - default List suggestLocal(@NotNull String[] args) { - return args.length < 2 ? getPlugin().getLocalPlayerList(false) : null; + return args.length < 2 ? getPlugin().getUserList().stream().map(User::getName).toList() : null; } @NotNull diff --git a/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java b/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java index 0c311078..596260c4 100644 --- a/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/WarpCommand.java @@ -33,7 +33,12 @@ import java.util.Optional; public class WarpCommand extends SavedPositionCommand { protected WarpCommand(@NotNull HuskHomes plugin) { - super("warp", List.of(), PositionCommandType.WARP, List.of(), plugin); + super( + List.of("warp"), + PositionCommandType.WARP, + List.of(), + plugin + ); addAdditionalPermissions(Map.of("player", true)); } diff --git a/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java b/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java index 81e80856..411c9814 100644 --- a/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/WarpListCommand.java @@ -34,7 +34,11 @@ import java.util.stream.Collectors; public class WarpListCommand extends ListCommand { protected WarpListCommand(@NotNull HuskHomes plugin) { - super("warplist", List.of("warps"), "[player] [page]", plugin); + super( + List.of("warplist", "warps"), + "[player] [page]", + plugin + ); } @Override @@ -89,7 +93,7 @@ public class WarpListCommand extends ListCommand { private List getItems(@NotNull CommandUser executor) { List warps = plugin.getDatabase().getWarps(); if (plugin.getSettings().getGeneral().isPermissionRestrictWarps() - && !executor.hasPermission(Warp.getWildcardPermission())) { + && !executor.hasPermission(Warp.getWildcardPermission())) { warps = warps.stream().filter(warp -> executor.hasPermission(warp.getPermission())).toList(); } return warps; diff --git a/common/src/main/java/net/william278/huskhomes/config/Locales.java b/common/src/main/java/net/william278/huskhomes/config/Locales.java index 908d46c4..745864d4 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Locales.java +++ b/common/src/main/java/net/william278/huskhomes/config/Locales.java @@ -47,7 +47,7 @@ public class Locales { ┃ Developed by William278 ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ┣╸ See plugin about menu for international locale credits - ┣╸ Formatted in MineDown: https://github.com/Phoenix616/MineDown + ┣╸ Formatted in MineDown: https://github.com/WiIIiam278/MineDown ┗╸ Translate HuskHomes: https://william278.net/docs/huskhomes/translations"""; protected static final String DEFAULT_LOCALE = "en-gb"; diff --git a/common/src/main/java/net/william278/huskhomes/database/Database.java b/common/src/main/java/net/william278/huskhomes/database/Database.java index 16d4f18a..b154360c 100644 --- a/common/src/main/java/net/william278/huskhomes/database/Database.java +++ b/common/src/main/java/net/william278/huskhomes/database/Database.java @@ -19,11 +19,12 @@ package net.william278.huskhomes.database; +import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.Setter; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.config.Server; -import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.position.Home; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.SavedPosition; @@ -33,80 +34,162 @@ import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.user.User; import net.william278.huskhomes.util.TransactionResolver; +import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.sql.Connection; import java.sql.SQLException; import java.time.Instant; import java.util.*; +import java.util.logging.Level; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import java.util.stream.Collectors; -/** - * An abstract representation of the plugin database, storing home, warp and player data. - * - *

Implemented by different database platforms - MySQL, SQLite, etc. - as configured by the administrator. - */ + +@AllArgsConstructor(access = AccessLevel.PROTECTED) public abstract class Database { - protected final HuskHomes plugin; + protected HuskHomes plugin; - /** - * Loads SQL table creation schema statements from a resource file as a string array. - * - * @param schemaFileName database script resource file to load from - * @return Array of string-formatted table creation schema statements - * @throws IOException if the resource could not be read - */ - protected final String[] getSchemaStatements(@NotNull String schemaFileName) throws IOException { - return formatStatementTables( - new String(Objects.requireNonNull(plugin.getResource(schemaFileName)).readAllBytes(), - StandardCharsets.UTF_8)) - .split(";"); - } + @Getter + @Setter + private boolean loaded; - /** - * Format all table name placeholder strings in an SQL statement. - * - * @param sql the SQL statement with unformatted table name placeholders - * @return the formatted statement, with table placeholders replaced with the correct names - */ - protected final String formatStatementTables(@NotNull String sql) { - final Settings.DatabaseSettings settings = plugin.getSettings().getDatabase(); - return sql - .replaceAll("%positions_table%", settings - .getTableName(Table.POSITION_DATA)) - .replaceAll("%players_table%", settings - .getTableName(Table.PLAYER_DATA)) - .replaceAll("%cooldowns_table%", settings - .getTableName(Table.PLAYER_COOLDOWNS_DATA)) - .replaceAll("%teleports_table%", settings - .getTableName(Table.TELEPORT_DATA)) - .replaceAll("%saved_positions_table%", settings - .getTableName(Table.SAVED_POSITION_DATA)) - .replaceAll("%homes_table%", settings - .getTableName(Table.HOME_DATA)) - .replaceAll("%warps_table%", settings - .getTableName(Table.WARP_DATA)); - } - - /** - * Create a database instance, pulling table names from the plugin config. - * - * @param plugin the implementing plugin instance - */ protected Database(@NotNull HuskHomes plugin) { this.plugin = plugin; } /** - * Initialize the database and ensure tables are present; create tables if they do not exist. + * Get the schema statements from the schema file. + * + * @return the {@link #format formatted} schema statements + */ + @NotNull + protected final String[] getScript(@NotNull String name) { + name = (name.startsWith("database/") ? "" : "database/") + name + (name.endsWith(".sql") ? "" : ".sql"); + try (InputStream file = Objects.requireNonNull(plugin.getResource(name), "Invalid script %s".formatted(name))) { + @Language("SQL") final String schema = new String(file.readAllBytes(), StandardCharsets.UTF_8); + return format(schema).split(";"); + } catch (IOException e) { + plugin.log(Level.SEVERE, "Failed to load database schema", e); + } + return new String[0]; + } + + protected abstract void executeScript(@NotNull Connection connection, @NotNull String name) throws SQLException; + + /** + * Format a string for use in an SQL query. + * + * @param statement The SQL statement to format + * @return The formatted SQL statement + */ + @NotNull + protected final String format(@NotNull @Language("SQL") String statement) { + final Pattern pattern = Pattern.compile("%(\\w+)%"); + final Matcher matcher = pattern.matcher(statement); + final StringBuilder sb = new StringBuilder(); + while (matcher.find()) { + final Table table = Table.match(matcher.group(1)); + matcher.appendReplacement(sb, plugin.getSettings().getDatabase().getTableName(table)); + } + matcher.appendTail(sb); + return sb.toString(); + } + + /** + * Backup a flat file database. + * + * @param file the file to back up + */ + protected final void backupFlatFile(@NotNull Path file) { + if (!file.toFile().exists()) { + return; + } + + final Path backup = file.getParent().resolve(String.format("%s.bak", file.getFileName().toString())); + try { + final File backupFile = backup.toFile(); + if (!backupFile.exists() || backupFile.delete()) { + Files.copy(file, backup); + } + } catch (IOException e) { + plugin.log(Level.WARNING, "Failed to backup flat file database", e); + } + } + + /** + * Initialize the database connection. + * + * @throws IllegalStateException if the database initialization fails */ public abstract void initialize() throws IllegalStateException; + /** + * Check if the database has been created. + * + * @return {@code true} if the database has been created; {@code false} otherwise + */ + public abstract boolean isCreated(); + + /** + * Perform database migrations. + * + * @param connection the database connection + * @throws SQLException if an SQL error occurs during migration + */ + protected final void performMigrations(@NotNull Connection connection, @NotNull Type type) throws SQLException { + final int currentVersion = getSchemaVersion(); + final int latestVersion = Migration.getLatestVersion(); + if (currentVersion < latestVersion) { + plugin.log(Level.INFO, "Performing database migrations (Target version: v" + latestVersion + ")"); + for (Migration migration : Migration.getOrderedMigrations()) { + if (!migration.isSupported(type)) { + continue; + } + if (migration.getVersion() > currentVersion) { + try { + plugin.log(Level.INFO, "Performing database migration: " + migration.getMigrationName() + + " (v" + migration.getVersion() + ")"); + executeScript(connection, "migrations/%s-%s-%s.sql".formatted( + migration.getVersion(), + type.name().toLowerCase(Locale.ENGLISH), + migration.getMigrationName() + )); + } catch (SQLException e) { + plugin.log(Level.WARNING, "Migration " + migration.getMigrationName() + + " (v" + migration.getVersion() + ") failed; skipping", e); + } + } + } + setSchemaVersion(latestVersion); + plugin.log(Level.INFO, "Completed database migration (Target version: v" + latestVersion + ")"); + } + } + + /** + * Get the database schema version. + * + * @return the database schema version + */ + public abstract int getSchemaVersion(); + + /** + * Set the database schema version. + * + * @param version the database schema version + */ + public abstract void setSchemaVersion(int version); + /** * (Internal use only) - Sets a position to the position table in the database. * @@ -166,7 +249,7 @@ public abstract class Database { * @param name Username of the {@link SavedUser} to get (case-insensitive) * @return An optional with the {@link SavedUser} present if they exist */ - public abstract Optional getUserDataByName(@NotNull String name); + public abstract Optional getUser(@NotNull String name); /** * Get {@link SavedUser} for a user by their Minecraft account {@link UUID}. @@ -174,14 +257,14 @@ public abstract class Database { * @param uuid Minecraft account {@link UUID} of the {@link SavedUser} to get * @return An optional with the {@link SavedUser} present if they exist */ - public abstract Optional getUserData(@NotNull UUID uuid); + public abstract Optional getUser(@NotNull UUID uuid); /** * Delete a {@link SavedUser} from the database. * * @param uuid The {@link UUID} of the {@link SavedUser} to delete */ - public abstract void deleteUserData(@NotNull UUID uuid); + public abstract void deleteUser(@NotNull UUID uuid); /** * Get the currently active cooldown of a {@link User} for a specific {@link TransactionResolver.Action}. @@ -479,10 +562,9 @@ public abstract class Database { public abstract int deleteAllWarps(@NotNull String worldName, @NotNull String serverName); /** - * Close any remaining connection to the database source. + * Close the database connection. */ - public abstract void terminate(); - + public abstract void close(); /** * Identifies types of databases. @@ -506,6 +588,7 @@ public abstract class Database { @Getter @AllArgsConstructor public enum Table { + META_DATA("huskhomes_metadata"), PLAYER_DATA("huskhomes_users"), PLAYER_COOLDOWNS_DATA("huskhomes_user_cooldowns"), POSITION_DATA("huskhomes_position_data"), @@ -514,8 +597,19 @@ public abstract class Database { WARP_DATA("huskhomes_warps"), TELEPORT_DATA("huskhomes_teleports"); + @NotNull private final String defaultName; + @NotNull + public static Database.Table match(@NotNull String placeholder) throws IllegalArgumentException { + return Table.valueOf(placeholder.toUpperCase(Locale.ENGLISH)); + } + + @NotNull + public String getDefaultName() { + return defaultName; + } + @NotNull public static Map getConfigMap() { return Arrays.stream(values()).collect( @@ -524,4 +618,49 @@ public abstract class Database { } } + + /** + * Represents database migrations that need to be run. + */ + public enum Migration { + ADD_METADATA_TABLE( + 0, "add_metadata_table", + Type.MYSQL, Type.MARIADB, Type.POSTGRESQL, Type.SQLITE, Type.H2 + ); + + private final int version; + private final String migrationName; + private final Type[] supportedTypes; + + Migration(int version, @NotNull String migrationName, @NotNull Type... supportedTypes) { + this.version = version; + this.migrationName = migrationName; + this.supportedTypes = supportedTypes; + } + + private int getVersion() { + return version; + } + + private String getMigrationName() { + return migrationName; + } + + private boolean isSupported(@NotNull Type type) { + return Arrays.stream(supportedTypes).anyMatch(supportedType -> supportedType == type); + } + + @NotNull + public static List getOrderedMigrations() { + return Arrays.stream(Migration.values()) + .sorted(Comparator.comparingInt(Migration::getVersion)) + .collect(Collectors.toList()); + } + + public static int getLatestVersion() { + return getOrderedMigrations().get(getOrderedMigrations().size() - 1).getVersion(); + } + + } + } diff --git a/common/src/main/java/net/william278/huskhomes/database/DatabaseProvider.java b/common/src/main/java/net/william278/huskhomes/database/DatabaseProvider.java new file mode 100644 index 00000000..7e69e399 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/database/DatabaseProvider.java @@ -0,0 +1,74 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.database; + +import net.william278.huskhomes.HuskHomes; +import org.jetbrains.annotations.NotNull; + +public interface DatabaseProvider { + + @NotNull + String DATA_POOL_NAME = "HuskHomesHikariPool"; + + @NotNull + Database getDatabase(); + + void setDatabase(@NotNull Database database); + + void closeDatabase(); + + default void loadDatabase() throws IllegalStateException { + // Create database instance + final Database database = createDatabase(); + + // Initialize database + database.initialize(); + if (!database.isLoaded()) { + throw new IllegalStateException("Failed to initialize database"); + } + + // Set database + setDatabase(database); + } + + @NotNull + private Database createDatabase() { + final Database.Type type = getPlugin().getSettings().getDatabase().getType(); + switch (type) { + case MYSQL, MARIADB -> { + return new MySqlDatabase(getPlugin()); + } + case POSTGRESQL -> { + return new PostgreSqlDatabase(getPlugin()); + } + case SQLITE -> { + return new SqLiteDatabase(getPlugin()); + } + case H2 -> { + return new H2Database(getPlugin()); + } + default -> throw new IllegalStateException("Unexpected value: " + type); + } + } + + @NotNull + HuskHomes getPlugin(); + +} diff --git a/common/src/main/java/net/william278/huskhomes/database/H2Database.java b/common/src/main/java/net/william278/huskhomes/database/H2Database.java index b4d6b3af..8ecf123b 100644 --- a/common/src/main/java/net/william278/huskhomes/database/H2Database.java +++ b/common/src/main/java/net/william278/huskhomes/database/H2Database.java @@ -31,8 +31,7 @@ import org.h2.jdbcx.JdbcConnectionPool; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.File; -import java.io.IOException; +import java.nio.file.Path; import java.sql.*; import java.time.Instant; import java.util.*; @@ -47,7 +46,7 @@ public class H2Database extends Database { /** * Path to the H2 HuskHomesData.h2 file. */ - private final File databaseFile; + private final Path databaseFile; /** * The name of the database file. @@ -58,7 +57,7 @@ public class H2Database extends Database { public H2Database(@NotNull HuskHomes plugin) { super(plugin); - this.databaseFile = plugin.getConfigDirectory().resolve(DATABASE_FILE_NAME).toFile(); + this.databaseFile = plugin.getConfigDirectory().resolve(DATABASE_FILE_NAME); } /** @@ -71,29 +70,112 @@ public class H2Database extends Database { return connectionPool.getConnection(); } + @SuppressWarnings("SqlSourceToSinkFlow") @Override - public void initialize() throws IllegalStateException { + protected void executeScript(@NotNull Connection connection, @NotNull String name) throws SQLException { + try (Statement statement = connection.createStatement()) { + for (String schemaStatement : getScript(name)) { + statement.execute(schemaStatement); + } + } + } + + @Override + public void initialize() throws RuntimeException { + // Backup database file + this.backupFlatFile(databaseFile); + // Prepare the database flat file - final String url = String.format("jdbc:h2:%s", databaseFile.getAbsolutePath()); + final String url = String.format("jdbc:h2:%s", databaseFile.toAbsolutePath()); this.connectionPool = JdbcConnectionPool.create(url, "sa", "sa"); - // Prepare database schema; make tables if they don't exist - try (Connection connection = getConnection()) { - final String[] databaseSchema = getSchemaStatements("database/h2_schema.sql"); - try (Statement statement = connection.createStatement()) { - for (String tableCreationStatement : databaseSchema) { - statement.execute(tableCreationStatement); - } + // Create tables + if (!isCreated()) { + plugin.log(Level.INFO, "Creating H2 database tables"); + try { + executeScript(getConnection(), "h2_schema.sql"); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to create H2 database tables"); + setLoaded(false); + return; } - } catch (SQLException | IOException e) { - throw new IllegalStateException("Failed to initialize the H2 database", e); + setSchemaVersion(Migration.getLatestVersion()); + plugin.log(Level.INFO, "H2 database tables created!"); + setLoaded(true); + return; + } + + // Perform migrations + try { + performMigrations(getConnection(), Type.H2); + setLoaded(true); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to perform H2 database migrations"); + setLoaded(false); + } + } + + @Override + public boolean isCreated() { + if (!databaseFile.toFile().exists()) { + return false; + } + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + SELECT `uuid` + FROM `%player_data%` + LIMIT 1;"""))) { + statement.executeQuery(); + return true; + } catch (SQLException e) { + return false; + } + } + + @Override + public int getSchemaVersion() { + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + SELECT `schema_version` + FROM `%meta_data%` + LIMIT 1;"""))) { + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return resultSet.getInt("schema_version"); + } + } catch (SQLException e) { + plugin.log(Level.WARNING, "The database schema version could not be fetched; " + + "migrations will be carried out."); + } + return -1; + } + + @Override + public void setSchemaVersion(int version) { + if (getSchemaVersion() == -1) { + try (PreparedStatement insertStatement = getConnection().prepareStatement(format(""" + INSERT INTO `%meta_data%` (`schema_version`) + VALUES (?);"""))) { + insertStatement.setInt(1, version); + insertStatement.executeUpdate(); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to insert schema version in table", e); + } + return; + } + + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + UPDATE `%meta_data%` + SET `schema_version` = ?;"""))) { + statement.setInt(1, version); + statement.executeUpdate(); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to update schema version in table", e); } } @Override protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%positions_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO `%position_data%` (`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`) VALUES (?,?,?,?,?,?,?,?);"""), @@ -120,8 +202,8 @@ public class H2Database extends Database { @Override protected void updatePosition(int positionId, @NotNull Position position, @NotNull Connection connection) throws SQLException { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%positions_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + UPDATE `%position_data%` SET `x`=?, `y`=?, `z`=?, @@ -147,8 +229,8 @@ public class H2Database extends Database { @Override protected int setSavedPosition(@NotNull SavedPosition position, @NotNull Connection connection) throws SQLException { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%saved_positions_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO `%saved_position_data%` (`position_id`, `name`, `description`, `tags`, `timestamp`) VALUES (?,?,?,?,?);"""), @@ -172,9 +254,9 @@ public class H2Database extends Database { @Override protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position, @NotNull Connection connection) throws SQLException { - try (PreparedStatement selectStatement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement selectStatement = connection.prepareStatement(format(""" SELECT `position_id` - FROM `%saved_positions_table%` + FROM `%saved_position_data%` WHERE `id`=?;"""))) { selectStatement.setInt(1, savedPositionId); @@ -183,8 +265,8 @@ public class H2Database extends Database { final int positionId = resultSet.getInt("position_id"); updatePosition(positionId, position, connection); - try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%saved_positions_table%` + try (PreparedStatement updateStatement = connection.prepareStatement(format(""" + UPDATE `%saved_position_data%` SET `name`=?, `description`=?, `tags`=? @@ -201,23 +283,23 @@ public class H2Database extends Database { @Override public void ensureUser(@NotNull User onlineUser) { - getUserData(onlineUser.getUuid()).ifPresentOrElse( + getUser(onlineUser.getUuid()).ifPresentOrElse( existingUserData -> { - if (!existingUserData.getUsername().equals(onlineUser.getUsername())) { + if (!existingUserData.getUsername().equals(onlineUser.getName())) { // Update a player's name if it has changed in the database try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + UPDATE `%player_data%` SET `username`=? WHERE `uuid`=?"""))) { - statement.setString(1, onlineUser.getUsername()); + statement.setString(1, onlineUser.getName()); statement.setString(2, existingUserData.getUserUuid().toString()); statement.executeUpdate(); } - plugin.log(Level.INFO, "Updated " + onlineUser.getUsername() - + "'s name in the database (" + existingUserData.getUsername() - + " -> " + onlineUser.getUsername() + ")"); + plugin.log(Level.INFO, "Updated " + onlineUser.getName() + + "'s name in the database (" + existingUserData.getUsername() + + " -> " + onlineUser.getName() + ")"); } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e); } @@ -226,12 +308,12 @@ public class H2Database extends Database { () -> { // Insert new player data into the database try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%players_table%` (`uuid`,`username`) + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO `%player_data%` (`uuid`,`username`) VALUES (?,?);"""))) { statement.setString(1, onlineUser.getUuid().toString()); - statement.setString(2, onlineUser.getUsername()); + statement.setString(2, onlineUser.getName()); statement.executeUpdate(); } } catch (SQLException e) { @@ -241,11 +323,11 @@ public class H2Database extends Database { } @Override - public Optional getUserDataByName(@NotNull String name) { + public Optional getUser(@NotNull String name) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT `uuid`, `username`, `home_slots`, `ignoring_requests` - FROM `%players_table%` + FROM `%player_data%` WHERE `username`=?"""))) { statement.setString(1, name); @@ -266,11 +348,11 @@ public class H2Database extends Database { } @Override - public Optional getUserData(@NotNull UUID uuid) { + public Optional getUser(@NotNull UUID uuid) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT `uuid`, `username`, `home_slots`, `ignoring_requests` - FROM `%players_table%` + FROM `%player_data%` WHERE `uuid`=?"""))) { statement.setString(1, uuid.toString()); @@ -292,22 +374,22 @@ public class H2Database extends Database { } @Override - public void deleteUserData(@NotNull UUID uuid) { + public void deleteUser(@NotNull UUID uuid) { try (Connection connection = getConnection()) { // Delete Position - PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` + PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` WHERE `id` - IN ((SELECT `last_position` FROM `%players_table%` WHERE `uuid` = ?), - (SELECT `offline_position` FROM `%players_table%` WHERE `uuid` = ?), - (SELECT `respawn_position` FROM `%players_table%` WHERE `uuid` = ?));""")); + IN ((SELECT `last_position` FROM `%player_data%` WHERE `uuid` = ?), + (SELECT `offline_position` FROM `%player_data%` WHERE `uuid` = ?), + (SELECT `respawn_position` FROM `%player_data%` WHERE `uuid` = ?));""")); statement.setString(1, uuid.toString()); statement.setString(2, uuid.toString()); statement.setString(3, uuid.toString()); statement.executeUpdate(); - statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%players_table%` + statement = connection.prepareStatement(format(""" + DELETE FROM `%player_data%` WHERE `uuid`=?;""")); statement.setString(1, uuid.toString()); statement.executeUpdate(); @@ -320,9 +402,9 @@ public class H2Database extends Database { @Override public Optional getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT `type`, `start_timestamp`, `end_timestamp` - FROM `%cooldowns_table%` + FROM `%player_cooldowns_data%` WHERE `player_uuid`=? AND `type`=? ORDER BY `start_timestamp` DESC LIMIT 1;"""))) { @@ -344,8 +426,8 @@ public class H2Database extends Database { public void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user, @NotNull Instant cooldownExpiry) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%cooldowns_table%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`) + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO `%player_cooldowns_data%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`) VALUES (?,?,?,?);"""))) { statement.setString(1, user.getUuid().toString()); statement.setString(2, action.name().toLowerCase(Locale.ENGLISH)); @@ -361,8 +443,8 @@ public class H2Database extends Database { @Override public void removeCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%cooldowns_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM `%player_cooldowns_data%` WHERE `player_uuid`=? AND `type`=?;"""))) { statement.setString(1, user.getUuid().toString()); @@ -378,16 +460,16 @@ public class H2Database extends Database { public List getHomes(@NotNull User user) { final List userHomes = new ArrayList<>(); try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` - ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` - ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + FROM `%home_data%` + INNER JOIN `%saved_position_data%` + ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` + INNER JOIN `%player_data%` + ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid` WHERE `owner_uuid`=? ORDER BY `name`;"""))) { @@ -413,7 +495,7 @@ public class H2Database extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getUsername()); + plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getName()); } return userHomes; } @@ -422,14 +504,14 @@ public class H2Database extends Database { public List getWarps() { final List warps = new ArrayList<>(); try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `%warp_data%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` - ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + FROM `%warp_data%` + INNER JOIN `%saved_position_data%` + ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` ORDER BY `name`;"""))) { final ResultSet resultSet = statement.executeQuery(); @@ -459,17 +541,17 @@ public class H2Database extends Database { public List getPublicHomes() { final List userHomes = new ArrayList<>(); try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` - ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` - ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + FROM `%home_data%` + INNER JOIN `%saved_position_data%` + ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` + INNER JOIN `%player_data%` + ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid` WHERE `public`=true ORDER BY `name`;"""))) { final ResultSet resultSet = statement.executeQuery(); @@ -502,17 +584,17 @@ public class H2Database extends Database { public List getPublicHomes(@NotNull String name, boolean caseInsensitive) { final List userHomes = new ArrayList<>(); try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` - ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + FROM `%home_data%` + INNER JOIN `%saved_position_data%` + ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id` INNER JOIN `%positions_table` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` INNER JOIN `%players_table` - ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid` WHERE `public`=true AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?)) ORDER BY `name`;"""))) { @@ -549,17 +631,17 @@ public class H2Database extends Database { @Override public Optional getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` - ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` - ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + FROM `%home_data%` + INNER JOIN `%saved_position_data%` + ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` + INNER JOIN `%player_data%` + ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid` WHERE `owner_uuid`=? AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { statement.setString(1, user.getUuid().toString()); @@ -595,18 +677,18 @@ public class H2Database extends Database { @Override public Optional getHome(@NotNull UUID uuid) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` - ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` - ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` - WHERE `%homes_table%`.`uuid`=?;"""))) { + FROM `%home_data%` + INNER JOIN `%saved_position_data%` + ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` + INNER JOIN `%player_data%` + ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid` + WHERE `%home_data%`.`uuid`=?;"""))) { statement.setString(1, uuid.toString()); final ResultSet resultSet = statement.executeQuery(); @@ -638,14 +720,14 @@ public class H2Database extends Database { @Override public Optional getWarp(@NotNull String warpName, boolean caseInsensitive) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `%warp_data%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` - ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + FROM `%warp_data%` + INNER JOIN `%saved_position_data%` + ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { statement.setBoolean(1, caseInsensitive); statement.setString(2, warpName); @@ -677,15 +759,15 @@ public class H2Database extends Database { @Override public Optional getWarp(@NotNull UUID uuid) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `%warp_data%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` - ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - WHERE `%warps_table%`.uuid=?;"""))) { + FROM `%warp_data%` + INNER JOIN `%saved_position_data%` + ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` + WHERE `%warp_data%`.uuid=?;"""))) { statement.setString(1, uuid.toString()); final ResultSet resultSet = statement.executeQuery(); @@ -714,10 +796,10 @@ public class H2Database extends Database { @Override public Optional getCurrentTeleport(@NotNull OnlineUser onlineUser) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `type` - FROM `%teleports_table%` - INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id` + FROM `%teleport_data%` + INNER JOIN `%position_data%` ON `%teleport_data%`.`destination_id` = `%position_data%`.`id` WHERE `player_uuid`=?"""))) { statement.setString(1, onlineUser.getUuid().toString()); @@ -740,7 +822,7 @@ public class H2Database extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getName(), e); } catch (TeleportationException e) { e.displayMessage(onlineUser); } @@ -750,8 +832,8 @@ public class H2Database extends Database { @Override public void updateUserData(@NotNull SavedUser savedUser) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + UPDATE `%player_data%` SET `home_slots`=?, `ignoring_requests`=? WHERE `uuid`=?"""))) { @@ -769,12 +851,12 @@ public class H2Database extends Database { public void setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) { try (Connection connection = getConnection()) { // Clear the user's current teleport - try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` + try (PreparedStatement deleteStatement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` WHERE `id`=( SELECT `destination_id` - FROM `%teleports_table%` - WHERE `%teleports_table%`.`player_uuid`=? + FROM `%teleport_data%` + WHERE `%teleport_data%`.`player_uuid`=? );"""))) { deleteStatement.setString(1, user.getUuid().toString()); deleteStatement.executeUpdate(); @@ -782,8 +864,8 @@ public class H2Database extends Database { // Set the user's teleport into the database (if it's not null) if (teleport != null) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`) + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO `%teleport_data%` (`player_uuid`, `destination_id`, `type`) VALUES (?,?,?);"""))) { statement.setString(1, user.getUuid().toString()); statement.setInt(2, setPosition((Position) teleport.getTarget(), connection)); @@ -793,17 +875,17 @@ public class H2Database extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getName(), e); } } @Override public Optional getLastPosition(@NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`last_position` = `%positions_table%`.`id` + FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.`last_position` = `%position_data%`.`id` WHERE `uuid`=?"""))) { statement.setString(1, user.getUuid().toString()); @@ -820,7 +902,7 @@ public class H2Database extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getName(), e); } return Optional.empty(); } @@ -828,10 +910,10 @@ public class H2Database extends Database { @Override public void setLastPosition(@NotNull User user, @NotNull Position position) { try (Connection connection = getConnection()) { - try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement queryStatement = connection.prepareStatement(format(""" SELECT `last_position` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id` + FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.last_position = `%position_data%`.`id` WHERE `uuid`=?;"""))) { queryStatement.setString(1, user.getUuid().toString()); @@ -841,8 +923,8 @@ public class H2Database extends Database { updatePosition(resultSet.getInt("last_position"), position, connection); } else { // Set the last position - try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` + try (PreparedStatement updateStatement = connection.prepareStatement(format(""" + UPDATE `%player_data%` SET `last_position`=? WHERE `uuid`=?;"""))) { updateStatement.setInt(1, setPosition(position, connection)); @@ -852,17 +934,17 @@ public class H2Database extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getName(), e); } } @Override public Optional getOfflinePosition(@NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id` + FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.`offline_position` = `%position_data%`.`id` WHERE `uuid`=?"""))) { statement.setString(1, user.getUuid().toString()); @@ -879,7 +961,7 @@ public class H2Database extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getName(), e); } return Optional.empty(); } @@ -887,9 +969,9 @@ public class H2Database extends Database { @Override public void setOfflinePosition(@NotNull User user, @NotNull Position position) { try (Connection connection = getConnection()) { - try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" - SELECT `offline_position` FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id` + try (PreparedStatement queryStatement = connection.prepareStatement(format(""" + SELECT `offline_position` FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.`offline_position` = `%position_data%`.`id` WHERE `uuid`=?;"""))) { queryStatement.setString(1, user.getUuid().toString()); @@ -899,8 +981,8 @@ public class H2Database extends Database { updatePosition(resultSet.getInt("offline_position"), position, connection); } else { // Set the offline position - try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` + try (PreparedStatement updateStatement = connection.prepareStatement(format(""" + UPDATE `%player_data%` SET `offline_position`=? WHERE `uuid`=?;"""))) { updateStatement.setInt(1, setPosition(position, connection)); @@ -910,17 +992,17 @@ public class H2Database extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getName(), e); } } @Override public Optional getRespawnPosition(@NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`respawn_position` = `%positions_table%`.`id` + FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.`respawn_position` = `%position_data%`.`id` WHERE `uuid`=?"""))) { statement.setString(1, user.getUuid().toString()); @@ -937,7 +1019,7 @@ public class H2Database extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getName(), e); } return Optional.empty(); } @@ -945,9 +1027,9 @@ public class H2Database extends Database { @Override public void setRespawnPosition(@NotNull User user, @Nullable Position position) { try (Connection connection = getConnection()) { - try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" - SELECT `respawn_position` FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = `%positions_table%`.`id` + try (PreparedStatement queryStatement = connection.prepareStatement(format(""" + SELECT `respawn_position` FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.respawn_position = `%position_data%`.`id` WHERE `uuid`=?;"""))) { queryStatement.setString(1, user.getUuid().toString()); @@ -955,12 +1037,12 @@ public class H2Database extends Database { if (resultSet.next()) { if (position == null) { // Delete a respawn position - try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` + try (PreparedStatement deleteStatement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` WHERE `id`=( SELECT `respawn_position` - FROM `%players_table%` - WHERE `%players_table%`.`uuid`=? + FROM `%player_data%` + WHERE `%player_data%`.`uuid`=? );"""))) { deleteStatement.setString(1, user.getUuid().toString()); deleteStatement.executeUpdate(); @@ -972,8 +1054,8 @@ public class H2Database extends Database { } else { if (position != null) { // Set a respawn position - try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` + try (PreparedStatement updateStatement = connection.prepareStatement(format(""" + UPDATE `%player_data%` SET `respawn_position`=? WHERE `uuid`=?;"""))) { updateStatement.setInt(1, setPosition(position, connection)); @@ -984,7 +1066,7 @@ public class H2Database extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getName(), e); } } @@ -993,8 +1075,8 @@ public class H2Database extends Database { getHome(home.getUuid()).ifPresentOrElse(presentHome -> { try (Connection connection = getConnection()) { // Update the home's saved position, including metadata - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `saved_position_id` FROM `%homes_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `saved_position_id` FROM `%home_data%` WHERE `uuid`=?;"""))) { statement.setString(1, home.getUuid().toString()); @@ -1005,8 +1087,8 @@ public class H2Database extends Database { } // Update the home privacy - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%homes_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + UPDATE `%home_data%` SET `public`=? WHERE `uuid`=?;"""))) { statement.setBoolean(1, home.isPublic()); @@ -1015,12 +1097,12 @@ public class H2Database extends Database { } } catch (SQLException e) { plugin.log(Level.SEVERE, - "Failed to update a home in the database for " + home.getOwner().getUsername(), e); + "Failed to update a home in the database for " + home.getOwner().getName(), e); } }, () -> { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`) + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO `%home_data%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`) VALUES (?,?,?,?);"""))) { statement.setString(1, home.getUuid().toString()); statement.setInt(2, setSavedPosition(home, connection)); @@ -1031,7 +1113,7 @@ public class H2Database extends Database { } } catch (SQLException e) { plugin.log(Level.SEVERE, - "Failed to set a home to the database for " + home.getOwner().getUsername(), e); + "Failed to set a home to the database for " + home.getOwner().getName(), e); } }); } @@ -1040,8 +1122,8 @@ public class H2Database extends Database { public void saveWarp(@NotNull Warp warp) { getWarp(warp.getUuid()).ifPresentOrElse(presentWarp -> { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `saved_position_id` FROM `%warps_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `saved_position_id` FROM `%warp_data%` WHERE `uuid`=?;"""))) { statement.setString(1, warp.getUuid().toString()); @@ -1055,8 +1137,8 @@ public class H2Database extends Database { } }, () -> { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`) + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO `%warp_data%` (`uuid`, `saved_position_id`) VALUES (?,?);"""))) { statement.setString(1, warp.getUuid().toString()); statement.setInt(2, setSavedPosition(warp, connection)); @@ -1072,14 +1154,14 @@ public class H2Database extends Database { @Override public void deleteHome(@NotNull UUID uuid) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id`=( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id`=( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id`=( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id`=( SELECT `saved_position_id` - FROM `%homes_table%` + FROM `%home_data%` WHERE `uuid`=? ) );"""))) { @@ -1095,14 +1177,14 @@ public class H2Database extends Database { @Override public int deleteAllHomes(@NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id` IN ( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id` IN ( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id` IN ( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id` IN ( SELECT `saved_position_id` - FROM `%homes_table%` + FROM `%home_data%` WHERE `owner_uuid`=? ) );"""))) { @@ -1111,7 +1193,7 @@ public class H2Database extends Database { return statement.executeUpdate(); } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getUsername() + " from the database", e); + plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getName() + " from the database", e); } return 0; } @@ -1119,14 +1201,14 @@ public class H2Database extends Database { @Override public int deleteAllHomes(@NotNull String worldName, @NotNull String serverName) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id` IN ( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id` IN ( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id` IN ( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id` IN ( SELECT `saved_position_id` - FROM `%homes_table%` + FROM `%home_data%` WHERE `world_name`=? AND `server_name`=? ) @@ -1138,7 +1220,7 @@ public class H2Database extends Database { } } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to delete homes in the world " + worldName + " on the server " - + serverName + " from the database", e); + + serverName + " from the database", e); } return 0; } @@ -1146,14 +1228,14 @@ public class H2Database extends Database { @Override public void deleteWarp(@NotNull UUID uuid) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id`=( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id`=( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id`=( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id`=( SELECT `saved_position_id` - FROM `%warps_table%` + FROM `%warp_data%` WHERE `uuid`=? ) );"""))) { @@ -1169,14 +1251,14 @@ public class H2Database extends Database { @Override public int deleteAllWarps() { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id` IN ( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id` IN ( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id` IN ( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id` IN ( SELECT `saved_position_id` - FROM `%warps_table%` + FROM `%warp_data%` ) );"""))) { return statement.executeUpdate(); @@ -1190,14 +1272,14 @@ public class H2Database extends Database { @Override public int deleteAllWarps(@NotNull String worldName, @NotNull String serverName) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id` IN ( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id` IN ( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id` IN ( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id` IN ( SELECT `saved_position_id` - FROM `%warps_table%` + FROM `%warp_data%` WHERE `world_name`=? AND `server_name`=? ) @@ -1209,13 +1291,13 @@ public class H2Database extends Database { } } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to delete warps in the world " + worldName + " on the server " - + serverName + " from the database", e); + + serverName + " from the database", e); } return 0; } @Override - public void terminate() { + public void close() { if (connectionPool != null) { connectionPool.dispose(); } diff --git a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java index c9b1d9d5..4a0d13df 100644 --- a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java @@ -28,17 +28,16 @@ import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.user.User; import net.william278.huskhomes.util.TransactionResolver; -import org.jetbrains.annotations.Blocking; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.IOException; import java.sql.*; import java.time.Instant; import java.util.*; import java.util.logging.Level; import static net.william278.huskhomes.config.Settings.DatabaseSettings; +import static net.william278.huskhomes.database.DatabaseProvider.DATA_POOL_NAME; /** * A MySQL / MariaDB implementation of the plugin {@link Database}. @@ -46,39 +45,27 @@ import static net.william278.huskhomes.config.Settings.DatabaseSettings; @SuppressWarnings("DuplicatedCode") public class MySqlDatabase extends Database { - private static final String DATA_POOL_NAME = "HuskHomesHikariPool"; private final String flavor; private final String driverClass; private HikariDataSource dataSource; public MySqlDatabase(@NotNull HuskHomes plugin) { super(plugin); - - final Type type = plugin.getSettings().getDatabase().getType(); - this.flavor = type.getProtocol(); - this.driverClass = type == Type.MARIADB ? "org.mariadb.jdbc.Driver" : "com.mysql.cj.jdbc.Driver"; + this.flavor = plugin.getSettings().getDatabase().getType() == Type.MARIADB + ? "mariadb" : "mysql"; + this.driverClass = plugin.getSettings().getDatabase().getType() == Type.MARIADB + ? "org.mariadb.jdbc.Driver" : "com.mysql.cj.jdbc.Driver"; } - /** - * Fetch the auto-closeable connection from the hikariDataSource. - * - * @return The {@link Connection} to the MySQL database - * @throws SQLException if the connection fails for some reason - */ - @Blocking - @NotNull private Connection getConnection() throws SQLException { - if (dataSource == null) { - throw new IllegalStateException("The database has not been initialized"); - } return dataSource.getConnection(); } - @Blocking - @Override - public void initialize() throws IllegalStateException { + private void setConnection() { // Initialize the Hikari pooled connection - final DatabaseSettings.DatabaseCredentials credentials = plugin.getSettings().getDatabase().getCredentials(); + final DatabaseSettings databaseSettings = plugin.getSettings().getDatabase(); + final DatabaseSettings.DatabaseCredentials credentials = databaseSettings.getCredentials(); + dataSource = new HikariDataSource(); dataSource.setDriverClassName(driverClass); dataSource.setJdbcUrl(String.format("jdbc:%s://%s:%s/%s%s", @@ -94,12 +81,12 @@ public class MySqlDatabase extends Database { dataSource.setPassword(credentials.getPassword()); // Set connection pool options - final DatabaseSettings.PoolOptions pool = plugin.getSettings().getDatabase().getPoolOptions(); - dataSource.setMaximumPoolSize(pool.getSize()); - dataSource.setMinimumIdle(pool.getIdle()); - dataSource.setMaxLifetime(pool.getLifetime()); - dataSource.setKeepaliveTime(pool.getKeepAlive()); - dataSource.setConnectionTimeout(pool.getTimeout()); + final DatabaseSettings.PoolOptions poolOptions = databaseSettings.getPoolOptions(); + dataSource.setMaximumPoolSize(poolOptions.getSize()); + dataSource.setMinimumIdle(poolOptions.getIdle()); + dataSource.setMaxLifetime(poolOptions.getLifetime()); + dataSource.setKeepaliveTime(poolOptions.getKeepAlive()); + dataSource.setConnectionTimeout(poolOptions.getTimeout()); dataSource.setPoolName(DATA_POOL_NAME); // Set additional connection pool properties @@ -121,28 +108,115 @@ public class MySqlDatabase extends Database { "maintainTimeStats", "false") ); dataSource.setDataSourceProperties(properties); + } - // Prepare database schema; make tables if they don't exist - try (Connection connection = dataSource.getConnection()) { - final String[] databaseSchema = getSchemaStatements(String.format("database/%s_schema.sql", flavor)); - try (Statement statement = connection.createStatement()) { - for (String tableCreationStatement : databaseSchema) { - statement.execute(tableCreationStatement); + @SuppressWarnings("SqlSourceToSinkFlow") + @Override + protected void executeScript(@NotNull Connection connection, @NotNull String name) throws SQLException { + try (Statement statement = connection.createStatement()) { + for (String schemaStatement : getScript(name)) { + statement.execute(schemaStatement); + } + } + } + + @Override + public void initialize() throws RuntimeException { + // Establish connection + this.setConnection(); + + // Create tables + if (!isCreated()) { + plugin.log(Level.INFO, "Creating MySQL database tables"); + try { + executeScript(getConnection(), String.format("%s_schema.sql", flavor)); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to create MySQL database tables", e); + setLoaded(false); + return; + } + setSchemaVersion(Migration.getLatestVersion()); + plugin.log(Level.INFO, "MySQL database tables created!"); + setLoaded(true); + return; + } + + // Perform migrations + try { + performMigrations(getConnection(), plugin.getSettings().getDatabase().getType()); + setLoaded(true); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to perform MySQL database migrations", e); + setLoaded(false); + } + } + + @Override + public boolean isCreated() { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `uuid` + FROM `%player_data%` + LIMIT 1;"""))) { + statement.executeQuery(); + return true; + } + } catch (SQLException e) { + return false; + } + } + + @Override + public int getSchemaVersion() { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `schema_version` + FROM `%meta_data%` + LIMIT 1;"""))) { + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return resultSet.getInt("schema_version"); + } + } + } catch (SQLException e) { + plugin.log(Level.WARNING, "The database schema version could not be fetched; " + + "migrations will be carried out."); + } + return -1; + } + + @Override + public void setSchemaVersion(int version) { + if (getSchemaVersion() == -1) { + try (Connection connection = getConnection()) { + try (PreparedStatement insertStatement = connection.prepareStatement(format(""" + INSERT INTO `%meta_data%` (`schema_version`) + VALUES (?)"""))) { + insertStatement.setInt(1, version); + insertStatement.executeUpdate(); } } catch (SQLException e) { - throw new IllegalStateException("Failed to create database tables. Please ensure you are running " - + "MySQL v8.0+ and that your connecting user account has privileges to create tables.", e); + plugin.log(Level.SEVERE, "Failed to insert schema version in table", e); } - } catch (SQLException | IOException e) { - throw new IllegalStateException("Failed to establish a connection to the MySQL database. " - + "Please check the supplied database credentials in the config file", e); + return; + } + + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(format(""" + UPDATE `%meta_data%` + SET `schema_version` = ?;"""))) { + statement.setInt(1, version); + statement.executeUpdate(); + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to update schema version in table", e); } } @Override protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%positions_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO `%position_data%` (`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`) VALUES (?,?,?,?,?,?,?,?);"""), @@ -169,8 +243,8 @@ public class MySqlDatabase extends Database { @Override protected void updatePosition(int positionId, @NotNull Position position, @NotNull Connection connection) throws SQLException { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%positions_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + UPDATE `%position_data%` SET `x`=?, `y`=?, `z`=?, @@ -196,8 +270,8 @@ public class MySqlDatabase extends Database { @Override protected int setSavedPosition(@NotNull SavedPosition position, @NotNull Connection connection) throws SQLException { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%saved_positions_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO `%saved_position_data%` (`position_id`, `name`, `description`, `tags`, `timestamp`) VALUES (?,?,?,?,?);"""), @@ -221,9 +295,9 @@ public class MySqlDatabase extends Database { @Override protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position, @NotNull Connection connection) throws SQLException { - try (PreparedStatement selectStatement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement selectStatement = connection.prepareStatement(format(""" SELECT `position_id` - FROM `%saved_positions_table%` + FROM `%saved_position_data%` WHERE `id`=?;"""))) { selectStatement.setInt(1, savedPositionId); @@ -232,8 +306,8 @@ public class MySqlDatabase extends Database { final int positionId = resultSet.getInt("position_id"); updatePosition(positionId, position, connection); - try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%saved_positions_table%` + try (PreparedStatement updateStatement = connection.prepareStatement(format(""" + UPDATE `%saved_position_data%` SET `name`=?, `description`=?, `tags`=? @@ -250,23 +324,23 @@ public class MySqlDatabase extends Database { @Override public void ensureUser(@NotNull User onlineUser) { - getUserData(onlineUser.getUuid()).ifPresentOrElse( + getUser(onlineUser.getUuid()).ifPresentOrElse( existingUserData -> { - if (!existingUserData.getUsername().equals(onlineUser.getUsername())) { + if (!existingUserData.getUsername().equals(onlineUser.getName())) { // Update a player's name if it has changed in the database try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + UPDATE `%player_data%` SET `username`=? WHERE `uuid`=?"""))) { - statement.setString(1, onlineUser.getUsername()); + statement.setString(1, onlineUser.getName()); statement.setString(2, existingUserData.getUserUuid().toString()); statement.executeUpdate(); } - plugin.log(Level.INFO, "Updated " + onlineUser.getUsername() - + "'s name in the database (" + existingUserData.getUsername() - + " -> " + onlineUser.getUsername() + ")"); + plugin.log(Level.INFO, "Updated " + onlineUser.getName() + + "'s name in the database (" + existingUserData.getUsername() + + " -> " + onlineUser.getName() + ")"); } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e); } @@ -275,12 +349,12 @@ public class MySqlDatabase extends Database { () -> { // Insert new player data into the database try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%players_table%` (`uuid`,`username`) + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO `%player_data%` (`uuid`,`username`) VALUES (?,?);"""))) { statement.setString(1, onlineUser.getUuid().toString()); - statement.setString(2, onlineUser.getUsername()); + statement.setString(2, onlineUser.getName()); statement.executeUpdate(); } } catch (SQLException e) { @@ -290,11 +364,11 @@ public class MySqlDatabase extends Database { } @Override - public Optional getUserDataByName(@NotNull String name) { + public Optional getUser(@NotNull String name) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT `uuid`, `username`, `home_slots`, `ignoring_requests` - FROM `%players_table%` + FROM `%player_data%` WHERE `username`=?"""))) { statement.setString(1, name); @@ -315,11 +389,11 @@ public class MySqlDatabase extends Database { } @Override - public Optional getUserData(@NotNull UUID uuid) { + public Optional getUser(@NotNull UUID uuid) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT `uuid`, `username`, `home_slots`, `ignoring_requests` - FROM `%players_table%` + FROM `%player_data%` WHERE `uuid`=?"""))) { statement.setString(1, uuid.toString()); @@ -341,14 +415,14 @@ public class MySqlDatabase extends Database { } @Override - public void deleteUserData(@NotNull UUID uuid) { + public void deleteUser(@NotNull UUID uuid) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` WHERE `id` - IN ((SELECT `last_position` FROM `%players_table%` WHERE `uuid` = ?), - (SELECT `offline_position` FROM `%players_table%` WHERE `uuid` = ?), - (SELECT `respawn_position` FROM `%players_table%` WHERE `uuid` = ?));"""))) { + IN ((SELECT `last_position` FROM `%player_data%` WHERE `uuid` = ?), + (SELECT `offline_position` FROM `%player_data%` WHERE `uuid` = ?), + (SELECT `respawn_position` FROM `%player_data%` WHERE `uuid` = ?));"""))) { statement.setString(1, uuid.toString()); statement.setString(2, uuid.toString()); statement.setString(3, uuid.toString()); @@ -358,8 +432,8 @@ public class MySqlDatabase extends Database { return; } - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%players_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM `%player_data%` WHERE `uuid`=?;"""))) { statement.setString(1, uuid.toString()); statement.executeUpdate(); @@ -374,9 +448,9 @@ public class MySqlDatabase extends Database { @Override public Optional getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT `type`, `start_timestamp`, `end_timestamp` - FROM `%cooldowns_table%` + FROM `%player_cooldowns_data%` WHERE `player_uuid`=? AND `type`=? ORDER BY `start_timestamp` DESC LIMIT 1;"""))) { @@ -398,8 +472,8 @@ public class MySqlDatabase extends Database { public void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user, @NotNull Instant cooldownExpiry) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%cooldowns_table%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`) + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO `%player_cooldowns_data%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`) VALUES (?,?,?,?);"""))) { statement.setString(1, user.getUuid().toString()); statement.setString(2, action.name().toLowerCase(Locale.ENGLISH)); @@ -415,8 +489,8 @@ public class MySqlDatabase extends Database { @Override public void removeCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%cooldowns_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM `%player_cooldowns_data%` WHERE `player_uuid`=? AND `type`=?;"""))) { statement.setString(1, user.getUuid().toString()); @@ -432,16 +506,16 @@ public class MySqlDatabase extends Database { public List getHomes(@NotNull User user) { final List userHomes = new ArrayList<>(); try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` - ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` - ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + FROM `%home_data%` + INNER JOIN `%saved_position_data%` + ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` + INNER JOIN `%player_data%` + ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid` WHERE `owner_uuid`=? ORDER BY `name`;"""))) { @@ -467,7 +541,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getUsername()); + plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getName()); } return userHomes; } @@ -476,14 +550,14 @@ public class MySqlDatabase extends Database { public List getWarps() { final List warps = new ArrayList<>(); try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `%warp_data%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` - ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + FROM `%warp_data%` + INNER JOIN `%saved_position_data%` + ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` ORDER BY `name`;"""))) { final ResultSet resultSet = statement.executeQuery(); @@ -513,17 +587,17 @@ public class MySqlDatabase extends Database { public List getPublicHomes() { final List userHomes = new ArrayList<>(); try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` - ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` - ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + FROM `%home_data%` + INNER JOIN `%saved_position_data%` + ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` + INNER JOIN `%player_data%` + ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid` WHERE `public`=true ORDER BY `name`;"""))) { final ResultSet resultSet = statement.executeQuery(); @@ -556,17 +630,17 @@ public class MySqlDatabase extends Database { public List getPublicHomes(@NotNull String name, boolean caseInsensitive) { final List userHomes = new ArrayList<>(); try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` - ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` - ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + FROM `%home_data%` + INNER JOIN `%saved_position_data%` + ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` + INNER JOIN `%player_data%` + ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid` WHERE `public`=true AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?)) ORDER BY `name`;"""))) { @@ -603,17 +677,17 @@ public class MySqlDatabase extends Database { @Override public Optional getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` - ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` - ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + FROM `%home_data%` + INNER JOIN `%saved_position_data%` + ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` + INNER JOIN `%player_data%` + ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid` WHERE `owner_uuid`=? AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { statement.setString(1, user.getUuid().toString()); @@ -649,18 +723,18 @@ public class MySqlDatabase extends Database { @Override public Optional getHome(@NotNull UUID uuid) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` - ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` - ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` - WHERE `%homes_table%`.`uuid`=?;"""))) { + FROM `%home_data%` + INNER JOIN `%saved_position_data%` + ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` + INNER JOIN `%player_data%` + ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid` + WHERE `%home_data%`.`uuid`=?;"""))) { statement.setString(1, uuid.toString()); final ResultSet resultSet = statement.executeQuery(); @@ -692,14 +766,14 @@ public class MySqlDatabase extends Database { @Override public Optional getWarp(@NotNull String warpName, boolean caseInsensitive) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `%warp_data%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` - ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + FROM `%warp_data%` + INNER JOIN `%saved_position_data%` + ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { statement.setBoolean(1, caseInsensitive); statement.setString(2, warpName); @@ -731,15 +805,15 @@ public class MySqlDatabase extends Database { @Override public Optional getWarp(@NotNull UUID uuid) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `%warp_data%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` - ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - WHERE `%warps_table%`.uuid=?;"""))) { + FROM `%warp_data%` + INNER JOIN `%saved_position_data%` + ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` + WHERE `%warp_data%`.uuid=?;"""))) { statement.setString(1, uuid.toString()); final ResultSet resultSet = statement.executeQuery(); @@ -768,10 +842,10 @@ public class MySqlDatabase extends Database { @Override public Optional getCurrentTeleport(@NotNull OnlineUser onlineUser) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `type` - FROM `%teleports_table%` - INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id` + FROM `%teleport_data%` + INNER JOIN `%position_data%` ON `%teleport_data%`.`destination_id` = `%position_data%`.`id` WHERE `player_uuid`=?"""))) { statement.setString(1, onlineUser.getUuid().toString()); @@ -794,7 +868,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getName(), e); } catch (TeleportationException e) { e.displayMessage(onlineUser); } @@ -804,8 +878,8 @@ public class MySqlDatabase extends Database { @Override public void updateUserData(@NotNull SavedUser savedUser) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + UPDATE `%player_data%` SET `home_slots`=?, `ignoring_requests`=? WHERE `uuid`=?"""))) { @@ -823,12 +897,12 @@ public class MySqlDatabase extends Database { public void setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) { try (Connection connection = getConnection()) { // Clear the user's current teleport - try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` + try (PreparedStatement deleteStatement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` WHERE `id`=( SELECT `destination_id` - FROM `%teleports_table%` - WHERE `%teleports_table%`.`player_uuid`=? + FROM `%teleport_data%` + WHERE `%teleport_data%`.`player_uuid`=? );"""))) { deleteStatement.setString(1, user.getUuid().toString()); deleteStatement.executeUpdate(); @@ -836,8 +910,8 @@ public class MySqlDatabase extends Database { // Set the user's teleport into the database (if it's not null) if (teleport != null) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`) + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO `%teleport_data%` (`player_uuid`, `destination_id`, `type`) VALUES (?,?,?);"""))) { statement.setString(1, user.getUuid().toString()); statement.setInt(2, setPosition((Position) teleport.getTarget(), connection)); @@ -847,17 +921,17 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getName(), e); } } @Override public Optional getLastPosition(@NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`last_position` = `%positions_table%`.`id` + FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.`last_position` = `%position_data%`.`id` WHERE `uuid`=?"""))) { statement.setString(1, user.getUuid().toString()); @@ -874,7 +948,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getName(), e); } return Optional.empty(); } @@ -882,10 +956,10 @@ public class MySqlDatabase extends Database { @Override public void setLastPosition(@NotNull User user, @NotNull Position position) { try (Connection connection = getConnection()) { - try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement queryStatement = connection.prepareStatement(format(""" SELECT `last_position` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id` + FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.last_position = `%position_data%`.`id` WHERE `uuid`=?;"""))) { queryStatement.setString(1, user.getUuid().toString()); @@ -895,8 +969,8 @@ public class MySqlDatabase extends Database { updatePosition(resultSet.getInt("last_position"), position, connection); } else { // Set the last position - try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` + try (PreparedStatement updateStatement = connection.prepareStatement(format(""" + UPDATE `%player_data%` SET `last_position`=? WHERE `uuid`=?;"""))) { updateStatement.setInt(1, setPosition(position, connection)); @@ -906,17 +980,17 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getName(), e); } } @Override public Optional getOfflinePosition(@NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id` + FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.`offline_position` = `%position_data%`.`id` WHERE `uuid`=?"""))) { statement.setString(1, user.getUuid().toString()); @@ -933,7 +1007,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getName(), e); } return Optional.empty(); } @@ -941,9 +1015,9 @@ public class MySqlDatabase extends Database { @Override public void setOfflinePosition(@NotNull User user, @NotNull Position position) { try (Connection connection = getConnection()) { - try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" - SELECT `offline_position` FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id` + try (PreparedStatement queryStatement = connection.prepareStatement(format(""" + SELECT `offline_position` FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.`offline_position` = `%position_data%`.`id` WHERE `uuid`=?;"""))) { queryStatement.setString(1, user.getUuid().toString()); @@ -953,8 +1027,8 @@ public class MySqlDatabase extends Database { updatePosition(resultSet.getInt("offline_position"), position, connection); } else { // Set the offline position - try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` + try (PreparedStatement updateStatement = connection.prepareStatement(format(""" + UPDATE `%player_data%` SET `offline_position`=? WHERE `uuid`=?;"""))) { updateStatement.setInt(1, setPosition(position, connection)); @@ -964,17 +1038,17 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getName(), e); } } @Override public Optional getRespawnPosition(@NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`respawn_position` = `%positions_table%`.`id` + FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.`respawn_position` = `%position_data%`.`id` WHERE `uuid`=?"""))) { statement.setString(1, user.getUuid().toString()); @@ -991,7 +1065,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getName(), e); } return Optional.empty(); } @@ -999,9 +1073,9 @@ public class MySqlDatabase extends Database { @Override public void setRespawnPosition(@NotNull User user, @Nullable Position position) { try (Connection connection = getConnection()) { - try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" - SELECT `respawn_position` FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = `%positions_table%`.`id` + try (PreparedStatement queryStatement = connection.prepareStatement(format(""" + SELECT `respawn_position` FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.respawn_position = `%position_data%`.`id` WHERE `uuid`=?;"""))) { queryStatement.setString(1, user.getUuid().toString()); @@ -1009,12 +1083,12 @@ public class MySqlDatabase extends Database { if (resultSet.next()) { if (position == null) { // Delete a respawn position - try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` + try (PreparedStatement deleteStatement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` WHERE `id`=( SELECT `respawn_position` - FROM `%players_table%` - WHERE `%players_table%`.`uuid`=? + FROM `%player_data%` + WHERE `%player_data%`.`uuid`=? );"""))) { deleteStatement.setString(1, user.getUuid().toString()); deleteStatement.executeUpdate(); @@ -1026,8 +1100,8 @@ public class MySqlDatabase extends Database { } else { if (position != null) { // Set a respawn position - try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` + try (PreparedStatement updateStatement = connection.prepareStatement(format(""" + UPDATE `%player_data%` SET `respawn_position`=? WHERE `uuid`=?;"""))) { updateStatement.setInt(1, setPosition(position, connection)); @@ -1038,7 +1112,7 @@ public class MySqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getName(), e); } } @@ -1047,8 +1121,8 @@ public class MySqlDatabase extends Database { getHome(home.getUuid()).ifPresentOrElse(presentHome -> { try (Connection connection = getConnection()) { // Update the home's saved position, including metadata - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `saved_position_id` FROM `%homes_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `saved_position_id` FROM `%home_data%` WHERE `uuid`=?;"""))) { statement.setString(1, home.getUuid().toString()); @@ -1059,8 +1133,8 @@ public class MySqlDatabase extends Database { } // Update the home privacy - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%homes_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + UPDATE `%home_data%` SET `public`=? WHERE `uuid`=?;"""))) { statement.setBoolean(1, home.isPublic()); @@ -1069,12 +1143,12 @@ public class MySqlDatabase extends Database { } } catch (SQLException e) { plugin.log(Level.SEVERE, - "Failed to update a home in the database for " + home.getOwner().getUsername(), e); + "Failed to update a home in the database for " + home.getOwner().getName(), e); } }, () -> { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`) + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO `%home_data%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`) VALUES (?,?,?,?);"""))) { statement.setString(1, home.getUuid().toString()); statement.setInt(2, setSavedPosition(home, connection)); @@ -1085,7 +1159,7 @@ public class MySqlDatabase extends Database { } } catch (SQLException e) { plugin.log(Level.SEVERE, - "Failed to set a home to the database for " + home.getOwner().getUsername(), e); + "Failed to set a home to the database for " + home.getOwner().getName(), e); } }); } @@ -1094,8 +1168,8 @@ public class MySqlDatabase extends Database { public void saveWarp(@NotNull Warp warp) { getWarp(warp.getUuid()).ifPresentOrElse(presentWarp -> { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `saved_position_id` FROM `%warps_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT `saved_position_id` FROM `%warp_data%` WHERE `uuid`=?;"""))) { statement.setString(1, warp.getUuid().toString()); @@ -1109,8 +1183,8 @@ public class MySqlDatabase extends Database { } }, () -> { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`) + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO `%warp_data%` (`uuid`, `saved_position_id`) VALUES (?,?);"""))) { statement.setString(1, warp.getUuid().toString()); statement.setInt(2, setSavedPosition(warp, connection)); @@ -1126,14 +1200,14 @@ public class MySqlDatabase extends Database { @Override public void deleteHome(@NotNull UUID uuid) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id`=( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id`=( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id`=( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id`=( SELECT `saved_position_id` - FROM `%homes_table%` + FROM `%home_data%` WHERE `uuid`=? ) );"""))) { @@ -1149,14 +1223,14 @@ public class MySqlDatabase extends Database { @Override public int deleteAllHomes(@NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id` IN ( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id` IN ( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id` IN ( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id` IN ( SELECT `saved_position_id` - FROM `%homes_table%` + FROM `%home_data%` WHERE `owner_uuid`=? ) );"""))) { @@ -1165,7 +1239,7 @@ public class MySqlDatabase extends Database { return statement.executeUpdate(); } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getUsername() + " from the database", e); + plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getName() + " from the database", e); } return 0; } @@ -1173,14 +1247,14 @@ public class MySqlDatabase extends Database { @Override public int deleteAllHomes(@NotNull String worldName, @NotNull String serverName) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id` IN ( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id` IN ( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id` IN ( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id` IN ( SELECT `saved_position_id` - FROM `%homes_table%` + FROM `%home_data%` WHERE `world_name`=? AND `server_name`=? ) @@ -1192,7 +1266,7 @@ public class MySqlDatabase extends Database { } } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to delete homes in the world " + worldName + " on the server " - + serverName + " from the database", e); + + serverName + " from the database", e); } return 0; } @@ -1200,14 +1274,14 @@ public class MySqlDatabase extends Database { @Override public void deleteWarp(@NotNull UUID uuid) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id`=( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id`=( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id`=( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id`=( SELECT `saved_position_id` - FROM `%warps_table%` + FROM `%warp_data%` WHERE `uuid`=? ) );"""))) { @@ -1223,14 +1297,14 @@ public class MySqlDatabase extends Database { @Override public int deleteAllWarps() { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id` IN ( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id` IN ( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id` IN ( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id` IN ( SELECT `saved_position_id` - FROM `%warps_table%` + FROM `%warp_data%` ) );"""))) { return statement.executeUpdate(); @@ -1244,14 +1318,14 @@ public class MySqlDatabase extends Database { @Override public int deleteAllWarps(@NotNull String worldName, @NotNull String serverName) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id` IN ( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id` IN ( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id` IN ( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id` IN ( SELECT `saved_position_id` - FROM `%warps_table%` + FROM `%warp_data%` WHERE `world_name`=? AND `server_name`=? ) @@ -1263,13 +1337,13 @@ public class MySqlDatabase extends Database { } } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to delete warps in the world " + worldName + " on the server " - + serverName + " from the database", e); + + serverName + " from the database", e); } return 0; } @Override - public void terminate() { + public void close() { if (dataSource != null) { if (!dataSource.isClosed()) { dataSource.close(); diff --git a/common/src/main/java/net/william278/huskhomes/database/PostgreSqlDatabase.java b/common/src/main/java/net/william278/huskhomes/database/PostgreSqlDatabase.java index b98090a8..9f18faac 100644 --- a/common/src/main/java/net/william278/huskhomes/database/PostgreSqlDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/PostgreSqlDatabase.java @@ -28,17 +28,16 @@ import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.SavedUser; import net.william278.huskhomes.user.User; import net.william278.huskhomes.util.TransactionResolver; -import org.jetbrains.annotations.Blocking; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.IOException; import java.sql.*; import java.time.Instant; import java.util.*; import java.util.logging.Level; import static net.william278.huskhomes.config.Settings.DatabaseSettings; +import static net.william278.huskhomes.database.DatabaseProvider.DATA_POOL_NAME; /** * A PostgreSQL implementation of the plugin {@link Database}. @@ -46,38 +45,23 @@ import static net.william278.huskhomes.config.Settings.DatabaseSettings; @SuppressWarnings("DuplicatedCode") public class PostgreSqlDatabase extends Database { - private static final String DATA_POOL_NAME = "HuskHomesHikariPool"; - private final String driverClass; private HikariDataSource dataSource; public PostgreSqlDatabase(@NotNull HuskHomes plugin) { super(plugin); - - this.driverClass = "org.postgresql.Driver"; } - /** - * Fetch the auto-closeable connection from the hikariDataSource. - * - * @return The {@link Connection} to the PostgreSQL database - * @throws SQLException if the connection fails for some reason - */ - @Blocking - @NotNull private Connection getConnection() throws SQLException { - if (dataSource == null) { - throw new IllegalStateException("The database has not been initialized"); - } return dataSource.getConnection(); } - @Blocking - @Override - public void initialize() throws IllegalStateException { + private void setConnection() { // Initialize the Hikari pooled connection - final DatabaseSettings.DatabaseCredentials credentials = plugin.getSettings().getDatabase().getCredentials(); + final DatabaseSettings databaseSettings = plugin.getSettings().getDatabase(); + final DatabaseSettings.DatabaseCredentials credentials = databaseSettings.getCredentials(); + dataSource = new HikariDataSource(); - dataSource.setDriverClassName(driverClass); + dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setJdbcUrl(String.format("jdbc:postgresql://%s:%s/%s%s", credentials.getHost(), credentials.getPort(), @@ -90,12 +74,12 @@ public class PostgreSqlDatabase extends Database { dataSource.setPassword(credentials.getPassword()); // Set connection pool options - final DatabaseSettings.PoolOptions pool = plugin.getSettings().getDatabase().getPoolOptions(); - dataSource.setMaximumPoolSize(pool.getSize()); - dataSource.setMinimumIdle(pool.getIdle()); - dataSource.setMaxLifetime(pool.getLifetime()); - dataSource.setKeepaliveTime(pool.getKeepAlive()); - dataSource.setConnectionTimeout(pool.getTimeout()); + final DatabaseSettings.PoolOptions poolOptions = databaseSettings.getPoolOptions(); + dataSource.setMaximumPoolSize(poolOptions.getSize()); + dataSource.setMinimumIdle(poolOptions.getIdle()); + dataSource.setMaxLifetime(poolOptions.getLifetime()); + dataSource.setKeepaliveTime(poolOptions.getKeepAlive()); + dataSource.setConnectionTimeout(poolOptions.getTimeout()); dataSource.setPoolName(DATA_POOL_NAME); // Set additional connection pool properties @@ -117,28 +101,115 @@ public class PostgreSqlDatabase extends Database { "maintainTimeStats", "false") ); dataSource.setDataSourceProperties(properties); + } - // Prepare database schema; make tables if they don't exist - try (Connection connection = dataSource.getConnection()) { - final String[] databaseSchema = getSchemaStatements("database/postgresql_schema.sql"); - try (Statement statement = connection.createStatement()) { - for (String tableCreationStatement : databaseSchema) { - statement.execute(tableCreationStatement); + @SuppressWarnings("SqlSourceToSinkFlow") + @Override + protected void executeScript(@NotNull Connection connection, @NotNull String name) throws SQLException { + try (Statement statement = connection.createStatement()) { + for (String schemaStatement : getScript(name)) { + statement.execute(schemaStatement); + } + } + } + + @Override + public void initialize() throws RuntimeException { + // Establish connection + this.setConnection(); + + // Create tables + if (!isCreated()) { + plugin.log(Level.INFO, "Creating PostgreSQL database tables"); + try { + executeScript(getConnection(), "postgresql_schema.sql"); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to create PostgreSQL database tables", e); + setLoaded(false); + return; + } + setSchemaVersion(Migration.getLatestVersion()); + plugin.log(Level.INFO, "PostgreSQL database tables created!"); + setLoaded(true); + return; + } + + // Perform migrations + try { + performMigrations(getConnection(), plugin.getSettings().getDatabase().getType()); + setLoaded(true); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to perform PostgreSQL database migrations", e); + setLoaded(false); + } + } + + @Override + public boolean isCreated() { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT uuid + FROM "%player_data%" + LIMIT 1;"""))) { + statement.executeQuery(); + return true; + } + } catch (SQLException e) { + return false; + } + } + + @Override + public int getSchemaVersion() { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT schema_version + FROM "%meta_data%" + LIMIT 1;"""))) { + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return resultSet.getInt("schema_version"); + } + } + } catch (SQLException e) { + plugin.log(Level.WARNING, "The database schema version could not be fetched; " + + "migrations will be carried out."); + } + return -1; + } + + @Override + public void setSchemaVersion(int version) { + if (getSchemaVersion() == -1) { + try (Connection connection = getConnection()) { + try (PreparedStatement insertStatement = connection.prepareStatement(format(""" + INSERT INTO "%meta_data%" (`schema_version`) + VALUES (?)"""))) { + insertStatement.setInt(1, version); + insertStatement.executeUpdate(); } } catch (SQLException e) { - throw new IllegalStateException("Failed to create database tables. Please ensure that your connecting " - + "user account has privileges to create tables.", e); + plugin.log(Level.SEVERE, "Failed to insert schema version in table", e); } - } catch (SQLException | IOException e) { - throw new IllegalStateException("Failed to establish a connection to the PostgreSQL database. " - + "Please check the supplied database credentials in the config file", e); + return; + } + + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(format(""" + UPDATE "%meta_data%" + SET `schema_version` = ?;"""))) { + statement.setInt(1, version); + statement.executeUpdate(); + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to update schema version in table", e); } } @Override protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO "%positions_table%" + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO "%position_data%" ("x","y","z","yaw","pitch","world_name","world_uuid","server_name") VALUES (?,?,?,?,?,?,?,?);"""), @@ -165,8 +236,8 @@ public class PostgreSqlDatabase extends Database { @Override protected void updatePosition(int positionId, @NotNull Position position, @NotNull Connection connection) throws SQLException { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE "%positions_table%" + try (PreparedStatement statement = connection.prepareStatement(format(""" + UPDATE "%position_data%" SET "x"=?, "y"=?, "z"=?, @@ -192,8 +263,8 @@ public class PostgreSqlDatabase extends Database { @Override protected int setSavedPosition(@NotNull SavedPosition position, @NotNull Connection connection) throws SQLException { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO "%saved_positions_table%" + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO "%saved_position_data%" ("position_id", "name", "description", "tags", "timestamp") VALUES (?,?,?,?,?);"""), @@ -217,9 +288,9 @@ public class PostgreSqlDatabase extends Database { @Override protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position, @NotNull Connection connection) throws SQLException { - try (PreparedStatement selectStatement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement selectStatement = connection.prepareStatement(format(""" SELECT "position_id" - FROM "%saved_positions_table%" + FROM "%saved_position_data%" WHERE "id"=?;"""))) { selectStatement.setInt(1, savedPositionId); @@ -228,8 +299,8 @@ public class PostgreSqlDatabase extends Database { final int positionId = resultSet.getInt("position_id"); updatePosition(positionId, position, connection); - try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" - UPDATE "%saved_positions_table%" + try (PreparedStatement updateStatement = connection.prepareStatement(format(""" + UPDATE "%saved_position_data%" SET "name"=?, "description"=?, "tags"=? @@ -246,23 +317,23 @@ public class PostgreSqlDatabase extends Database { @Override public void ensureUser(@NotNull User onlineUser) { - getUserData(onlineUser.getUuid()).ifPresentOrElse( + getUser(onlineUser.getUuid()).ifPresentOrElse( existingUserData -> { - if (!existingUserData.getUsername().equals(onlineUser.getUsername())) { + if (!existingUserData.getUsername().equals(onlineUser.getName())) { // Update a player's name if it has changed in the database try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE "%players_table%" + try (PreparedStatement statement = connection.prepareStatement(format(""" + UPDATE "%player_data%" SET "username"=? WHERE "uuid"=?"""))) { - statement.setString(1, onlineUser.getUsername()); + statement.setString(1, onlineUser.getName()); statement.setString(2, existingUserData.getUserUuid().toString()); statement.executeUpdate(); } - plugin.log(Level.INFO, "Updated " + onlineUser.getUsername() - + "'s name in the database (" + existingUserData.getUsername() - + " -> " + onlineUser.getUsername() + ")"); + plugin.log(Level.INFO, "Updated " + onlineUser.getName() + + "'s name in the database (" + existingUserData.getUsername() + + " -> " + onlineUser.getName() + ")"); } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e); } @@ -271,12 +342,12 @@ public class PostgreSqlDatabase extends Database { () -> { // Insert new player data into the database try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO "%players_table%" ("uuid","username") + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO "%player_data%" ("uuid","username") VALUES (?,?);"""))) { statement.setString(1, onlineUser.getUuid().toString()); - statement.setString(2, onlineUser.getUsername()); + statement.setString(2, onlineUser.getName()); statement.executeUpdate(); } } catch (SQLException e) { @@ -286,11 +357,11 @@ public class PostgreSqlDatabase extends Database { } @Override - public Optional getUserDataByName(@NotNull String name) { + public Optional getUser(@NotNull String name) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT "uuid", "username", "home_slots", "ignoring_requests" - FROM "%players_table%" + FROM "%player_data%" WHERE "username"=?"""))) { statement.setString(1, name); @@ -311,11 +382,11 @@ public class PostgreSqlDatabase extends Database { } @Override - public Optional getUserData(@NotNull UUID uuid) { + public Optional getUser(@NotNull UUID uuid) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT "uuid", "username", "home_slots", "ignoring_requests" - FROM "%players_table%" + FROM "%player_data%" WHERE "uuid"=?"""))) { statement.setString(1, uuid.toString()); @@ -337,14 +408,14 @@ public class PostgreSqlDatabase extends Database { } @Override - public void deleteUserData(@NotNull UUID uuid) { + public void deleteUser(@NotNull UUID uuid) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM "%positions_table%" + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM "%position_data%" WHERE "id" - IN ((SELECT "last_position" FROM "%players_table%" WHERE "uuid" = ?), - (SELECT "offline_position" FROM "%players_table%" WHERE "uuid" = ?), - (SELECT "respawn_position" FROM "%players_table%" WHERE "uuid" = ?));"""))) { + IN ((SELECT "last_position" FROM "%player_data%" WHERE "uuid" = ?), + (SELECT "offline_position" FROM "%player_data%" WHERE "uuid" = ?), + (SELECT "respawn_position" FROM "%player_data%" WHERE "uuid" = ?));"""))) { statement.setString(1, uuid.toString()); statement.setString(2, uuid.toString()); statement.setString(3, uuid.toString()); @@ -354,8 +425,8 @@ public class PostgreSqlDatabase extends Database { return; } - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM "%players_table%" + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM "%player_data%" WHERE "uuid"=?;"""))) { statement.setString(1, uuid.toString()); statement.executeUpdate(); @@ -370,9 +441,9 @@ public class PostgreSqlDatabase extends Database { @Override public Optional getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT "type", "start_timestamp", "end_timestamp" - FROM "%cooldowns_table%" + FROM "%player_cooldowns_data%" WHERE "player_uuid"=? AND "type"=? ORDER BY "start_timestamp" DESC LIMIT 1;"""))) { @@ -394,8 +465,8 @@ public class PostgreSqlDatabase extends Database { public void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user, @NotNull Instant cooldownExpiry) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO "%cooldowns_table%" ("player_uuid", "type", "start_timestamp", "end_timestamp") + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO "%player_cooldowns_data%" ("player_uuid", "type", "start_timestamp", "end_timestamp") VALUES (?,?,?,?);"""))) { statement.setString(1, user.getUuid().toString()); statement.setString(2, action.name().toLowerCase(Locale.ENGLISH)); @@ -411,8 +482,8 @@ public class PostgreSqlDatabase extends Database { @Override public void removeCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM "%cooldowns_table%" + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM "%player_cooldowns_data%" WHERE "player_uuid"=? AND "type"=?;"""))) { statement.setString(1, user.getUuid().toString()); @@ -428,16 +499,16 @@ public class PostgreSqlDatabase extends Database { public List getHomes(@NotNull User user) { final List userHomes = new ArrayList<>(); try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT "%homes_table%"."uuid" AS "home_uuid", "owner_uuid", "name", "description", "tags", + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT "%home_data%"."uuid" AS "home_uuid", "owner_uuid", "name", "description", "tags", "timestamp", "x", "y", "z", "yaw", "pitch", "world_name", "world_uuid", "server_name", "public" - FROM "%homes_table%" - INNER JOIN "%saved_positions_table%" - ON "%homes_table%"."saved_position_id"="%saved_positions_table%"."id" - INNER JOIN "%positions_table%" - ON "%saved_positions_table%"."position_id"="%positions_table%"."id" - INNER JOIN "%players_table%" - ON "%homes_table%"."owner_uuid"="%players_table%"."uuid" + FROM "%home_data%" + INNER JOIN "%saved_position_data%" + ON "%home_data%"."saved_position_id"="%saved_position_data%"."id" + INNER JOIN "%position_data%" + ON "%saved_position_data%"."position_id"="%position_data%"."id" + INNER JOIN "%player_data%" + ON "%home_data%"."owner_uuid"="%player_data%"."uuid" WHERE "owner_uuid"=? ORDER BY "name";"""))) { @@ -463,7 +534,7 @@ public class PostgreSqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getUsername()); + plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getName()); } return userHomes; } @@ -472,14 +543,14 @@ public class PostgreSqlDatabase extends Database { public List getWarps() { final List warps = new ArrayList<>(); try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT "%warps_table%"."uuid" AS "warp_uuid", "name", "description", "tags", "timestamp", + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT "%warp_data%"."uuid" AS "warp_uuid", "name", "description", "tags", "timestamp", "x", "y", "z", "yaw", "pitch", "world_name", "world_uuid", "server_name" - FROM "%warps_table%" - INNER JOIN "%saved_positions_table%" - ON "%warps_table%"."saved_position_id"="%saved_positions_table%"."id" - INNER JOIN "%positions_table%" - ON "%saved_positions_table%"."position_id"="%positions_table%"."id" + FROM "%warp_data%" + INNER JOIN "%saved_position_data%" + ON "%warp_data%"."saved_position_id"="%saved_position_data%"."id" + INNER JOIN "%position_data%" + ON "%saved_position_data%"."position_id"="%position_data%"."id" ORDER BY "name";"""))) { final ResultSet resultSet = statement.executeQuery(); @@ -509,17 +580,17 @@ public class PostgreSqlDatabase extends Database { public List getPublicHomes() { final List userHomes = new ArrayList<>(); try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT "%homes_table%"."uuid" AS "home_uuid", "owner_uuid", "username" AS "owner_username", "name", + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT "%home_data%"."uuid" AS "home_uuid", "owner_uuid", "username" AS "owner_username", "name", "description", "tags", "timestamp", "x", "y", "z", "yaw", "pitch", "world_name", "world_uuid", "server_name", "public" - FROM "%homes_table%" - INNER JOIN "%saved_positions_table%" - ON "%homes_table%"."saved_position_id"="%saved_positions_table%"."id" - INNER JOIN "%positions_table%" - ON "%saved_positions_table%"."position_id"="%positions_table%"."id" - INNER JOIN "%players_table%" - ON "%homes_table%"."owner_uuid"="%players_table%"."uuid" + FROM "%home_data%" + INNER JOIN "%saved_position_data%" + ON "%home_data%"."saved_position_id"="%saved_position_data%"."id" + INNER JOIN "%position_data%" + ON "%saved_position_data%"."position_id"="%position_data%"."id" + INNER JOIN "%player_data%" + ON "%home_data%"."owner_uuid"="%player_data%"."uuid" WHERE "public"=true ORDER BY "name";"""))) { final ResultSet resultSet = statement.executeQuery(); @@ -552,17 +623,17 @@ public class PostgreSqlDatabase extends Database { public List getPublicHomes(@NotNull String name, boolean caseInsensitive) { final List userHomes = new ArrayList<>(); try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT "%homes_table%"."uuid" AS "home_uuid", "owner_uuid", "username" AS "owner_username", "name", + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT "%home_data%"."uuid" AS "home_uuid", "owner_uuid", "username" AS "owner_username", "name", "description", "tags", "timestamp", "x", "y", "z", "yaw", "pitch", "world_name", "world_uuid", "server_name", "public" - FROM "%homes_table%" - INNER JOIN "%saved_positions_table%" - ON "%homes_table%"."saved_position_id"="%saved_positions_table%"."id" - INNER JOIN "%positions_table%" - ON "%saved_positions_table%"."position_id"="%positions_table%"."id" - INNER JOIN "%players_table%" - ON "%homes_table%"."owner_uuid"="%players_table%"."uuid" + FROM "%home_data%" + INNER JOIN "%saved_position_data%" + ON "%home_data%"."saved_position_id"="%saved_position_data%"."id" + INNER JOIN "%position_data%" + ON "%saved_position_data%"."position_id"="%position_data%"."id" + INNER JOIN "%player_data%" + ON "%home_data%"."owner_uuid"="%player_data%"."uuid" WHERE "public"=true AND ((? AND UPPER("name") LIKE UPPER(?)) OR ("name"=?)) ORDER BY "name";"""))) { @@ -599,17 +670,17 @@ public class PostgreSqlDatabase extends Database { @Override public Optional getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT "%homes_table%"."uuid" AS "home_uuid", "owner_uuid", "username" AS "owner_username", + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT "%home_data%"."uuid" AS "home_uuid", "owner_uuid", "username" AS "owner_username", "name", "description", "tags", "timestamp", "x", "y", "z", "yaw", "pitch", "world_name", "world_uuid", "server_name", "public" - FROM "%homes_table%" - INNER JOIN "%saved_positions_table%" - ON "%homes_table%"."saved_position_id"="%saved_positions_table%"."id" - INNER JOIN "%positions_table%" - ON "%saved_positions_table%"."position_id"="%positions_table%"."id" - INNER JOIN "%players_table%" - ON "%homes_table%"."owner_uuid"="%players_table%"."uuid" + FROM "%home_data%" + INNER JOIN "%saved_position_data%" + ON "%home_data%"."saved_position_id"="%saved_position_data%"."id" + INNER JOIN "%position_data%" + ON "%saved_position_data%"."position_id"="%position_data%"."id" + INNER JOIN "%player_data%" + ON "%home_data%"."owner_uuid"="%player_data%"."uuid" WHERE "owner_uuid"=? AND ((? AND UPPER("name") LIKE UPPER(?)) OR ("name"=?))"""))) { statement.setString(1, user.getUuid().toString()); @@ -645,18 +716,18 @@ public class PostgreSqlDatabase extends Database { @Override public Optional getHome(@NotNull UUID uuid) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT "%homes_table%"."uuid" AS "home_uuid", "owner_uuid", "username" AS "owner_username", + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT "%home_data%"."uuid" AS "home_uuid", "owner_uuid", "username" AS "owner_username", "name", "description", "tags", "timestamp", "x", "y", "z", "yaw", "pitch", "world_name", "world_uuid", "server_name", "public" - FROM "%homes_table%" - INNER JOIN "%saved_positions_table%" - ON "%homes_table%"."saved_position_id"="%saved_positions_table%"."id" - INNER JOIN "%positions_table%" - ON "%saved_positions_table%"."position_id"="%positions_table%"."id" - INNER JOIN "%players_table%" - ON "%homes_table%"."owner_uuid"="%players_table%"."uuid" - WHERE "%homes_table%"."uuid"=?;"""))) { + FROM "%home_data%" + INNER JOIN "%saved_position_data%" + ON "%home_data%"."saved_position_id"="%saved_position_data%"."id" + INNER JOIN "%position_data%" + ON "%saved_position_data%"."position_id"="%position_data%"."id" + INNER JOIN "%player_data%" + ON "%home_data%"."owner_uuid"="%player_data%"."uuid" + WHERE "%home_data%"."uuid"=?;"""))) { statement.setString(1, uuid.toString()); final ResultSet resultSet = statement.executeQuery(); @@ -688,14 +759,14 @@ public class PostgreSqlDatabase extends Database { @Override public Optional getWarp(@NotNull String warpName, boolean caseInsensitive) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT "%warps_table%"."uuid" AS "warp_uuid", "name", "description", "tags", "timestamp", + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT "%warp_data%"."uuid" AS "warp_uuid", "name", "description", "tags", "timestamp", "x", "y", "z", "yaw", "pitch", "world_name", "world_uuid", "server_name" - FROM "%warps_table%" - INNER JOIN "%saved_positions_table%" - ON "%warps_table%"."saved_position_id"="%saved_positions_table%"."id" - INNER JOIN "%positions_table%" - ON "%saved_positions_table%"."position_id"="%positions_table%"."id" + FROM "%warp_data%" + INNER JOIN "%saved_position_data%" + ON "%warp_data%"."saved_position_id"="%saved_position_data%"."id" + INNER JOIN "%position_data%" + ON "%saved_position_data%"."position_id"="%position_data%"."id" AND ((? AND UPPER("name") LIKE UPPER(?)) OR ("name"=?))"""))) { statement.setBoolean(1, caseInsensitive); statement.setString(2, warpName); @@ -727,15 +798,15 @@ public class PostgreSqlDatabase extends Database { @Override public Optional getWarp(@NotNull UUID uuid) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT "%warps_table%"."uuid" AS "warp_uuid", "name", "description", "tags", "timestamp", + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT "%warp_data%"."uuid" AS "warp_uuid", "name", "description", "tags", "timestamp", "x", "y", "z", "yaw", "pitch", "world_name", "world_uuid", "server_name" - FROM "%warps_table%" - INNER JOIN "%saved_positions_table%" - ON "%warps_table%"."saved_position_id"="%saved_positions_table%"."id" - INNER JOIN "%positions_table%" - ON "%saved_positions_table%"."position_id"="%positions_table%"."id" - WHERE "%warps_table%".uuid=?;"""))) { + FROM "%warp_data%" + INNER JOIN "%saved_position_data%" + ON "%warp_data%"."saved_position_id"="%saved_position_data%"."id" + INNER JOIN "%position_data%" + ON "%saved_position_data%"."position_id"="%position_data%"."id" + WHERE "%warp_data%".uuid=?;"""))) { statement.setString(1, uuid.toString()); final ResultSet resultSet = statement.executeQuery(); @@ -764,10 +835,10 @@ public class PostgreSqlDatabase extends Database { @Override public Optional getCurrentTeleport(@NotNull OnlineUser onlineUser) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT "x", "y", "z", "yaw", "pitch", "world_name", "world_uuid", "server_name", "type" - FROM "%teleports_table%" - INNER JOIN "%positions_table%" ON "%teleports_table%"."destination_id" = "%positions_table%"."id" + FROM "%teleport_data%" + INNER JOIN "%position_data%" ON "%teleport_data%"."destination_id" = "%position_data%"."id" WHERE "player_uuid"=?"""))) { statement.setString(1, onlineUser.getUuid().toString()); @@ -790,7 +861,7 @@ public class PostgreSqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getName(), e); } catch (TeleportationException e) { e.displayMessage(onlineUser); } @@ -800,8 +871,8 @@ public class PostgreSqlDatabase extends Database { @Override public void updateUserData(@NotNull SavedUser savedUser) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE "%players_table%" + try (PreparedStatement statement = connection.prepareStatement(format(""" + UPDATE "%player_data%" SET "home_slots"=?, "ignoring_requests"=? WHERE "uuid"=?"""))) { @@ -819,12 +890,12 @@ public class PostgreSqlDatabase extends Database { public void setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) { try (Connection connection = getConnection()) { // Clear the user's current teleport - try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM "%positions_table%" + try (PreparedStatement deleteStatement = connection.prepareStatement(format(""" + DELETE FROM "%position_data%" WHERE "id"=( SELECT "destination_id" - FROM "%teleports_table%" - WHERE "%teleports_table%"."player_uuid"=? + FROM "%teleport_data%" + WHERE "%teleport_data%"."player_uuid"=? );"""))) { deleteStatement.setString(1, user.getUuid().toString()); deleteStatement.executeUpdate(); @@ -832,8 +903,8 @@ public class PostgreSqlDatabase extends Database { // Set the user's teleport into the database (if it's not null) if (teleport != null) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO "%teleports_table%" ("player_uuid", "destination_id", "type") + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO "%teleport_data%" ("player_uuid", "destination_id", "type") VALUES (?,?,?);"""))) { statement.setString(1, user.getUuid().toString()); statement.setInt(2, setPosition((Position) teleport.getTarget(), connection)); @@ -843,17 +914,17 @@ public class PostgreSqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getName(), e); } } @Override public Optional getLastPosition(@NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT "x", "y", "z", "yaw", "pitch", "world_name", "world_uuid", "server_name" - FROM "%players_table%" - INNER JOIN "%positions_table%" ON "%players_table%"."last_position" = "%positions_table%"."id" + FROM "%player_data%" + INNER JOIN "%position_data%" ON "%player_data%"."last_position" = "%position_data%"."id" WHERE "uuid"=?"""))) { statement.setString(1, user.getUuid().toString()); @@ -870,7 +941,7 @@ public class PostgreSqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getName(), e); } return Optional.empty(); } @@ -878,10 +949,10 @@ public class PostgreSqlDatabase extends Database { @Override public void setLastPosition(@NotNull User user, @NotNull Position position) { try (Connection connection = getConnection()) { - try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement queryStatement = connection.prepareStatement(format(""" SELECT "last_position" - FROM "%players_table%" - INNER JOIN "%positions_table%" ON "%players_table%".last_position = "%positions_table%"."id" + FROM "%player_data%" + INNER JOIN "%position_data%" ON "%player_data%".last_position = "%position_data%"."id" WHERE "uuid"=?;"""))) { queryStatement.setString(1, user.getUuid().toString()); @@ -891,8 +962,8 @@ public class PostgreSqlDatabase extends Database { updatePosition(resultSet.getInt("last_position"), position, connection); } else { // Set the last position - try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" - UPDATE "%players_table%" + try (PreparedStatement updateStatement = connection.prepareStatement(format(""" + UPDATE "%player_data%" SET "last_position"=? WHERE "uuid"=?;"""))) { updateStatement.setInt(1, setPosition(position, connection)); @@ -902,17 +973,17 @@ public class PostgreSqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getName(), e); } } @Override public Optional getOfflinePosition(@NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT "x", "y", "z", "yaw", "pitch", "world_name", "world_uuid", "server_name" - FROM "%players_table%" - INNER JOIN "%positions_table%" ON "%players_table%"."offline_position" = "%positions_table%"."id" + FROM "%player_data%" + INNER JOIN "%position_data%" ON "%player_data%"."offline_position" = "%position_data%"."id" WHERE "uuid"=?"""))) { statement.setString(1, user.getUuid().toString()); @@ -929,7 +1000,7 @@ public class PostgreSqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getName(), e); } return Optional.empty(); } @@ -937,9 +1008,9 @@ public class PostgreSqlDatabase extends Database { @Override public void setOfflinePosition(@NotNull User user, @NotNull Position position) { try (Connection connection = getConnection()) { - try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" - SELECT "offline_position" FROM "%players_table%" - INNER JOIN "%positions_table%" ON "%players_table%"."offline_position" = "%positions_table%"."id" + try (PreparedStatement queryStatement = connection.prepareStatement(format(""" + SELECT "offline_position" FROM "%player_data%" + INNER JOIN "%position_data%" ON "%player_data%"."offline_position" = "%position_data%"."id" WHERE "uuid"=?;"""))) { queryStatement.setString(1, user.getUuid().toString()); @@ -949,8 +1020,8 @@ public class PostgreSqlDatabase extends Database { updatePosition(resultSet.getInt("offline_position"), position, connection); } else { // Set the offline position - try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" - UPDATE "%players_table%" + try (PreparedStatement updateStatement = connection.prepareStatement(format(""" + UPDATE "%player_data%" SET "offline_position"=? WHERE "uuid"=?;"""))) { updateStatement.setInt(1, setPosition(position, connection)); @@ -960,17 +1031,17 @@ public class PostgreSqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getName(), e); } } @Override public Optional getRespawnPosition(@NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = connection.prepareStatement(format(""" SELECT "x", "y", "z", "yaw", "pitch", "world_name", "world_uuid", "server_name" - FROM "%players_table%" - INNER JOIN "%positions_table%" ON "%players_table%"."respawn_position" = "%positions_table%"."id" + FROM "%player_data%" + INNER JOIN "%position_data%" ON "%player_data%"."respawn_position" = "%position_data%"."id" WHERE "uuid"=?"""))) { statement.setString(1, user.getUuid().toString()); @@ -987,7 +1058,7 @@ public class PostgreSqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getName(), e); } return Optional.empty(); } @@ -995,9 +1066,9 @@ public class PostgreSqlDatabase extends Database { @Override public void setRespawnPosition(@NotNull User user, @Nullable Position position) { try (Connection connection = getConnection()) { - try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" - SELECT "respawn_position" FROM "%players_table%" - INNER JOIN "%positions_table%" ON "%players_table%".respawn_position = "%positions_table%"."id" + try (PreparedStatement queryStatement = connection.prepareStatement(format(""" + SELECT "respawn_position" FROM "%player_data%" + INNER JOIN "%position_data%" ON "%player_data%".respawn_position = "%position_data%"."id" WHERE "uuid"=?;"""))) { queryStatement.setString(1, user.getUuid().toString()); @@ -1005,12 +1076,12 @@ public class PostgreSqlDatabase extends Database { if (resultSet.next()) { if (position == null) { // Delete a respawn position - try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM "%positions_table%" + try (PreparedStatement deleteStatement = connection.prepareStatement(format(""" + DELETE FROM "%position_data%" WHERE "id"=( SELECT "respawn_position" - FROM "%players_table%" - WHERE "%players_table%"."uuid"=? + FROM "%player_data%" + WHERE "%player_data%"."uuid"=? );"""))) { deleteStatement.setString(1, user.getUuid().toString()); deleteStatement.executeUpdate(); @@ -1022,8 +1093,8 @@ public class PostgreSqlDatabase extends Database { } else { if (position != null) { // Set a respawn position - try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" - UPDATE "%players_table%" + try (PreparedStatement updateStatement = connection.prepareStatement(format(""" + UPDATE "%player_data%" SET "respawn_position"=? WHERE "uuid"=?;"""))) { updateStatement.setInt(1, setPosition(position, connection)); @@ -1034,7 +1105,7 @@ public class PostgreSqlDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getName(), e); } } @@ -1043,8 +1114,8 @@ public class PostgreSqlDatabase extends Database { getHome(home.getUuid()).ifPresentOrElse(presentHome -> { try (Connection connection = getConnection()) { // Update the home's saved position, including metadata - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT "saved_position_id" FROM "%homes_table%" + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT "saved_position_id" FROM "%home_data%" WHERE "uuid"=?;"""))) { statement.setString(1, home.getUuid().toString()); @@ -1055,8 +1126,8 @@ public class PostgreSqlDatabase extends Database { } // Update the home privacy - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE "%homes_table%" + try (PreparedStatement statement = connection.prepareStatement(format(""" + UPDATE "%home_data%" SET "public"=? WHERE "uuid"=?;"""))) { statement.setBoolean(1, home.isPublic()); @@ -1065,12 +1136,12 @@ public class PostgreSqlDatabase extends Database { } } catch (SQLException e) { plugin.log(Level.SEVERE, - "Failed to update a home in the database for " + home.getOwner().getUsername(), e); + "Failed to update a home in the database for " + home.getOwner().getName(), e); } }, () -> { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO "%homes_table%" ("uuid", "saved_position_id", "owner_uuid", "public") + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO "%home_data%" ("uuid", "saved_position_id", "owner_uuid", "public") VALUES (?,?,?,?);"""))) { statement.setString(1, home.getUuid().toString()); statement.setInt(2, setSavedPosition(home, connection)); @@ -1081,7 +1152,7 @@ public class PostgreSqlDatabase extends Database { } } catch (SQLException e) { plugin.log(Level.SEVERE, - "Failed to set a home to the database for " + home.getOwner().getUsername(), e); + "Failed to set a home to the database for " + home.getOwner().getName(), e); } }); } @@ -1090,8 +1161,8 @@ public class PostgreSqlDatabase extends Database { public void saveWarp(@NotNull Warp warp) { getWarp(warp.getUuid()).ifPresentOrElse(presentWarp -> { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT "saved_position_id" FROM "%warps_table%" + try (PreparedStatement statement = connection.prepareStatement(format(""" + SELECT "saved_position_id" FROM "%warp_data%" WHERE "uuid"=?;"""))) { statement.setString(1, warp.getUuid().toString()); @@ -1105,8 +1176,8 @@ public class PostgreSqlDatabase extends Database { } }, () -> { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO "%warps_table%" ("uuid", "saved_position_id") + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO "%warp_data%" ("uuid", "saved_position_id") VALUES (?,?);"""))) { statement.setString(1, warp.getUuid().toString()); statement.setInt(2, setSavedPosition(warp, connection)); @@ -1122,14 +1193,14 @@ public class PostgreSqlDatabase extends Database { @Override public void deleteHome(@NotNull UUID uuid) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM "%positions_table%" - WHERE "%positions_table%"."id"=( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM "%position_data%" + WHERE "%position_data%"."id"=( SELECT "position_id" - FROM "%saved_positions_table%" - WHERE "%saved_positions_table%"."id"=( + FROM "%saved_position_data%" + WHERE "%saved_position_data%"."id"=( SELECT "saved_position_id" - FROM "%homes_table%" + FROM "%home_data%" WHERE "uuid"=? ) );"""))) { @@ -1145,14 +1216,14 @@ public class PostgreSqlDatabase extends Database { @Override public int deleteAllHomes(@NotNull User user) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM "%positions_table%" - WHERE "%positions_table%"."id" IN ( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM "%position_data%" + WHERE "%position_data%"."id" IN ( SELECT "position_id" - FROM "%saved_positions_table%" - WHERE "%saved_positions_table%"."id" IN ( + FROM "%saved_position_data%" + WHERE "%saved_position_data%"."id" IN ( SELECT "saved_position_id" - FROM "%homes_table%" + FROM "%home_data%" WHERE "owner_uuid"=? ) );"""))) { @@ -1161,7 +1232,7 @@ public class PostgreSqlDatabase extends Database { return statement.executeUpdate(); } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getUsername() + " from the database", e); + plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getName() + " from the database", e); } return 0; } @@ -1169,14 +1240,14 @@ public class PostgreSqlDatabase extends Database { @Override public int deleteAllHomes(@NotNull String worldName, @NotNull String serverName) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM "%positions_table%" - WHERE "%positions_table%"."id" IN ( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM "%position_data%" + WHERE "%position_data%"."id" IN ( SELECT "position_id" - FROM "%saved_positions_table%" - WHERE "%saved_positions_table%"."id" IN ( + FROM "%saved_position_data%" + WHERE "%saved_position_data%"."id" IN ( SELECT "saved_position_id" - FROM "%homes_table%" + FROM "%home_data%" WHERE "world_name"=? AND "server_name"=? ) @@ -1188,7 +1259,7 @@ public class PostgreSqlDatabase extends Database { } } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to delete homes in the world " + worldName + " on the server " - + serverName + " from the database", e); + + serverName + " from the database", e); } return 0; } @@ -1196,14 +1267,14 @@ public class PostgreSqlDatabase extends Database { @Override public void deleteWarp(@NotNull UUID uuid) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM "%positions_table%" - WHERE "%positions_table%"."id"=( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM "%position_data%" + WHERE "%position_data%"."id"=( SELECT "position_id" - FROM "%saved_positions_table%" - WHERE "%saved_positions_table%"."id"=( + FROM "%saved_position_data%" + WHERE "%saved_position_data%"."id"=( SELECT "saved_position_id" - FROM "%warps_table%" + FROM "%warp_data%" WHERE "uuid"=? ) );"""))) { @@ -1219,14 +1290,14 @@ public class PostgreSqlDatabase extends Database { @Override public int deleteAllWarps() { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM "%positions_table%" - WHERE "%positions_table%"."id" IN ( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM "%position_data%" + WHERE "%position_data%"."id" IN ( SELECT "position_id" - FROM "%saved_positions_table%" - WHERE "%saved_positions_table%"."id" IN ( + FROM "%saved_position_data%" + WHERE "%saved_position_data%"."id" IN ( SELECT "saved_position_id" - FROM "%warps_table%" + FROM "%warp_data%" ) );"""))) { return statement.executeUpdate(); @@ -1240,14 +1311,14 @@ public class PostgreSqlDatabase extends Database { @Override public int deleteAllWarps(@NotNull String worldName, @NotNull String serverName) { try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM "%positions_table%" - WHERE "%positions_table%"."id" IN ( + try (PreparedStatement statement = connection.prepareStatement(format(""" + DELETE FROM "%position_data%" + WHERE "%position_data%"."id" IN ( SELECT "position_id" - FROM "%saved_positions_table%" - WHERE "%saved_positions_table%"."id" IN ( + FROM "%saved_position_data%" + WHERE "%saved_position_data%"."id" IN ( SELECT "saved_position_id" - FROM "%warps_table%" + FROM "%warp_data%" WHERE "world_name"=? AND "server_name"=? ) @@ -1259,13 +1330,13 @@ public class PostgreSqlDatabase extends Database { } } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to delete warps in the world " + worldName + " on the server " - + serverName + " from the database", e); + + serverName + " from the database", e); } return 0; } @Override - public void terminate() { + public void close() { if (dataSource != null) { if (!dataSource.isClosed()) { dataSource.close(); diff --git a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java index 4b8938bd..cf2ba191 100644 --- a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java @@ -31,8 +31,8 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.sqlite.SQLiteConfig; -import java.io.File; import java.io.IOException; +import java.nio.file.Path; import java.sql.*; import java.time.Instant; import java.util.*; @@ -47,7 +47,7 @@ public class SqLiteDatabase extends Database { /** * Path to the SQLite HuskHomesData.db file. */ - private final File databaseFile; + private final Path databaseFile; /** * The name of the database file. @@ -59,16 +59,14 @@ public class SqLiteDatabase extends Database { */ private Connection connection; - public SqLiteDatabase(@NotNull HuskHomes plugin) { super(plugin); - this.databaseFile = plugin.getConfigDirectory().resolve(DATABASE_FILE_NAME).toFile(); + this.databaseFile = plugin.getConfigDirectory().resolve(DATABASE_FILE_NAME); } + @NotNull private Connection getConnection() throws SQLException { - if (connection == null) { - setConnection(); - } else if (connection.isClosed()) { + if (connection == null || connection.isClosed()) { setConnection(); } return connection; @@ -77,7 +75,7 @@ public class SqLiteDatabase extends Database { private void setConnection() { try { // Ensure that the database file exists - if (databaseFile.createNewFile()) { + if (databaseFile.toFile().createNewFile()) { plugin.log(Level.INFO, "Created the SQLite database file"); } @@ -88,16 +86,15 @@ public class SqLiteDatabase extends Database { SQLiteConfig config = new SQLiteConfig(); config.enforceForeignKeys(true); config.setEncoding(SQLiteConfig.Encoding.UTF8); - config.setJournalMode(SQLiteConfig.JournalMode.WAL); - config.setSynchronous(SQLiteConfig.SynchronousMode.NORMAL); + config.setSynchronous(SQLiteConfig.SynchronousMode.FULL); // Establish the connection connection = DriverManager.getConnection( - String.format("jdbc:sqlite:%s", databaseFile.getAbsolutePath()), + String.format("jdbc:sqlite:%s", databaseFile.toAbsolutePath()), config.toProperties() ); } catch (IOException e) { - plugin.log(Level.SEVERE, "An exception occurred creating the SQLite database file", e); + plugin.log(Level.SEVERE, "An exception occurred creating the database file", e); } catch (SQLException e) { plugin.log(Level.SEVERE, "An SQL exception occurred initializing the SQLite database", e); } catch (ClassNotFoundException e) { @@ -105,29 +102,111 @@ public class SqLiteDatabase extends Database { } } + @SuppressWarnings("SqlSourceToSinkFlow") @Override - public void initialize() throws IllegalStateException { - // Set up the connection - setConnection(); - - // Prepare database schema; make tables if they don't exist - try { - // Load the database schema CREATE statements from schema file - final String[] databaseSchema = getSchemaStatements("database/sqlite_schema.sql"); - try (Statement statement = getConnection().createStatement()) { - for (String tableCreationStatement : databaseSchema) { - statement.execute(tableCreationStatement); - } + protected void executeScript(@NotNull Connection connection, @NotNull String name) throws SQLException { + try (Statement statement = connection.createStatement()) { + for (String schemaStatement : getScript(name)) { + statement.execute(schemaStatement); } - } catch (SQLException | IOException e) { - throw new IllegalStateException("Failed to initialize the SQLite database", e); + } + } + + @Override + public void initialize() throws RuntimeException { + // Establish connection + this.setConnection(); + + // Backup database file + this.backupFlatFile(databaseFile); + + // Create tables + if (!isCreated()) { + plugin.log(Level.INFO, "Creating SQLite database tables"); + try { + executeScript(getConnection(), "sqlite_schema.sql"); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to create SQLite database tables"); + setLoaded(false); + return; + } + setSchemaVersion(Migration.getLatestVersion()); + plugin.log(Level.INFO, "SQLite database tables created!"); + setLoaded(true); + return; + } + + // Perform migrations + try { + performMigrations(getConnection(), Type.SQLITE); + setLoaded(true); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to perform SQLite database migrations"); + setLoaded(false); + } + } + + @Override + public boolean isCreated() { + if (!databaseFile.toFile().exists()) { + return false; + } + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + SELECT `uuid` + FROM `%player_data%` + LIMIT 1;"""))) { + statement.executeQuery(); + return true; + } catch (SQLException e) { + return false; + } + } + + @Override + public int getSchemaVersion() { + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + SELECT `schema_version` + FROM `%meta_data%` + LIMIT 1;"""))) { + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return resultSet.getInt("schema_version"); + } + } catch (SQLException e) { + plugin.log(Level.WARNING, "The database schema version could not be fetched; " + + "migrations will be carried out."); + } + return -1; + } + + @Override + public void setSchemaVersion(int version) { + if (getSchemaVersion() == -1) { + try (PreparedStatement insertStatement = getConnection().prepareStatement(format(""" + INSERT INTO `%meta_data%` (`schema_version`) + VALUES (?);"""))) { + insertStatement.setInt(1, version); + insertStatement.executeUpdate(); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to insert schema version in table", e); + } + return; + } + + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + UPDATE `%meta_data%` + SET `schema_version` = ?;"""))) { + statement.setInt(1, version); + statement.executeUpdate(); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to update schema version in table", e); } } @Override protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - INSERT INTO `%positions_table%` + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + INSERT INTO `%position_data%` (`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`) VALUES (?,?,?,?,?,?,?,?) @@ -155,8 +234,8 @@ public class SqLiteDatabase extends Database { @Override protected void updatePosition(int positionId, @NotNull Position position, @NotNull Connection connection) throws SQLException { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%positions_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + UPDATE `%position_data%` SET `x`=?, `y`=?, `z`=?, @@ -182,8 +261,8 @@ public class SqLiteDatabase extends Database { @Override protected int setSavedPosition(@NotNull SavedPosition position, @NotNull Connection connection) throws SQLException { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%saved_positions_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + INSERT INTO `%saved_position_data%` (`position_id`, `name`, `description`, `tags`, `timestamp`) VALUES (?,?,?,?,?) @@ -208,9 +287,9 @@ public class SqLiteDatabase extends Database { @Override protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position, @NotNull Connection connection) throws SQLException { - try (PreparedStatement selectStatement = connection.prepareStatement(formatStatementTables(""" + try (PreparedStatement selectStatement = connection.prepareStatement(format(""" SELECT `position_id` - FROM `%saved_positions_table%` + FROM `%saved_position_data%` WHERE `id`=?;"""))) { selectStatement.setInt(1, savedPositionId); @@ -219,8 +298,8 @@ public class SqLiteDatabase extends Database { final int positionId = resultSet.getInt("position_id"); updatePosition(positionId, position, connection); - try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%saved_positions_table%` + try (PreparedStatement updateStatement = connection.prepareStatement(format(""" + UPDATE `%saved_position_data%` SET `name`=?, `description`=?, `tags`=? @@ -237,21 +316,21 @@ public class SqLiteDatabase extends Database { @Override public void ensureUser(@NotNull User onlineUser) { - getUserData(onlineUser.getUuid()).ifPresentOrElse( + getUser(onlineUser.getUuid()).ifPresentOrElse( existingUser -> { - if (!existingUser.getUsername().equals(onlineUser.getUsername())) { + if (!existingUser.getUsername().equals(onlineUser.getName())) { // Update a player's name if it has changed in the database - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + UPDATE `%player_data%` SET `username`=? WHERE `uuid`=?"""))) { - statement.setString(1, onlineUser.getUsername()); + statement.setString(1, onlineUser.getName()); statement.setString(2, existingUser.getUserUuid().toString()); statement.executeUpdate(); - plugin.log(Level.INFO, "Updated " + onlineUser.getUsername() - + "'s name in the database (" + existingUser.getUsername() - + " -> " + onlineUser.getUsername() + ")"); + plugin.log(Level.INFO, "Updated " + onlineUser.getName() + + "'s name in the database (" + existingUser.getUsername() + + " -> " + onlineUser.getName() + ")"); } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e); } @@ -259,12 +338,12 @@ public class SqLiteDatabase extends Database { }, () -> { // Insert new player data into the database - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - INSERT INTO `%players_table%` (`uuid`,`username`) + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + INSERT INTO `%player_data%` (`uuid`,`username`) VALUES (?,?);"""))) { statement.setString(1, onlineUser.getUuid().toString()); - statement.setString(2, onlineUser.getUsername()); + statement.setString(2, onlineUser.getName()); statement.executeUpdate(); } catch (SQLException e) { @@ -274,10 +353,10 @@ public class SqLiteDatabase extends Database { } @Override - public Optional getUserDataByName(@NotNull String name) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + public Optional getUser(@NotNull String name) { + try (PreparedStatement statement = getConnection().prepareStatement(format(""" SELECT `uuid`, `username`, `home_slots`, `ignoring_requests` - FROM `%players_table%` + FROM `%player_data%` WHERE `username`=?"""))) { statement.setString(1, name); @@ -297,10 +376,10 @@ public class SqLiteDatabase extends Database { } @Override - public Optional getUserData(@NotNull UUID uuid) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + public Optional getUser(@NotNull UUID uuid) { + try (PreparedStatement statement = getConnection().prepareStatement(format(""" SELECT `uuid`, `username`, `home_slots`, `ignoring_requests` - FROM `%players_table%` + FROM `%player_data%` WHERE `uuid`=?"""))) { statement.setString(1, uuid.toString()); @@ -321,13 +400,13 @@ public class SqLiteDatabase extends Database { } @Override - public void deleteUserData(@NotNull UUID uuid) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` + public void deleteUser(@NotNull UUID uuid) { + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + DELETE FROM `%position_data%` WHERE `id` - IN ((SELECT `last_position` FROM `%players_table%` WHERE `uuid` = ?), - (SELECT `offline_position` FROM `%players_table%` WHERE `uuid` = ?), - (SELECT `respawn_position` FROM `%players_table%` WHERE `uuid` = ?));"""))) { + IN ((SELECT `last_position` FROM `%player_data%` WHERE `uuid` = ?), + (SELECT `offline_position` FROM `%player_data%` WHERE `uuid` = ?), + (SELECT `respawn_position` FROM `%player_data%` WHERE `uuid` = ?));"""))) { statement.setString(1, uuid.toString()); statement.setString(2, uuid.toString()); statement.setString(3, uuid.toString()); @@ -337,8 +416,8 @@ public class SqLiteDatabase extends Database { return; } - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - DELETE FROM `%players_table%` + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + DELETE FROM `%player_data%` WHERE `uuid`=?;"""))) { statement.setString(1, uuid.toString()); statement.executeUpdate(); @@ -349,9 +428,9 @@ public class SqLiteDatabase extends Database { @Override public Optional getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = getConnection().prepareStatement(format(""" SELECT `type`, `start_timestamp`, `end_timestamp` - FROM `%cooldowns_table%` + FROM `%player_cooldowns_data%` WHERE `player_uuid`=? AND `type`=? ORDER BY `start_timestamp` DESC LIMIT 1;"""))) { @@ -370,8 +449,8 @@ public class SqLiteDatabase extends Database { @Override public void removeCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - DELETE FROM `%cooldowns_table%` + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + DELETE FROM `%player_cooldowns_data%` WHERE `player_uuid`=? AND `type`=?;"""))) { statement.setString(1, user.getUuid().toString()); statement.setString(2, action.name().toLowerCase(Locale.ENGLISH)); @@ -384,8 +463,8 @@ public class SqLiteDatabase extends Database { @Override public void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user, @NotNull Instant cooldownExpiry) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - INSERT INTO `%cooldowns_table%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`) + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + INSERT INTO `%player_cooldowns_data%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`) VALUES (?,?,?,?);"""))) { statement.setString(1, user.getUuid().toString()); statement.setString(2, action.name().toLowerCase(Locale.ENGLISH)); @@ -400,16 +479,16 @@ public class SqLiteDatabase extends Database { @Override public List getHomes(@NotNull User user) { final List userHomes = new ArrayList<>(); - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, `timestamp`, + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` - ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` - ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + FROM `%home_data%` + INNER JOIN `%saved_position_data%` + ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` + INNER JOIN `%player_data%` + ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid` WHERE `owner_uuid`=? ORDER BY `name`;"""))) { statement.setString(1, user.getUuid().toString()); @@ -434,7 +513,7 @@ public class SqLiteDatabase extends Database { } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getUsername()); + plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getName()); } return userHomes; } @@ -442,14 +521,14 @@ public class SqLiteDatabase extends Database { @Override public List getWarps() { final List warps = new ArrayList<>(); - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + SELECT `%warp_data%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` - ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + FROM `%warp_data%` + INNER JOIN `%saved_position_data%` + ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` ORDER BY `name`;"""))) { final ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { @@ -476,17 +555,17 @@ public class SqLiteDatabase extends Database { @Override public List getPublicHomes() { final List userHomes = new ArrayList<>(); - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` - ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` - ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + FROM `%home_data%` + INNER JOIN `%saved_position_data%` + ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` + INNER JOIN `%player_data%` + ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid` WHERE `public`=true ORDER BY `name`;"""))) { final ResultSet resultSet = statement.executeQuery(); @@ -518,17 +597,17 @@ public class SqLiteDatabase extends Database { @Override public List getPublicHomes(@NotNull String name, boolean caseInsensitive) { final List userHomes = new ArrayList<>(); - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` - ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` - ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + FROM `%home_data%` + INNER JOIN `%saved_position_data%` + ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` + INNER JOIN `%player_data%` + ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid` WHERE `public`=true AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?)) ORDER BY `name`;"""))) { @@ -563,17 +642,17 @@ public class SqLiteDatabase extends Database { @Override public Optional getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` - ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` - ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + FROM `%home_data%` + INNER JOIN `%saved_position_data%` + ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` + INNER JOIN `%player_data%` + ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid` WHERE `owner_uuid`=? AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { statement.setString(1, user.getUuid().toString()); @@ -607,18 +686,18 @@ public class SqLiteDatabase extends Database { @Override public Optional getHome(@NotNull UUID uuid) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + SELECT `%home_data%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` - FROM `%homes_table%` - INNER JOIN `%saved_positions_table%` - ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - INNER JOIN `%players_table%` - ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` - WHERE `%homes_table%`.`uuid`=?;"""))) { + FROM `%home_data%` + INNER JOIN `%saved_position_data%` + ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` + INNER JOIN `%player_data%` + ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid` + WHERE `%home_data%`.`uuid`=?;"""))) { statement.setString(1, uuid.toString()); final ResultSet resultSet = statement.executeQuery(); @@ -648,14 +727,14 @@ public class SqLiteDatabase extends Database { @Override public Optional getWarp(@NotNull String warpName, boolean caseInsensitive) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + SELECT `%warp_data%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` - ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + FROM `%warp_data%` + INNER JOIN `%saved_position_data%` + ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { statement.setBoolean(1, caseInsensitive); statement.setString(2, warpName); @@ -685,15 +764,15 @@ public class SqLiteDatabase extends Database { @Override public Optional getWarp(@NotNull UUID uuid) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + SELECT `%warp_data%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%warps_table%` - INNER JOIN `%saved_positions_table%` - ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` - INNER JOIN `%positions_table%` - ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` - WHERE `%warps_table%`.uuid=?;"""))) { + FROM `%warp_data%` + INNER JOIN `%saved_position_data%` + ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id` + INNER JOIN `%position_data%` + ON `%saved_position_data%`.`position_id`=`%position_data%`.`id` + WHERE `%warp_data%`.uuid=?;"""))) { statement.setString(1, uuid.toString()); final ResultSet resultSet = statement.executeQuery(); @@ -720,10 +799,10 @@ public class SqLiteDatabase extends Database { @Override public Optional getCurrentTeleport(@NotNull OnlineUser onlineUser) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = getConnection().prepareStatement(format(""" SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `type` - FROM `%teleports_table%` - INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id` + FROM `%teleport_data%` + INNER JOIN `%position_data%` ON `%teleport_data%`.`destination_id` = `%position_data%`.`id` WHERE `player_uuid`=?"""))) { statement.setString(1, onlineUser.getUuid().toString()); @@ -745,7 +824,7 @@ public class SqLiteDatabase extends Database { .toTeleport()); } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getName(), e); } catch (TeleportationException e) { e.displayMessage(onlineUser); } @@ -754,8 +833,8 @@ public class SqLiteDatabase extends Database { @Override public void updateUserData(@NotNull SavedUser savedUser) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + UPDATE `%player_data%` SET `home_slots`=?, `ignoring_requests`=? WHERE `uuid`=?"""))) { @@ -771,40 +850,40 @@ public class SqLiteDatabase extends Database { @Override public void setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) { // Clear the user's current teleport - try (PreparedStatement deleteStatement = getConnection().prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` + try (PreparedStatement deleteStatement = getConnection().prepareStatement(format(""" + DELETE FROM `%position_data%` WHERE `id`=( SELECT `destination_id` - FROM `%teleports_table%` - WHERE `%teleports_table%`.`player_uuid`=? + FROM `%teleport_data%` + WHERE `%teleport_data%`.`player_uuid`=? );"""))) { deleteStatement.setString(1, user.getUuid().toString()); deleteStatement.executeUpdate(); } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getName(), e); } // Set the user's teleport into the database (if it's not null) if (teleport != null) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`) + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + INSERT INTO `%teleport_data%` (`player_uuid`, `destination_id`, `type`) VALUES (?,?,?);"""))) { statement.setString(1, user.getUuid().toString()); statement.setInt(2, setPosition((Position) teleport.getTarget(), connection)); statement.setInt(3, teleport.getType().getTypeId()); statement.executeUpdate(); } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to set the current teleport of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the current teleport of " + user.getName(), e); } } } @Override public Optional getLastPosition(@NotNull User user) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = getConnection().prepareStatement(format(""" SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`last_position` = `%positions_table%`.`id` + FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.`last_position` = `%position_data%`.`id` WHERE `uuid`=?"""))) { statement.setString(1, user.getUuid().toString()); @@ -820,16 +899,16 @@ public class SqLiteDatabase extends Database { resultSet.getString("server_name"))); } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getName(), e); } return Optional.empty(); } @Override public void setLastPosition(@NotNull User user, @NotNull Position position) { - try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `last_position` FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id` + try (PreparedStatement queryStatement = getConnection().prepareStatement(format(""" + SELECT `last_position` FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.last_position = `%position_data%`.`id` WHERE `uuid`=?;"""))) { queryStatement.setString(1, user.getUuid().toString()); @@ -839,8 +918,8 @@ public class SqLiteDatabase extends Database { updatePosition(resultSet.getInt("last_position"), position, connection); } else { // Set the last position - try (PreparedStatement updateStatement = getConnection().prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` + try (PreparedStatement updateStatement = getConnection().prepareStatement(format(""" + UPDATE `%player_data%` SET `last_position`=? WHERE `uuid`=?;"""))) { updateStatement.setInt(1, setPosition(position, connection)); @@ -849,16 +928,16 @@ public class SqLiteDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getName(), e); } } @Override public Optional getOfflinePosition(@NotNull User user) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = getConnection().prepareStatement(format(""" SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id` + FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.`offline_position` = `%position_data%`.`id` WHERE `uuid`=?"""))) { statement.setString(1, user.getUuid().toString()); @@ -875,16 +954,16 @@ public class SqLiteDatabase extends Database { } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getName(), e); } return Optional.empty(); } @Override public void setOfflinePosition(@NotNull User user, @NotNull Position position) { - try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `offline_position` FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.offline_position = `%positions_table%`.`id` + try (PreparedStatement queryStatement = getConnection().prepareStatement(format(""" + SELECT `offline_position` FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.offline_position = `%position_data%`.`id` WHERE `uuid`=?;"""))) { queryStatement.setString(1, user.getUuid().toString()); @@ -894,8 +973,8 @@ public class SqLiteDatabase extends Database { updatePosition(resultSet.getInt("offline_position"), position, connection); } else { // Set the offline position - try (PreparedStatement updateStatement = getConnection().prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` + try (PreparedStatement updateStatement = getConnection().prepareStatement(format(""" + UPDATE `%player_data%` SET `offline_position`=? WHERE `uuid`=?;"""))) { updateStatement.setInt(1, setPosition(position, connection)); @@ -904,16 +983,16 @@ public class SqLiteDatabase extends Database { } } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getName(), e); } } @Override public Optional getRespawnPosition(@NotNull User user) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" + try (PreparedStatement statement = getConnection().prepareStatement(format(""" SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` - FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.`respawn_position` = `%positions_table%`.`id` + FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.`respawn_position` = `%position_data%`.`id` WHERE `uuid`=?"""))) { statement.setString(1, user.getUuid().toString()); @@ -929,16 +1008,16 @@ public class SqLiteDatabase extends Database { resultSet.getString("server_name"))); } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getName(), e); } return Optional.empty(); } @Override public void setRespawnPosition(@NotNull User user, @Nullable Position position) { - try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `respawn_position` FROM `%players_table%` - INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = `%positions_table%`.`id` + try (PreparedStatement queryStatement = getConnection().prepareStatement(format(""" + SELECT `respawn_position` FROM `%player_data%` + INNER JOIN `%position_data%` ON `%player_data%`.respawn_position = `%position_data%`.`id` WHERE `uuid`=?;"""))) { queryStatement.setString(1, user.getUuid().toString()); @@ -946,12 +1025,12 @@ public class SqLiteDatabase extends Database { if (resultSet.next()) { if (position == null) { // Delete a respawn position - try (PreparedStatement deleteStatement = getConnection().prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` + try (PreparedStatement deleteStatement = getConnection().prepareStatement(format(""" + DELETE FROM `%position_data%` WHERE `id`=( SELECT `respawn_position` - FROM `%players_table%` - WHERE `%players_table%`.`uuid`=? + FROM `%player_data%` + WHERE `%player_data%`.`uuid`=? );"""))) { deleteStatement.setString(1, user.getUuid().toString()); deleteStatement.executeUpdate(); @@ -963,8 +1042,8 @@ public class SqLiteDatabase extends Database { } else { if (position != null) { // Set a respawn position - try (PreparedStatement updateStatement = getConnection().prepareStatement(formatStatementTables(""" - UPDATE `%players_table%` + try (PreparedStatement updateStatement = getConnection().prepareStatement(format(""" + UPDATE `%player_data%` SET `respawn_position`=? WHERE `uuid`=?;"""))) { updateStatement.setInt(1, setPosition(position, connection)); @@ -975,7 +1054,7 @@ public class SqLiteDatabase extends Database { } } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getName(), e); } } @@ -984,8 +1063,8 @@ public class SqLiteDatabase extends Database { getHome(home.getUuid()).ifPresentOrElse(presentHome -> { try { // Update the home's saved position, including metadata - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `saved_position_id` FROM `%homes_table%` + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + SELECT `saved_position_id` FROM `%home_data%` WHERE `uuid`=?;"""))) { statement.setString(1, home.getUuid().toString()); @@ -996,8 +1075,8 @@ public class SqLiteDatabase extends Database { } // Update the home privacy - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%homes_table%` + try (PreparedStatement statement = connection.prepareStatement(format(""" + UPDATE `%home_data%` SET `public`=? WHERE `uuid`=?;"""))) { statement.setBoolean(1, home.isPublic()); @@ -1006,11 +1085,11 @@ public class SqLiteDatabase extends Database { } } catch (SQLException e) { plugin.log(Level.SEVERE, - "Failed to update a home in the database for " + home.getOwner().getUsername(), e); + "Failed to update a home in the database for " + home.getOwner().getName(), e); } }, () -> { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`) + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + INSERT INTO `%home_data%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`) VALUES (?,?,?,?);"""))) { statement.setString(1, home.getUuid().toString()); statement.setInt(2, setSavedPosition(home, connection)); @@ -1019,7 +1098,7 @@ public class SqLiteDatabase extends Database { statement.executeUpdate(); } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to set home for " + home.getOwner().getUsername(), e); + plugin.log(Level.SEVERE, "Failed to set home for " + home.getOwner().getName(), e); } }); } @@ -1028,8 +1107,8 @@ public class SqLiteDatabase extends Database { public void saveWarp(@NotNull Warp warp) { getWarp(warp.getUuid()) .ifPresentOrElse(presentWarp -> { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - SELECT `saved_position_id` FROM `%warps_table%` + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + SELECT `saved_position_id` FROM `%warp_data%` WHERE `uuid`=?;"""))) { statement.setString(1, warp.getUuid().toString()); @@ -1041,8 +1120,8 @@ public class SqLiteDatabase extends Database { plugin.log(Level.SEVERE, "Failed to update a warp in the database", e); } }, () -> { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`) + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + INSERT INTO `%warp_data%` (`uuid`, `saved_position_id`) VALUES (?,?);"""))) { statement.setString(1, warp.getUuid().toString()); statement.setInt(2, setSavedPosition(warp, connection)); @@ -1056,14 +1135,14 @@ public class SqLiteDatabase extends Database { @Override public void deleteHome(@NotNull UUID uuid) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id`=( + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id`=( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id`=( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id`=( SELECT `saved_position_id` - FROM `%homes_table%` + FROM `%home_data%` WHERE `uuid`=? ) );"""))) { @@ -1076,14 +1155,14 @@ public class SqLiteDatabase extends Database { @Override public int deleteAllHomes(@NotNull User user) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id` IN ( + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id` IN ( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id` IN ( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id` IN ( SELECT `saved_position_id` - FROM `%homes_table%` + FROM `%home_data%` WHERE `owner_uuid`=? ) );"""))) { @@ -1091,21 +1170,21 @@ public class SqLiteDatabase extends Database { statement.setString(1, user.getUuid().toString()); return statement.executeUpdate(); } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getUsername() + " from the database", e); + plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getName() + " from the database", e); } return 0; } @Override public int deleteAllHomes(@NotNull String worldName, @NotNull String serverName) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id` IN ( + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id` IN ( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id` IN ( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id` IN ( SELECT `saved_position_id` - FROM `%homes_table%` + FROM `%home_data%` WHERE `world_name`=? AND `server_name`=? ) @@ -1115,21 +1194,21 @@ public class SqLiteDatabase extends Database { return statement.executeUpdate(); } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to delete homes in the world " + worldName + " on the server " - + serverName + " from the database", e); + + serverName + " from the database", e); } return 0; } @Override public void deleteWarp(@NotNull UUID uuid) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id`=( + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id`=( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id`=( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id`=( SELECT `saved_position_id` - FROM `%warps_table%` + FROM `%warp_data%` WHERE `uuid`=? ) );"""))) { @@ -1142,14 +1221,14 @@ public class SqLiteDatabase extends Database { @Override public int deleteAllWarps() { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id` IN ( + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id` IN ( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id` IN ( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id` IN ( SELECT `saved_position_id` - FROM `%warps_table%` + FROM `%warp_data%` ) );"""))) { return statement.executeUpdate(); @@ -1161,14 +1240,14 @@ public class SqLiteDatabase extends Database { @Override public int deleteAllWarps(@NotNull String worldName, @NotNull String serverName) { - try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables(""" - DELETE FROM `%positions_table%` - WHERE `%positions_table%`.`id` IN ( + try (PreparedStatement statement = getConnection().prepareStatement(format(""" + DELETE FROM `%position_data%` + WHERE `%position_data%`.`id` IN ( SELECT `position_id` - FROM `%saved_positions_table%` - WHERE `%saved_positions_table%`.`id` IN ( + FROM `%saved_position_data%` + WHERE `%saved_position_data%`.`id` IN ( SELECT `saved_position_id` - FROM `%warps_table%` + FROM `%warp_data%` WHERE `world_name`=? AND `server_name`=? ) @@ -1178,13 +1257,13 @@ public class SqLiteDatabase extends Database { return statement.executeUpdate(); } catch (SQLException e) { plugin.log(Level.SEVERE, "Failed to delete warps in the world " + worldName + " on the server " - + serverName + " from the database", e); + + serverName + " from the database", e); } return 0; } @Override - public void terminate() { + public void close() { try { if (connection != null) { if (!connection.isClosed()) { diff --git a/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java b/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java index 7722e43c..48b3d77f 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java @@ -43,20 +43,21 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; -/** - * Hook to display warps and public homes on BlueMap maps. - */ +@PluginHook( + name = "BlueMap", + register = PluginHook.Register.ON_ENABLE +) public class BlueMapHook extends MapHook { private Map publicHomesMarkerSets; private Map warpsMarkerSets; public BlueMapHook(@NotNull HuskHomes plugin) { - super(plugin, "BlueMap"); + super(plugin); } @Override - public void initialize() { + public void load() { BlueMapAPI.onEnable(api -> { this.publicHomesMarkerSets = new ConcurrentHashMap<>(); this.warpsMarkerSets = new ConcurrentHashMap<>(); @@ -81,7 +82,7 @@ public class BlueMapHook extends MapHook { } @Override - public void updateHome(@NotNull Home home) { + public void addHome(@NotNull Home home) { if (!isValidPosition(home)) { return; } @@ -121,7 +122,7 @@ public class BlueMapHook extends MapHook { } @Override - public void updateWarp(@NotNull Warp warp) { + public void addWarp(@NotNull Warp warp) { if (!isValidPosition(warp)) { return; } diff --git a/common/src/main/java/net/william278/huskhomes/hook/DynmapHook.java b/common/src/main/java/net/william278/huskhomes/hook/DynmapHook.java index a1d030a1..b94b4d15 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/DynmapHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/DynmapHook.java @@ -34,9 +34,10 @@ import org.jetbrains.annotations.Nullable; import java.util.Optional; -/** - * Hook to display warps and public homes on Dynmap. - */ +@PluginHook( + name = "Dynmap", + register = PluginHook.Register.ON_ENABLE +) public class DynmapHook extends MapHook { private static final String ICON_PATH = "/tiles/_markers_/"; @@ -48,11 +49,11 @@ public class DynmapHook extends MapHook { private MarkerSet warpsMarkers; public DynmapHook(@NotNull HuskHomes plugin) { - super(plugin, "Dynmap"); + super(plugin); } @Override - public void initialize() { + public void load() { DynmapCommonAPIListener.register(new DynmapCommonAPIListener() { @Override public void apiEnabled(@NotNull DynmapCommonAPI dynmapCommonAPI) { @@ -76,7 +77,7 @@ public class DynmapHook extends MapHook { } @Override - public void updateHome(@NotNull Home home) { + public void addHome(@NotNull Home home) { if (!isValidPosition(home)) { return; } @@ -122,7 +123,7 @@ public class DynmapHook extends MapHook { } @Override - public void updateWarp(@NotNull Warp warp) { + public void addWarp(@NotNull Warp warp) { if (!isValidPosition(warp)) { return; } diff --git a/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java b/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java index 011de2db..936d0d8d 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java @@ -32,8 +32,8 @@ import java.util.Locale; */ public abstract class EconomyHook extends Hook { - protected EconomyHook(@NotNull HuskHomes plugin, @NotNull String hookName) { - super(plugin, hookName); + protected EconomyHook(@NotNull HuskHomes plugin) { + super(plugin); } /** diff --git a/common/src/main/java/net/william278/huskhomes/hook/Hook.java b/common/src/main/java/net/william278/huskhomes/hook/Hook.java index 5ae68b88..54c7546a 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/Hook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/Hook.java @@ -19,47 +19,35 @@ package net.william278.huskhomes.hook; +import com.google.common.base.Preconditions; +import lombok.Getter; import net.william278.huskhomes.HuskHomes; import org.jetbrains.annotations.NotNull; -/** - * A plugin hook, where HuskHomes hooks into another plugin. - */ +@Getter public abstract class Hook { - /** - * The plugin that this hook is for. - */ protected final HuskHomes plugin; + protected final PluginHook hook; - /** - * The name of the hook. - */ - protected final String name; - - /** - * Construct a new {@link Hook}. - * - * @param plugin the {@link HuskHomes} instance - */ - protected Hook(@NotNull HuskHomes plugin, @NotNull String name) { + protected Hook(@NotNull HuskHomes plugin) { this.plugin = plugin; - this.name = name; + this.hook = getClass().getAnnotation(PluginHook.class); + Preconditions.checkNotNull(hook, "Hook class must be annotated with PluginHook"); } - /** - * Initialize the hook and return {@code true} if it could be enabled. - */ - public abstract void initialize(); - - /** - * Get the name of the hook. - * - * @return the name of the hook - */ @NotNull public String getName() { - return name; + return hook.name(); } -} + @NotNull + public PluginHook.Register getRegister() { + return hook.register(); + } + + public abstract void load(); + + public abstract void unload(); + +} \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/hook/HookProvider.java b/common/src/main/java/net/william278/huskhomes/hook/HookProvider.java new file mode 100644 index 00000000..ba89fdf2 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/hook/HookProvider.java @@ -0,0 +1,120 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.hook; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.importer.Importer; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; + +import java.util.*; +import java.util.logging.Level; +import java.util.stream.Collectors; + +public interface HookProvider extends MapHookProvider { + + @NotNull + Set getHooks(); + + default Optional getHook(@NotNull Class hookClass) { + return getHooks().stream() + .filter(hook -> hookClass.isAssignableFrom(hook.getClass())) + .map(hookClass::cast) + .findFirst(); + } + + @NotNull + @Unmodifiable + default Set getImporters() { + return getHooks().stream() + .filter(hook -> hook instanceof Importer) + .map(hook -> (Importer) hook) + .collect(Collectors.toSet()); + } + + default Optional getImporterByName(@NotNull String name) { + return getImporters().stream() + .filter(i -> i.getName().toLowerCase(Locale.ENGLISH).equals(name.toLowerCase(Locale.ENGLISH))) + .findFirst(); + } + + void setHooks(@NotNull Set hooks); + + default void loadHooks() { + setHooks(Sets.newHashSet(getAvailableHooks())); + } + + default void registerHooks(@NotNull PluginHook.Register... register) { + final Set registers = Arrays.stream(register).collect(Collectors.toSet()); + getHooks().removeIf(hook -> { + if (!registers.contains(hook.getRegister())) { + return false; + } + try { + hook.load(); + return false; + } catch (Throwable e) { + getPlugin().log(Level.SEVERE, "Failed to register the %s hook".formatted(hook.getName()), e); + } + return true; + }); + getPlugin().log(Level.INFO, "Registered '%s' hooks".formatted(registers.stream() + .map(h -> h.name().toLowerCase(Locale.ENGLISH)).collect(Collectors.joining(" & ")))); + } + + default void unloadHooks() { + getHooks().removeIf(hook -> { + try { + hook.unload(); + } catch (Throwable e) { + getPlugin().log(Level.SEVERE, "Failed to unload the %s hook".formatted(hook.getName()), e); + } + return true; + }); + } + + @NotNull + default List getAvailableHooks() { + final List hooks = Lists.newArrayList(); + + if (getPlugin().getSettings().getMapHook().isEnabled()) { + if (isDependencyAvailable("Dynmap")) { + getHooks().add(new DynmapHook(getPlugin())); + } else if (isDependencyAvailable("BlueMap")) { + getHooks().add(new BlueMapHook(getPlugin())); + } else if (isDependencyAvailable("Pl3xMap")) { + getHooks().add(new Pl3xMapHook(getPlugin())); + } + } + if (isDependencyAvailable("Plan")) { + getHooks().add(new PlanHook(getPlugin())); + } + + return hooks; + } + + boolean isDependencyAvailable(@NotNull String name); + + @NotNull + HuskHomes getPlugin(); + +} diff --git a/common/src/main/java/net/william278/huskhomes/hook/MapHook.java b/common/src/main/java/net/william278/huskhomes/hook/MapHook.java index 139c76d4..fc803e62 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/MapHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/MapHook.java @@ -40,8 +40,14 @@ public abstract class MapHook extends Hook { protected static final String WARP_MARKER_IMAGE_NAME = "warp"; protected static final String PUBLIC_HOME_MARKER_IMAGE_NAME = "public-home"; - protected MapHook(@NotNull HuskHomes plugin, @NotNull String name) { - super(plugin, name); + protected MapHook(@NotNull HuskHomes plugin) { + super(plugin); + } + + @Override + public void unload() { + getPlugin().getWorlds().forEach(world -> clearHomes(world.getName())); + clearWarps(); } /** @@ -52,12 +58,12 @@ public abstract class MapHook extends Hook { if (settings.isShowPublicHomes()) { plugin.getDatabase() .getLocalPublicHomes(plugin) - .forEach(this::updateHome); + .forEach(this::addHome); } if (settings.isShowWarps()) { plugin.getDatabase() .getLocalWarps(plugin) - .forEach(this::updateWarp); + .forEach(this::addWarp); } } @@ -66,7 +72,7 @@ public abstract class MapHook extends Hook { * * @param home the home to update */ - public abstract void updateHome(@NotNull Home home); + public abstract void addHome(@NotNull Home home); /** * Removes a home from the map. @@ -94,7 +100,7 @@ public abstract class MapHook extends Hook { * * @param warp the warp to update */ - public abstract void updateWarp(@NotNull Warp warp); + public abstract void addWarp(@NotNull Warp warp); /** * Removes a warp from the map. @@ -191,7 +197,7 @@ public abstract class MapHook extends Hook { protected static MarkerInformationPopup publicHome(@NotNull Home home, @NotNull String thumbnail) { final MarkerInformationPopup popup = MarkerInformationPopup.create(home.getName()) .thumbnail(thumbnail) - .field("Owner", home.getOwner().getUsername()) + .field("Owner", home.getOwner().getName()) .field("Location", home.toString()) .field("Command", "/phome " + home.getSafeIdentifier()); if (!home.getMeta().getDescription().isBlank()) { diff --git a/common/src/main/java/net/william278/huskhomes/hook/MapHookProvider.java b/common/src/main/java/net/william278/huskhomes/hook/MapHookProvider.java new file mode 100644 index 00000000..b4fe9953 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/hook/MapHookProvider.java @@ -0,0 +1,77 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.hook; + +import net.william278.huskhomes.position.Home; +import net.william278.huskhomes.position.Warp; +import net.william278.huskhomes.user.User; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; + +import java.util.Set; +import java.util.stream.Collectors; + +public interface MapHookProvider { + + @NotNull + @Unmodifiable + default Set getMapHooks() { + return getHooks().stream() + .filter(hook -> hook instanceof MapHook) + .map(hook -> (MapHook) hook) + .collect(Collectors.toSet()); + } + + default void addMappedHome(@NotNull Home home) { + getMapHooks().forEach(h -> h.addHome(home)); + } + + default void removeMappedHome(@NotNull Home home) { + getMapHooks().forEach(h -> h.removeHome(home)); + } + + default void removeAllMappedHomes(@NotNull String worldName) { + getMapHooks().forEach(h -> h.clearHomes(worldName)); + } + + default void removeAllMappedHomes(@NotNull User user) { + getMapHooks().forEach(h -> h.clearHomes(user)); + } + + default void addMappedWarp(@NotNull Warp warp) { + getMapHooks().forEach(h -> h.addWarp(warp)); + } + + default void removeMappedWarp(@NotNull Warp warp) { + getMapHooks().forEach(h -> h.removeWarp(warp)); + } + + default void removeAllMappedWarps(@NotNull String worldName) { + getMapHooks().forEach(h -> h.clearWarps(worldName)); + } + + default void removeAllMappedWarps() { + getMapHooks().forEach(MapHook::clearWarps); + } + + @NotNull + Set getHooks(); + +} diff --git a/common/src/main/java/net/william278/huskhomes/hook/Pl3xMapHook.java b/common/src/main/java/net/william278/huskhomes/hook/Pl3xMapHook.java index 33af5fc8..79717374 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/Pl3xMapHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/Pl3xMapHook.java @@ -62,11 +62,11 @@ public class Pl3xMapHook extends MapHook implements EventListener { private final ConcurrentLinkedQueue warps = new ConcurrentLinkedQueue<>(); public Pl3xMapHook(@NotNull HuskHomes plugin) { - super(plugin, "Pl3xMap"); + super(plugin); } @Override - public void initialize() { + public void load() { Pl3xMap.api().getEventRegistry().register(this); if (Pl3xMap.api().isEnabled()) { onPl3xMapEnabled(new Pl3xMapEnabledEvent()); @@ -74,7 +74,7 @@ public class Pl3xMapHook extends MapHook implements EventListener { } @Override - public void updateHome(@NotNull Home home) { + public void addHome(@NotNull Home home) { publicHomes.remove(home); if (isValidPosition(home)) { publicHomes.add(home); @@ -97,7 +97,7 @@ public class Pl3xMapHook extends MapHook implements EventListener { } @Override - public void updateWarp(@NotNull Warp warp) { + public void addWarp(@NotNull Warp warp) { warps.remove(warp); if (isValidPosition(warp)) { warps.add(warp); @@ -159,8 +159,8 @@ public class Pl3xMapHook extends MapHook implements EventListener { // Update home positions plugin.runAsync(() -> { - plugin.getDatabase().getLocalPublicHomes(plugin).forEach(this::updateHome); - plugin.getDatabase().getLocalWarps(plugin).forEach(this::updateWarp); + plugin.getDatabase().getLocalPublicHomes(plugin).forEach(this::addHome); + plugin.getDatabase().getLocalWarps(plugin).forEach(this::addWarp); }); } diff --git a/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java b/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java index 94d2dc80..029c475c 100644 --- a/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java +++ b/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java @@ -39,20 +39,17 @@ import org.jetbrains.annotations.NotNull; import java.util.UUID; import java.util.logging.Level; -/** - * Hooks into Plan to provide the {@link PlanDataExtension} with stats on the web panel. - */ +@PluginHook( + name = "Plan", + register = PluginHook.Register.ON_ENABLE +) public class PlanHook extends Hook { - private final HuskHomes plugin; - public PlanHook(@NotNull HuskHomes plugin) { - super(plugin, "Plan"); - this.plugin = plugin; + super(plugin); } - @Override - public void initialize() { + public void load() { if (!areAllCapabilitiesAvailable()) { return; } @@ -60,6 +57,9 @@ public class PlanHook extends Hook { handlePlanReload(); } + @Override + public void unload() { + } private boolean areAllCapabilitiesAvailable() { CapabilityService capabilities = CapabilityService.getInstance(); @@ -114,7 +114,7 @@ public class PlanHook extends Hook { hidden = true ) public boolean getHasUserData(@NotNull UUID uuid) { - return database.getUserData(uuid).isPresent(); + return database.getUser(uuid).isPresent(); } @NumberProvider( @@ -126,7 +126,7 @@ public class PlanHook extends Hook { ) @Conditional("hasData") public long getHomeCount(@NotNull UUID uuid) { - return database.getUserData(uuid) + return database.getUser(uuid) .map(userData -> (long) database.getHomes(userData.getUser()).size()) .orElse(0L); } @@ -140,7 +140,7 @@ public class PlanHook extends Hook { ) @Conditional("hasData") public long getPublicHomeCount(@NotNull UUID uuid) { - return database.getUserData(uuid) + return database.getUser(uuid) .map(userData -> database.getHomes(userData.getUser()).stream() .filter(Home::isPublic).count()) .orElse(0L); @@ -155,7 +155,7 @@ public class PlanHook extends Hook { ) @Conditional("hasData") public long getPurchasedHomeSlots(@NotNull UUID uuid) { - return database.getUserData(uuid) + return database.getUser(uuid) .map(userData -> (long) userData.getHomeSlots()) .orElse(0L); } @@ -169,7 +169,7 @@ public class PlanHook extends Hook { ) @Conditional("hasData") public boolean isIgnoringTeleportRequests(@NotNull UUID uuid) { - return database.getUserData(uuid) + return database.getUser(uuid) .map(SavedUser::isIgnoringTeleports) .orElse(false); } @@ -183,7 +183,7 @@ public class PlanHook extends Hook { ) @Conditional("hasData") public String getOfflinePosition(@NotNull UUID uuid) { - return database.getUserData(uuid) + return database.getUser(uuid) .map(userData -> database.getOfflinePosition(userData.getUser()) .map(Position::toString) .orElse(UNKNOWN_STRING)) diff --git a/common/src/main/java/net/william278/huskhomes/hook/PluginHook.java b/common/src/main/java/net/william278/huskhomes/hook/PluginHook.java new file mode 100644 index 00000000..4e46853d --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/hook/PluginHook.java @@ -0,0 +1,44 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.hook; + +import org.jetbrains.annotations.NotNull; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(value = ElementType.TYPE) +@Retention(value = RetentionPolicy.RUNTIME) +public @interface PluginHook { + + @NotNull + String name(); + + @NotNull + Register register(); + + enum Register { + ON_LOAD, + ON_ENABLE + } + +} diff --git a/common/src/main/java/net/william278/huskhomes/importer/Importer.java b/common/src/main/java/net/william278/huskhomes/importer/Importer.java index 98d17059..67e24e07 100644 --- a/common/src/main/java/net/william278/huskhomes/importer/Importer.java +++ b/common/src/main/java/net/william278/huskhomes/importer/Importer.java @@ -35,24 +35,27 @@ import java.util.logging.Level; public abstract class Importer extends Hook { protected final HuskHomes plugin; - private final String name; private final List supportedImportData; - protected Importer(@NotNull String name, @NotNull List supportedData, @NotNull HuskHomes plugin) { - super(plugin, name + " Importer"); - this.name = name; + protected Importer(@NotNull List supportedData, @NotNull HuskHomes plugin) { + super(plugin); this.supportedImportData = supportedData; this.plugin = plugin; } @Override - public void initialize() { - // No initialization required + public void load() { + // Empty + } + + @Override + public void unload() { + // Empty } public final void start(@NotNull CommandUser user) { final LocalDateTime startTime = LocalDateTime.now(); - log(user, Level.INFO, "⌚ Starting " + name + " data import..."); + log(user, Level.INFO, "⌚ Starting " + getName() + " data import..."); for (ImportData data : supportedImportData) { try { @@ -66,7 +69,7 @@ public abstract class Importer extends Hook { } final long timeTaken = startTime.until(LocalDateTime.now(), ChronoUnit.SECONDS); - log(user, Level.INFO, "✔ Completed import from " + name + " (took " + timeTaken + "s)"); + log(user, Level.INFO, "✔ Completed import from " + getName() + " (took " + timeTaken + "s)"); } protected abstract int importData(@NotNull ImportData importData) throws Throwable; @@ -83,11 +86,6 @@ public abstract class Importer extends Hook { plugin.log(level, message, e); } - @NotNull - public String getImporterName() { - return name; - } - @NotNull public List getSupportedImportData() { return supportedImportData; diff --git a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java index 43b826e4..dce513fe 100644 --- a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java +++ b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java @@ -20,6 +20,8 @@ package net.william278.huskhomes.listener; import de.themoep.minedown.adventure.MineDown; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.command.BackCommand; import net.william278.huskhomes.command.Command; @@ -32,23 +34,22 @@ import net.william278.huskhomes.teleport.Teleport; import net.william278.huskhomes.teleport.TeleportBuilder; import net.william278.huskhomes.teleport.TeleportationException; import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.user.User; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Optional; -import java.util.logging.Level; /** * A handler for when events take place. */ -public class EventListener { +@AllArgsConstructor(access = AccessLevel.PROTECTED) +public abstract class EventListener { @NotNull - protected final HuskHomes plugin; + private final HuskHomes plugin; - protected EventListener(@NotNull HuskHomes plugin) { - this.plugin = plugin; - } + public abstract void register(); /** * Handle when a {@link OnlineUser} joins the server. @@ -67,7 +68,7 @@ public class EventListener { // Synchronize the global player list plugin.runSyncDelayed(() -> this.synchronizeGlobalPlayerList( - onlineUser, plugin.getLocalPlayerList()), + onlineUser, plugin.getOnlineUsers().stream().map(User::getName).toList()), onlineUser, 40L ); @@ -82,7 +83,7 @@ public class EventListener { plugin.getManager().homes().cacheUserHomes(onlineUser); // Set their ignoring requests state - plugin.getDatabase().getUserData(onlineUser.getUuid()).ifPresent(userData -> { + plugin.getDatabase().getUser(onlineUser.getUuid()).ifPresent(userData -> { plugin.getSavedUsers().add(userData); // Send a reminder message if they are still ignoring requests @@ -111,10 +112,8 @@ public class EventListener { // Update global lists if (plugin.getSettings().getCrossServer().isEnabled()) { - final List localPlayerList = plugin.getLocalPlayerList().stream() - .filter(player -> !player.equals(onlineUser.getUsername())) - .toList(); - + final List localPlayerList = plugin.getOnlineUsers().stream().map(User::getName) + .filter(player -> !player.equals(onlineUser.getName())).toList(); if (plugin.getSettings().getCrossServer().getBrokerType() == Broker.Type.REDIS) { this.synchronizeGlobalPlayerList(onlineUser, localPlayerList); return; @@ -125,6 +124,9 @@ public class EventListener { .findAny() .ifPresent(player -> this.synchronizeGlobalPlayerList(player, localPlayerList)); } + + // Remove from user map + plugin.getOnlineUserMap().remove(onlineUser.getUuid()); }); } @@ -164,7 +166,7 @@ public class EventListener { if (bedPosition.isEmpty()) { plugin.getSpawn().ifPresent(spawn -> { if (plugin.getSettings().getCrossServer().isEnabled() - && !spawn.getServer().equals(plugin.getServerName())) { + && !spawn.getServer().equals(plugin.getServerName())) { plugin.runSyncDelayed(() -> Teleport.builder(plugin) .teleporter(teleporter) .target(spawn) @@ -190,25 +192,27 @@ public class EventListener { plugin.getDatabase().setRespawnPosition(teleporter, bedPosition.orElse(null)); } - // Synchronize the global player list + // Synchronize the global player list TODO CHECK private void synchronizeGlobalPlayerList(@NotNull OnlineUser user, @NotNull List localPlayerList) { - // Send this server's player list to all servers - Message.builder() - .type(Message.Type.PLAYER_LIST) - .scope(Message.Scope.SERVER) - .target(Message.TARGET_ALL) - .payload(Payload.withStringList(localPlayerList)) - .build().send(plugin.getMessenger(), user); - - // Clear cached global player lists and request updated lists from all servers - if (plugin.getOnlineUsers().size() == 1) { - plugin.getGlobalPlayerList().clear(); + plugin.getBroker().ifPresent(broker -> { + // Send this server's player list to all servers Message.builder() - .type(Message.Type.REQUEST_PLAYER_LIST) + .type(Message.Type.PLAYER_LIST) .scope(Message.Scope.SERVER) .target(Message.TARGET_ALL) - .build().send(plugin.getMessenger(), user); - } + .payload(Payload.withStringList(localPlayerList)) + .build().send(broker, user); + + // Clear cached global player lists and request updated lists from all servers + if (plugin.getOnlineUsers().size() == 1) { + plugin.getGlobalUserList().clear(); + Message.builder() + .type(Message.Type.REQUEST_PLAYER_LIST) + .scope(Message.Scope.SERVER) + .target(Message.TARGET_ALL) + .build().send(broker, user); + } + }); } /** @@ -233,7 +237,7 @@ public class EventListener { // Display the return by death via /back notification final boolean canReturnByDeath = plugin.getCommand(BackCommand.class) .map(command -> onlineUser.hasPermission(command.getPermission()) - && onlineUser.hasPermission(command.getPermission("death"))) + && onlineUser.hasPermission(command.getPermission("death"))) .orElse(false); if (plugin.getSettings().getGeneral().getBackCommand().isReturnByDeath() && canReturnByDeath) { plugin.getLocales().getLocale("return_by_death_notification") @@ -288,7 +292,7 @@ public class EventListener { return; } - plugin.runAsync(() -> plugin.getDatabase().getUserData(onlineUser.getUuid()) + plugin.runAsync(() -> plugin.getDatabase().getUser(onlineUser.getUuid()) .ifPresent(data -> plugin.getDatabase().setLastPosition(data.getUser(), sourcePosition))); } @@ -300,17 +304,15 @@ public class EventListener { */ protected final void handlePlayerUpdateSpawnPoint(@NotNull OnlineUser onlineUser, @NotNull Position position) { if (!plugin.getSettings().getGeneral().isAlwaysRespawnAtSpawn() - && plugin.getSettings().getCrossServer().isEnabled() - && plugin.getSettings().getCrossServer().isGlobalRespawning()) { + && plugin.getSettings().getCrossServer().isEnabled() + && plugin.getSettings().getCrossServer().isGlobalRespawning()) { plugin.getDatabase().setRespawnPosition(onlineUser, position); } } - /** - * Handle when the plugin is disabling (server is shutting down). - */ - public final void handlePluginDisable() { - plugin.log(Level.INFO, "Successfully disabled HuskHomes v" + plugin.getVersion()); + @NotNull + protected HuskHomes getPlugin() { + return plugin; } } diff --git a/common/src/main/java/net/william278/huskhomes/listener/ListenerProvider.java b/common/src/main/java/net/william278/huskhomes/listener/ListenerProvider.java new file mode 100644 index 00000000..52db913d --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/listener/ListenerProvider.java @@ -0,0 +1,34 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.listener; + +import org.jetbrains.annotations.NotNull; + +public interface ListenerProvider { + + @NotNull + EventListener createListener(); + + default void loadListeners() { + createListener().register(); + } + + +} diff --git a/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java index f1d09d17..2392d3e5 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java @@ -83,7 +83,7 @@ public class HomesManager { public Map> getPublicHomes() { return publicHomes.stream().collect( HashMap::new, - (m, e) -> m.put(e.getOwner().getUsername(), List.of(e.getName())), + (m, e) -> m.put(e.getOwner().getName(), List.of(e.getName())), HashMap::putAll ); } @@ -123,7 +123,7 @@ public class HomesManager { * @param user the user to cache homes for */ public void cacheUserHomes(@NotNull User user) { - userHomes.put(user.getUsername(), new ConcurrentLinkedQueue<>(plugin.getDatabase().getHomes(user))); + userHomes.put(user.getName(), new ConcurrentLinkedQueue<>(plugin.getDatabase().getHomes(user))); } /** @@ -133,17 +133,17 @@ public class HomesManager { * @param propagate whether to propagate the cache update to other servers (if cross-server is enabled) */ public void cacheHome(@NotNull Home home, boolean propagate) { - userHomes.computeIfPresent(home.getOwner().getUsername(), (k, v) -> { + userHomes.computeIfPresent(home.getOwner().getName(), (k, v) -> { v.remove(home); v.add(home); return v; }); if (publicHomes.remove(home) && !home.isPublic()) { - plugin.getMapHook().ifPresent(hook -> hook.removeHome(home)); + plugin.removeMappedHome(home); } if (home.isPublic()) { publicHomes.add(home); - plugin.getMapHook().ifPresent(hook -> hook.updateHome(home)); + plugin.addMappedHome(home); } plugin.getCommands().stream() @@ -159,7 +159,7 @@ public class HomesManager { userHomes.values().forEach(homes -> homes.removeIf(home -> home.getUuid().equals(homeId))); publicHomes.removeIf(home -> { if (home.getUuid().equals(homeId)) { - plugin.getMapHook().ifPresent(hook -> hook.removeHome(home)); + plugin.removeMappedHome(home); return true; } return false; @@ -182,14 +182,13 @@ public class HomesManager { * @param homeId the UUID of the home/warp to update */ private void propagateCacheUpdate(@NotNull UUID homeId) { - if (plugin.getSettings().getCrossServer().isEnabled()) { - plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder() - .type(Message.Type.UPDATE_HOME) - .scope(Message.Scope.SERVER) - .target(Message.TARGET_ALL) - .payload(Payload.withString(homeId.toString())) - .build().send(plugin.getMessenger(), user)); - } + plugin.getBroker().ifPresent(b -> plugin.getOnlineUsers().stream().findAny() + .ifPresent(user -> Message.builder() + .type(Message.Type.UPDATE_HOME) + .scope(Message.Scope.SERVER) + .target(Message.TARGET_ALL) + .payload(Payload.withString(homeId.toString())) + .build().send(b, user))); } public void updatePublicHomeCache() { @@ -210,7 +209,7 @@ public class HomesManager { } // Validate the home name; throw an exception if invalid - plugin.getValidator().validateName(name); + plugin.validateName(name); // Determine what the new home count would be & validate against user max homes int homes = plugin.getDatabase().getHomes(owner).size() + (existingHome.isPresent() ? 0 : 1); @@ -220,10 +219,10 @@ public class HomesManager { // Validate against user home slots final SavedUser savedOwner = plugin.getSavedUser(owner) - .or(() -> plugin.getDatabase().getUserData(owner.getUuid())) + .or(() -> plugin.getDatabase().getUser(owner.getUuid())) .orElseThrow(() -> new IllegalStateException("User data not found for " + owner.getUuid())); if (plugin.getSettings().getEconomy().isEnabled() - && homes > getFreeHomes(owner) && homes > savedOwner.getHomeSlots()) { + && homes > getFreeHomes(owner) && homes > savedOwner.getHomeSlots()) { if (!buyAdditionalSlots || plugin.getEconomyHook().isEmpty() || !(owner instanceof OnlineUser online)) { throw new ValidationException(ValidationException.Type.NOT_ENOUGH_HOME_SLOTS); } @@ -233,7 +232,7 @@ public class HomesManager { throw new ValidationException(ValidationException.Type.TRANSACTION_FAILED); } plugin.performTransaction(online, TransactionResolver.Action.ADDITIONAL_HOME_SLOT); - plugin.editUserData(online, (SavedUser saved) -> saved.setHomeSlots(saved.getHomeSlots() + 1)); + plugin.editSavedUser(online, (SavedUser saved) -> saved.setHomeSlots(saved.getHomeSlots() + 1)); } final Home home = existingHome @@ -272,12 +271,12 @@ public class HomesManager { public int deleteAllHomes(@NotNull User owner) { final int deleted = plugin.getDatabase().deleteAllHomes(owner); - userHomes.computeIfPresent(owner.getUsername(), (k, v) -> { + userHomes.computeIfPresent(owner.getName(), (k, v) -> { v.clear(); return v; }); publicHomes.removeIf(h -> h.getOwner().getUuid().equals(owner.getUuid())); - plugin.getMapHook().ifPresent(hook -> hook.clearHomes(owner)); + plugin.removeAllMappedHomes(owner); plugin.getCommands().stream() .filter(command -> command instanceof ListCommand) .map(command -> (ListCommand) command) @@ -293,7 +292,7 @@ public class HomesManager { )); publicHomes.removeIf(h -> h.getWorld().getName().equals(worldName) && h.getServer().equals(serverName)); if (plugin.getSettings().getCrossServer().isEnabled() && serverName.equals(plugin.getServerName())) { - plugin.getMapHook().ifPresent(hook -> hook.clearHomes(worldName)); + plugin.removeAllMappedHomes(worldName); } plugin.getCommands().stream() .filter(command -> command instanceof ListCommand) @@ -333,7 +332,7 @@ public class HomesManager { if (plugin.getDatabase().getHome(home.getOwner(), newName).isPresent()) { throw new ValidationException(ValidationException.Type.NAME_TAKEN); } - plugin.getValidator().validateName(newName); + plugin.validateName(newName); home.getMeta().setName(newName); plugin.getDatabase().saveHome(home); this.cacheHome(home, true); @@ -350,7 +349,7 @@ public class HomesManager { } public void setHomeDescription(@NotNull Home home, @NotNull String description) { - plugin.getValidator().validateDescription(description); + plugin.validateDescription(description); home.getMeta().setDescription(description); plugin.getDatabase().saveHome(home); this.cacheHome(home, true); diff --git a/common/src/main/java/net/william278/huskhomes/manager/Manager.java b/common/src/main/java/net/william278/huskhomes/manager/Manager.java index 8696e7e9..31d9c3d1 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/Manager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/Manager.java @@ -54,12 +54,11 @@ public class Manager { // Update caches on all servers protected void propagateCacheUpdate() { - if (plugin.getSettings().getCrossServer().isEnabled()) { - plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder() - .type(Message.Type.UPDATE_CACHES) - .scope(Message.Scope.SERVER) - .target(Message.TARGET_ALL) - .build().send(plugin.getMessenger(), user)); - } + plugin.getBroker().ifPresent(b -> plugin.getOnlineUsers().stream() + .findAny().ifPresent(user -> Message.builder() + .type(Message.Type.UPDATE_CACHES) + .scope(Message.Scope.SERVER) + .target(Message.TARGET_ALL) + .build().send(b, user))); } } diff --git a/common/src/main/java/net/william278/huskhomes/manager/ManagerProvider.java b/common/src/main/java/net/william278/huskhomes/manager/ManagerProvider.java new file mode 100644 index 00000000..bc322386 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/manager/ManagerProvider.java @@ -0,0 +1,39 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.manager; + +import net.william278.huskhomes.HuskHomes; +import org.jetbrains.annotations.NotNull; + +public interface ManagerProvider { + + default void loadManager() { + setManager(new Manager(getPlugin())); + } + + @NotNull + Manager getManager(); + + void setManager(Manager manager); + + @NotNull + HuskHomes getPlugin(); + +} diff --git a/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java b/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java index d8868781..4e0d5573 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/RequestsManager.java @@ -117,23 +117,21 @@ public class RequestsManager { public void sendTeleportAllRequest(@NotNull OnlineUser requester) { final long expiry = Instant.now().getEpochSecond() - + plugin.getSettings().getGeneral().getTeleportRequestExpiryTime(); + + plugin.getSettings().getGeneral().getTeleportRequestExpiryTime(); final TeleportRequest request = new TeleportRequest(requester, TeleportRequest.Type.TPA_HERE, expiry); for (OnlineUser onlineUser : plugin.getOnlineUsers()) { if (onlineUser.equals(requester)) { continue; } - request.setRecipientName(onlineUser.getUsername()); + request.setRecipientName(onlineUser.getName()); sendLocalTeleportRequest(request, onlineUser); } - if (plugin.getSettings().getCrossServer().isEnabled()) { - Message.builder() - .type(Message.Type.TELEPORT_REQUEST) - .payload(Payload.withTeleportRequest(request)) - .target(Message.TARGET_ALL) - .build().send(plugin.getMessenger(), requester); - } + plugin.getBroker().ifPresent(b -> Message.builder() + .type(Message.Type.TELEPORT_REQUEST) + .payload(Payload.withTeleportRequest(request)) + .target(Message.TARGET_ALL) + .build().send(b, requester)); } /** @@ -146,7 +144,7 @@ public class RequestsManager { public void sendTeleportRequest(@NotNull OnlineUser requester, @NotNull String targetUser, @NotNull TeleportRequest.Type type) throws IllegalArgumentException { final long expiry = Instant.now().getEpochSecond() - + plugin.getSettings().getGeneral().getTeleportRequestExpiryTime(); + + plugin.getSettings().getGeneral().getTeleportRequestExpiryTime(); final TeleportRequest request = new TeleportRequest(requester, type, expiry); final Optional localTarget = plugin.getOnlineUser(targetUser); if (localTarget.isPresent()) { @@ -164,11 +162,14 @@ public class RequestsManager { // If the player couldn't be found locally, send the request cross-server if (plugin.getSettings().getCrossServer().isEnabled()) { request.setRecipientName(targetUser); - plugin.fireEvent(plugin.getSendTeleportRequestEvent(requester, request), (event -> Message.builder() - .type(Message.Type.TELEPORT_REQUEST) - .payload(Payload.withTeleportRequest(request)) - .target(targetUser) - .build().send(plugin.getMessenger(), requester))); + plugin.fireEvent( + plugin.getSendTeleportRequestEvent(requester, request), + (event -> plugin.getBroker().ifPresent(b -> Message.builder() + .type(Message.Type.TELEPORT_REQUEST) + .payload(Payload.withTeleportRequest(request)) + .target(targetUser) + .build().send(b, requester))) + ); return; } throw new IllegalArgumentException("Player not found"); @@ -181,7 +182,7 @@ public class RequestsManager { * @param recipient The online recipient of the request */ public void sendLocalTeleportRequest(@NotNull TeleportRequest request, @NotNull OnlineUser recipient) { - request.setRecipientName(recipient.getUsername()); + request.setRecipientName(recipient.getName()); // Silently ignore the request if the recipient is ignoring requests or is vanished if (isIgnoringRequests(recipient) || recipient.isVanished()) { @@ -201,7 +202,7 @@ public class RequestsManager { plugin.fireEvent(plugin.getReceiveTeleportRequestEvent(recipient, request), (event -> { addTeleportRequest(request, recipient); plugin.getLocales().getLocale((request.getType() == TeleportRequest.Type.TPA ? "tpa" : "tpahere") - + "_request_received", request.getRequesterName()) + + "_request_received", request.getRequesterName()) .ifPresent(recipient::sendMessage); plugin.getLocales().getLocale("teleport_request_buttons", request.getRequesterName()) .ifPresent(recipient::sendMessage); @@ -298,12 +299,12 @@ public class RequestsManager { if (localRequester.isPresent()) { handleLocalRequestResponse(localRequester.get(), request); } else if (plugin.getSettings().getCrossServer().isEnabled()) { - Message.builder() + plugin.getBroker().ifPresent(b -> Message.builder() .type(Message.Type.TELEPORT_REQUEST_RESPONSE) .payload(Payload.withTeleportRequest(request)) .target(request.getRequesterName()) .build() - .send(plugin.getMessenger(), recipient); + .send(b, recipient)); } else { plugin.getLocales().getLocale("error_teleport_request_sender_not_online") .ifPresent(recipient::sendMessage); diff --git a/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java b/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java index 5363df6c..de9fb772 100644 --- a/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java +++ b/common/src/main/java/net/william278/huskhomes/manager/WarpsManager.java @@ -21,7 +21,6 @@ package net.william278.huskhomes.manager; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.command.ListCommand; -import net.william278.huskhomes.hook.MapHook; import net.william278.huskhomes.network.Message; import net.william278.huskhomes.network.Payload; import net.william278.huskhomes.position.Position; @@ -49,7 +48,7 @@ public class WarpsManager { public void cacheWarp(@NotNull Warp warp, boolean propagate) { warps.remove(warp); warps.add(warp); - plugin.getMapHook().ifPresent(hook -> hook.updateWarp(warp)); + plugin.addMappedWarp(warp); plugin.getCommands().stream() .filter(command -> command instanceof ListCommand) @@ -63,7 +62,7 @@ public class WarpsManager { public void unCacheWarp(@NotNull UUID warpId, boolean propagate) { warps.removeIf(warp -> { if (warp.getUuid().equals(warpId)) { - plugin.getMapHook().ifPresent(hook -> hook.removeWarp(warp)); + plugin.removeMappedWarp(warp); return true; } return false; @@ -79,14 +78,13 @@ public class WarpsManager { } private void propagateCacheUpdate(@NotNull UUID warpId) { - if (plugin.getSettings().getCrossServer().isEnabled()) { - plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder() - .type(Message.Type.UPDATE_WARP) - .scope(Message.Scope.SERVER) - .target(Message.TARGET_ALL) - .payload(Payload.withString(warpId.toString())) - .build().send(plugin.getMessenger(), user)); - } + plugin.getOnlineUsers().stream().findAny().ifPresent(user -> plugin.getBroker() + .ifPresent(b -> Message.builder() + .type(Message.Type.UPDATE_WARP) + .scope(Message.Scope.SERVER) + .target(Message.TARGET_ALL) + .payload(Payload.withString(warpId.toString())) + .build().send(b, user))); } public void updateWarpCache() { @@ -104,7 +102,7 @@ public class WarpsManager { @NotNull public List getUsableWarps(@NotNull CommandUser user) { if (!plugin.getSettings().getGeneral().isPermissionRestrictWarps() - || user.hasPermission(Warp.getWildcardPermission())) { + || user.hasPermission(Warp.getWildcardPermission())) { return getWarps(); } return warps.stream() @@ -122,7 +120,7 @@ public class WarpsManager { } // Validate the home name; throw an exception if invalid - plugin.getValidator().validateName(name); + plugin.validateName(name); final Warp warp = existingWarp .map(existing -> { @@ -158,7 +156,7 @@ public class WarpsManager { public int deleteAllWarps() { final int deleted = plugin.getDatabase().deleteAllWarps(); warps.clear(); - plugin.getMapHook().ifPresent(MapHook::clearWarps); + plugin.removeAllMappedWarps(); plugin.getCommands().stream() .filter(command -> command instanceof ListCommand) .map(command -> (ListCommand) command) @@ -171,7 +169,7 @@ public class WarpsManager { final int deleted = plugin.getDatabase().deleteAllWarps(worldName, serverName); warps.removeIf(warp -> warp.getServer().equals(serverName) && warp.getWorld().getName().equals(worldName)); if (plugin.getSettings().getCrossServer().isEnabled() && plugin.getServerName().equals(serverName)) { - plugin.getMapHook().ifPresent(hook -> hook.clearWarps(worldName)); + plugin.removeAllMappedWarps(worldName); } plugin.getCommands().stream() .filter(command -> command instanceof ListCommand) @@ -209,7 +207,7 @@ public class WarpsManager { if (plugin.getDatabase().getWarp(newName).isPresent()) { throw new ValidationException(ValidationException.Type.NAME_TAKEN); } - plugin.getValidator().validateName(newName); + plugin.validateName(newName); warp.getMeta().setName(newName); plugin.getDatabase().saveWarp(warp); this.cacheWarp(warp, true); @@ -225,7 +223,7 @@ public class WarpsManager { } public void setWarpDescription(@NotNull Warp warp, @NotNull String description) { - plugin.getValidator().validateDescription(description); + plugin.validateDescription(description); warp.getMeta().setDescription(description); plugin.getDatabase().saveWarp(warp); this.cacheWarp(warp, true); diff --git a/common/src/main/java/net/william278/huskhomes/network/Broker.java b/common/src/main/java/net/william278/huskhomes/network/Broker.java index ac3cbc7c..707d8587 100644 --- a/common/src/main/java/net/william278/huskhomes/network/Broker.java +++ b/common/src/main/java/net/william278/huskhomes/network/Broker.java @@ -27,6 +27,7 @@ import net.william278.huskhomes.position.World; import net.william278.huskhomes.teleport.Teleport; import net.william278.huskhomes.teleport.TeleportBuilder; import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.user.User; import net.william278.huskhomes.util.TransactionResolver; import org.jetbrains.annotations.NotNull; @@ -87,11 +88,11 @@ public abstract class Broker { .type(Message.Type.PLAYER_LIST) .scope(Message.Scope.SERVER) .target(message.getSourceServer()) - .payload(Payload.withStringList(plugin.getLocalPlayerList())) + .payload(Payload.withUserList(plugin.getOnlineUsers().stream().map(u -> (User) u).toList())) .build().send(this, receiver); case PLAYER_LIST -> message.getPayload() - .getStringList() - .ifPresent(players -> plugin.setPlayerList(message.getSourceServer(), players)); + .getUserList() + .ifPresent(players -> plugin.setUserList(message.getSourceServer(), players)); case UPDATE_HOME -> message.getPayload().getString() .map(UUID::fromString) .ifPresent(homeId -> { @@ -148,11 +149,11 @@ public abstract class Broker { if (world.isEmpty()) { plugin.log(Level.SEVERE, "%s requested a position in a world we don't have! World: %s" .formatted(message.getSourceServer(), request.getWorldName())); - Message.builder() + plugin.getBroker().ifPresent(b -> Message.builder() .type(Message.Type.RTP_LOCATION) .target(request.getUsername()) .payload(Payload.empty()) - .build().send(plugin.getMessenger(), request.getUsername()); + .build().send(b, request.getUsername())); return; } plugin.getRandomTeleportEngine().getRandomPosition(world.get(), null) @@ -166,7 +167,7 @@ public abstract class Broker { builder.payload(Payload.withRTPResponse( Payload.RTPResponse.of(request.getUsername(), position.get()))); } - builder.build().send(plugin.getMessenger(), request.getUsername()); + plugin.getBroker().ifPresent(b -> builder.build().send(b, request.getUsername())); }); }); } @@ -209,7 +210,11 @@ public abstract class Broker { // Get the formatted channel ID for the broker @NotNull protected String getSubChannelId() { - final String version = String.format("%s.%s", plugin.getVersion().getMajor(), plugin.getVersion().getMinor()); + final String version = String.format( + "%s.%s", + plugin.getPluginVersion().getMajor(), + plugin.getPluginVersion().getMinor() + ); try { return plugin.getKey( plugin.getSettings().getCrossServer().getClusterId().toLowerCase(Locale.ENGLISH), diff --git a/common/src/main/java/net/william278/huskhomes/network/BrokerProvider.java b/common/src/main/java/net/william278/huskhomes/network/BrokerProvider.java new file mode 100644 index 00000000..bb353f4f --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/network/BrokerProvider.java @@ -0,0 +1,53 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.network; + +import net.william278.huskhomes.HuskHomes; +import org.jetbrains.annotations.NotNull; + +import java.util.Optional; + +public interface BrokerProvider { + + Optional getBroker(); + + void setBroker(@NotNull Broker broker); + + void closeBroker(); + + void setupPluginMessagingChannels(); + + default void loadBroker() { + if (!getPlugin().getSettings().getCrossServer().isEnabled()) { + return; + } + + switch (getPlugin().getSettings().getCrossServer().getBrokerType()) { + case REDIS -> setBroker(new RedisBroker(getPlugin())); + case PLUGIN_MESSAGE -> setBroker(new PluginMessageBroker(getPlugin())); + } + getBroker().ifPresent(Broker::initialize); + } + + @NotNull + HuskHomes getPlugin(); + + +} diff --git a/common/src/main/java/net/william278/huskhomes/network/Message.java b/common/src/main/java/net/william278/huskhomes/network/Message.java index ecfb4768..96e3b3c0 100644 --- a/common/src/main/java/net/william278/huskhomes/network/Message.java +++ b/common/src/main/java/net/william278/huskhomes/network/Message.java @@ -70,7 +70,7 @@ public class Message { } public void send(@NotNull Broker broker, @NotNull OnlineUser sender) { - this.sender = sender.getUsername(); + this.sender = sender.getName(); this.sourceServer = broker.getServer(); broker.send(this, sender); } diff --git a/common/src/main/java/net/william278/huskhomes/network/Payload.java b/common/src/main/java/net/william278/huskhomes/network/Payload.java index d92e22d4..abd8f173 100644 --- a/common/src/main/java/net/william278/huskhomes/network/Payload.java +++ b/common/src/main/java/net/william278/huskhomes/network/Payload.java @@ -21,10 +21,12 @@ package net.william278.huskhomes.network; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; +import lombok.NoArgsConstructor; import lombok.Value; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.World; import net.william278.huskhomes.teleport.TeleportRequest; +import net.william278.huskhomes.user.User; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -34,6 +36,7 @@ import java.util.Optional; /** * Represents a payload sent in a cross-server {@link Message}. */ +@NoArgsConstructor public class Payload { @Nullable @@ -68,6 +71,11 @@ public class Payload { @SerializedName("string_list") private List stringList; + @Nullable + @Expose + @SerializedName("user_list") + private List userList; + /** * Returns an empty cross-server message payload. * @@ -137,6 +145,16 @@ public class Payload { return payload; } + /** + * A usr list field. + */ + @NotNull + public static Payload withUserList(@NotNull List target) { + final Payload payload = new Payload(); + payload.userList = target; + return payload; + } + /** * An RTP Response field. */ @@ -157,9 +175,6 @@ public class Payload { return payload; } - private Payload() { - } - /** * A position field. */ @@ -195,6 +210,13 @@ public class Payload { return Optional.ofNullable(stringList); } + /** + * A string list field. + */ + public Optional> getUserList() { + return Optional.ofNullable(userList); + } + /** * An RTP response. */ diff --git a/common/src/main/java/net/william278/huskhomes/network/PluginMessageBroker.java b/common/src/main/java/net/william278/huskhomes/network/PluginMessageBroker.java index 45c95852..1069fb1d 100644 --- a/common/src/main/java/net/william278/huskhomes/network/PluginMessageBroker.java +++ b/common/src/main/java/net/william278/huskhomes/network/PluginMessageBroker.java @@ -49,7 +49,7 @@ public class PluginMessageBroker extends Broker { @Override public void initialize() throws IllegalStateException { - plugin.initializePluginChannels(); + plugin.setupPluginMessagingChannels(); } public final void onReceive(@NotNull String channel, @NotNull OnlineUser user, byte[] message) { diff --git a/common/src/main/java/net/william278/huskhomes/network/RedisBroker.java b/common/src/main/java/net/william278/huskhomes/network/RedisBroker.java index ce622d59..925a1e81 100644 --- a/common/src/main/java/net/william278/huskhomes/network/RedisBroker.java +++ b/common/src/main/java/net/william278/huskhomes/network/RedisBroker.java @@ -214,7 +214,7 @@ public class RedisBroker extends PluginMessageBroker { if (message.getScope() == Message.Scope.PLAYER) { broker.plugin.getOnlineUsers().stream() .filter(online -> message.getTarget().equals(Message.TARGET_ALL) - || online.getUsername().equals(message.getTarget())) + || online.getName().equals(message.getTarget())) .forEach(receiver -> broker.handle(receiver, message)); return; } diff --git a/common/src/main/java/net/william278/huskhomes/position/Home.java b/common/src/main/java/net/william278/huskhomes/position/Home.java index 7d502684..d6e8ff43 100644 --- a/common/src/main/java/net/william278/huskhomes/position/Home.java +++ b/common/src/main/java/net/william278/huskhomes/position/Home.java @@ -134,7 +134,7 @@ public class Home extends SavedPosition { @NotNull @Override public String getSafeIdentifier() { - return getOwner().getUsername() + IDENTIFIER_DELIMITER + super.getSafeIdentifier(); + return getOwner().getName() + IDENTIFIER_DELIMITER + super.getSafeIdentifier(); } /** @@ -148,7 +148,7 @@ public class Home extends SavedPosition { @NotNull @Override public String getIdentifier() { - return getOwner().getUsername() + IDENTIFIER_DELIMITER + super.getIdentifier(); + return getOwner().getName() + IDENTIFIER_DELIMITER + super.getIdentifier(); } } diff --git a/common/src/main/java/net/william278/huskhomes/random/RandomTeleportProvider.java b/common/src/main/java/net/william278/huskhomes/random/RandomTeleportProvider.java new file mode 100644 index 00000000..29d7b841 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/random/RandomTeleportProvider.java @@ -0,0 +1,49 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.random; + +import net.william278.huskhomes.HuskHomes; +import org.jetbrains.annotations.NotNull; + +public interface RandomTeleportProvider { + + /** + * The {@link RandomTeleportEngine} that manages random teleports. + * + * @return the {@link RandomTeleportEngine} implementation + */ + @NotNull + RandomTeleportEngine getRandomTeleportEngine(); + + /** + * Sets the {@link RandomTeleportEngine} to be used for processing random teleports. + * + * @param randomTeleportEngine the {@link RandomTeleportEngine} to use + */ + void setRandomTeleportEngine(@NotNull RandomTeleportEngine randomTeleportEngine); + + default void loadRandomTeleportEngine() { + setRandomTeleportEngine(new NormalDistributionEngine(getPlugin())); + } + + @NotNull + HuskHomes getPlugin(); + +} diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java b/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java index bd669e77..caffde61 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Teleport.java @@ -66,7 +66,7 @@ public class Teleport implements Completable { this.async = plugin.getSettings().getGeneral().isTeleportAsync(); this.updateLastPosition = updateLastPosition && plugin.getCommand(BackCommand.class) .map(command -> executor.hasPermission(command.getPermission()) - && executor.hasPermission(command.getPermission("previous"))) + && executor.hasPermission(command.getPermission("previous"))) .orElse(false); } @@ -105,10 +105,10 @@ public class Teleport implements Completable { if (plugin.getSettings().getCrossServer().isEnabled()) { fireEvent((event) -> { performTransactions(); - Message.builder() + plugin.getBroker().ifPresent(b -> Message.builder() .type(Message.Type.TELEPORT_TO_NETWORKED_POSITION) .target(username.name()) - .build().send(plugin.getMessenger(), executor); + .build().send(b, executor)); }); return; } @@ -124,7 +124,7 @@ public class Teleport implements Completable { final Position target = (Position) this.target; if (!plugin.getSettings().getCrossServer().isEnabled() - || target.getServer().equals(plugin.getServerName())) { + || target.getServer().equals(plugin.getServerName())) { teleporter.teleportLocally(target, async); this.displayTeleportingComplete(teleporter); teleporter.handleInvulnerability(); @@ -132,7 +132,7 @@ public class Teleport implements Completable { } plugin.getDatabase().setCurrentTeleport(teleporter, this); - plugin.getMessenger().changeServer(teleporter, target.getServer()); + plugin.getBroker().ifPresent(b -> b.changeServer(teleporter, target.getServer())); }); } @@ -142,14 +142,14 @@ public class Teleport implements Completable { throw new TeleportationException(TeleportationException.Type.TELEPORTER_NOT_FOUND, plugin); } - fireEvent((event) -> { + fireEvent((event) -> plugin.getBroker().ifPresent(b -> { performTransactions(); if (target instanceof Username username) { Message.builder() .type(Message.Type.TELEPORT_TO_NETWORKED_USER) .target(teleporter.name()) .payload(Payload.withString(username.name())) - .build().send(plugin.getMessenger(), executor); + .build().send(b, executor); return; } @@ -157,8 +157,8 @@ public class Teleport implements Completable { .type(Message.Type.TELEPORT_TO_POSITION) .target(teleporter.name()) .payload(Payload.withPosition((Position) target)) - .build().send(plugin.getMessenger(), executor); - }); + .build().send(b, executor); + })); } @NotNull diff --git a/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java b/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java index 1aff0993..0358acd2 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/TeleportRequest.java @@ -64,7 +64,7 @@ public class TeleportRequest { * @param requester The user making the request */ public TeleportRequest(@NotNull OnlineUser requester, @NotNull TeleportRequest.Type type, final long expiryTime) { - this.setRequesterName(requester.getUsername()); + this.setRequesterName(requester.getName()); this.setRequesterPosition(requester.getPosition()); this.setType(type); this.setStatus(Status.PENDING); diff --git a/common/src/main/java/net/william278/huskhomes/teleport/Username.java b/common/src/main/java/net/william278/huskhomes/teleport/Username.java index 95aad351..a0e31a77 100644 --- a/common/src/main/java/net/william278/huskhomes/teleport/Username.java +++ b/common/src/main/java/net/william278/huskhomes/teleport/Username.java @@ -36,7 +36,7 @@ public record Username(@NotNull String name) implements Teleportable, Target { /** * Search for a local {@link OnlineUser} by their name. * - *

If a user by the name provided is on the {@link HuskHomes#getPlayerList() player list}, then this + *

If a user by the name provided is on the {@link HuskHomes#getUserList() player list}, then this * method will search for the user by exact name. * *

Otherwise, the lookup will first attempt to find the user by exact name, and if that fails, it will search for @@ -48,7 +48,8 @@ public record Username(@NotNull String name) implements Teleportable, Target { */ @NotNull public Optional findLocally(@NotNull HuskHomes plugin) { - return plugin.getPlayerList(true).stream().anyMatch(listedName -> listedName.equalsIgnoreCase(name)) + return plugin.getUserList().stream() + .anyMatch((user) -> user.getName().equalsIgnoreCase(name)) ? plugin.getOnlineUserExact(name) : plugin.getOnlineUser(name); } diff --git a/common/src/main/java/net/william278/huskhomes/user/ConsoleUser.java b/common/src/main/java/net/william278/huskhomes/user/ConsoleUser.java index f7fbf389..26d810b2 100644 --- a/common/src/main/java/net/william278/huskhomes/user/ConsoleUser.java +++ b/common/src/main/java/net/william278/huskhomes/user/ConsoleUser.java @@ -19,26 +19,26 @@ package net.william278.huskhomes.user; +import lombok.AllArgsConstructor; +import lombok.Getter; import net.kyori.adventure.audience.Audience; import org.jetbrains.annotations.NotNull; +@Getter +@AllArgsConstructor public final class ConsoleUser implements CommandUser { @NotNull private final Audience audience; - public ConsoleUser(@NotNull Audience console) { - this.audience = console; - } - - @Override @NotNull - public Audience getAudience() { - return audience; + public static ConsoleUser wrap(@NotNull Audience audience) { + return new ConsoleUser(audience); } @Override public boolean hasPermission(@NotNull String permission) { return true; } + } \ No newline at end of file diff --git a/common/src/main/java/net/william278/huskhomes/user/SavedUser.java b/common/src/main/java/net/william278/huskhomes/user/SavedUser.java index fe0f2e78..7205d9b2 100644 --- a/common/src/main/java/net/william278/huskhomes/user/SavedUser.java +++ b/common/src/main/java/net/william278/huskhomes/user/SavedUser.java @@ -63,7 +63,7 @@ public class SavedUser { @NotNull public String getUsername() { - return getUser().getUsername(); + return getUser().getName(); } diff --git a/common/src/main/java/net/william278/huskhomes/user/User.java b/common/src/main/java/net/william278/huskhomes/user/User.java index 6924817d..b29370f7 100644 --- a/common/src/main/java/net/william278/huskhomes/user/User.java +++ b/common/src/main/java/net/william278/huskhomes/user/User.java @@ -37,13 +37,19 @@ public class User implements Comparable { private final UUID uuid; @NotNull - private final String username; + private final String name; @NotNull public static User of(@NotNull UUID uuid, @NotNull String username) { return new User(uuid, username); } + @Deprecated(since = "4.8") + @NotNull + public String getUsername() { + return getName(); + } + @Override public boolean equals(@NotNull Object obj) { if (obj instanceof User user) { @@ -54,7 +60,7 @@ public class User implements Comparable { @Override public int compareTo(@NotNull User o) { - return getUsername().compareTo(o.getUsername()); + return getName().compareTo(o.getName()); } } diff --git a/common/src/main/java/net/william278/huskhomes/user/UserProvider.java b/common/src/main/java/net/william278/huskhomes/user/UserProvider.java new file mode 100644 index 00000000..28c770bc --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/user/UserProvider.java @@ -0,0 +1,105 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.user; + +import net.william278.huskhomes.HuskHomes; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; + +import java.util.*; +import java.util.function.Consumer; +import java.util.stream.Stream; + +/** + * A provider for the plugin user list, tracking online users across the network. + * + * @since 4.8 + */ +public interface UserProvider { + + @NotNull + Map getOnlineUserMap(); + + @NotNull + Map> getGlobalUserList(); + + @NotNull + Set getSavedUsers(); + + @NotNull + OnlineUser getOnlineUser(@NotNull UUID uuid); + + @NotNull + @Unmodifiable + default Collection getOnlineUsers() { + return getOnlineUserMap().values(); + } + + @NotNull + default List getUserList() { + return Stream.concat( + getGlobalUserList().values().stream().flatMap(Collection::stream), + getOnlineUsers().stream().filter(o -> !o.isVanished()) + ).distinct().sorted().toList(); + } + + default void setUserList(@NotNull String server, @NotNull List players) { + getGlobalUserList().values().forEach(list -> { + list.removeAll(players); + list.removeAll(getOnlineUsers()); + }); + getGlobalUserList().put(server, players); + } + + default boolean isUserOnline(@NotNull User user) { + return getOnlineUserMap().containsKey(user.getUuid()); + } + + default Optional getOnlineUser(@NotNull String playerName) { + return getOnlineUserExact(playerName) + .or(() -> getOnlineUsers().stream() + .filter(user -> user.getName().toLowerCase().startsWith(playerName.toLowerCase())) + .findFirst()); + } + + default Optional getOnlineUserExact(@NotNull String playerName) { + return getOnlineUsers().stream() + .filter(user -> user.getName().equalsIgnoreCase(playerName)) + .findFirst(); + } + + default Optional getSavedUser(@NotNull User user) { + return getSavedUsers().stream() + .filter(savedUser -> savedUser.getUser().equals(user)) + .findFirst(); + } + + default void editSavedUser(@NotNull User user, @NotNull Consumer editor) { + getPlugin().runAsync(() -> getSavedUser(user) + .ifPresent(result -> { + editor.accept(result); + getPlugin().getDatabase().updateUserData(result); + })); + } + + @NotNull + HuskHomes getPlugin(); + +} diff --git a/common/src/main/java/net/william278/huskhomes/util/AudiencesProvider.java b/common/src/main/java/net/william278/huskhomes/util/AudiencesProvider.java new file mode 100644 index 00000000..34983090 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/util/AudiencesProvider.java @@ -0,0 +1,69 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.util; + +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.audience.Audiences; +import net.kyori.adventure.platform.AudienceProvider; +import net.william278.huskhomes.user.ConsoleUser; +import net.william278.huskhomes.user.OnlineUser; +import org.jetbrains.annotations.NotNull; + +import java.util.UUID; + +/** + * Interface for providing the {@link ConsoleUser} and {@link Audiences} instances + * + * @since 4.8 + */ +public interface AudiencesProvider { + + /** + * Get the {@link Audiences} instance. + * + * @return the {@link Audiences} instance + * @since 4.8 + */ + @NotNull + AudienceProvider getAudiences(); + + /** + * Get the {@link Audience} instance for the given {@link OnlineUser}. + * + * @param user the {@link OnlineUser} to get the {@link Audience} for + * @return the {@link Audience} instance + */ + @NotNull + default Audience getAudience(@NotNull UUID user) { + return getAudiences().player(user); + } + + /** + * Get the {@link ConsoleUser} instance. + * + * @return the {@link ConsoleUser} instance + * @since 4.8 + */ + @NotNull + default ConsoleUser getConsole() { + return ConsoleUser.wrap(getAudiences().console()); + } + +} diff --git a/common/src/main/java/net/william278/huskhomes/util/MetaProvider.java b/common/src/main/java/net/william278/huskhomes/util/MetaProvider.java new file mode 100644 index 00000000..71dd9f5e --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/util/MetaProvider.java @@ -0,0 +1,98 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.util; + +import net.william278.desertwell.util.UpdateChecker; +import net.william278.desertwell.util.Version; +import net.william278.huskhomes.HuskHomes; +import org.jetbrains.annotations.NotNull; + +import java.util.logging.Level; + +public interface MetaProvider { + + int SPIGOT_RESOURCE_ID = 83767; + + /** + * Get the plugin {@link Version}. + * + * @return the plugin version + * @since 4.8 + */ + @NotNull + Version getPluginVersion(); + + /** + * Get the plugin {@link UpdateChecker}. + * + * @return the plugin {@link UpdateChecker} + * @since 4.8 + */ + @NotNull + default UpdateChecker getUpdateChecker() { + return UpdateChecker.builder() + .currentVersion(getPluginVersion()) + .endpoint(UpdateChecker.Endpoint.SPIGOT) + .resource(Integer.toString(SPIGOT_RESOURCE_ID)) + .build(); + } + + /** + * Check for updates and log a warning if an update is available. + * + * @since 4.8 + */ + default void checkForUpdates() { + if (!getPlugin().getSettings().isCheckForUpdates()) { + return; + } + getUpdateChecker().check().thenAccept(checked -> { + if (checked.isUpToDate()) { + return; + } + getPlugin().log(Level.WARNING, String.format( + "A new version of HuskHomes is available: v%s (running v%s)", + checked.getLatestVersion(), getPluginVersion()) + ); + }); + } + + /** + * Get the server type. + * + * @return the server type + * @since 4.8 + */ + @NotNull + String getServerType(); + + /** + * Get the Minecraft version. + * + * @return the Minecraft version + * @since 4.8 + */ + @NotNull + Version getMinecraftVersion(); + + @NotNull + HuskHomes getPlugin(); + +} diff --git a/common/src/main/java/net/william278/huskhomes/util/SafetyResolver.java b/common/src/main/java/net/william278/huskhomes/util/SavePositionProvider.java similarity index 98% rename from common/src/main/java/net/william278/huskhomes/util/SafetyResolver.java rename to common/src/main/java/net/william278/huskhomes/util/SavePositionProvider.java index d12a0642..98d1bbe8 100644 --- a/common/src/main/java/net/william278/huskhomes/util/SafetyResolver.java +++ b/common/src/main/java/net/william278/huskhomes/util/SavePositionProvider.java @@ -26,7 +26,7 @@ import org.jetbrains.annotations.NotNull; import java.util.Optional; import java.util.concurrent.CompletableFuture; -public interface SafetyResolver { +public interface SavePositionProvider { int SEARCH_RADIUS = 2; diff --git a/common/src/main/java/net/william278/huskhomes/util/Validator.java b/common/src/main/java/net/william278/huskhomes/util/TextValidator.java similarity index 75% rename from common/src/main/java/net/william278/huskhomes/util/Validator.java rename to common/src/main/java/net/william278/huskhomes/util/TextValidator.java index 67ccfdc0..e3871dde 100644 --- a/common/src/main/java/net/william278/huskhomes/util/Validator.java +++ b/common/src/main/java/net/william278/huskhomes/util/TextValidator.java @@ -19,27 +19,18 @@ package net.william278.huskhomes.util; -import lombok.AllArgsConstructor; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.position.Home; import org.jetbrains.annotations.NotNull; -@AllArgsConstructor -public class Validator { +public interface TextValidator { - public static final int MAX_NAME_LENGTH = 16; - public static final int MAX_DESCRIPTION_LENGTH = 256; + int MAX_NAME_LENGTH = 16; + int MAX_DESCRIPTION_LENGTH = 256; - private final HuskHomes plugin; - - /** - * Validate home and warp names. - * - * @param name The name to validate - * @throws ValidationException If the name is invalid - */ - public void validateName(@NotNull String name) throws ValidationException { + // Validate home and warp names + default void validateName(@NotNull String name) throws ValidationException { if (!isValidNameCharacters(name)) { throw new ValidationException(ValidationException.Type.NAME_INVALID_CHARACTERS); } @@ -48,13 +39,8 @@ public class Validator { } } - /** - * Validate home and warp descriptions. - * - * @param description The description to validate - * @throws ValidationException If the description is invalid - */ - public void validateDescription(@NotNull String description) throws ValidationException { + // Validate home and warp descriptions. + default void validateDescription(@NotNull String description) throws ValidationException { if (!isValidDescriptionCharacters(description)) { throw new ValidationException(ValidationException.Type.DESCRIPTION_INVALID_CHARACTERS); } @@ -65,7 +51,7 @@ public class Validator { // Check a home/warp name contains only valid characters private boolean isValidNameCharacters(@NotNull String name) { - final Settings.GeneralSettings.NameSettings config = plugin.getSettings().getGeneral().getNames(); + final Settings.GeneralSettings.NameSettings config = getSettings().getGeneral().getNames(); return (name.matches(config.getRegex()) || !config.isRestrict()) && !name.contains("\u0000") && !containsWhitespace(name) @@ -79,7 +65,7 @@ public class Validator { // Check a home/warp description contains only valid characters private boolean isValidDescriptionCharacters(@NotNull String description) { - final Settings.GeneralSettings.DescriptionSettings config = plugin.getSettings().getGeneral().getDescriptions(); + final Settings.GeneralSettings.DescriptionSettings config = getSettings().getGeneral().getDescriptions(); return (description.matches(config.getRegex()) || !config.isRestrict()) && !description.contains("\u0000"); } @@ -93,5 +79,11 @@ public class Validator { private boolean containsWhitespace(@NotNull String string) { return string.matches(".*\\s.*"); } + + @NotNull + HuskHomes getPlugin(); + + @NotNull + Settings getSettings(); } diff --git a/common/src/main/resources/database/h2_schema.sql b/common/src/main/resources/database/h2_schema.sql index 2bd68d4a..1b0378f6 100644 --- a/common/src/main/resources/database/h2_schema.sql +++ b/common/src/main/resources/database/h2_schema.sql @@ -1,5 +1,13 @@ +/* Create the metadata table if it does not exist */ +CREATE TABLE IF NOT EXISTS `%meta_data%` +( + `schema_version` integer NOT NULL, + + PRIMARY KEY (`schema_version`) +); + /* Create the positions table if it does not exist */ -CREATE TABLE IF NOT EXISTS `%positions_table%` +CREATE TABLE IF NOT EXISTS `%position_data%` ( `id` INT NOT NULL AUTO_INCREMENT, `x` DOUBLE NOT NULL, @@ -15,7 +23,7 @@ CREATE TABLE IF NOT EXISTS `%positions_table%` ); /* Create the players table if it does not exist */ -CREATE TABLE IF NOT EXISTS `%players_table%` +CREATE TABLE IF NOT EXISTS `%player_data%` ( `uuid` UUID NOT NULL PRIMARY KEY, `username` VARCHAR(16) NOT NULL, @@ -25,14 +33,14 @@ CREATE TABLE IF NOT EXISTS `%players_table%` `home_slots` INT NOT NULL DEFAULT 0, `ignoring_requests` BOOLEAN NOT NULL DEFAULT FALSE, - FOREIGN KEY (`last_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, - FOREIGN KEY (`offline_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, - FOREIGN KEY (`respawn_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION + FOREIGN KEY (`last_position`) REFERENCES `%position_data%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, + FOREIGN KEY (`offline_position`) REFERENCES `%position_data%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, + FOREIGN KEY (`respawn_position`) REFERENCES `%position_data%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION ); -CREATE INDEX IF NOT EXISTS `%players_table%_username` ON `%players_table%` (`username`); +CREATE INDEX IF NOT EXISTS `%player_data%_username` ON `%player_data%` (`username`); /* Create the cooldowns table if it does not exist */ -CREATE TABLE IF NOT EXISTS `%cooldowns_table%` +CREATE TABLE IF NOT EXISTS `%player_cooldowns_data%` ( `id` INT NOT NULL AUTO_INCREMENT, `player_uuid` UUID NOT NULL, @@ -41,23 +49,23 @@ CREATE TABLE IF NOT EXISTS `%cooldowns_table%` `end_timestamp` TIMESTAMP NOT NULL, PRIMARY KEY (`id`), - FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE + FOREIGN KEY (`player_uuid`) REFERENCES `%player_data%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE ); -CREATE INDEX IF NOT EXISTS `%cooldowns_table%_player_uuid` ON `%cooldowns_table%` (`player_uuid`); +CREATE INDEX IF NOT EXISTS `%player_cooldowns_data%_player_uuid` ON `%player_cooldowns_data%` (`player_uuid`); /* Create the current cross-server teleports table if it does not exist */ -CREATE TABLE IF NOT EXISTS `%teleports_table%` +CREATE TABLE IF NOT EXISTS `%teleport_data%` ( `player_uuid` UUID NOT NULL PRIMARY KEY, `destination_id` INT NOT NULL, `type` INT NOT NULL DEFAULT 0, - FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, - FOREIGN KEY (`destination_id`) REFERENCES `%positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION + FOREIGN KEY (`player_uuid`) REFERENCES `%player_data%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (`destination_id`) REFERENCES `%position_data%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ); /* Create the saved positions table if it does not exist */ -CREATE TABLE IF NOT EXISTS `%saved_positions_table%` +CREATE TABLE IF NOT EXISTS `%saved_position_data%` ( `id` INT NOT NULL AUTO_INCREMENT, `position_id` INT NOT NULL, @@ -67,28 +75,28 @@ CREATE TABLE IF NOT EXISTS `%saved_positions_table%` `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), - FOREIGN KEY (`position_id`) REFERENCES `%positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION + FOREIGN KEY (`position_id`) REFERENCES `%position_data%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ); -CREATE INDEX IF NOT EXISTS `%saved_positions_table%_name` ON `%saved_positions_table%` (`name`); +CREATE INDEX IF NOT EXISTS `%saved_position_data%_name` ON `%saved_position_data%` (`name`); /* Create the homes table if it does not exist */ -CREATE TABLE IF NOT EXISTS `%homes_table%` +CREATE TABLE IF NOT EXISTS `%home_data%` ( `uuid` UUID NOT NULL PRIMARY KEY, `saved_position_id` INT NOT NULL, `owner_uuid` UUID NOT NULL, `public` BOOLEAN NOT NULL DEFAULT FALSE, - FOREIGN KEY (`owner_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, - FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION + FOREIGN KEY (`owner_uuid`) REFERENCES `%player_data%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_position_data%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ); -CREATE INDEX IF NOT EXISTS `%homes_table%_owner_uuid` ON `%homes_table%` (`owner_uuid`); +CREATE INDEX IF NOT EXISTS `%home_data%_owner_uuid` ON `%home_data%` (`owner_uuid`); /* Create the warps table if it does not exist */ -CREATE TABLE IF NOT EXISTS `%warps_table%` +CREATE TABLE IF NOT EXISTS `%warp_data%` ( `uuid` UUID NOT NULL PRIMARY KEY, `saved_position_id` INT NOT NULL, - FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION + FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_position_data%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ); \ No newline at end of file diff --git a/common/src/main/resources/database/mariadb_schema.sql b/common/src/main/resources/database/mariadb_schema.sql index a1ec8d74..450afe92 100644 --- a/common/src/main/resources/database/mariadb_schema.sql +++ b/common/src/main/resources/database/mariadb_schema.sql @@ -4,8 +4,16 @@ SET DEFAULT_STORAGE_ENGINE = InnoDB; -- Enable foreign key constraints SET FOREIGN_KEY_CHECKS = 1; +-- Create the metadata table if it does not exist +CREATE TABLE IF NOT EXISTS `%meta_data%` +( + `schema_version` integer NOT NULL, + + PRIMARY KEY (`schema_version`) +); + -- Create the positions table if it does not exist -CREATE TABLE IF NOT EXISTS `%positions_table%` +CREATE TABLE IF NOT EXISTS `%position_data%` ( `id` INTEGER NOT NULL AUTO_INCREMENT, `x` DOUBLE NOT NULL, @@ -23,7 +31,7 @@ CREATE TABLE IF NOT EXISTS `%positions_table%` COLLATE = utf8mb4_unicode_ci; -- Create the players table if it does not exist -CREATE TABLE IF NOT EXISTS `%players_table%` +CREATE TABLE IF NOT EXISTS `%player_data%` ( `uuid` CHAR(36) NOT NULL, `username` VARCHAR(16) NOT NULL, @@ -34,16 +42,16 @@ CREATE TABLE IF NOT EXISTS `%players_table%` `ignoring_requests` BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (`uuid`), - FOREIGN KEY (`last_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, - FOREIGN KEY (`offline_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, - FOREIGN KEY (`respawn_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION + FOREIGN KEY (`last_position`) REFERENCES `%position_data%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, + FOREIGN KEY (`offline_position`) REFERENCES `%position_data%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, + FOREIGN KEY (`respawn_position`) REFERENCES `%position_data%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci; -CREATE INDEX IF NOT EXISTS `%players_table%_username` ON `%players_table%` (`username`); +CREATE INDEX IF NOT EXISTS `%player_data%_username` ON `%player_data%` (`username`); -- Create the cooldowns table if it does not exist -CREATE TABLE IF NOT EXISTS `%cooldowns_table%` +CREATE TABLE IF NOT EXISTS `%player_cooldowns_data%` ( `id` INTEGER NOT NULL AUTO_INCREMENT, `player_uuid` CHAR(36) NOT NULL, @@ -52,28 +60,28 @@ CREATE TABLE IF NOT EXISTS `%cooldowns_table%` `end_timestamp` DATETIME NOT NULL, PRIMARY KEY (`id`), - FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE + FOREIGN KEY (`player_uuid`) REFERENCES `%player_data%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci; -CREATE INDEX IF NOT EXISTS `%cooldowns_table%_player_uuid` ON `%cooldowns_table%` (`player_uuid`); +CREATE INDEX IF NOT EXISTS `%player_cooldowns_data%_player_uuid` ON `%player_cooldowns_data%` (`player_uuid`); -- Create the current cross-server teleports table if it does not exist -CREATE TABLE IF NOT EXISTS `%teleports_table%` +CREATE TABLE IF NOT EXISTS `%teleport_data%` ( `player_uuid` CHAR(36) NOT NULL, `destination_id` INTEGER NOT NULL, `type` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (`player_uuid`), - FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, - FOREIGN KEY (`destination_id`) REFERENCES `%positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION + FOREIGN KEY (`player_uuid`) REFERENCES `%player_data%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (`destination_id`) REFERENCES `%position_data%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci; -- Create the saved positions table if it does not exist -CREATE TABLE IF NOT EXISTS `%saved_positions_table%` +CREATE TABLE IF NOT EXISTS `%saved_position_data%` ( `id` INTEGER NOT NULL AUTO_INCREMENT, `position_id` INTEGER NOT NULL, @@ -83,14 +91,14 @@ CREATE TABLE IF NOT EXISTS `%saved_positions_table%` `timestamp` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), - FOREIGN KEY (`position_id`) REFERENCES `%positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION + FOREIGN KEY (`position_id`) REFERENCES `%position_data%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci; -CREATE INDEX IF NOT EXISTS `%saved_positions_table%_name` ON `%saved_positions_table%` (`name`); +CREATE INDEX IF NOT EXISTS `%saved_position_data%_name` ON `%saved_position_data%` (`name`); -- Create the homes table if it does not exist -CREATE TABLE IF NOT EXISTS `%homes_table%` +CREATE TABLE IF NOT EXISTS `%home_data%` ( `uuid` CHAR(36) NOT NULL, `saved_position_id` INTEGER NOT NULL, @@ -98,21 +106,21 @@ CREATE TABLE IF NOT EXISTS `%homes_table%` `public` BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (`uuid`), - FOREIGN KEY (`owner_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, - FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION + FOREIGN KEY (`owner_uuid`) REFERENCES `%player_data%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_position_data%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci; -CREATE INDEX IF NOT EXISTS `%homes_table%_owner_uuid` ON `%homes_table%` (`owner_uuid`); +CREATE INDEX IF NOT EXISTS `%home_data%_owner_uuid` ON `%home_data%` (`owner_uuid`); -- Create the warps table if it does not exist -CREATE TABLE IF NOT EXISTS `%warps_table%` +CREATE TABLE IF NOT EXISTS `%warp_data%` ( `uuid` CHAR(36) NOT NULL, `saved_position_id` INTEGER NOT NULL, PRIMARY KEY (`uuid`), - FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION + FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_position_data%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci; \ No newline at end of file diff --git a/common/src/main/resources/database/migrations/0-h2-add_metadata_table.sql b/common/src/main/resources/database/migrations/0-h2-add_metadata_table.sql new file mode 100644 index 00000000..26fb104e --- /dev/null +++ b/common/src/main/resources/database/migrations/0-h2-add_metadata_table.sql @@ -0,0 +1,7 @@ +/* Create the metadata table if it does not exist */ +CREATE TABLE IF NOT EXISTS `%meta_data%` +( + `schema_version` integer NOT NULL, + + PRIMARY KEY (`schema_version`) +); \ No newline at end of file diff --git a/common/src/main/resources/database/migrations/0-mariadb-add_metadata_table.sql b/common/src/main/resources/database/migrations/0-mariadb-add_metadata_table.sql new file mode 100644 index 00000000..f0fd0782 --- /dev/null +++ b/common/src/main/resources/database/migrations/0-mariadb-add_metadata_table.sql @@ -0,0 +1,6 @@ +# Create the metadata table if it does not exist +CREATE TABLE IF NOT EXISTS `%meta_data%` +( + `schema_version` int NOT NULL PRIMARY KEY +) CHARACTER SET utf8 + COLLATE utf8_unicode_ci; \ No newline at end of file diff --git a/common/src/main/resources/database/migrations/0-mysql-add_metadata_table.sql b/common/src/main/resources/database/migrations/0-mysql-add_metadata_table.sql new file mode 100644 index 00000000..f0fd0782 --- /dev/null +++ b/common/src/main/resources/database/migrations/0-mysql-add_metadata_table.sql @@ -0,0 +1,6 @@ +# Create the metadata table if it does not exist +CREATE TABLE IF NOT EXISTS `%meta_data%` +( + `schema_version` int NOT NULL PRIMARY KEY +) CHARACTER SET utf8 + COLLATE utf8_unicode_ci; \ No newline at end of file diff --git a/common/src/main/resources/database/migrations/0-postgresql-add_metadata_table.sql b/common/src/main/resources/database/migrations/0-postgresql-add_metadata_table.sql new file mode 100644 index 00000000..91407d4a --- /dev/null +++ b/common/src/main/resources/database/migrations/0-postgresql-add_metadata_table.sql @@ -0,0 +1,7 @@ +/* Create the metadata table if it does not exist */ +CREATE TABLE IF NOT EXISTS "%meta_data%" +( + schema_version integer NOT NULL, + + PRIMARY KEY (schema_version) +); \ No newline at end of file diff --git a/common/src/main/resources/database/migrations/0-sqlite-add_metadata_table.sql b/common/src/main/resources/database/migrations/0-sqlite-add_metadata_table.sql new file mode 100644 index 00000000..530cba69 --- /dev/null +++ b/common/src/main/resources/database/migrations/0-sqlite-add_metadata_table.sql @@ -0,0 +1,5 @@ +-- Create the metadata table if it does not exist +CREATE TABLE IF NOT EXISTS `%meta_data%` +( + `schema_version` int NOT NULL PRIMARY KEY +); \ No newline at end of file diff --git a/common/src/main/resources/database/mysql_schema.sql b/common/src/main/resources/database/mysql_schema.sql index 9b941097..e09a05db 100644 --- a/common/src/main/resources/database/mysql_schema.sql +++ b/common/src/main/resources/database/mysql_schema.sql @@ -4,8 +4,16 @@ SET DEFAULT_STORAGE_ENGINE = INNODB; # Enable foreign key constraints SET FOREIGN_KEY_CHECKS = 1; +# Create the metadata table if it does not exist +CREATE TABLE IF NOT EXISTS `%meta_data%` +( + `schema_version` integer NOT NULL, + + PRIMARY KEY (`schema_version`) +); + # Create the positions table if it does not exist -CREATE TABLE IF NOT EXISTS `%positions_table%` +CREATE TABLE IF NOT EXISTS `%position_data%` ( `id` integer NOT NULL AUTO_INCREMENT, `x` double NOT NULL, @@ -22,7 +30,7 @@ CREATE TABLE IF NOT EXISTS `%positions_table%` COLLATE utf8_unicode_ci; # Create the players table if it does not exist -CREATE TABLE IF NOT EXISTS `%players_table%` +CREATE TABLE IF NOT EXISTS `%player_data%` ( `uuid` char(36) NOT NULL UNIQUE, `username` varchar(16) NOT NULL, @@ -33,14 +41,14 @@ CREATE TABLE IF NOT EXISTS `%players_table%` `ignoring_requests` boolean NOT NULL DEFAULT FALSE, PRIMARY KEY (`uuid`), - FOREIGN KEY (`last_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, - FOREIGN KEY (`offline_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, - FOREIGN KEY (`respawn_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION + FOREIGN KEY (`last_position`) REFERENCES `%position_data%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, + FOREIGN KEY (`offline_position`) REFERENCES `%position_data%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, + FOREIGN KEY (`respawn_position`) REFERENCES `%position_data%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION ) CHARACTER SET utf8 COLLATE utf8_unicode_ci; # Create the cooldowns table if it does not exist -CREATE TABLE IF NOT EXISTS `%cooldowns_table%` +CREATE TABLE IF NOT EXISTS `%player_cooldowns_data%` ( `id` integer NOT NULL AUTO_INCREMENT, `player_uuid` char(36) NOT NULL, @@ -49,25 +57,25 @@ CREATE TABLE IF NOT EXISTS `%cooldowns_table%` `end_timestamp` datetime NOT NULL, PRIMARY KEY (`id`), - FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE + FOREIGN KEY (`player_uuid`) REFERENCES `%player_data%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE ) CHARACTER SET utf8 COLLATE utf8_unicode_ci; # Create the current cross-server teleports table if it does not exist -CREATE TABLE IF NOT EXISTS `%teleports_table%` +CREATE TABLE IF NOT EXISTS `%teleport_data%` ( `player_uuid` char(36) NOT NULL UNIQUE, `destination_id` integer NOT NULL, `type` integer NOT NULL DEFAULT 0, PRIMARY KEY (`player_uuid`), - FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, - FOREIGN KEY (`destination_id`) REFERENCES `%positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION + FOREIGN KEY (`player_uuid`) REFERENCES `%player_data%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (`destination_id`) REFERENCES `%position_data%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ) CHARACTER SET utf8 COLLATE utf8_unicode_ci; # Create the saved positions table if it does not exist -CREATE TABLE IF NOT EXISTS `%saved_positions_table%` +CREATE TABLE IF NOT EXISTS `%saved_position_data%` ( `id` integer NOT NULL AUTO_INCREMENT, `position_id` integer NOT NULL, @@ -77,12 +85,12 @@ CREATE TABLE IF NOT EXISTS `%saved_positions_table%` `timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), - FOREIGN KEY (`position_id`) REFERENCES `%positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION + FOREIGN KEY (`position_id`) REFERENCES `%position_data%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ) CHARACTER SET utf8 COLLATE utf8_unicode_ci; # Create the homes table if it does not exist -CREATE TABLE IF NOT EXISTS `%homes_table%` +CREATE TABLE IF NOT EXISTS `%home_data%` ( `uuid` char(36) NOT NULL UNIQUE, `saved_position_id` integer NOT NULL, @@ -90,18 +98,18 @@ CREATE TABLE IF NOT EXISTS `%homes_table%` `public` boolean NOT NULL DEFAULT FALSE, PRIMARY KEY (`uuid`), - FOREIGN KEY (`owner_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, - FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION + FOREIGN KEY (`owner_uuid`) REFERENCES `%player_data%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_position_data%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ) CHARACTER SET utf8 COLLATE utf8_unicode_ci; # Create the warps table if it does not exist -CREATE TABLE IF NOT EXISTS `%warps_table%` +CREATE TABLE IF NOT EXISTS `%warp_data%` ( `uuid` char(36) NOT NULL UNIQUE, `saved_position_id` integer NOT NULL, PRIMARY KEY (`uuid`), - FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION + FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_position_data%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ) CHARACTER SET utf8 COLLATE utf8_unicode_ci; \ No newline at end of file diff --git a/common/src/main/resources/database/postgresql_schema.sql b/common/src/main/resources/database/postgresql_schema.sql index ee62e140..95b266fb 100644 --- a/common/src/main/resources/database/postgresql_schema.sql +++ b/common/src/main/resources/database/postgresql_schema.sql @@ -1,94 +1,102 @@ -/* Create the positions table if it does not exist */ -CREATE TABLE IF NOT EXISTS "%positions_table%" +/* Create the metadata table if it does not exist */ +CREATE TABLE IF NOT EXISTS "%meta_data%" ( - "id" SERIAL, - "x" double precision NOT NULL, - "y" double precision NOT NULL, - "z" double precision NOT NULL, - "yaw" real NOT NULL, - "pitch" real NOT NULL, - "world_name" varchar(255) NOT NULL, - "world_uuid" char(36) NOT NULL, - "server_name" varchar(255) NOT NULL, + schema_version integer NOT NULL, - PRIMARY KEY ("id") + PRIMARY KEY (schema_version) +); + +/* Create the positions table if it does not exist */ +CREATE TABLE IF NOT EXISTS "%position_data%" +( + id SERIAL, + x double precision NOT NULL, + y double precision NOT NULL, + z double precision NOT NULL, + yaw real NOT NULL, + pitch real NOT NULL, + world_name varchar(255) NOT NULL, + world_uuid char(36) NOT NULL, + server_name varchar(255) NOT NULL, + + PRIMARY KEY (id) ); /* Create the players table if it does not exist */ -CREATE TABLE IF NOT EXISTS "%players_table%" +CREATE TABLE IF NOT EXISTS "%player_data%" ( - "uuid" char(36) NOT NULL UNIQUE, - "username" varchar(16) NOT NULL, - "last_position" integer DEFAULT NULL, - "offline_position" integer DEFAULT NULL, - "respawn_position" integer DEFAULT NULL, - "home_slots" integer NOT NULL DEFAULT 0, - "ignoring_requests" boolean NOT NULL DEFAULT FALSE, + uuid char(36) NOT NULL UNIQUE, + username varchar(16) NOT NULL, + last_position integer DEFAULT NULL, + offline_position integer DEFAULT NULL, + respawn_position integer DEFAULT NULL, + home_slots integer NOT NULL DEFAULT 0, + ignoring_requests boolean NOT NULL DEFAULT FALSE, - PRIMARY KEY ("uuid"), - FOREIGN KEY ("last_position") REFERENCES "%positions_table%" ("id") ON DELETE SET NULL ON UPDATE NO ACTION, - FOREIGN KEY ("offline_position") REFERENCES "%positions_table%" ("id") ON DELETE SET NULL ON UPDATE NO ACTION, - FOREIGN KEY ("respawn_position") REFERENCES "%positions_table%" ("id") ON DELETE SET NULL ON UPDATE NO ACTION + PRIMARY KEY (uuid), + FOREIGN KEY (last_position) REFERENCES "%position_data%" (id) ON DELETE SET NULL, + FOREIGN KEY (offline_position) REFERENCES "%position_data%" (id) ON DELETE SET NULL, + FOREIGN KEY (respawn_position) REFERENCES "%position_data%" (id) ON DELETE SET NULL ); /* Create the cooldowns table if it does not exist */ -CREATE TABLE IF NOT EXISTS "%cooldowns_table%" +CREATE TABLE IF NOT EXISTS "%player_cooldowns_data%" ( - "id" SERIAL, - "player_uuid" char(36) NOT NULL, - "type" varchar(255) NOT NULL, - "start_timestamp" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - "end_timestamp" timestamp NOT NULL, + id SERIAL, + player_uuid char(36) NOT NULL, + type varchar(255) NOT NULL, + start_timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + end_timestamp timestamp NOT NULL, - PRIMARY KEY ("id"), - FOREIGN KEY ("player_uuid") REFERENCES "%players_table%" ("uuid") ON DELETE CASCADE ON UPDATE CASCADE + PRIMARY KEY (id), + FOREIGN KEY (player_uuid) REFERENCES "%player_data%" (uuid) ON DELETE CASCADE ON UPDATE CASCADE ); /* Create the current cross-server teleports table if it does not exist */ -CREATE TABLE IF NOT EXISTS "%teleports_table%" +CREATE TABLE IF NOT EXISTS "%teleport_data%" ( - "player_uuid" char(36) NOT NULL UNIQUE, - "destination_id" integer NOT NULL, - "type" integer NOT NULL DEFAULT 0, + player_uuid char(36) NOT NULL UNIQUE, + destination_id integer NOT NULL, + type integer NOT NULL DEFAULT 0, - PRIMARY KEY ("player_uuid"), - FOREIGN KEY ("player_uuid") REFERENCES "%players_table%" ("uuid") ON DELETE CASCADE ON UPDATE CASCADE, - FOREIGN KEY ("destination_id") REFERENCES "%positions_table%" ("id") ON DELETE CASCADE ON UPDATE NO ACTION + PRIMARY KEY (player_uuid), + FOREIGN KEY (player_uuid) REFERENCES "%player_data%" (uuid) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (destination_id) REFERENCES "%position_data%" (id) ON DELETE CASCADE ); /* Create the saved positions table if it does not exist */ -CREATE TABLE IF NOT EXISTS "%saved_positions_table%" +CREATE TABLE IF NOT EXISTS "%saved_position_data%" ( - "id" SERIAL, - "position_id" integer NOT NULL, - "name" varchar(64) NOT NULL, - "description" varchar(255) NOT NULL, - "tags" text DEFAULT NULL, - "timestamp" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + id SERIAL, + position_id integer NOT NULL, + name varchar(64) NOT NULL, + description varchar(255) NOT NULL, + tags text DEFAULT NULL, + timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY ("id"), - FOREIGN KEY ("position_id") REFERENCES "%positions_table%" ("id") ON DELETE CASCADE ON UPDATE NO ACTION + PRIMARY KEY (id), + FOREIGN KEY (position_id) REFERENCES "%position_data%" (id) ON DELETE CASCADE ); /* Create the homes table if it does not exist */ -CREATE TABLE IF NOT EXISTS "%homes_table%" +CREATE TABLE IF NOT EXISTS "%home_data%" ( - "uuid" char(36) NOT NULL UNIQUE, - "saved_position_id" integer NOT NULL, - "owner_uuid" char(36) NOT NULL, - "public" boolean NOT NULL DEFAULT FALSE, + uuid char(36) NOT NULL UNIQUE, + saved_position_id integer NOT NULL, + owner_uuid char(36) NOT NULL, + public boolean NOT NULL DEFAULT FALSE, - PRIMARY KEY ("uuid"), - FOREIGN KEY ("owner_uuid") REFERENCES "%players_table%" ("uuid") ON DELETE CASCADE ON UPDATE CASCADE, - FOREIGN KEY ("saved_position_id") REFERENCES "%saved_positions_table%" ("id") ON DELETE CASCADE ON UPDATE NO ACTION + PRIMARY KEY (uuid), + FOREIGN KEY (owner_uuid) REFERENCES "%player_data%" (uuid) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (saved_position_id) REFERENCES "%saved_position_data%" (id) ON DELETE CASCADE ); /* Create the warps table if it does not exist */ -CREATE TABLE IF NOT EXISTS "%warps_table%" +CREATE TABLE IF NOT EXISTS "%warp_data%" ( - "uuid" char(36) NOT NULL UNIQUE, - "saved_position_id" integer NOT NULL, + uuid char(36) NOT NULL UNIQUE, + saved_position_id integer NOT NULL, - PRIMARY KEY ("uuid"), - FOREIGN KEY ("saved_position_id") REFERENCES "%saved_positions_table%" ("id") ON DELETE CASCADE ON UPDATE NO ACTION + PRIMARY KEY (uuid), + FOREIGN KEY (saved_position_id) REFERENCES "%saved_position_data%" (id) ON DELETE CASCADE ); \ No newline at end of file diff --git a/common/src/main/resources/database/sqlite_schema.sql b/common/src/main/resources/database/sqlite_schema.sql index 0486c0ed..212e1ff3 100644 --- a/common/src/main/resources/database/sqlite_schema.sql +++ b/common/src/main/resources/database/sqlite_schema.sql @@ -1,5 +1,13 @@ -/* Create the positions table if it does not exist */ -CREATE TABLE IF NOT EXISTS `%positions_table%` +-- Create the metadata table if it does not exist +CREATE TABLE IF NOT EXISTS `%meta_data%` +( + `schema_version` integer NOT NULL, + + PRIMARY KEY (`schema_version`) +); + +-- Create the positions table if it does not exist +CREATE TABLE IF NOT EXISTS `%position_data%` ( `id` integer NOT NULL, `x` double NOT NULL, @@ -14,8 +22,8 @@ CREATE TABLE IF NOT EXISTS `%positions_table%` PRIMARY KEY (`id`) ); -/* Create the players table if it does not exist */ -CREATE TABLE IF NOT EXISTS `%players_table%` +-- Create the players table if it does not exist +CREATE TABLE IF NOT EXISTS `%player_data%` ( `uuid` char(36) NOT NULL UNIQUE, `username` varchar(16) NOT NULL, @@ -26,14 +34,14 @@ CREATE TABLE IF NOT EXISTS `%players_table%` `ignoring_requests` boolean NOT NULL DEFAULT FALSE, PRIMARY KEY (`uuid`), - FOREIGN KEY (`last_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, - FOREIGN KEY (`offline_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, - FOREIGN KEY (`respawn_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION + FOREIGN KEY (`last_position`) REFERENCES `%position_data%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, + FOREIGN KEY (`offline_position`) REFERENCES `%position_data%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, + FOREIGN KEY (`respawn_position`) REFERENCES `%position_data%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION ); -CREATE INDEX IF NOT EXISTS `%players_table%_username` ON `%players_table%` (`username`); +CREATE INDEX IF NOT EXISTS `%player_data%_username` ON `%player_data%` (`username`); -/* Create the cooldowns table if it does not exist */ -CREATE TABLE IF NOT EXISTS `%cooldowns_table%` +-- Create the cooldowns table if it does not exist +CREATE TABLE IF NOT EXISTS `%player_cooldowns_data%` ( `id` integer NOT NULL, `player_uuid` char(36) NOT NULL, @@ -42,24 +50,24 @@ CREATE TABLE IF NOT EXISTS `%cooldowns_table%` `end_timestamp` datetime NOT NULL, PRIMARY KEY (`id`), - FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE + FOREIGN KEY (`player_uuid`) REFERENCES `%player_data%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE ); -CREATE INDEX IF NOT EXISTS `%cooldowns_table%_player_uuid` ON `%cooldowns_table%` (`player_uuid`); +CREATE INDEX IF NOT EXISTS `%player_cooldowns_data%_player_uuid` ON `%player_cooldowns_data%` (`player_uuid`); -/* Create the current cross-server teleports table if it does not exist */ -CREATE TABLE IF NOT EXISTS `%teleports_table%` +-- Create the current cross-server teleports table if it does not exist +CREATE TABLE IF NOT EXISTS `%teleport_data%` ( `player_uuid` char(36) NOT NULL UNIQUE, `destination_id` integer NOT NULL, `type` integer NOT NULL DEFAULT 0, PRIMARY KEY (`player_uuid`), - FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, - FOREIGN KEY (`destination_id`) REFERENCES `%positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION + FOREIGN KEY (`player_uuid`) REFERENCES `%player_data%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (`destination_id`) REFERENCES `%position_data%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ); -/* Create the saved positions table if it does not exist */ -CREATE TABLE IF NOT EXISTS `%saved_positions_table%` +-- Create the saved positions table if it does not exist +CREATE TABLE IF NOT EXISTS `%saved_position_data%` ( `id` integer NOT NULL, `position_id` integer NOT NULL, @@ -69,12 +77,12 @@ CREATE TABLE IF NOT EXISTS `%saved_positions_table%` `timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), - FOREIGN KEY (`position_id`) REFERENCES `%positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION + FOREIGN KEY (`position_id`) REFERENCES `%position_data%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ); -CREATE INDEX IF NOT EXISTS `%saved_positions_table%_name` ON `%saved_positions_table%` (`name`); +CREATE INDEX IF NOT EXISTS `%saved_position_data%_name` ON `%saved_position_data%` (`name`); -/* Create the homes table if it does not exist */ -CREATE TABLE IF NOT EXISTS `%homes_table%` +-- Create the homes table if it does not exist +CREATE TABLE IF NOT EXISTS `%home_data%` ( `uuid` char(36) NOT NULL UNIQUE, `saved_position_id` integer NOT NULL, @@ -82,17 +90,17 @@ CREATE TABLE IF NOT EXISTS `%homes_table%` `public` boolean NOT NULL DEFAULT FALSE, PRIMARY KEY (`uuid`), - FOREIGN KEY (`owner_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, - FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION + FOREIGN KEY (`owner_uuid`) REFERENCES `%player_data%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_position_data%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ); -CREATE INDEX IF NOT EXISTS `%homes_table%_owner_uuid` ON `%homes_table%` (`owner_uuid`); +CREATE INDEX IF NOT EXISTS `%home_data%_owner_uuid` ON `%home_data%` (`owner_uuid`); -/* Create the warps table if it does not exist */ -CREATE TABLE IF NOT EXISTS `%warps_table%` +-- Create the warps table if it does not exist +CREATE TABLE IF NOT EXISTS `%warp_data%` ( `uuid` char(36) NOT NULL UNIQUE, `saved_position_id` integer NOT NULL, PRIMARY KEY (`uuid`), - FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION + FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_position_data%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ); \ No newline at end of file diff --git a/common/src/test/java/net/william278/huskhomes/network/MessageSerializationTests.java b/common/src/test/java/net/william278/huskhomes/network/MessageSerializationTests.java index 9fb5adc0..71d22a59 100644 --- a/common/src/test/java/net/william278/huskhomes/network/MessageSerializationTests.java +++ b/common/src/test/java/net/william278/huskhomes/network/MessageSerializationTests.java @@ -69,7 +69,7 @@ public class MessageSerializationTests { .build() ); - // Parameterized test for Message serialization + // Parameterized 0-mariadb-add_metadata_table.sql for Message serialization @DisplayName("Test Message Serialization/Deserialization") @ParameterizedTest(name = "{1} Message") @MethodSource("provideMessages") diff --git a/common/src/test/java/net/william278/huskhomes/position/SavedPositionTests.java b/common/src/test/java/net/william278/huskhomes/position/SavedPositionTests.java index 4582ecbc..9b39e911 100644 --- a/common/src/test/java/net/william278/huskhomes/position/SavedPositionTests.java +++ b/common/src/test/java/net/william278/huskhomes/position/SavedPositionTests.java @@ -53,12 +53,12 @@ public class SavedPositionTests { public void testHomeIdentifiers(@NotNull Home home, @NotNull String name, boolean isUnsafeName) { Assertions.assertEquals( home.getIdentifier(), - home.getOwner().getUsername() + Home.IDENTIFIER_DELIMITER + home.getName() + home.getOwner().getName() + Home.IDENTIFIER_DELIMITER + home.getName() ); Assertions.assertEquals( home.getSafeIdentifier(), isUnsafeName - ? home.getOwner().getUsername() + Home.IDENTIFIER_DELIMITER + home.getUuid() + ? home.getOwner().getName() + Home.IDENTIFIER_DELIMITER + home.getUuid() : home.getIdentifier() ); } diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml deleted file mode 100644 index b706511f..00000000 --- a/config/checkstyle/checkstyle.xml +++ /dev/null @@ -1,361 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/docs/API-Events.md b/docs/API-Events.md index 90aa711f..487733a1 100644 --- a/docs/API-Events.md +++ b/docs/API-Events.md @@ -24,11 +24,9 @@ HuskHomes provides a number of API events your plugin can listen to when certain † If the player uses `/delhome all` or `/delwarp all` to delete all their homes or all the warps, a single `DeleteAllHomesEvent` or `DeleteAllWarpsEvent` is fired instead. ‡ Called on the server the player *is teleported from*; not necessarily where the executor of the teleport is. -## Events on Sponge & Fabric +## Events on Fabric > **Note:** Check the [[API]] introduction for details on targeting platforms -Sponge, which has a similar Event api as Bukkit, has equivalent events for all of the above, prefixed with `Sponge` (so HomeCreateEvent on Bukkit is SpongeHomeCreateEvent on Sponge). - Fabric uses callbacks for handling events. HuskHomes provides callback equivalents for all the above events. For instance, to handle what to do when someone creates a home, you can register a callback to handle what to do as follows:

HuskHomes and Fabric callbacks diff --git a/docs/API-Examples.md b/docs/API-Examples.md index 5cf6b2d7..530f397c 100644 --- a/docs/API-Examples.md +++ b/docs/API-Examples.md @@ -1,6 +1,5 @@ -> **Please Note:** The HuskHomes API itself is only available on Bukkit, but Fabric and Sponge do support [API events](api-events). - The HuskHomes API provides methods and classes for: + * getting, creating and updating `Home`s and `Warp`s * getting information about `SavedUser` data * building and executing (timed) `Teleport`s, including cross-server teleports diff --git a/docs/API.md b/docs/API.md index b8bafc2a..d08c2c51 100644 --- a/docs/API.md +++ b/docs/API.md @@ -21,7 +21,6 @@ The HuskHomes API is available for the following platforms: * `bukkit` - Bukkit, Spigot, Paper, etc. Provides Bukkit API event listeners and adapters to `org.bukkit` objects. * `fabric` - Fabric, Quilt, etc. Provides Fabric API event callbacks and adapters to `net.minecraft` objects. -* `sponge` - Sponge. Provides Sponge API events. * `common` - Common API for all platforms.
@@ -38,7 +37,7 @@ The HuskHomes API is available for the following platforms: 2. [Adding HuskHomes as a dependency](#2-adding-huskhomes-as-a-dependency) 3. [Next steps](#3-next-steps) -## API Introduction +## 1 API Introduction ### 1.1 Setup with Maven
Maven setup information @@ -84,7 +83,7 @@ dependencies { ```
-## 2. Adding HuskHomes as a dependency +## 2 Adding HuskHomes as a dependency Add HuskHomes to your `softdepend` (if you want to optionally use HuskHomes) or `depend` (if your plugin relies on HuskHomes) section in `plugin.yml` of your project. ```yaml @@ -97,7 +96,7 @@ softdepend: # Or, use 'depend' here - HuskHomes ``` -## 3. Next steps +## 3 Next steps Now that you've got everything ready, you can start doing stuff with the HuskHomes API! - [[API Examples]] - [[API Events]] diff --git a/docs/Command-Conflicts.md b/docs/Command-Conflicts.md index 913bc5ff..8e2c5e83 100644 --- a/docs/Command-Conflicts.md +++ b/docs/Command-Conflicts.md @@ -48,7 +48,7 @@ disabled-commands:
## Fallback namespace -> **Applies to:** Spigot, Paper, Fabric, Sponge +> **Applies to:** Spigot, Paper, or Fabric All commands are registered with a fallback namespace, so that you can still access them. For instance, `/minecraft:tp` will run the default Minecraft teleport command, while `/huskhomes:tp` will run HuskHomes' tp command. diff --git a/docs/Config-Files.md b/docs/Config-Files.md index e630e652..3e0ea0f5 100644 --- a/docs/Config-Files.md +++ b/docs/Config-Files.md @@ -1,7 +1,7 @@ This page contains the configuration structure for HuskHomes. ## Configuration structure -📁 `plugins/HuskHomes/` (Spigot) OR `config/huskhomes/` (Fabric, Sponge) +📁 `plugins/HuskHomes/` (Spigot) OR `config/huskhomes/` (Fabric) - 📄 `config.yml`: General plugin configuration - 📄 `server.yml`: (Cross-server setups only) Server ID configuration - 📄 `spawn.yml`: Local saved server spawn position. Use /setspawn to generate this file diff --git a/docs/Economy-Hook.md b/docs/Economy-Hook.md index 96bf8b58..af79118c 100644 --- a/docs/Economy-Hook.md +++ b/docs/Economy-Hook.md @@ -17,14 +17,6 @@ To enable the Economy Hook on a Spigot/Paper server, install both [Vault](https: To enable the Economy Hook on a Fabric server, the [Impactor Economy](https://modrinth.com/mod/impactor) mod must be installed to provide an API for plugins to perform economy operations. Then, set `enabled` to `true` under the `economy` section of [`config.yml`](config-files).
-
-Sponge setup - -> **Applies to:** Sponge - -To enable the Economy Hook on a Sponge server, you require a mod installed for managing player economy accounts through the Sponge economy API. Then, set `enabled` to `true` under the `economy` section of [`config.yml`](config-files). -
- ### Bypassing economy checks Players with the `huskhomes.bypass_economy_checks` [permission node](commands) bypass economy checks and can perform economy actions without paying. diff --git a/docs/Managing-Access.md b/docs/Managing-Access.md index bfd099d5..ce41a201 100644 --- a/docs/Managing-Access.md +++ b/docs/Managing-Access.md @@ -1,7 +1,7 @@ To manage access to HuskHomes' features on your server, you should use a permission management plugin. However, if you're just throwing up a server with a home plugin for a group of mates, you can also just use the plugin on it's own without one and change some settings in `config.yml`. ### LuckPerms -[LuckPerms](https://luckperms.net) is the standard, stable and recommended permissions plugin, and works on Spigot, Fabric and Sponge servers. Follow the LuckPerms setup guide to get started. You can then use the `/lp editor` to assign the permissions detailed on this page to groups. A lot of HuskHomes' permissions are enabled for default users ([see below](#without-a-permissions-plugin)). You can set permissions to "false" to revoke a node from a group. +[LuckPerms](https://luckperms.net) is the standard, stable and recommended permissions plugin, and works on Spigot or Fabric servers. Follow the LuckPerms setup guide to get started. You can then use the `/lp editor` to assign the permissions detailed on this page to groups. A lot of HuskHomes' permissions are enabled for default users ([see below](#without-a-permissions-plugin)). You can set permissions to "false" to revoke a node from a group. ### Without a permissions plugin All commands have default operator level access grants to let you use them without a permissions plugin. The following commands require operator (`/op `): diff --git a/docs/Setup.md b/docs/Setup.md index c8ba0ca0..72686035 100644 --- a/docs/Setup.md +++ b/docs/Setup.md @@ -1,9 +1,9 @@ -This will walk you through installing HuskHomes on your Spigot, Fabric or Sponge server, or proxy network of servers. +This will walk you through installing HuskHomes on your Spigot or Fabric server, or proxy network of servers. ## Requirements > **Note:** If the plugin fails to load, please check that you are not running an [incompatible version combination](Unsupported-Versions) -* A Spigot (1.17.1+), Fabric (latest Minecraft version), or Sponge (Implementing API v10) _Minecraft: Java Edition_ server running on Java 17+ +* A Spigot (1.17.1+) or Fabric (latest Minecraft version) _Minecraft: Java Edition_ server running on Java 17+ * (For proxy network support) A proxy server (Velocity, BungeeCord) and MySQL (v8.0+)/MariaDB/PostgreSQL database * (For optional [[Redis support]]) A Redis database (v5.0+) @@ -11,13 +11,12 @@ This will walk you through installing HuskHomes on your Spigot, Fabric or Sponge Download the correct jar file for your server from the [latest release page](https://github.com/WiIIiam278/HuskHomes/releases/latest): * the `HuskHomes-Paper` jar for Spigot or Paper servers * the `HuskHomes-Fabric` jar for Fabric servers -* or the `HuskHomes-Sponge` jar for Sponge servers ## Single-server Setup Instructions -These instructions are for simply installing HuskHomes on one Spigot, Fabric or Sponge server. +These instructions are for simply installing HuskHomes on one Spigot or Fabric server. ### 1. Install the jar -- Place the plugin jar file in the `/plugins/` directory of your Spigot server, or the `/mods` directory of your Fabric/Sponge server. +- Place the plugin jar file in the `/plugins/` directory of your Spigot server, or the `/mods` directory of your Fabric server. ### 2. Restart the server and configure - Start, then stop your server to let HuskHomes generate the config file. - You can now edit the [config](Config-Files) and locales to your liking. @@ -27,16 +26,16 @@ These instructions are for simply installing HuskHomes on one Spigot, Fabric or ----- ## Multi-server Setup Instructions -These instructions are for installing HuskHomes on multiple Spigot, Fabric or Sponge servers and having them network together. A MySQL database (v8.0+) is required. +These instructions are for installing HuskHomes on multiple Spigot or Fabric servers and having them network together. A MySQL database (v8.0+) is required. ### 1. Install the jar -- Place the plugin jar file in the `/plugins/` directory of each Spigot server, or the `/mods` directory of your Fabric/Sponge server. +- Place the plugin jar file in the `/plugins/` directory of each Spigot server, or the `/mods` directory of your Fabric server. - You do not need to install HuskHomes as a proxy plugin. ### 2. Restart the server and configure - Start, then stop every server to let HuskHomes generate the config file. -- Advanced users: If you'd prefer, you can just create one config.yml file and create symbolic links in each `/plugins/HuskHomes/` (`/config/huskhomes/` on Fabric/Sponge) folder to it to make updating it easier. +- Advanced users: If you'd prefer, you can just create one config.yml file and create symbolic links in each `/plugins/HuskHomes/` (`/config/huskhomes/` on Fabric) folder to it to make updating it easier. ### 3. Configure servers to use cross-server mode -- Navigate to the HuskHomes [config](Config-Files) file on each server (`~/plugins/HuskHomes/config.yml` on Spigot, `~/config/huskhomes/config.yml` on Fabric/Sponge) +- Navigate to the HuskHomes [config](Config-Files) file on each server (`~/plugins/HuskHomes/config.yml` on Spigot, `~/config/huskhomes/config.yml` on Fabric) - Under `database`, set `type` to `MYSQL`, `MARIADB` or `POSTGRESQL` (depending on which type of database you wish to use) - Under `mysql`/`credentials`, enter the credentials of your MySQL, MariaDB or PostgreSQL database server. - Scroll down and look for the `cross_server` section. Set `enabled` to `true`. diff --git a/fabric/build.gradle b/fabric/build.gradle index 198fc8c5..e00e7980 100644 --- a/fabric/build.gradle +++ b/fabric/build.gradle @@ -10,7 +10,6 @@ repositories { url 'https://s01.oss.sonatype.org/content/repositories/snapshots/' mavenContent { snapshotsOnly() } } - maven { url 'https://maven.impactdev.net/repository/development/' } maven { url 'https://maven.nucleoid.xyz/' } } @@ -26,8 +25,8 @@ dependencies { modImplementation include("net.impactdev.impactor.api:economy:${fabric_impactor_api_version}") modCompileOnly "net.fabricmc.fabric-api:fabric-api:${fabric_api_version}" + implementation include('org.apache.commons:commons-pool2:2.12.0') implementation include("redis.clients:jedis:$jedis_version") - implementation include("org.apache.commons:commons-pool2:$commons_pool_version") implementation include("com.mysql:mysql-connector-j:$mysql_driver_version") implementation include("org.mariadb.jdbc:mariadb-java-client:$mariadb_driver_version") implementation include("org.xerial:sqlite-jdbc:$sqlite_driver_version") diff --git a/fabric/src/main/java/net/william278/huskhomes/FabricHuskHomes.java b/fabric/src/main/java/net/william278/huskhomes/FabricHuskHomes.java index 9b90689f..5c717f78 100644 --- a/fabric/src/main/java/net/william278/huskhomes/FabricHuskHomes.java +++ b/fabric/src/main/java/net/william278/huskhomes/FabricHuskHomes.java @@ -51,10 +51,9 @@ import net.william278.huskhomes.config.Locales; import net.william278.huskhomes.config.Server; import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.config.Spawn; -import net.william278.huskhomes.database.*; +import net.william278.huskhomes.database.Database; import net.william278.huskhomes.event.FabricEventDispatcher; -import net.william278.huskhomes.hook.FabricImpactorEconomyHook; -import net.william278.huskhomes.hook.FabricPlaceholderAPIHook; +import net.william278.huskhomes.hook.FabricHookProvider; import net.william278.huskhomes.hook.Hook; import net.william278.huskhomes.listener.EventListener; import net.william278.huskhomes.listener.FabricEventListener; @@ -62,20 +61,14 @@ import net.william278.huskhomes.manager.Manager; import net.william278.huskhomes.network.Broker; import net.william278.huskhomes.network.FabricPluginMessage; import net.william278.huskhomes.network.PluginMessageBroker; -import net.william278.huskhomes.network.RedisBroker; import net.william278.huskhomes.position.Location; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.World; -import net.william278.huskhomes.random.NormalDistributionEngine; import net.william278.huskhomes.random.RandomTeleportEngine; -import net.william278.huskhomes.user.ConsoleUser; -import net.william278.huskhomes.user.FabricUser; -import net.william278.huskhomes.user.OnlineUser; -import net.william278.huskhomes.user.SavedUser; -import net.william278.huskhomes.util.FabricSafetyResolver; +import net.william278.huskhomes.user.*; +import net.william278.huskhomes.util.FabricSavePositionProvider; import net.william278.huskhomes.util.FabricTask; import net.william278.huskhomes.util.UnsafeBlocks; -import net.william278.huskhomes.util.Validator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; @@ -87,152 +80,92 @@ import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; -import java.util.concurrent.ConcurrentMap; import java.util.function.Consumer; import java.util.logging.Level; -import java.util.stream.Collectors; @Getter -@Setter @NoArgsConstructor public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes, FabricTask.Supplier, - FabricEventDispatcher, FabricSafetyResolver, ServerPlayNetworking.PlayPayloadHandler { + FabricEventDispatcher, FabricSavePositionProvider, FabricUserProvider, FabricHookProvider, + ServerPlayNetworking.PlayPayloadHandler { public static final Logger LOGGER = LoggerFactory.getLogger("HuskHomes"); private final ModContainer modContainer = FabricLoader.getInstance().getModContainer("huskhomes") .orElseThrow(() -> new RuntimeException("Failed to get Mod Container")); private final Map permissions = Maps.newHashMap(); - private final Set savedUsers = Sets.newHashSet(); - private final ConcurrentMap> globalPlayerList = Maps.newConcurrentMap(); - private final Set currentlyOnWarmup = Sets.newHashSet(); - private final Set currentlyInvulnerable = Sets.newHashSet(); - private MinecraftServer minecraftServer; + private MinecraftServer minecraftServer; + private MinecraftServerAudiences audiences; + + private final Set savedUsers = Sets.newHashSet(); + private final Set currentlyOnWarmup = Sets.newConcurrentHashSet(); + private final Set currentlyInvulnerable = Sets.newConcurrentHashSet(); + private final Map onlineUserMap = Maps.newHashMap(); + private final Map> globalUserList = Maps.newConcurrentMap(); + private final List commands = Lists.newArrayList(); + + @Setter + private Set hooks = Sets.newHashSet(); + @Setter private Settings settings; + @Setter private Locales locales; + @Setter private Database database; - private Validator validator; + @Setter private Manager manager; + @Setter private EventListener eventListener; + @Setter private RandomTeleportEngine randomTeleportEngine; + @Setter private Spawn serverSpawn; + @Setter private UnsafeBlocks unsafeBlocks; - private List hooks; - private List commands; - private Server server; + @Setter @Nullable private Broker broker; - private MinecraftServerAudiences audiences; + @Setter + @Nullable + private Server serverName; @Override public void onInitializeServer() { - // Get plugin version from mod container - this.validator = new Validator(this); + this.load(); + this.loadCommands(); - // Load settings and locales - initialize("plugin config & locale files", (plugin) -> loadConfigs()); - - // Pre-register commands - initialize("commands", (plugin) -> this.commands = registerCommands()); - - ServerLifecycleEvents.SERVER_STARTING.register(server -> { - this.minecraftServer = server; - this.onEnable(); - }); - ServerLifecycleEvents.SERVER_STOPPING.register(server -> this.onDisable()); + ServerLifecycleEvents.SERVER_STARTING.register(this::onEnable); + ServerLifecycleEvents.SERVER_STOPPING.register(this::onDisable); } - private void onEnable() { - // Create adventure audience + private void onEnable(@NotNull MinecraftServer server) { + this.minecraftServer = server; this.audiences = MinecraftServerAudiences.of(minecraftServer); - - // Initialize the database - final Database.Type type = getSettings().getDatabase().getType(); - initialize(type.getDisplayName() + " database connection", (plugin) -> { - this.database = switch (type) { - case MYSQL, MARIADB -> new MySqlDatabase(this); - case SQLITE -> new SqLiteDatabase(this); - case H2 -> new H2Database(this); - case POSTGRESQL -> new PostgreSqlDatabase(this); - }; - - database.initialize(); - }); - - // Initialize the manager - this.manager = new Manager(this); - - // Initialize the network messenger if proxy mode is enabled - final Settings.CrossServerSettings crossServer = getSettings().getCrossServer(); - if (crossServer.isEnabled()) { - initialize(crossServer.getBrokerType().getDisplayName() + " message broker", (plugin) -> { - broker = switch (crossServer.getBrokerType()) { - case PLUGIN_MESSAGE -> new PluginMessageBroker(this); - case REDIS -> new RedisBroker(this); - }; - broker.initialize(); - }); - } - - setRandomTeleportEngine(new NormalDistributionEngine(this)); - - // Register plugin hooks (Economy, Maps, Plan) - initialize("hooks", (plugin) -> { - this.registerHooks(); - - if (!hooks.isEmpty()) { - hooks.forEach(hook -> { - try { - hook.initialize(); - } catch (Throwable e) { - log(Level.WARNING, "Failed to initialize " + hook.getName() + " hook", e); - } - }); - log(Level.INFO, "Registered " + hooks.size() + " mod hooks: " + hooks.stream() - .map(Hook::getName) - .collect(Collectors.joining(", "))); - } - }); - - // Register events - initialize("events", (plugin) -> this.eventListener = new FabricEventListener(this)); - - // Initialize the API - initialize("API", (plugin) -> FabricHuskHomesAPI.register(this)); - - this.checkForUpdates(); + this.enable(); } - @Override - public void registerHooks() { - HuskHomes.super.registerHooks(); - - // Register the impactor economy service if it is available - if (getSettings().getEconomy().isEnabled() && isDependencyLoaded("impactor")) { - getHooks().add(new FabricImpactorEconomyHook(this)); - } - - if (isDependencyLoaded("placeholder-api")) { - getHooks().add(new FabricPlaceholderAPIHook(this)); - } - } - - private void onDisable() { - if (this.eventListener != null) { - this.eventListener.handlePluginDisable(); - } - if (database != null) { - database.terminate(); - } - if (broker != null) { - broker.close(); - } + private void onDisable(@NotNull MinecraftServer server) { + this.shutdown(); if (audiences != null) { audiences.close(); audiences = null; } - cancelTasks(); + } + + @Override + public void loadAPI() { + FabricHuskHomesAPI.register(this); + } + + @Override + public void loadMetrics() { + // No metrics on Fabric + } + + @Override + public void disablePlugin() { + onDisable(minecraftServer); } @Override @@ -241,14 +174,6 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes return new ConsoleUser(audiences.console()); } - @Override - @NotNull - public List getOnlineUsers() { - return minecraftServer.getPlayerManager().getPlayerList() - .stream().map(user -> (OnlineUser) FabricUser.adapt(user, this)) - .toList(); - } - @NotNull @Override public Audience getAudience(@NotNull UUID user) { @@ -274,21 +199,12 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes @Override @NotNull public String getServerName() { - return server == null ? "server" : server.getName(); + return serverName == null ? "server" : serverName.getName(); } @Override - public void setServerName(@NotNull Server server) { - this.server = server; - } - - @Override - @NotNull - public Broker getMessenger() { - if (broker == null) { - throw new IllegalStateException("Attempted to access message broker when it was not initialized"); - } - return broker; + public boolean isDependencyAvailable(@NotNull String name) { + return FabricLoader.getInstance().isModLoaded(name); } @Override @@ -322,31 +238,44 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes @Override @NotNull - public Version getVersion() { + public Version getPluginVersion() { return Version.fromString(modContainer.getMetadata().getVersion().getFriendlyString(), "-"); } + @Override @NotNull - public List registerCommands() { - final List commands = FabricCommand.Type.getCommands(getPlugin()); - CommandRegistrationCallback.EVENT.register((dispatcher, ignored, ignored2) -> - commands.forEach(command -> new FabricCommand(command, this).register(dispatcher))); - return commands; + public String getServerType() { + return String.format("fabric %s/%s", FabricLoader.getInstance() + .getModContainer("fabricloader").map(l -> l.getMetadata().getVersion().getFriendlyString()) + .orElse("unknown"), minecraftServer.getVersion()); } @Override - public boolean isDependencyLoaded(@NotNull String name) { - return FabricLoader.getInstance().isModLoaded(name) - || FabricLoader.getInstance().isModLoaded(name.toLowerCase(Locale.ENGLISH)); + @NotNull + public Version getMinecraftVersion() { + return Version.fromString(minecraftServer.getVersion()); } @Override - public void registerMetrics(int metricsId) { - // No metrics for Fabric + public void registerCommands(@NotNull List commands) { + CommandRegistrationCallback.EVENT.register((dispatcher, ignored, ignored2) -> commands.forEach( + (command) -> new FabricCommand(command, this).register(dispatcher)) + ); } @Override - public void initializePluginChannels() { + @NotNull + public EventListener createListener() { + return new FabricEventListener(this); + } + + @Override + public Optional getBroker() { + return Optional.ofNullable(broker); + } + + @Override + public void setupPluginMessagingChannels() { PayloadTypeRegistry.playC2S().register(FabricPluginMessage.CHANNEL_ID, FabricPluginMessage.CODEC); PayloadTypeRegistry.playS2C().register(FabricPluginMessage.CHANNEL_ID, FabricPluginMessage.CODEC); ServerPlayNetworking.registerGlobalReceiver(FabricPluginMessage.CHANNEL_ID, this); @@ -356,10 +285,10 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes @Override public void receive(@NotNull FabricPluginMessage payload, @NotNull ServerPlayNetworking.Context context) { if (broker instanceof PluginMessageBroker messenger - && getSettings().getCrossServer().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { + && getSettings().getCrossServer().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { messenger.onReceive( PluginMessageBroker.BUNGEE_CHANNEL_ID, - FabricUser.adapt(context.player(), this), + getOnlineUser(context.player()), payload.getData() ); } @@ -380,14 +309,18 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes logEvent.log(message); } - @NotNull - public Map getPermissions() { - return permissions; + @Override + public void closeDatabase() { + if (database != null) { + database.close(); + } } - @NotNull - public MinecraftServer getMinecraftServer() { - return minecraftServer; + @Override + public void closeBroker() { + if (broker != null) { + broker.close(); + } } @Override diff --git a/fabric/src/main/java/net/william278/huskhomes/api/FabricHuskHomesAPI.java b/fabric/src/main/java/net/william278/huskhomes/api/FabricHuskHomesAPI.java index 26cf22a4..10ead01f 100644 --- a/fabric/src/main/java/net/william278/huskhomes/api/FabricHuskHomesAPI.java +++ b/fabric/src/main/java/net/william278/huskhomes/api/FabricHuskHomesAPI.java @@ -87,7 +87,7 @@ public class FabricHuskHomesAPI extends BaseHuskHomesAPI { */ @NotNull public OnlineUser adaptUser(@NotNull ServerPlayerEntity player) { - return FabricUser.adapt(player, (FabricHuskHomes) plugin); + return ((FabricHuskHomes) plugin).getOnlineUser(player); } /** diff --git a/fabric/src/main/java/net/william278/huskhomes/command/FabricCommand.java b/fabric/src/main/java/net/william278/huskhomes/command/FabricCommand.java index 7a881282..0ebf367c 100644 --- a/fabric/src/main/java/net/william278/huskhomes/command/FabricCommand.java +++ b/fabric/src/main/java/net/william278/huskhomes/command/FabricCommand.java @@ -28,17 +28,10 @@ import net.fabricmc.fabric.api.util.TriState; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.network.ServerPlayerEntity; import net.william278.huskhomes.FabricHuskHomes; -import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.teleport.TeleportRequest; import net.william278.huskhomes.user.CommandUser; -import net.william278.huskhomes.user.FabricUser; import org.jetbrains.annotations.NotNull; -import java.util.Arrays; -import java.util.List; import java.util.Map; -import java.util.Objects; -import java.util.function.Function; import java.util.function.Predicate; import static com.mojang.brigadier.arguments.StringArgumentType.greedyString; @@ -97,7 +90,7 @@ public class FabricCommand { } private com.mojang.brigadier.suggestion.SuggestionProvider getBrigadierSuggester() { - if (!(command instanceof TabProvider provider)) { + if (!(command instanceof TabCompletable provider)) { return (context, builder) -> com.mojang.brigadier.suggestion.Suggestions.empty(); } return (context, builder) -> { @@ -118,64 +111,9 @@ public class FabricCommand { private CommandUser resolveExecutor(@NotNull ServerCommandSource source) { if (source.getEntity() instanceof ServerPlayerEntity player) { - return FabricUser.adapt(player, plugin); + return plugin.getOnlineUser(player); } return plugin.getConsole(); } - - /** - * Commands available on the Fabric HuskHomes implementation. - */ - public enum Type { - HOME_COMMAND(PrivateHomeCommand::new), - SET_HOME_COMMAND(SetHomeCommand::new), - HOME_LIST_COMMAND(HomeListCommand::new), - DEL_HOME_COMMAND(DelHomeCommand::new), - EDIT_HOME_COMMAND(EditHomeCommand::new), - PUBLIC_HOME_COMMAND(PublicHomeCommand::new), - PUBLIC_HOME_LIST_COMMAND(PublicHomeListCommand::new), - WARP_COMMAND(WarpCommand::new), - SET_WARP_COMMAND(SetWarpCommand::new), - WARP_LIST_COMMAND(WarpListCommand::new), - DEL_WARP_COMMAND(DelWarpCommand::new), - EDIT_WARP_COMMAND(EditWarpCommand::new), - TP_COMMAND(TpCommand::new), - TP_HERE_COMMAND(TpHereCommand::new), - TPA_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA)), - TPA_HERE_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA_HERE)), - TPACCEPT_COMMAND((plugin) -> new TpRespondCommand(plugin, true)), - TPDECLINE_COMMAND((plugin) -> new TpRespondCommand(plugin, false)), - RTP_COMMAND(RTPCommand::new), - TP_IGNORE_COMMAND(TpIgnoreCommand::new), - TP_OFFLINE_COMMAND(TpOfflineCommand::new), - TP_ALL_COMMAND(TpAllCommand::new), - TPA_ALL_COMMAND(TpaAllCommand::new), - SPAWN_COMMAND(SpawnCommand::new), - SET_SPAWN_COMMAND(SetSpawnCommand::new), - BACK_COMMAND(BackCommand::new), - HUSKHOMES_COMMAND(HuskHomesCommand::new); - - private final Function supplier; - - Type(@NotNull Function supplier) { - this.supplier = supplier; - } - - @NotNull - public Command createCommand(@NotNull HuskHomes plugin) { - return supplier.apply(plugin); - } - - @NotNull - public static List getCommands(@NotNull FabricHuskHomes plugin) { - return Arrays.stream(values()) - .map(type -> type.createCommand(plugin)) - .map(command -> plugin.getSettings().isCommandDisabled(command) ? null : command) - .filter(Objects::nonNull) - .toList(); - } - - } - } diff --git a/fabric/src/main/java/net/william278/huskhomes/hook/FabricHookProvider.java b/fabric/src/main/java/net/william278/huskhomes/hook/FabricHookProvider.java new file mode 100644 index 00000000..f919dbbb --- /dev/null +++ b/fabric/src/main/java/net/william278/huskhomes/hook/FabricHookProvider.java @@ -0,0 +1,60 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.hook; + +import net.fabricmc.loader.api.FabricLoader; +import net.william278.huskhomes.FabricHuskHomes; +import org.jetbrains.annotations.NotNull; + +import java.util.List; +import java.util.Locale; + +public interface FabricHookProvider extends HookProvider { + + @Override + @NotNull + default List getAvailableHooks() { + final List hooks = HookProvider.super.getAvailableHooks(); + + // Register the impactor economy service if it is available + if (getPlugin().getSettings().getEconomy().isEnabled() && isDependencyAvailable("impactor")) { + getHooks().add(new FabricImpactorEconomyHook(getPlugin())); + } + + if (isDependencyAvailable("placeholder-api")) { + getHooks().add(new FabricPlaceholderAPIHook(getPlugin())); + } + + return hooks; + } + + + @Override + default boolean isDependencyAvailable(@NotNull String name) { + return FabricLoader.getInstance().isModLoaded(name) + || FabricLoader.getInstance().isModLoaded(name.toLowerCase(Locale.ENGLISH)); + + } + + @Override + @NotNull + FabricHuskHomes getPlugin(); + +} diff --git a/fabric/src/main/java/net/william278/huskhomes/hook/FabricImpactorEconomyHook.java b/fabric/src/main/java/net/william278/huskhomes/hook/FabricImpactorEconomyHook.java index efc42e0f..2f9ac48d 100644 --- a/fabric/src/main/java/net/william278/huskhomes/hook/FabricImpactorEconomyHook.java +++ b/fabric/src/main/java/net/william278/huskhomes/hook/FabricImpactorEconomyHook.java @@ -35,7 +35,21 @@ public class FabricImpactorEconomyHook extends EconomyHook { private Currency currency; public FabricImpactorEconomyHook(@NotNull HuskHomes plugin) { - super(plugin, "Fabric Impactor Economy"); + super(plugin); + } + + @Override + public void load() { + this.economyService = EconomyService.instance(); + if (this.economyService == null) { + throw new IllegalStateException("Impactor API is not available, No economy service has been registered!"); + } + this.currency = this.economyService.currencies().primary(); + } + + @Override + public void unload() { + this.economyService = null; } @Override @@ -73,13 +87,4 @@ public class FabricImpactorEconomyHook extends EconomyHook { public String formatCurrency(double amount) { return PlainTextComponentSerializer.plainText().serialize(currency.format(BigDecimal.valueOf(amount))); } - - @Override - public void initialize() { - this.economyService = EconomyService.instance(); - if (this.economyService == null) { - throw new IllegalStateException("Impactor API is not available, No economy service has been registered!"); - } - this.currency = this.economyService.currencies().primary(); - } } \ No newline at end of file diff --git a/fabric/src/main/java/net/william278/huskhomes/hook/FabricPlaceholderAPIHook.java b/fabric/src/main/java/net/william278/huskhomes/hook/FabricPlaceholderAPIHook.java index 015019c6..2bc362f1 100644 --- a/fabric/src/main/java/net/william278/huskhomes/hook/FabricPlaceholderAPIHook.java +++ b/fabric/src/main/java/net/william278/huskhomes/hook/FabricPlaceholderAPIHook.java @@ -23,17 +23,20 @@ import eu.pb4.placeholders.api.PlaceholderResult; import eu.pb4.placeholders.api.Placeholders; import net.minecraft.util.Identifier; import net.william278.huskhomes.FabricHuskHomes; -import net.william278.huskhomes.user.FabricUser; import net.william278.huskhomes.user.OnlineUser; import net.william278.huskhomes.user.SavedUser; import org.jetbrains.annotations.NotNull; import java.util.List; +@PluginHook( + name = "Fabric PlaceholderAPI", + register = PluginHook.Register.ON_ENABLE +) public class FabricPlaceholderAPIHook extends Hook { public FabricPlaceholderAPIHook(@NotNull FabricHuskHomes plugin) { - super(plugin, "Fabric PlaceholderAPI"); + super(plugin); } @SuppressWarnings("SameParameterValue") @@ -43,7 +46,7 @@ public class FabricPlaceholderAPIHook extends Hook { } @Override - public void initialize() { + public void load() { Placeholders.register(createIdentifier("player"), (ctx, arg) -> { if (!ctx.hasPlayer()) { return PlaceholderResult.invalid("No player!"); @@ -54,12 +57,12 @@ public class FabricPlaceholderAPIHook extends Hook { } assert ctx.player() != null; - final OnlineUser player = FabricUser.adapt(ctx.player(), (FabricHuskHomes) plugin); + final OnlineUser player = ((FabricHuskHomes) plugin).getOnlineUser(ctx.player()); final String response = switch (arg) { case "homes_count" -> String.valueOf(plugin.getManager().homes() .getUserHomes() - .getOrDefault(player.getUsername(), List.of()).size()); + .getOrDefault(player.getName(), List.of()).size()); case "max_homes" -> String.valueOf(plugin.getManager().homes().getMaxHomes(player)); case "max_public_homes" -> String.valueOf(plugin.getManager().homes().getMaxPublicHomes(player)); case "free_home_slots" -> String.valueOf(plugin.getManager().homes().getFreeHomes(player)); @@ -67,13 +70,13 @@ public class FabricPlaceholderAPIHook extends Hook { .map(SavedUser::getHomeSlots).orElse(0)); case "homes_list" -> String.join(", ", plugin.getManager().homes() .getUserHomes() - .getOrDefault(player.getUsername(), List.of())); + .getOrDefault(player.getName(), List.of())); case "public_homes_count" -> String.valueOf(plugin.getManager().homes() .getPublicHomes() - .getOrDefault(player.getUsername(), List.of()).size()); + .getOrDefault(player.getName(), List.of()).size()); case "public_homes_list" -> String.join(", ", plugin.getManager().homes() .getPublicHomes() - .getOrDefault(player.getUsername(), List.of())); + .getOrDefault(player.getName(), List.of())); case "ignoring_tp_requests" -> String.valueOf(plugin.getManager().requests() .isIgnoringRequests(player)); default -> null; @@ -86,4 +89,10 @@ public class FabricPlaceholderAPIHook extends Hook { return PlaceholderResult.value(response); }); } + + @Override + public void unload() { + Placeholders.remove(createIdentifier("player")); + } + } \ No newline at end of file diff --git a/fabric/src/main/java/net/william278/huskhomes/listener/FabricEventListener.java b/fabric/src/main/java/net/william278/huskhomes/listener/FabricEventListener.java index ba97ce55..9431878e 100644 --- a/fabric/src/main/java/net/william278/huskhomes/listener/FabricEventListener.java +++ b/fabric/src/main/java/net/william278/huskhomes/listener/FabricEventListener.java @@ -24,7 +24,6 @@ import net.fabricmc.fabric.api.entity.event.v1.ServerPlayerEvents; import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; import net.minecraft.server.network.ServerPlayerEntity; import net.william278.huskhomes.FabricHuskHomes; -import net.william278.huskhomes.user.FabricUser; import org.jetbrains.annotations.NotNull; // Note that the teleport event and update player respawn position events are not handled on Fabric. @@ -33,32 +32,37 @@ public class FabricEventListener extends EventListener { public FabricEventListener(@NotNull FabricHuskHomes plugin) { super(plugin); - this.registerEvents(plugin); } - // Register fabric event callback listeners to internal handlers - private void registerEvents(@NotNull FabricHuskHomes plugin) { + @Override + public void register() { // Join event ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> handlePlayerJoin( - FabricUser.adapt(handler.player, plugin) + getPlugin().getOnlineUser(handler.player) )); // Quit event ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> handlePlayerLeave( - FabricUser.adapt(handler.player, plugin) + getPlugin().getOnlineUser(handler.player) )); // Death event ServerLivingEntityEvents.AFTER_DEATH.register((entity, source) -> { if (entity instanceof ServerPlayerEntity player) { - handlePlayerDeath(FabricUser.adapt(player, plugin)); + handlePlayerDeath(getPlugin().getOnlineUser(player)); } }); // Respawn event ServerPlayerEvents.AFTER_RESPAWN.register((oldPlayer, newPlayer, alive) -> handlePlayerRespawn( - FabricUser.adapt(newPlayer, plugin) + getPlugin().getOnlineUser(newPlayer) )); } - + + @NotNull + @Override + protected FabricHuskHomes getPlugin() { + return (FabricHuskHomes) super.getPlugin(); + } + } diff --git a/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java b/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java index 8c07675d..8db62f21 100644 --- a/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java +++ b/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java @@ -33,6 +33,7 @@ import net.william278.huskhomes.position.Location; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.World; import net.william278.huskhomes.teleport.TeleportationException; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.util.*; @@ -48,6 +49,7 @@ public class FabricUser extends OnlineUser { } @NotNull + @ApiStatus.Internal public static FabricUser adapt(@NotNull ServerPlayerEntity player, @NotNull FabricHuskHomes plugin) { return new FabricUser(player, plugin); } diff --git a/fabric/src/main/java/net/william278/huskhomes/user/FabricUserProvider.java b/fabric/src/main/java/net/william278/huskhomes/user/FabricUserProvider.java new file mode 100644 index 00000000..8cdf9752 --- /dev/null +++ b/fabric/src/main/java/net/william278/huskhomes/user/FabricUserProvider.java @@ -0,0 +1,54 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.user; + +import net.minecraft.server.network.ServerPlayerEntity; +import net.william278.huskhomes.FabricHuskHomes; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.UUID; + +public interface FabricUserProvider extends UserProvider { + + @Override + @NotNull + default OnlineUser getOnlineUser(@NotNull UUID uuid) { + return getOnlineUser(getPlugin().getMinecraftServer().getPlayerManager().getPlayer(uuid)); + } + + @NotNull + default FabricUser getOnlineUser(@Nullable ServerPlayerEntity player) { + if (player == null) { + throw new IllegalArgumentException("Player is not online"); + } + FabricUser user = (FabricUser) getOnlineUserMap().get(player.getUuid()); + if (user == null) { + user = FabricUser.adapt(player, getPlugin()); + getOnlineUserMap().put(player.getUuid(), user); + return user; + } + return user; + } + + @NotNull + FabricHuskHomes getPlugin(); + +} diff --git a/fabric/src/main/java/net/william278/huskhomes/util/FabricSafetyResolver.java b/fabric/src/main/java/net/william278/huskhomes/util/FabricSavePositionProvider.java similarity index 98% rename from fabric/src/main/java/net/william278/huskhomes/util/FabricSafetyResolver.java rename to fabric/src/main/java/net/william278/huskhomes/util/FabricSavePositionProvider.java index 15eb62ef..088c4926 100644 --- a/fabric/src/main/java/net/william278/huskhomes/util/FabricSafetyResolver.java +++ b/fabric/src/main/java/net/william278/huskhomes/util/FabricSavePositionProvider.java @@ -36,7 +36,7 @@ import org.jetbrains.annotations.NotNull; import java.util.Optional; import java.util.concurrent.CompletableFuture; -public interface FabricSafetyResolver extends SafetyResolver { +public interface FabricSavePositionProvider extends SavePositionProvider { @Override default CompletableFuture> findSafeGroundLocation(@NotNull Location location) { diff --git a/gradle.properties b/gradle.properties index c935ddf6..2bd6eae9 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,18 +4,17 @@ org.gradle.jvmargs='-Dfile.encoding=UTF-8' org.gradle.daemon=true # Plugin metadata -plugin_version=4.7.1 +plugin_version=4.8 plugin_archive=huskhomes plugin_description=The powerful & intuitive homes, warps, and teleportation suite # General settings -jedis_version=5.1.5 -mysql_driver_version=9.0.0 -mariadb_driver_version=3.4.1 -sqlite_driver_version=3.46.1.0 +jedis_version=5.2.0 +mysql_driver_version=9.1.0 +mariadb_driver_version=3.5.0 +sqlite_driver_version=3.47.0.0 h2_driver_version=2.3.232 -postgresql_driver_version=42.7.3 -commons_pool_version=2.12.0 +postgresql_driver_version=42.7.4 # Fabric settings fabric_loom_version=1.8-SNAPSHOT diff --git a/paper/src/main/java/net/william278/huskhomes/PaperHuskHomes.java b/paper/src/main/java/net/william278/huskhomes/PaperHuskHomes.java index 7eaa18cc..5cdbc2d6 100644 --- a/paper/src/main/java/net/william278/huskhomes/PaperHuskHomes.java +++ b/paper/src/main/java/net/william278/huskhomes/PaperHuskHomes.java @@ -30,7 +30,7 @@ public class PaperHuskHomes extends BukkitHuskHomes { @Override @NotNull - protected PaperEventListener getListener() { + public PaperEventListener createListener() { return new PaperEventListener(this); } diff --git a/paper/src/main/java/net/william278/huskhomes/listener/PaperEventListener.java b/paper/src/main/java/net/william278/huskhomes/listener/PaperEventListener.java index 8f874b55..86607a05 100644 --- a/paper/src/main/java/net/william278/huskhomes/listener/PaperEventListener.java +++ b/paper/src/main/java/net/william278/huskhomes/listener/PaperEventListener.java @@ -23,7 +23,6 @@ import com.destroystokyo.paper.event.player.PlayerSetSpawnEvent; import net.william278.huskhomes.BukkitHuskHomes; import net.william278.huskhomes.PaperHuskHomes; import net.william278.huskhomes.config.Settings; -import net.william278.huskhomes.user.BukkitUser; import org.bukkit.Location; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -39,15 +38,13 @@ public class PaperEventListener extends BukkitEventListener implements Listener } @Override - @NotNull - public PaperEventListener register(@NotNull BukkitHuskHomes plugin) { - plugin.getServer().getPluginManager().registerEvents(this, plugin); - return this; + public void register() { + getPlugin().getServer().getPluginManager().registerEvents(this, getPlugin()); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onPlayerUpdateRespawnLocation(PlayerSetSpawnEvent event) { - final Settings.CrossServerSettings crossServer = plugin.getSettings().getCrossServer(); + final Settings.CrossServerSettings crossServer = getPlugin().getSettings().getCrossServer(); if (!(crossServer.isEnabled() && crossServer.isGlobalRespawning())) { return; } @@ -60,8 +57,8 @@ public class PaperEventListener extends BukkitEventListener implements Listener // Update the player's respawn location this.handlePlayerUpdateSpawnPoint( - BukkitUser.adapt(event.getPlayer(), (BukkitHuskHomes) plugin), - BukkitHuskHomes.Adapter.adapt(location, plugin.getServerName()) + getPlugin().getOnlineUser(event.getPlayer()), + BukkitHuskHomes.Adapter.adapt(location, getPlugin().getServerName()) ); } @@ -71,7 +68,13 @@ public class PaperEventListener extends BukkitEventListener implements Listener if (event.getRespawnReason() != PlayerRespawnEvent.RespawnReason.DEATH) { return; } - super.handlePlayerRespawn(BukkitUser.adapt(event.getPlayer(), (BukkitHuskHomes) plugin)); + super.handlePlayerRespawn(getPlugin().getOnlineUser(event.getPlayer())); + } + + @NotNull + @Override + public PaperHuskHomes getPlugin() { + return (PaperHuskHomes) super.getPlugin(); } } diff --git a/settings.gradle b/settings.gradle index 2120d2b2..9881f43e 100644 --- a/settings.gradle +++ b/settings.gradle @@ -15,7 +15,4 @@ include( // Fabric 'fabric', - - // Sponge - 'sponge' ) \ No newline at end of file diff --git a/sponge/build.gradle b/sponge/build.gradle deleted file mode 100644 index 312eaf47..00000000 --- a/sponge/build.gradle +++ /dev/null @@ -1,81 +0,0 @@ -import org.spongepowered.gradle.plugin.config.PluginLoaders -import org.spongepowered.plugin.metadata.model.PluginDependency - -plugins { - id 'org.spongepowered.gradle.plugin' version '2.2.0' -} - -dependencies { - implementation project(path: ':common') - - implementation 'org.bstats:bstats-sponge:3.1.0' - implementation "redis.clients:jedis:${jedis_version}" - implementation "com.mysql:mysql-connector-j:${mysql_driver_version}" - implementation "org.mariadb.jdbc:mariadb-java-client:${mariadb_driver_version}" - implementation "org.xerial:sqlite-jdbc:${sqlite_driver_version}" - implementation "com.h2database:h2:${h2_driver_version}" - - compileOnly 'org.projectlombok:lombok:1.18.34' - - annotationProcessor 'org.projectlombok:lombok:1.18.34' -} - -sponge { - apiVersion("10.0.0") - loader { - name(PluginLoaders.JAVA_PLAIN) - version("1.0") - } - license("Apache-2.0") - plugin("huskhomes") { - displayName("HuskHomes") - version(project.version.toString()) - entrypoint("net.william278.huskhomes.SpongeHuskHomes") - description(project.description.toString()) - links { - homepage("https://william278.net/project/huskhomes") - source("https://github.com/WiIIiam278/HuskHomes") - issues("https://github.com/WiIIiam278/HuskHomes/issues") - } - contributor("William278") { - description("Author") - } - dependency("spongeapi") { - loadOrder(PluginDependency.LoadOrder.AFTER) - optional(false) - } - dependency("bluemap") { - loadOrder(PluginDependency.LoadOrder.AFTER) - optional(true) - version("3.4") - } - dependency("plan") { - loadOrder(PluginDependency.LoadOrder.AFTER) - optional(true) - version("5.4") - } - } -} - -shadowJar { - destinationDirectory.set(file("$rootDir/target/")) - archiveClassifier.set('') - - exclude('org.spongepowered:.*') - exclude('net.kyori:.*') - - relocate 'org.apache.commons.io', 'net.william278.huskhomes.libraries.commons.io' - relocate 'org.apache.commons.text', 'net.william278.huskhomes.libraries.commons.text' - relocate 'org.apache.commons.lang3', 'net.william278.huskhomes.libraries.commons.lang3' - relocate 'de.themoep', 'net.william278.huskhomes.libraries' - relocate 'org.jetbrains', 'net.william278.huskhomes.libraries' - relocate 'org.intellij', 'net.william278.huskhomes.libraries' - relocate 'com.zaxxer', 'net.william278.huskhomes.libraries' - relocate 'net.william278.paginedown', 'net.william278.huskhomes.libraries.paginedown' - relocate 'net.william278.desertwell', 'net.william278.huskhomes.libraries.desertwell' - relocate 'de.exlll', 'net.william278.huskhomes.libraries' - relocate 'org.json', 'net.william278.huskhomes.libraries.json' - relocate 'org.yaml.snakeyaml', 'net.william278.huskhomes.libraries.snakeyaml' - relocate 'com.google.gson', 'net.william278.huskhomes.libraries.gson' - relocate 'org.bstats', 'net.william278.huskhomes.libraries.bstats' -} \ No newline at end of file diff --git a/sponge/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java b/sponge/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java deleted file mode 100644 index a71bce03..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java +++ /dev/null @@ -1,445 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes; - -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.google.inject.Inject; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import net.kyori.adventure.audience.Audience; -import net.william278.desertwell.util.Version; -import net.william278.huskhomes.command.Command; -import net.william278.huskhomes.command.SpongeCommand; -import net.william278.huskhomes.config.Locales; -import net.william278.huskhomes.config.Server; -import net.william278.huskhomes.config.Settings; -import net.william278.huskhomes.config.Spawn; -import net.william278.huskhomes.database.*; -import net.william278.huskhomes.event.SpongeEventDispatcher; -import net.william278.huskhomes.hook.Hook; -import net.william278.huskhomes.hook.SpongeEconomyHook; -import net.william278.huskhomes.listener.SpongeEventListener; -import net.william278.huskhomes.manager.Manager; -import net.william278.huskhomes.network.Broker; -import net.william278.huskhomes.network.PluginMessageBroker; -import net.william278.huskhomes.network.RedisBroker; -import net.william278.huskhomes.position.Location; -import net.william278.huskhomes.position.Position; -import net.william278.huskhomes.position.World; -import net.william278.huskhomes.random.NormalDistributionEngine; -import net.william278.huskhomes.random.RandomTeleportEngine; -import net.william278.huskhomes.user.ConsoleUser; -import net.william278.huskhomes.user.OnlineUser; -import net.william278.huskhomes.user.SavedUser; -import net.william278.huskhomes.user.SpongeUser; -import net.william278.huskhomes.util.SpongeSafetyResolver; -import net.william278.huskhomes.util.SpongeTask; -import net.william278.huskhomes.util.UnsafeBlocks; -import net.william278.huskhomes.util.Validator; -import org.bstats.charts.SimplePie; -import org.bstats.sponge.Metrics; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.spongepowered.api.Game; -import org.spongepowered.api.ResourceKey; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.command.Command.Raw; -import org.spongepowered.api.config.ConfigDir; -import org.spongepowered.api.event.Listener; -import org.spongepowered.api.event.lifecycle.ConstructPluginEvent; -import org.spongepowered.api.event.lifecycle.RegisterCommandEvent; -import org.spongepowered.api.event.lifecycle.StartedEngineEvent; -import org.spongepowered.api.event.lifecycle.StoppingEngineEvent; -import org.spongepowered.api.network.EngineConnection; -import org.spongepowered.api.network.channel.ChannelBuf; -import org.spongepowered.api.network.channel.raw.RawDataChannel; -import org.spongepowered.api.network.channel.raw.play.RawPlayDataChannel; -import org.spongepowered.api.network.channel.raw.play.RawPlayDataHandler; -import org.spongepowered.api.world.WorldTypes; -import org.spongepowered.api.world.server.ServerLocation; -import org.spongepowered.api.world.server.ServerWorld; -import org.spongepowered.plugin.PluginContainer; -import org.spongepowered.plugin.builtin.jvm.Plugin; - -import java.io.InputStream; -import java.net.URI; -import java.nio.file.Path; -import java.util.*; -import java.util.logging.Level; -import java.util.stream.Collectors; - -@Getter -@Setter -@NoArgsConstructor -@Plugin("huskhomes") -public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSafetyResolver, SpongeEventDispatcher, - RawPlayDataHandler { - - /** - * Metrics ID for HuskHomes on Sponge. - */ - private static final int METRICS_ID = 18423; - private static final ResourceKey PLUGIN_MESSAGE_CHANNEL_KEY = ResourceKey.of("bungeecord", "main"); - - private final Set savedUsers = Sets.newHashSet(); - private final Map> globalPlayerList = Maps.newConcurrentMap(); - private final Set currentlyOnWarmup = Sets.newHashSet(); - private final Set currentlyInvulnerable = Sets.newHashSet(); - - @Inject - @ConfigDir(sharedRoot = false) - private Path configDirectory; - @Inject - private PluginContainer pluginContainer; - @Inject - private Game game; - @Inject - private Metrics.Factory metricsFactory; - private RawPlayDataChannel pluginMessageChannel; - - private Settings settings; - private Locales locales; - private Database database; - private Validator validator; - private Manager manager; - private RandomTeleportEngine randomTeleportEngine; - private Spawn serverSpawn; - private UnsafeBlocks unsafeBlocks; - private List hooks; - private List commands; - private Server server; - @Nullable - private Broker broker; - - @Listener - public void onConstructPlugin(final ConstructPluginEvent event) { - // Get plugin version from mod container - this.validator = new Validator(this); - - // Load settings and locales - initialize("plugin config & locale files", (plugin) -> loadConfigs()); - - // Initialize the database - final Database.Type type = getSettings().getDatabase().getType(); - initialize(type.getDisplayName() + " database connection", (plugin) -> { - this.database = switch (type) { - case MYSQL, MARIADB -> new MySqlDatabase(this); - case SQLITE -> new SqLiteDatabase(this); - case H2 -> new H2Database(this); - case POSTGRESQL -> new PostgreSqlDatabase(this); - }; - - database.initialize(); - }); - - // Initialize the network messenger if proxy mode is enabled - final Settings.CrossServerSettings crossServer = getSettings().getCrossServer(); - if (crossServer.isEnabled()) { - initialize(crossServer.getBrokerType().getDisplayName() + " message broker", (plugin) -> { - broker = switch (crossServer.getBrokerType()) { - case PLUGIN_MESSAGE -> new PluginMessageBroker(this); - case REDIS -> new RedisBroker(this); - }; - broker.initialize(); - }); - } - - // Check for updates - this.checkForUpdates(); - } - - @Listener - public void onServerStarted(final StartedEngineEvent event) { - // Initialize the manager - this.manager = new Manager(this); - - // Setup RTP engine - setRandomTeleportEngine(new NormalDistributionEngine(this)); - - // Register events - initialize("events", (plugin) -> new SpongeEventListener(this)); - - // Register permissions - initialize("permissions", (plugin) -> registerPermissions()); - - // Initialize hooks - initialize("hooks", (plugin) -> { - this.registerHooks(); - - if (!hooks.isEmpty()) { - hooks.forEach(hook -> { - try { - hook.initialize(); - } catch (Throwable e) { - log(Level.WARNING, "Failed to initialize " + hook.getName() + " hook", e); - } - }); - log(Level.INFO, "Registered " + hooks.size() + " mod hooks: " + hooks.stream() - .map(Hook::getName) - .collect(Collectors.joining(", "))); - } - }); - - // Hook into bStats - initialize("metrics", (plugin) -> this.registerMetrics(METRICS_ID)); - } - - @Listener - public void onShutdown(final StoppingEngineEvent event) { - if (database != null) { - database.terminate(); - } - if (broker != null) { - broker.close(); - } - cancelTasks(); - } - - @Listener - public void onRegisterCommands(final RegisterCommandEvent event) { - initialize("commands", (plugin) -> this.commands = registerCommands(event)); - } - - @NotNull - @Override - public ConsoleUser getConsole() { - return new ConsoleUser(game.server()); - } - - @NotNull - @Override - public List getOnlineUsers() { - return game.server().onlinePlayers().stream() - .map(user -> SpongeUser.adapt(user, this)) - .collect(Collectors.toList()); - } - - @NotNull - @Override - public Audience getAudience(@NotNull UUID user) { - return game.server().player(user).map(player -> (Audience) player).orElse(Audience.empty()); - } - - @Override - public void setWorldSpawn(@NotNull Position position) { - final ServerLocation loc = Adapter.adapt(position); - loc.world().properties().setSpawnPosition(loc.blockPosition()); - } - - @Override - public Optional getServerSpawn() { - return Optional.ofNullable(serverSpawn); - } - - @NotNull - @Override - public String getServerName() { - return server == null ? "server" : server.getName(); - } - - @Override - public void setServerName(@NotNull Server server) { - this.server = server; - } - - @NotNull - @Override - public Broker getMessenger() { - if (broker == null) { - throw new IllegalStateException("Attempted to access message broker when it was not initialized"); - } - return broker; - } - - @Override - public void registerHooks() { - HuskHomes.super.registerHooks(); - - // Register the sponge economy service if it is available - if (getSettings().getEconomy().isEnabled() - && getGame().server().serviceProvider().economyService().isPresent()) { - getHooks().add(new SpongeEconomyHook(this)); - } - } - - @Nullable - @Override - public InputStream getResource(@NotNull String name) { - return pluginContainer.openResource(URI.create(name)).orElse(null); - } - - @NotNull - @Override - public List getWorlds() { - return game.server().worldManager().worlds() - .stream() - .map(world -> World.from(world.key().toString(), world.uniqueId())) - .collect(Collectors.toList()); - } - - @NotNull - @Override - public Version getVersion() { - return Version.fromString(pluginContainer.metadata().version().toString(), "-"); - } - - @NotNull - @Override - public List getCommands() { - return commands.stream().map(SpongeCommand::getCommand).collect(Collectors.toList()); - } - - @NotNull - public List registerCommands(@NotNull RegisterCommandEvent event) { - return SpongeCommand.Type.getCommands(getPlugin()).stream() - .map(command -> new SpongeCommand(command, this)) - .peek(command -> command.registerCommand(event)) - .toList(); - } - - public void registerPermissions() { - commands.forEach(SpongeCommand::registerPermissions); - } - - @Override - public boolean isDependencyLoaded(@NotNull String name) { - return game.pluginManager().plugin(name).isPresent(); - } - - @Override - public void registerMetrics(int metricsId) { - if (!getVersion().getMetadata().isBlank()) { - return; - } - - try { - final Metrics metrics = metricsFactory.make(METRICS_ID); - metrics.addCustomChart(new SimplePie("bungee_mode", - () -> Boolean.toString(getSettings().getCrossServer().isEnabled()))); - if (getSettings().getCrossServer().isEnabled()) { - metrics.addCustomChart(new SimplePie("messenger_type", - () -> getSettings().getCrossServer().getBrokerType().getDisplayName()) - ); - } - metrics.addCustomChart(new SimplePie("language", - () -> getSettings().getLanguage().toLowerCase())); - metrics.addCustomChart(new SimplePie("database_type", - () -> getSettings().getDatabase().getType().getDisplayName())); - metrics.addCustomChart(new SimplePie("using_economy", - () -> Boolean.toString(getSettings().getEconomy().isEnabled()))); - metrics.addCustomChart(new SimplePie("using_map", - () -> Boolean.toString(getSettings().getMapHook().isEnabled()))); - getMapHook().ifPresent(hook -> metrics.addCustomChart(new SimplePie("map_type", hook::getName))); - } catch (Throwable e) { - log(Level.WARNING, "Failed to register bStats metrics (" + e.getMessage() + ")"); - } - } - - @Override - public void initializePluginChannels() { - this.pluginMessageChannel = game.channelManager().ofType( - PLUGIN_MESSAGE_CHANNEL_KEY, RawDataChannel.class - ).play(); - this.pluginMessageChannel.addHandler(this); - } - - @Override - public void handlePayload(@NotNull ChannelBuf pluginMessage, @NotNull EngineConnection connection) { - final Optional playerConnection = getOnlineUsers().stream() - .filter(onlineUser -> ((SpongeUser) onlineUser).getPlayer().connection().equals(connection)) - .findFirst(); - - // Get the associated engine connection - if (playerConnection.isEmpty()) { - log(Level.WARNING, "Received a message from a player that is not online"); - return; - } - - // Read the message and handle - final SpongeUser user = (SpongeUser) playerConnection.get(); - final String channel = pluginMessage.readUTF(); - if (broker instanceof PluginMessageBroker messenger - && getSettings().getCrossServer().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) { - messenger.onReceive(channel, user, pluginMessage.readBytes(pluginMessage.available())); - } - } - - @Override - public void log(@NotNull Level level, @NotNull String message, Throwable... exceptions) { - final org.apache.logging.log4j.Level adaptedLevel = Optional - .ofNullable(org.apache.logging.log4j.Level.getLevel(level.getName())) - .orElse(org.apache.logging.log4j.Level.INFO); - - if (exceptions.length > 0) { - pluginContainer.logger().log(adaptedLevel, message, exceptions[0]); - return; - } - pluginContainer.logger().log(adaptedLevel, message); - } - - @NotNull - @Override - public SpongeHuskHomes getPlugin() { - return this; - } - - public static final class Adapter { - - @NotNull - public static Location adapt(@NotNull ServerLocation location) { - return Location.at( - location.x(), location.y(), location.z(), - adapt(location.world()) - ); - } - - @NotNull - public static Position adapt(@NotNull ServerLocation location, @NotNull String server) { - return Position.at(adapt(location), server); - } - - @NotNull - public static ServerLocation adapt(@NotNull Location location) { - return ServerLocation.of( - Objects.requireNonNull(adapt(location.getWorld())), - location.getX(), location.getY(), location.getZ() - ); - } - - @Nullable - public static ServerWorld adapt(@NotNull World world) { - return Sponge.server().worldManager().world(ResourceKey.resolve(world.getName())).orElse(null); - } - - @NotNull - public static World adapt(@NotNull ServerWorld world) { - final String worldType = world.properties().worldType().key(WorldTypes.registry().type() - .asDefaultedType(world::engine)).value(); - return World.from( - world.properties().name(), - world.uniqueId(), - World.Environment.match(worldType) - ); - } - - } -} diff --git a/sponge/src/main/java/net/william278/huskhomes/command/SpongeCommand.java b/sponge/src/main/java/net/william278/huskhomes/command/SpongeCommand.java deleted file mode 100644 index 8356613b..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/command/SpongeCommand.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.command; - -import net.kyori.adventure.text.Component; -import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.SpongeHuskHomes; -import net.william278.huskhomes.teleport.TeleportRequest; -import net.william278.huskhomes.user.CommandUser; -import net.william278.huskhomes.user.SpongeUser; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.command.Command.Raw; -import org.spongepowered.api.command.CommandCause; -import org.spongepowered.api.command.CommandCompletion; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.parameter.ArgumentReader; -import org.spongepowered.api.entity.living.player.server.ServerPlayer; -import org.spongepowered.api.event.lifecycle.RegisterCommandEvent; -import org.spongepowered.api.service.permission.PermissionDescription; -import org.spongepowered.api.util.Tristate; - -import java.util.*; -import java.util.function.Function; - -public class SpongeCommand implements Raw { - - private final Command command; - private final SpongeHuskHomes plugin; - - public SpongeCommand(@NotNull Command command, @NotNull SpongeHuskHomes plugin) { - this.command = command; - this.plugin = plugin; - } - - // Register command - public void registerCommand(@NotNull RegisterCommandEvent event) { - event.register( - plugin.getPluginContainer(), - this, - command.getName(), - command.getAliases().toArray(String[]::new) - ); - } - - // Register command permissions - public void registerPermissions() { - final Map permissionDescriptions = new HashMap<>(command.getAdditionalPermissions()); - permissionDescriptions.put(command.getPermission(), command.isOperatorCommand()); - - for (Map.Entry node : permissionDescriptions.entrySet()) { - final PermissionDescription.Builder builder = plugin.getGame().server() - .serviceProvider().permissionService() - .newDescriptionBuilder(plugin.getPluginContainer()) - .id(node.getKey()); - - // Set default access level - if (node.getValue()) { - builder.defaultValue(Tristate.UNDEFINED) - .assign(PermissionDescription.ROLE_ADMIN, true); - } else { - builder.defaultValue(Tristate.TRUE) - .assign(PermissionDescription.ROLE_USER, true); - } - builder.register(); - } - } - - @NotNull - public Command getCommand() { - return command; - } - - @Override - @NotNull - public CommandResult process(@NotNull CommandCause cause, @NotNull ArgumentReader.Mutable arguments) { - command.onExecuted(resolveExecutor(cause), assimilateArguments(arguments)); - return CommandResult.success(); - } - - @Override - @NotNull - public List complete(@NotNull CommandCause cause, @NotNull ArgumentReader.Mutable arguments) { - if (this.command instanceof TabProvider provider) { - return provider.getSuggestions(resolveExecutor(cause), assimilateArguments(arguments)).stream() - .map(CommandCompletion::of) - .toList(); - } - return List.of(); - } - - @NotNull - private CommandUser resolveExecutor(@NotNull CommandCause cause) { - if (cause.root() instanceof ServerPlayer player) { - return SpongeUser.adapt(player, plugin); - } - return plugin.getConsole(); - } - - /** - * Assimilate the arguments from a {@link ArgumentReader} into a spaced {@link String} array. - * - * @param arguments the {@link ArgumentReader} to assimilate - * @return the assimilated {@link String} array - */ - @NotNull - private String[] assimilateArguments(@NotNull ArgumentReader.Mutable arguments) { - final String argumentString = arguments.immutable().remaining(); - if (argumentString.isBlank()) { - return new String[0]; - } - return argumentString.split(" "); - } - - @Override - public boolean canExecute(@NotNull CommandCause cause) { - return resolveExecutor(cause).hasPermission(command.getPermission()); - } - - @Override - @NotNull - public Optional shortDescription(@NotNull CommandCause cause) { - return Optional.of(Component.text(command.getDescription())); - } - - @Override - @NotNull - public Optional extendedDescription(@NotNull CommandCause cause) { - return shortDescription(cause); - } - - @Override - @NotNull - public Component usage(@NotNull CommandCause cause) { - return Component.text(command.getUsage()); - } - - /** - * Commands available on the Sponge HuskHomes implementation. - */ - public enum Type { - HOME_COMMAND(PrivateHomeCommand::new), - SET_HOME_COMMAND(SetHomeCommand::new), - HOME_LIST_COMMAND(HomeListCommand::new), - DEL_HOME_COMMAND(DelHomeCommand::new), - EDIT_HOME_COMMAND(EditHomeCommand::new), - PUBLIC_HOME_COMMAND(PublicHomeCommand::new), - PUBLIC_HOME_LIST_COMMAND(PublicHomeListCommand::new), - WARP_COMMAND(WarpCommand::new), - SET_WARP_COMMAND(SetWarpCommand::new), - WARP_LIST_COMMAND(WarpListCommand::new), - DEL_WARP_COMMAND(DelWarpCommand::new), - EDIT_WARP_COMMAND(EditWarpCommand::new), - TP_COMMAND(TpCommand::new), - TP_HERE_COMMAND(TpHereCommand::new), - TPA_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA)), - TPA_HERE_COMMAND((plugin) -> new TeleportRequestCommand(plugin, TeleportRequest.Type.TPA_HERE)), - TPACCEPT_COMMAND((plugin) -> new TpRespondCommand(plugin, true)), - TPDECLINE_COMMAND((plugin) -> new TpRespondCommand(plugin, false)), - RTP_COMMAND(RTPCommand::new), - TP_IGNORE_COMMAND(TpIgnoreCommand::new), - TP_OFFLINE_COMMAND(TpOfflineCommand::new), - TP_ALL_COMMAND(TpAllCommand::new), - TPA_ALL_COMMAND(TpaAllCommand::new), - SPAWN_COMMAND(SpawnCommand::new), - SET_SPAWN_COMMAND(SetSpawnCommand::new), - BACK_COMMAND(BackCommand::new), - HUSKHOMES_COMMAND(HuskHomesCommand::new); - - private final Function supplier; - - Type(@NotNull Function supplier) { - this.supplier = supplier; - } - - @NotNull - public Command createCommand(@NotNull HuskHomes plugin) { - return supplier.apply(plugin); - } - - @NotNull - public static List getCommands(@NotNull SpongeHuskHomes plugin) { - return Arrays.stream(values()) - .map(type -> type.createCommand(plugin)) - .map(command -> plugin.getSettings().isCommandDisabled(command) ? null : command) - .filter(Objects::nonNull) - .toList(); - } - - } - -} diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeDeleteAllHomesEvent.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeDeleteAllHomesEvent.java deleted file mode 100644 index b822e48e..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeDeleteAllHomesEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.user.CommandUser; -import net.william278.huskhomes.user.User; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Cancellable; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.Event; - -public class SpongeDeleteAllHomesEvent implements IDeleteAllHomesEvent, Event, Cancellable { - - private boolean cancelled = false; - private final User user; - private final CommandUser deleter; - - public SpongeDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter) { - this.user = user; - this.deleter = deleter; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @NotNull - @Override - public User getHomeOwner() { - return user; - } - - @NotNull - @Override - public CommandUser getDeleter() { - return deleter; - } - - @Override - public Cause cause() { - return Cause.builder() - .append(deleter) - .build(); - } - -} diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeDeleteAllWarpsEvent.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeDeleteAllWarpsEvent.java deleted file mode 100644 index 22e639e2..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeDeleteAllWarpsEvent.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.user.CommandUser; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Cancellable; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.Event; - -public class SpongeDeleteAllWarpsEvent implements IDeleteAllWarpsEvent, Event, Cancellable { - - private boolean cancelled = false; - private final CommandUser deleter; - - public SpongeDeleteAllWarpsEvent(@NotNull CommandUser deleter) { - this.deleter = deleter; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @NotNull - @Override - public CommandUser getDeleter() { - return deleter; - } - - @Override - public Cause cause() { - return Cause.builder() - .append(deleter) - .build(); - } - -} diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeEventDispatcher.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeEventDispatcher.java deleted file mode 100644 index d3b41708..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeEventDispatcher.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.SpongeHuskHomes; -import net.william278.huskhomes.position.Home; -import net.william278.huskhomes.position.Position; -import net.william278.huskhomes.position.Warp; -import net.william278.huskhomes.teleport.Teleport; -import net.william278.huskhomes.teleport.TeleportRequest; -import net.william278.huskhomes.teleport.TimedTeleport; -import net.william278.huskhomes.user.CommandUser; -import net.william278.huskhomes.user.OnlineUser; -import net.william278.huskhomes.user.User; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Event; - -import java.util.List; - -import static net.william278.huskhomes.event.ITeleportWarmupCancelledEvent.CancelReason; - -public interface SpongeEventDispatcher extends EventDispatcher { - - @Override - default boolean fireIsCancelled(@NotNull T event) { - return getPlugin().getGame().eventManager().post((Event) event); - } - - @Override - @NotNull - default ITeleportEvent getTeleportEvent(@NotNull Teleport teleport) { - return teleport.getType() == Teleport.Type.RANDOM_TELEPORT ? new SpongeRandomTeleportEvent(teleport) : - new SpongeTeleportEvent(teleport); - } - - @Override - default @NotNull ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) { - return new SpongeTeleportWarmupEvent(teleport, duration); - } - - @Override - @NotNull - default ITeleportWarmupCancelledEvent getTeleportWarmupCancelledEvent(@NotNull TimedTeleport teleport, - int duration, - int cancelledAfter, - @NotNull CancelReason cancelReason) { - return new SpongeTeleportWarmupCancelledEvent(teleport, duration, cancelledAfter, cancelReason); - } - - @Override - default @NotNull ISendTeleportRequestEvent getSendTeleportRequestEvent(@NotNull OnlineUser sender, - @NotNull TeleportRequest request) { - return new SpongeSendTeleportRequestEvent(sender, request); - } - - @Override - default @NotNull IReceiveTeleportRequestEvent getReceiveTeleportRequestEvent(@NotNull OnlineUser recipient, - @NotNull TeleportRequest request) { - return new SpongeReceiveTeleportRequestEvent(recipient, request); - } - - @Override - default @NotNull IReplyTeleportRequestEvent getReplyTeleportRequestEvent(@NotNull OnlineUser recipient, - @NotNull TeleportRequest request) { - return new SpongeReplyTeleportRequestEvent(recipient, request); - } - - @Override - default @NotNull IHomeCreateEvent getHomeCreateEvent(@NotNull User owner, @NotNull String name, - @NotNull Position position, @NotNull CommandUser creator) { - return new SpongeHomeCreateEvent(owner, name, position, creator); - } - - @Override - default @NotNull IHomeEditEvent getHomeEditEvent(@NotNull Home home, @NotNull Home original, - @NotNull CommandUser editor) { - return new SpongeHomeEditEvent(home, original, editor); - } - - @Override - default @NotNull IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter) { - return new SpongeHomeDeleteEvent(home, deleter); - } - - @Override - default @NotNull IWarpCreateEvent getWarpCreateEvent(@NotNull String name, @NotNull Position position, - @NotNull CommandUser creator) { - return new SpongeWarpCreateEvent(name, position, creator); - } - - @Override - default @NotNull IWarpEditEvent getWarpEditEvent(@NotNull Warp warp, @NotNull Warp original, - @NotNull CommandUser editor) { - return new SpongeWarpEditEvent(warp, original, editor); - } - - @Override - default @NotNull IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter) { - return new SpongeWarpDeleteEvent(warp, deleter); - } - - @Override - default @NotNull IHomeListEvent getViewHomeListEvent(@NotNull List homes, @NotNull CommandUser listViewer, - boolean publicHomeList) { - return new SpongeHomeListEvent(homes, listViewer, publicHomeList); - } - - @Override - default @NotNull IWarpListEvent getViewWarpListEvent(@NotNull List homes, @NotNull CommandUser listViewer) { - return new SpongeWarpListEvent(homes, listViewer); - } - - @Override - default @NotNull IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter) { - return new SpongeDeleteAllHomesEvent(user, deleter); - } - - @NotNull - @Override - default IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter) { - return new SpongeDeleteAllWarpsEvent(deleter); - } - - @NotNull - @Override - SpongeHuskHomes getPlugin(); - -} diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeCreateEvent.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeCreateEvent.java deleted file mode 100644 index afb5d61c..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeCreateEvent.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.position.Position; -import net.william278.huskhomes.user.CommandUser; -import net.william278.huskhomes.user.User; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Cancellable; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.Event; - -public class SpongeHomeCreateEvent implements IHomeCreateEvent, Event, Cancellable { - - private boolean cancelled = false; - private final User owner; - private String name; - private Position position; - private final CommandUser creator; - - public SpongeHomeCreateEvent(@NotNull User owner, @NotNull String name, @NotNull Position position, - @NotNull CommandUser creator) { - this.owner = owner; - this.name = name; - this.position = position; - this.creator = creator; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - - @NotNull - @Override - public User getOwner() { - return owner; - } - - @NotNull - @Override - public String getName() { - return name; - } - - @Override - public void setName(@NotNull String name) { - this.name = name; - } - - @NotNull - @Override - public Position getPosition() { - return position; - } - - @Override - public void setPosition(@NotNull Position position) { - this.position = position; - } - - @NotNull - @Override - public CommandUser getCreator() { - return creator; - } - - @Override - public Cause cause() { - return Cause.builder() - .append(creator) - .build(); - } - -} diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeDeleteEvent.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeDeleteEvent.java deleted file mode 100644 index b555a003..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeDeleteEvent.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.position.Home; -import net.william278.huskhomes.user.CommandUser; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Cancellable; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.Event; - -public class SpongeHomeDeleteEvent implements IHomeDeleteEvent, Event, Cancellable { - - private boolean cancelled = false; - private final Home home; - private final CommandUser deleter; - - public SpongeHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter) { - this.home = home; - this.deleter = deleter; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @NotNull - @Override - public Home getHome() { - return home; - } - - @NotNull - @Override - public CommandUser getDeleter() { - return deleter; - } - - @Override - public Cause cause() { - return Cause.builder() - .append(deleter) - .build(); - } -} diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeEditEvent.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeEditEvent.java deleted file mode 100644 index 2ed7620b..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeEditEvent.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.position.Home; -import net.william278.huskhomes.user.CommandUser; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Cancellable; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.Event; - -public class SpongeHomeEditEvent implements IHomeEditEvent, Event, Cancellable { - - private boolean cancelled = false; - private final Home home; - private final Home original; - private final CommandUser editor; - - public SpongeHomeEditEvent(@NotNull Home home, @NotNull Home original, @NotNull CommandUser editor) { - this.home = home; - this.original = original; - this.editor = editor; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @NotNull - @Override - public Home getHome() { - return home; - } - - @NotNull - @Override - public Home getOriginalHome() { - return original; - } - - @NotNull - @Override - public CommandUser getEditor() { - return editor; - } - - @Override - public Cause cause() { - return Cause.builder() - .append(editor) - .build(); - } -} diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeListEvent.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeListEvent.java deleted file mode 100644 index 5c141043..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeHomeListEvent.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.position.Home; -import net.william278.huskhomes.user.CommandUser; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Cancellable; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.Event; - -import java.util.List; - -public class SpongeHomeListEvent implements IHomeListEvent, Event, Cancellable { - - private boolean cancelled = false; - private List homes; - private final CommandUser listViewer; - private final boolean publicHomeList; - - public SpongeHomeListEvent(@NotNull List homes, @NotNull CommandUser listViewer, boolean publicHomeList) { - this.homes = homes; - this.listViewer = listViewer; - this.publicHomeList = publicHomeList; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @NotNull - @Override - public List getHomes() { - return homes; - } - - @Override - public void setHomes(@NotNull List homes) { - this.homes = homes; - } - - @NotNull - @Override - public CommandUser getListViewer() { - return listViewer; - } - - @Override - public boolean getIsPublicHomeList() { - return publicHomeList; - } - - @Override - public Cause cause() { - return Cause.builder() - .append(listViewer) - .build(); - } - -} diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeRandomTeleportEvent.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeRandomTeleportEvent.java deleted file mode 100644 index 7772f55e..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeRandomTeleportEvent.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.position.Position; -import net.william278.huskhomes.teleport.Teleport; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Cancellable; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.Event; - -public class SpongeRandomTeleportEvent implements IRandomTeleportEvent, Event, Cancellable { - - private boolean cancelled = false; - private final Teleport teleport; - - public SpongeRandomTeleportEvent(@NotNull Teleport teleport) { - this.teleport = teleport; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @NotNull - @Override - public Teleport getTeleport() { - return teleport; - } - - @Override - public Cause cause() { - return Cause.builder() - .append(teleport.getTeleporter()) - .build(); - } - - @Override - public @NotNull Position getPosition() { - return (Position) teleport.getTarget(); - } -} diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeReceiveTeleportRequestEvent.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeReceiveTeleportRequestEvent.java deleted file mode 100644 index 446f682f..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeReceiveTeleportRequestEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.teleport.TeleportRequest; -import net.william278.huskhomes.user.OnlineUser; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Cancellable; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.Event; - -public class SpongeReceiveTeleportRequestEvent implements IReceiveTeleportRequestEvent, Event, Cancellable { - - private boolean cancelled = false; - private final OnlineUser recipient; - private final TeleportRequest request; - - public SpongeReceiveTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request) { - this.recipient = recipient; - this.request = request; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - - @NotNull - @Override - public OnlineUser getRecipient() { - return recipient; - } - - @NotNull - @Override - public TeleportRequest getRequest() { - return request; - } - - @Override - public Cause cause() { - return Cause.builder() - .append(recipient) - .build(); - } -} diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeReplyTeleportRequestEvent.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeReplyTeleportRequestEvent.java deleted file mode 100644 index 865c4dc0..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeReplyTeleportRequestEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.teleport.TeleportRequest; -import net.william278.huskhomes.user.OnlineUser; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Cancellable; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.Event; - -public class SpongeReplyTeleportRequestEvent implements IReplyTeleportRequestEvent, Event, Cancellable { - - private boolean cancelled = false; - private final OnlineUser recipient; - private final TeleportRequest request; - - public SpongeReplyTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request) { - this.recipient = recipient; - this.request = request; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - - @NotNull - @Override - public OnlineUser getRecipient() { - return recipient; - } - - @NotNull - @Override - public TeleportRequest getRequest() { - return request; - } - - @Override - public Cause cause() { - return Cause.builder() - .append(recipient) - .build(); - } -} diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeSendTeleportRequestEvent.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeSendTeleportRequestEvent.java deleted file mode 100644 index beb0836f..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeSendTeleportRequestEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.teleport.TeleportRequest; -import net.william278.huskhomes.user.OnlineUser; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Cancellable; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.Event; - -public class SpongeSendTeleportRequestEvent implements ISendTeleportRequestEvent, Event, Cancellable { - - private boolean cancelled = false; - private final OnlineUser sender; - private final TeleportRequest request; - - public SpongeSendTeleportRequestEvent(@NotNull OnlineUser sender, @NotNull TeleportRequest request) { - this.sender = sender; - this.request = request; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @NotNull - @Override - public OnlineUser getSender() { - return sender; - } - - @NotNull - @Override - public TeleportRequest getRequest() { - return request; - } - - @Override - public Cause cause() { - return Cause.builder() - .append(sender) - .build(); - } - -} diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeTeleportEvent.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeTeleportEvent.java deleted file mode 100644 index 4b0cef9f..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeTeleportEvent.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.teleport.Teleport; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Cancellable; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.Event; - -public class SpongeTeleportEvent implements ITeleportEvent, Event, Cancellable { - - private boolean cancelled = false; - private final Teleport teleport; - - public SpongeTeleportEvent(@NotNull Teleport teleport) { - this.teleport = teleport; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @NotNull - @Override - public Teleport getTeleport() { - return teleport; - } - - @Override - public Cause cause() { - return Cause.builder() - .append(teleport.getTeleporter()) - .build(); - } - -} diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeTeleportWarmupCancelledEvent.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeTeleportWarmupCancelledEvent.java deleted file mode 100644 index 31a9e890..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeTeleportWarmupCancelledEvent.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.teleport.TimedTeleport; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.Event; - -public class SpongeTeleportWarmupCancelledEvent implements ITeleportWarmupCancelledEvent, Event { - - private final TimedTeleport teleport; - private final int duration; - private final int cancelledAfter; - private final CancelReason cancelReason; - - public SpongeTeleportWarmupCancelledEvent(@NotNull TimedTeleport teleport, int duration, - int cancelledAfter, @NotNull CancelReason cancelReason) { - this.teleport = teleport; - this.duration = duration; - this.cancelledAfter = cancelledAfter; - this.cancelReason = cancelReason; - } - - @Override - public Cause cause() { - return Cause.builder() - .append(teleport.getTeleporter()) - .build(); - } - - @Override - public int getWarmupDuration() { - return duration; - } - - @NotNull - @Override - public TimedTeleport getTimedTeleport() { - return teleport; - } - - @Override - public int cancelledAfter() { - return cancelledAfter; - } - - @Override - public @NotNull CancelReason getCancelReason() { - return cancelReason; - } - -} \ No newline at end of file diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeTeleportWarmupEvent.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeTeleportWarmupEvent.java deleted file mode 100644 index 448bec54..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeTeleportWarmupEvent.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.teleport.TimedTeleport; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Cancellable; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.Event; - -public class SpongeTeleportWarmupEvent implements ITeleportWarmupEvent, Event, Cancellable { - - private boolean cancelled = false; - private final TimedTeleport teleport; - private final int duration; - - public SpongeTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration) { - this.teleport = teleport; - this.duration = duration; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public Cause cause() { - return Cause.builder() - .append(teleport.getTeleporter()) - .build(); - } - - @Override - public int getWarmupDuration() { - return duration; - } - - @NotNull - @Override - public TimedTeleport getTimedTeleport() { - return teleport; - } - -} diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpCreateEvent.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpCreateEvent.java deleted file mode 100644 index 314f992a..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpCreateEvent.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.position.Position; -import net.william278.huskhomes.user.CommandUser; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Cancellable; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.Event; - -public class SpongeWarpCreateEvent implements IWarpCreateEvent, Event, Cancellable { - - private boolean cancelled = false; - private String name; - private Position position; - private final CommandUser creator; - - public SpongeWarpCreateEvent(@NotNull String name, @NotNull Position position, @NotNull CommandUser creator) { - this.name = name; - this.position = position; - this.creator = creator; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @NotNull - @Override - public String getName() { - return name; - } - - @Override - public void setName(@NotNull String name) { - this.name = name; - } - - @NotNull - @Override - public Position getPosition() { - return position; - } - - @Override - public void setPosition(@NotNull Position position) { - this.position = position; - } - - @NotNull - @Override - public CommandUser getCreator() { - return creator; - } - - @Override - public Cause cause() { - return Cause.builder() - .append(creator) - .build(); - } - -} diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpDeleteEvent.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpDeleteEvent.java deleted file mode 100644 index 44f59f40..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpDeleteEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.position.Warp; -import net.william278.huskhomes.user.CommandUser; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Cancellable; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.Event; - -public class SpongeWarpDeleteEvent implements IWarpDeleteEvent, Event, Cancellable { - - private boolean cancelled = false; - private final Warp warp; - private final CommandUser deleter; - - public SpongeWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter) { - this.warp = warp; - this.deleter = deleter; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @NotNull - @Override - public Warp getWarp() { - return warp; - } - - @NotNull - @Override - public CommandUser getDeleter() { - return deleter; - } - - @Override - public Cause cause() { - return Cause.builder() - .append(deleter) - .build(); - } - -} diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpEditEvent.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpEditEvent.java deleted file mode 100644 index 33daefe8..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpEditEvent.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.position.Warp; -import net.william278.huskhomes.user.CommandUser; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Cancellable; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.Event; - -public class SpongeWarpEditEvent implements IWarpEditEvent, Event, Cancellable { - - private boolean cancelled = false; - private final Warp warp; - private final Warp original; - private final CommandUser editor; - - public SpongeWarpEditEvent(@NotNull Warp warp, @NotNull Warp original, @NotNull CommandUser editor) { - this.warp = warp; - this.original = original; - this.editor = editor; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @NotNull - @Override - public Warp getWarp() { - return warp; - } - - @NotNull - @Override - public Warp getOriginalWarp() { - return original; - } - - @NotNull - @Override - public CommandUser getEditor() { - return editor; - } - - @Override - public Cause cause() { - return Cause.builder() - .append(editor) - .build(); - } - -} diff --git a/sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpListEvent.java b/sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpListEvent.java deleted file mode 100644 index 679b0db7..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/event/SpongeWarpListEvent.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.event; - -import net.william278.huskhomes.position.Warp; -import net.william278.huskhomes.user.CommandUser; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.event.Cancellable; -import org.spongepowered.api.event.Cause; -import org.spongepowered.api.event.Event; - -import java.util.List; - -public class SpongeWarpListEvent implements IWarpListEvent, Event, Cancellable { - - private boolean cancelled = false; - private List warps; - private final CommandUser listViewer; - - public SpongeWarpListEvent(@NotNull List warps, @NotNull CommandUser listViewer) { - this.warps = warps; - this.listViewer = listViewer; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @NotNull - @Override - public List getWarps() { - return warps; - } - - @Override - public void setWarps(@NotNull List warps) { - this.warps = warps; - } - - @NotNull - @Override - public CommandUser getListViewer() { - return listViewer; - } - - @Override - public Cause cause() { - return Cause.builder() - .append(listViewer) - .build(); - } - -} diff --git a/sponge/src/main/java/net/william278/huskhomes/hook/SpongeEconomyHook.java b/sponge/src/main/java/net/william278/huskhomes/hook/SpongeEconomyHook.java deleted file mode 100644 index c7831aec..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/hook/SpongeEconomyHook.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.hook; - -import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.SpongeHuskHomes; -import net.william278.huskhomes.user.OnlineUser; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.Server; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.service.economy.EconomyService; -import org.spongepowered.api.service.economy.account.Account; - -import java.math.BigDecimal; - -public class SpongeEconomyHook extends EconomyHook { - private EconomyService economyService; - private Currency currency; - - public SpongeEconomyHook(@NotNull HuskHomes plugin) { - super(plugin, "Sponge Economy"); - } - - @Override - public double getPlayerBalance(@NotNull OnlineUser player) { - return economyService.findOrCreateAccount(player.getUuid()) - .map(account -> account.balance(currency)) - .orElse(BigDecimal.ZERO) - .doubleValue(); - } - - @Override - public void changePlayerBalance(@NotNull OnlineUser player, double amount) { - if (amount != 0d) { - final Account account = economyService.findOrCreateAccount(player.getUuid()) - .orElseThrow(() -> new IllegalStateException("Account not found for " + player.getUsername())); - final double currentBalance = getPlayerBalance(player); - final double amountToChange = Math.abs(currentBalance - Math.max(0d, currentBalance + amount)); - if (amount < 0d) { - account.withdraw( - currency, - BigDecimal.valueOf(amountToChange), - getServer().causeStackManager().currentCause() - ); - } else { - account.deposit( - currency, - BigDecimal.valueOf(amountToChange), - getServer().causeStackManager().currentCause() - ); - } - } - } - - @Override - public String formatCurrency(double amount) { - return currency.format(BigDecimal.valueOf(amount)).insertion(); - } - - @Override - public void initialize() { - this.economyService = getServer().serviceProvider().economyService() - .orElseThrow(() -> new IllegalStateException("No economy service has been registered!")); - this.currency = economyService.defaultCurrency(); - } - - @NotNull - private Server getServer() { - return ((SpongeHuskHomes) plugin).getGame().server(); - } - -} diff --git a/sponge/src/main/java/net/william278/huskhomes/listener/SpongeEventListener.java b/sponge/src/main/java/net/william278/huskhomes/listener/SpongeEventListener.java deleted file mode 100644 index fbbe060e..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/listener/SpongeEventListener.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.listener; - -import net.william278.huskhomes.SpongeHuskHomes; -import net.william278.huskhomes.user.SpongeUser; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.block.BlockType; -import org.spongepowered.api.block.BlockTypes; -import org.spongepowered.api.entity.living.player.server.ServerPlayer; -import org.spongepowered.api.event.EventContextKeys; -import org.spongepowered.api.event.Listener; -import org.spongepowered.api.event.block.InteractBlockEvent; -import org.spongepowered.api.event.cause.entity.MovementType; -import org.spongepowered.api.event.cause.entity.MovementTypes; -import org.spongepowered.api.event.entity.DestructEntityEvent; -import org.spongepowered.api.event.entity.MoveEntityEvent; -import org.spongepowered.api.event.entity.living.player.RespawnPlayerEvent; -import org.spongepowered.api.event.network.ServerSideConnectionEvent; -import org.spongepowered.api.world.portal.Portal; -import org.spongepowered.api.world.portal.PortalTypes; -import org.spongepowered.api.world.server.ServerLocation; - -import java.util.Optional; - -public class SpongeEventListener extends EventListener { - - public SpongeEventListener(@NotNull SpongeHuskHomes plugin) { - super(plugin); - plugin.getGame().eventManager().registerListeners(plugin.getPluginContainer(), this); - } - - @Listener - public void onPlayerJoin(final ServerSideConnectionEvent.Join event) { - super.handlePlayerJoin(SpongeUser.adapt(event.player(), (SpongeHuskHomes) plugin)); - } - - @Listener - public void onPlayerLeave(final ServerSideConnectionEvent.Disconnect event) { - super.handlePlayerJoin(SpongeUser.adapt(event.player(), (SpongeHuskHomes) plugin)); - } - - @Listener - public void onPlayerDeath(final DestructEntityEvent.Death event) { - if (event.entity() instanceof ServerPlayer player) { - super.handlePlayerJoin(SpongeUser.adapt(player, (SpongeHuskHomes) plugin)); - } - } - - @Listener - public void onPlayerRespawn(final RespawnPlayerEvent event) { - final Optional type = event.context().get(EventContextKeys.PORTAL); - if (type.isPresent() && type.get().type().equals(PortalTypes.END.get())) { - return; - } - super.handlePlayerJoin(SpongeUser.adapt(event.entity(), (SpongeHuskHomes) plugin)); - } - - @Listener - public void onPlayerTeleport(final MoveEntityEvent event) { - if (event.entity() instanceof ServerPlayer player) { - final Optional type = event.context().get(EventContextKeys.MOVEMENT_TYPE); - if (type.isPresent() && type.get().equals(MovementTypes.ENTITY_TELEPORT.get())) { - super.handlePlayerTeleport( - SpongeUser.adapt(player, (SpongeHuskHomes) plugin), - SpongeHuskHomes.Adapter.adapt( - ServerLocation.of(player.world(), event.originalPosition()), - plugin.getServerName() - ) - ); - } - } - } - - @Listener - @SuppressWarnings("unchecked") - public void onPlayerUpdateRespawnLocation(InteractBlockEvent.Secondary event) { - if (event.context().get(EventContextKeys.PLAYER).isPresent()) { - final ServerPlayer player = (ServerPlayer) event.context().get(EventContextKeys.PLAYER).get(); - final BlockType type = event.block().state().type(); - - if (type.isAnyOf(BlockTypes.BLACK_BED, BlockTypes.BLUE_BED, BlockTypes.BROWN_BED, BlockTypes.CYAN_BED, - BlockTypes.GRAY_BED, BlockTypes.GREEN_BED, BlockTypes.LIGHT_BLUE_BED, BlockTypes.LIGHT_GRAY_BED, - BlockTypes.LIME_BED, BlockTypes.MAGENTA_BED, BlockTypes.ORANGE_BED, BlockTypes.PINK_BED, - BlockTypes.PURPLE_BED, BlockTypes.RED_BED, BlockTypes.WHITE_BED, BlockTypes.YELLOW_BED, - BlockTypes.RESPAWN_ANCHOR)) { - - super.handlePlayerUpdateSpawnPoint( - SpongeUser.adapt(player, (SpongeHuskHomes) plugin), - SpongeHuskHomes.Adapter.adapt( - player.serverLocation(), - plugin.getServerName() - ) - ); - } - } - } - -} diff --git a/sponge/src/main/java/net/william278/huskhomes/user/SpongeUser.java b/sponge/src/main/java/net/william278/huskhomes/user/SpongeUser.java deleted file mode 100644 index 68099095..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/user/SpongeUser.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.user; - -import net.kyori.adventure.audience.Audience; -import net.william278.huskhomes.SpongeHuskHomes; -import net.william278.huskhomes.position.Location; -import net.william278.huskhomes.position.Position; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.data.Keys; -import org.spongepowered.api.entity.living.player.server.ServerPlayer; -import org.spongepowered.api.service.permission.SubjectData; -import org.spongepowered.api.util.RespawnLocation; -import org.spongepowered.api.world.server.ServerWorld; - -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; - -public class SpongeUser extends OnlineUser { - - private final ServerPlayer player; - - private SpongeUser(@NotNull ServerPlayer player, @NotNull SpongeHuskHomes plugin) { - super(player.uniqueId(), player.name(), plugin); - this.player = player; - } - - /** - * Adapt a {@link ServerPlayer} to a {@link OnlineUser}. - * - * @param player the online {@link ServerPlayer} to adapt - * @return the adapted {@link OnlineUser} - */ - @NotNull - public static SpongeUser adapt(@NotNull ServerPlayer player, @NotNull SpongeHuskHomes plugin) { - return new SpongeUser(player, plugin); - } - - /** - * Get the {@link ServerPlayer} associated with this {@link OnlineUser}. - * - * @return the {@link ServerPlayer} - */ - @NotNull - public ServerPlayer getPlayer() { - return player; - } - - @Override - public Position getPosition() { - return SpongeHuskHomes.Adapter.adapt(player.serverLocation(), plugin.getServerName()); - } - - // Resolve the player's RespawnLocation from the world-key map and adapt as location - @Override - public Optional getBedSpawnPosition() { - return player.get(Keys.RESPAWN_LOCATIONS) - .flatMap(resourceMap -> resourceMap.values().stream().findFirst()).flatMap(RespawnLocation::asLocation) - .map(location -> SpongeHuskHomes.Adapter.adapt(location, plugin.getServerName())); - } - - @Override - public double getHealth() { - return player.health().asImmutable().get(); - } - - @Override - public boolean hasPermission(@NotNull String node) { - return player.hasPermission(node); - } - - @Override - @NotNull - public Map getPermissions() { - return player.transientSubjectData().permissions(SubjectData.GLOBAL_CONTEXT); - } - - @Override - @NotNull - public Audience getAudience() { - return player; - } - - @Override - public CompletableFuture dismount() { - final CompletableFuture future = new CompletableFuture<>(); - plugin.runSync(() -> { - player.vehicle().ifPresent(vehicle -> vehicle.get().passengers().remove(player)); - player.passengers().forEach(passenger -> player.passengers().remove(passenger)); - future.complete(null); - }, this); - return future; - } - - @Override - public void teleportLocally(@NotNull Location location, boolean async) { - plugin.runSync(() -> { - final ServerWorld world = SpongeHuskHomes.Adapter.adapt(location.getWorld()); - if (world == null) { - return; - } - player.vehicle().ifPresent(vehicle -> vehicle.get().passengers().remove(player)); - player.passengers().forEach(passenger -> player.passengers().remove(passenger)); - player.setLocation(SpongeHuskHomes.Adapter.adapt(location)); - }, this); - } - - @Override - public void sendPluginMessage(byte[] message) { - ((SpongeHuskHomes) plugin).getPluginMessageChannel().sendTo(player, buf -> buf.writeBytes(message)); - } - - @Override - public boolean isMoving() { - return player.velocity().get().lengthSquared() > 0.0075; - } - - @Override - public boolean isVanished() { - return false; - } - - /** - * Handles player invulnerability after teleporting. - */ - @Override - public void handleInvulnerability() { - if (plugin.getSettings().getGeneral().getTeleportInvulnerabilityTime() <= 0) { - return; - } - long invulnerabilityTimeInTicks = 20L * plugin.getSettings().getGeneral().getTeleportInvulnerabilityTime(); - player.invulnerable().set(true); - // Remove the invulnerability - plugin.runSyncDelayed(() -> player.invulnerable().set(false), this, invulnerabilityTimeInTicks); - } - - @Override - public void removeInvulnerabilityIfPermitted() { - if (plugin.isInvulnerable(this.getUuid())) { - player.invulnerable().set(false); - } - } -} diff --git a/sponge/src/main/java/net/william278/huskhomes/util/SpongeSafetyResolver.java b/sponge/src/main/java/net/william278/huskhomes/util/SpongeSafetyResolver.java deleted file mode 100644 index feb5f830..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/util/SpongeSafetyResolver.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.util; - -import net.william278.huskhomes.SpongeHuskHomes; -import net.william278.huskhomes.position.Location; -import net.william278.huskhomes.position.World; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.block.BlockState; -import org.spongepowered.api.registry.RegistryTypes; -import org.spongepowered.api.world.border.WorldBorder; -import org.spongepowered.api.world.server.ServerLocation; -import org.spongepowered.math.vector.Vector2d; -import org.spongepowered.math.vector.Vector3i; - -import java.util.Optional; -import java.util.concurrent.CompletableFuture; - -public interface SpongeSafetyResolver extends SafetyResolver { - - @Override - default CompletableFuture> findSafeGroundLocation(@NotNull Location location) { - // Ensure the location is within the world border - final ServerLocation serverLocation = SpongeHuskHomes.Adapter.adapt(location); - if (isInBorder(serverLocation.world().border(), serverLocation.blockPosition())) { - return CompletableFuture.completedFuture(Optional.empty()); - } - - return CompletableFuture.completedFuture(findSafeLocationNear(serverLocation, location.getWorld())); - } - - /** - * Search for a safe ground location near the given location. - * - * @param location The location to search around - * @param world The world to search in - * @return An optional safe location, within 4 blocks of the given location - */ - private Optional findSafeLocationNear(@NotNull ServerLocation location, @NotNull World world) { - for (int x = -SEARCH_RADIUS; x <= SEARCH_RADIUS; x++) { - for (int z = -SEARCH_RADIUS; z <= SEARCH_RADIUS; z++) { - final Vector3i cursor = location.asHighestLocation().blockPosition().add(x, -1, z); - final Vector3i cursorBody = location.asHighestLocation().blockPosition().add(x, 0, z); - final Vector3i cursorHead = location.asHighestLocation().blockPosition().add(x, 1, z); - final BlockState blockState = location.world().block(cursor); - final BlockState bodyBlockState = location.world().block(cursorBody); - final BlockState headBlockState = location.world().block(cursorHead); - if (isBlockSafeForStanding(blockState.type().key(RegistryTypes.BLOCK_TYPE).asString()) - && isBlockSafeForOccupation(bodyBlockState.type().key(RegistryTypes.BLOCK_TYPE).asString()) - && isBlockSafeForOccupation(headBlockState.type().key(RegistryTypes.BLOCK_TYPE).asString())) { - double locx = cursor.x(); - if (locx < 0) { - locx += 1.5d; - } else { - locx = locx + 0.5d; - } - double locz = cursor.z(); - if (locz < 0) { - locz += 1.5d; - } else { - locz = locz + 0.5d; - } - return Optional.of(Location.at( - locx, - cursor.y(), - locz, - world - )); - } - } - } - return Optional.empty(); - } - - private boolean isInBorder(WorldBorder border, Vector3i position) { - final Vector2d center = border.center(); - final double radius = border.diameter() / 2; - final double x = position.x() - center.x(); - final double z = position.z() - center.y(); - return x * x + z * z < radius * radius; - } - -} \ No newline at end of file diff --git a/sponge/src/main/java/net/william278/huskhomes/util/SpongeTask.java b/sponge/src/main/java/net/william278/huskhomes/util/SpongeTask.java deleted file mode 100644 index ab702e06..00000000 --- a/sponge/src/main/java/net/william278/huskhomes/util/SpongeTask.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * This file is part of HuskHomes, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.huskhomes.util; - -import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.SpongeHuskHomes; -import net.william278.huskhomes.user.OnlineUser; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.spongepowered.api.scheduler.ScheduledTask; -import org.spongepowered.api.util.Ticks; - -import static org.spongepowered.api.scheduler.Task.builder; - -public interface SpongeTask extends Task { - - class Sync extends Task.Sync implements SpongeTask { - - private ScheduledTask task; - - protected Sync(@NotNull HuskHomes plugin, @NotNull Runnable runnable, - @SuppressWarnings("unused") @Nullable OnlineUser user, long delayTicks) { - super(plugin, runnable, delayTicks); - } - - @Override - public void cancel() { - if (task != null && !cancelled) { - task.cancel(); - } - super.cancel(); - } - - @Override - public void run() { - if (!cancelled) { - final SpongeHuskHomes plugin = ((SpongeHuskHomes) getPlugin()); - this.task = plugin.getGame().server().scheduler().submit(builder() - .plugin(plugin.getPluginContainer()) - .delay(Ticks.of(delayTicks)) - .execute(runnable) - .build()); - } - } - } - - class Async extends Task.Async implements SpongeTask { - - private ScheduledTask task; - - protected Async(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long delayTicks) { - super(plugin, runnable, delayTicks); - } - - @Override - public void cancel() { - if (task != null && !cancelled) { - task.cancel(); - } - super.cancel(); - } - - @Override - public void run() { - if (!cancelled) { - final SpongeHuskHomes plugin = ((SpongeHuskHomes) getPlugin()); - this.task = plugin.getGame().asyncScheduler().submit(builder() - .plugin(plugin.getPluginContainer()) - .execute(runnable) - .build()); - } - } - } - - class Repeating extends Task.Repeating implements SpongeTask { - - private ScheduledTask task; - - protected Repeating(@NotNull HuskHomes plugin, @NotNull Runnable runnable, long repeatingTicks) { - super(plugin, runnable, repeatingTicks); - } - - @Override - public void cancel() { - if (task != null && !cancelled) { - task.cancel(); - } - super.cancel(); - } - - @Override - public void run() { - if (!cancelled) { - final SpongeHuskHomes plugin = ((SpongeHuskHomes) getPlugin()); - this.task = plugin.getGame().asyncScheduler().submit(builder() - .plugin(plugin.getPluginContainer()) - .interval(Ticks.of(repeatingTicks)) - .execute(runnable) - .build()); - } - } - } - - interface Supplier extends Task.Supplier { - - @NotNull - @Override - default Task.Sync getSyncTask(@NotNull Runnable runnable, @Nullable OnlineUser user, long delayTicks) { - return new Sync(getPlugin(), runnable, user, delayTicks); - } - - @NotNull - @Override - default Task.Async getAsyncTask(@NotNull Runnable runnable, long delayTicks) { - return new Async(getPlugin(), runnable, delayTicks); - } - - @NotNull - @Override - default Task.Repeating getRepeatingTask(@NotNull Runnable runnable, long repeatingTicks) { - return new Repeating(getPlugin(), runnable, repeatingTicks); - } - - @Override - default void cancelTasks() { - } - - } - -}